mirror of
https://git.triforceproject.com/triforce/source
synced 2026-11-21 00:59:59 -04:00
Triforce v0.6.0 "Sage Of Power"
Faster frames (the replay's memory work, held submits, helper threads, collection and capture cuts), the game letting old areas go (QueryMemoryInfo), the 0.5.2 stutter fixed, AMD RX 5000/6000 and integrated-GPU fixes, the GPU device chosen by name, the in-game menus and launcher reworked, controller, Linux and benchmark fixes.
This commit is contained in:
@@ -1,61 +0,0 @@
|
||||
// tests/test_debug_tab_layout.py builds and runs this: gpu/vk/debug_tab_layout.h, the Debug tab's cells' widths.
|
||||
#include "../gpu/vk/debug_tab_layout.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
|
||||
using mkwvk::debug_tab::Widths;
|
||||
using mkwvk::debug_tab::widths;
|
||||
|
||||
static int failures;
|
||||
#define CHECK(what, ...) do { if (!(what)) { failures++; printf("FAIL line %d: ", __LINE__); printf(__VA_ARGS__); printf("\n"); } } while (0)
|
||||
|
||||
int main() {
|
||||
// the tab as it measures in a 1280 x 720 window (the layout's unit is the window's height over 720): each half of the
|
||||
// column 317 wide, the names asking 181 and 167, the cells at their narrowest 147 and 158
|
||||
const float name[2] = {181, 167}, full[2] = {175, 186}, tight[2] = {147, 158};
|
||||
const float room = 2 * 317 + 24;
|
||||
{ // one column, and every cell one width: the widest any asks, the Developer row of more than two values among them
|
||||
const Widths w = widths(317, room, name, full, tight, 200);
|
||||
CHECK(!w.two, "two columns where neither fits its names and cells");
|
||||
CHECK(w.cell[0] == 200 && w.cell[1] == 200 && w.span == 200, "one column's cells are %g, %g and %g, not all 200", w.cell[0], w.cell[1], w.span);
|
||||
const Widths plain = widths(317, room, name, full, tight, 150);
|
||||
CHECK(plain.cell[0] == 186 && plain.span == 186, "with no wide Developer row the cells are not the tools' widest (%g, %g)", plain.cell[0], plain.span);
|
||||
}
|
||||
// the same at every window: the layout scales with the window's height, so what does not fit at 720 lines fits at none
|
||||
for (float k : {1.0f, 1.5f, 2.0f, 3.0f}) {
|
||||
const float n[2] = {name[0] * k, name[1] * k}, f[2] = {full[0] * k, full[1] * k}, t[2] = {tight[0] * k, tight[1] * k};
|
||||
const Widths w = widths(317 * k, room * k, n, f, t, 200 * k);
|
||||
CHECK(!w.two && std::fabs(w.span - 200 * k) < 0.01f && w.cell[0] == w.span && w.cell[1] == w.span, "at %g times the size the widths are not the same share", k);
|
||||
}
|
||||
{ // one column, a name that needs the room: the cells give way to their narrowest, and no further
|
||||
const float long_name[2] = {560, 167};
|
||||
const Widths w = widths(317, room, long_name, full, tight, 200);
|
||||
CHECK(!w.two && w.cell[0] == 158 && w.span == 158, "a long name leaves the cells %g, not their narrowest 158", w.cell[0]);
|
||||
const float longer[2] = {500, 167};
|
||||
CHECK(widths(317, room, longer, full, tight, 200).span == room - 500, "the cells do not take what the longest name leaves");
|
||||
}
|
||||
{ // a column wide enough for both: two columns, each column's cells alike, the spanning rows' cells alike
|
||||
const Widths w = widths(330, 2 * 330 + 24, name, full, tight, 200);
|
||||
CHECK(w.two, "one column where both fit");
|
||||
CHECK(w.cell[0] == 149 && w.cell[1] == 163, "two columns' cells are %g and %g, not what the names leave (149, 163)", w.cell[0], w.cell[1]);
|
||||
CHECK(w.span == 200, "the spanning rows' cells are %g, not the widest any of them asks", w.span);
|
||||
const Widths narrow = widths(330, 2 * 330 + 24, name, full, tight, 120);
|
||||
CHECK(narrow.span == narrow.cell[1], "the spanning rows' cells do not line up with the second column's (%g, %g)", narrow.span, narrow.cell[1]);
|
||||
const Widths wide = widths(400, 2 * 400 + 24, name, full, tight, 120);
|
||||
CHECK(wide.two && wide.cell[0] == 175 && wide.cell[1] == 186, "with room to spare the cells are not what they ask (%g, %g)", wide.cell[0], wide.cell[1]);
|
||||
}
|
||||
{ // one column only fits: no two columns
|
||||
const float n[2] = {100, 250};
|
||||
CHECK(!widths(317, room, n, full, tight, 150).two && widths(317, room, name, full, tight, 150).two == false, "two columns with one that does not fit");
|
||||
}
|
||||
// never under the narrowest, whatever is asked
|
||||
for (float span : {0.0f, 100.0f, 400.0f})
|
||||
for (float col : {200.0f, 317.0f, 500.0f}) {
|
||||
const Widths w = widths(col, 2 * col + 24, name, full, tight, span);
|
||||
CHECK(w.cell[0] >= tight[0] - 0.01f && w.cell[1] >= tight[1] - 0.01f && w.span >= (w.two ? w.cell[1] : tight[1]), "a cell under its narrowest (%g, %g)", span, col);
|
||||
}
|
||||
if (failures) return printf("%d failures\n", failures), 1;
|
||||
printf("ok\n");
|
||||
return 0;
|
||||
}
|
||||
@@ -79,10 +79,10 @@ VkImageView texture_view_of(uint32_t h, VkImageViewType vt, ViewUse use, VkForma
|
||||
*tex = &textures[slot & 15];
|
||||
return handle<VkImageView>(v | 1);
|
||||
}
|
||||
VkSampler sampler_for(int id, bool compare) {
|
||||
VkSampler sampler_for(int id, bool compare, bool scene) { // ((Triforce, S8) scene: the jittered scene's, biased)
|
||||
w.samplers++;
|
||||
if (w.sampler_fail) return VK_NULL_HANDLE;
|
||||
return handle<VkSampler>(0x7000000ull | (uint64_t)id << 8 | (uint64_t)compare << 4 | w.samp << 32 | w.bias);
|
||||
return handle<VkSampler>(0x7000000ull | (uint64_t)id << 8 | (uint64_t)scene << 5 | (uint64_t)compare << 4 | w.samp << 32 | w.bias);
|
||||
}
|
||||
struct RecordingRes {
|
||||
struct Stream { VkBuffer buffer; };
|
||||
@@ -109,10 +109,11 @@ Stage vs{0}, fs{1};
|
||||
NvnState s{};
|
||||
desc_keep::Prog* kp() { return &desc_keep::prog_of(kept_descs(), &prog, 8); }
|
||||
struct Tex { VkSampler smp; VkImageView view; Texture* tex; bool known; };
|
||||
Tex tex_of(uint32_t h, VkImageViewType vt = VK_IMAGE_VIEW_TYPE_2D, bool compare = false, size_t j = 4, bool keep = true) {
|
||||
Tex tex_of(uint32_t h, VkImageViewType vt = VK_IMAGE_VIEW_TYPE_2D, bool compare = false, size_t j = 4, bool keep = true,
|
||||
bool scene = false) {
|
||||
Tex t{};
|
||||
view_slot_known = !w.known; // (the taken path must say what the lookup said)
|
||||
t.smp = kept_texture(keep ? kp() : nullptr, j, h, vt, compare, test == "compute", &t.view, &t.tex);
|
||||
t.smp = kept_texture(keep ? kp() : nullptr, j, h, vt, compare, test == "compute", scene, &t.view, &t.tex);
|
||||
t.known = view_slot_known;
|
||||
CHECK(!upload_defer_ok);
|
||||
return t;
|
||||
@@ -122,9 +123,10 @@ bool operator==(const VkDescriptorBufferInfo& a, const VkDescriptorBufferInfo& b
|
||||
return a.buffer == b.buffer && a.offset == b.offset && a.range == b.range;
|
||||
}
|
||||
/// Resolved (the sampler and, for a handle, the view looked up) or taken (nothing looked up)
|
||||
bool tex_resolved(uint32_t h, Tex* out = nullptr, VkImageViewType vt = VK_IMAGE_VIEW_TYPE_2D, bool compare = false) {
|
||||
bool tex_resolved(uint32_t h, Tex* out = nullptr, VkImageViewType vt = VK_IMAGE_VIEW_TYPE_2D, bool compare = false,
|
||||
bool scene = false) {
|
||||
const int v0 = w.views, s0 = w.samplers;
|
||||
const Tex t = tex_of(h, vt, compare);
|
||||
const Tex t = tex_of(h, vt, compare, 4, true, scene);
|
||||
if (out) *out = t;
|
||||
CHECK((w.views - v0) == (h ? w.samplers - s0 : 0));
|
||||
return w.samplers != s0;
|
||||
@@ -215,6 +217,15 @@ int run() {
|
||||
CHECK(!tex_resolved(h)); // (and what was kept is still there)
|
||||
return 0;
|
||||
}
|
||||
if (test == "texture-scene") { // ((Triforce, S8) a draw into the scene and one into a shadow map: each its own sampler)
|
||||
Tex a, b, c;
|
||||
CHECK(tex_resolved(h, &a) && !tex_resolved(h));
|
||||
CHECK(tex_resolved(h, &b, VK_IMAGE_VIEW_TYPE_2D, false, true) && b.smp != a.smp && b.view == a.view);
|
||||
CHECK(((uint64_t)(uintptr_t)b.smp >> 5 & 1) == 1 && ((uint64_t)(uintptr_t)a.smp >> 5 & 1) == 0); // (scene passed on)
|
||||
CHECK(!tex_resolved(h, &c, VK_IMAGE_VIEW_TYPE_2D, false, true) && c == b); // (kept for the scene)
|
||||
CHECK(tex_resolved(h, &c) && c == a && !tex_resolved(h)); // (and back: the other pass's again)
|
||||
return 0;
|
||||
}
|
||||
if (test == "texture-moved") { // (a destroy while the lookup ran: what it gave is kept with the generation before it)
|
||||
w.move_destroy = true;
|
||||
CHECK(tex_resolved(h));
|
||||
|
||||
@@ -123,7 +123,7 @@ VkImageView texture_view_of(uint32_t h, VkImageViewType vt, ViewUse use, VkForma
|
||||
*tex = &textures[slot & 15];
|
||||
return handle<VkImageView>(v | 1);
|
||||
}
|
||||
VkSampler sampler_for(int id, bool compare) {
|
||||
VkSampler sampler_for(int id, bool compare, bool) { // ((Triforce, S8) the scene flag: a draw's own, none here)
|
||||
w.samplers++;
|
||||
if (w.sampler_fail) return VK_NULL_HANDLE;
|
||||
return handle<VkSampler>(0x7000000ull | (uint64_t)id << 8 | (uint64_t)compare << 4 | w.samp << 32 | w.bias);
|
||||
@@ -240,7 +240,7 @@ Built build(const NvnState& s, const Program& p) {
|
||||
const uint32_t h = sampled_handle(s, st, c, k);
|
||||
Texture* tex = nullptr;
|
||||
VkImageView view = VK_NULL_HANDLE;
|
||||
const VkSampler smp = kept_texture(kp, jb + k, h, VK_IMAGE_VIEW_TYPE_2D, c.is_depth, false, &view, &tex);
|
||||
const VkSampler smp = kept_texture(kp, jb + k, h, VK_IMAGE_VIEW_TYPE_2D, c.is_depth, false, false, &view, &tex);
|
||||
if (view && tex) b.tex.push_back(tex);
|
||||
if (view && tex && tex->gpu_written) draw_sampled().push_back(tex);
|
||||
if (!view) view = handle<VkImageView>(0xD0); // (the dummy)
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#define CHECK(c) do { if (!(c)) { std::fprintf(stderr, "FAIL line %d: %s\n", __LINE__, #c); std::exit(1); } } while (0)
|
||||
@@ -33,6 +34,9 @@ namespace dlssg { bool active() { return false; } }
|
||||
bool fine_mode = true;
|
||||
bool fine_vectors() { return fine_mode; }
|
||||
constexpr float kFineBias = 0.3f;
|
||||
struct PresentSourceRect { uint32_t x, y, w, h; }; // ((Triforce, FG-2) vk_present_rect.h's, which the state names)
|
||||
// ((Triforce, FG-5) the frames' format: RGBA8 here (HDR Native's 10-bit one is tests/test_framegen_amd.py's)
|
||||
VkFormat frames_format() { return VK_FORMAT_R8G8B8A8_UNORM; }
|
||||
/* ACTUAL_STRUCTS */
|
||||
int multiplier() { return opts.framegen; }
|
||||
int display_refresh_mhz() { return 60000; }
|
||||
|
||||
204
tests/launcher_music_test.js
Normal file
204
tests/launcher_music_test.js
Normal file
@@ -0,0 +1,204 @@
|
||||
// tests/test_launcher_music.py: the launcher page's music (launcher/ui/app.js, from "const TRACKS" to the end of
|
||||
// audioTick) run in node with stand-ins for what a page has: Web Audio, fetch and <audio> record what they are asked and
|
||||
// make no sound. The WAV files are written here, laid out as launcher/Core/GameFiles/Bwav.cs ToWav writes them; no game
|
||||
// file is read. The page's code goes where the marker below is.
|
||||
'use strict';
|
||||
const assert = require('assert');
|
||||
|
||||
// ---- stand-ins ----
|
||||
const FAKE = { files: {}, ctxs: [], audios: [], fetched: [], decodeFails: false, noWebAudio: false, oneShots: [] };
|
||||
class Param { constructor() { this.value = 0; this.set = []; } setTargetAtTime(v, t, c) { assert.ok(c > 0 && c < .1, 'a short smoothing'); this.set.push(v); this.value = v; } }
|
||||
class Ctx {
|
||||
constructor(opts) { this.opts = opts; this.state = 'running'; this.currentTime = 0; this.destination = { name: 'speakers' }; this.sources = []; this.resumes = 0; FAKE.ctxs.push(this); }
|
||||
resume() { this.resumes++; this.state = 'running'; return Promise.resolve(); }
|
||||
createGain() { return { gain: new Param(), to: [], connect(n) { this.to.push(n); return n; }, disconnect() { this.cut = true; } }; }
|
||||
createBufferSource() {
|
||||
const s = { loop: false, loopStart: 0, loopEnd: 0, starts: 0, stopAt: null, onended: null,
|
||||
connect(n) { this.to = n; return n; }, start() { this.starts++; }, stop(t) { this.stopAt = t; } };
|
||||
this.sources.push(s);
|
||||
return s;
|
||||
}
|
||||
decodeAudioData(ab, ok, no) {
|
||||
if (FAKE.decodeFails) { const e = new Error('cannot decode'); if (no) no(e); return Promise.reject(e); }
|
||||
const buf = { sampleRate: 48000, length: FAKE.frames, duration: FAKE.frames / 48000, numberOfChannels: 2 };
|
||||
if (ok) ok(buf);
|
||||
return Promise.resolve(buf);
|
||||
}
|
||||
}
|
||||
class FakeAudio {
|
||||
constructor(src) { this.src = src; this.loop = false; this.volume = 1; this.playing = false; FAKE.audios.push(this); }
|
||||
play() { this.playing = true; return Promise.resolve(); }
|
||||
pause() { this.playing = false; }
|
||||
removeAttribute(a) { if (a === 'src') this.src = ''; }
|
||||
}
|
||||
const window = { get AudioContext() { return FAKE.noWebAudio ? undefined : Ctx; } };
|
||||
const Audio = FakeAudio;
|
||||
const listeners = {};
|
||||
function addEventListener(type, fn) { (listeners[type] = listeners[type] || []).push(fn); }
|
||||
function fetch(url) {
|
||||
FAKE.fetched.push(url);
|
||||
const bytes = FAKE.files[url];
|
||||
return Promise.resolve({ ok: !!bytes, status: bytes ? 200 : 404, arrayBuffer: () => Promise.resolve(bytes.slice(0)) });
|
||||
}
|
||||
const HOST = 'win';
|
||||
const S = { media: { music: true, v: 1 }, sound: { music: .4, sfx: .7, muted: false } };
|
||||
function nowPlaying() {}
|
||||
function afterOneShot(name) { FAKE.oneShots.push(name); }
|
||||
|
||||
/*@@APP_SOUND@@*/
|
||||
|
||||
// ---- WAV files as Bwav.ToWav writes them: 16-bit stereo, the samples at 44, a smpl chunk after them for a loop ----
|
||||
function makeWav(frames, loop, rate = 48000) {
|
||||
const data = frames * 4, smpl = loop ? 68 : 0, b = new ArrayBuffer(44 + data + smpl), d = new DataView(b);
|
||||
const tag = (at, s) => { for (let i = 0; i < 4; i++) d.setUint8(at + i, s.charCodeAt(i)); };
|
||||
tag(0, 'RIFF'); d.setUint32(4, 36 + data + smpl, true); tag(8, 'WAVE');
|
||||
tag(12, 'fmt '); d.setUint32(16, 16, true); d.setUint16(20, 1, true); d.setUint16(22, 2, true); d.setUint32(24, rate, true);
|
||||
d.setUint32(28, rate * 4, true); d.setUint16(32, 4, true); d.setUint16(34, 16, true);
|
||||
tag(36, 'data'); d.setUint32(40, data, true);
|
||||
for (let i = 0; i < frames * 2; i++) d.setInt16(44 + 2 * i, (i * 37) % 2000 - 1000, true);
|
||||
if (loop) {
|
||||
const at = 44 + data;
|
||||
tag(at, 'smpl'); d.setUint32(at + 4, 60, true); d.setUint32(at + 16, Math.floor(1e9 / rate), true); d.setUint32(at + 20, 60, true);
|
||||
d.setUint32(at + 36, 1, true); d.setUint32(at + 52, loop[0], true); d.setUint32(at + 56, loop[1] - 1, true);
|
||||
}
|
||||
return b;
|
||||
}
|
||||
|
||||
let T = performance.now();
|
||||
function play(seconds) { for (let i = 0, n = Math.round(seconds * 60); i < n; i++) { T += 1000 / 60; audioTick(T); } }
|
||||
const settle = async () => { for (let i = 0; i < 10; i++) await new Promise(r => setImmediate(r)); };
|
||||
const near = (a, b, what) => assert.ok(Math.abs(a - b) < 1e-9, what + ': ' + a + ' and ' + b);
|
||||
|
||||
(async () => {
|
||||
FAKE.frames = 1000;
|
||||
// ---- the loop a file carries ----
|
||||
let lp = wavLoop(makeWav(1000, [300, 1000]));
|
||||
assert.deepStrictEqual(lp, { rate: 48000, frames: 1000, start: 300, end: 1000 }, 'the smpl loop, its end the sample after the last');
|
||||
assert.deepStrictEqual(wavLoop(makeWav(1000, null)), { rate: 48000, frames: 1000, start: 0, end: 1000 }, 'an older file: the whole file');
|
||||
assert.deepStrictEqual(wavLoop(makeWav(1000, [300, 1001])), { rate: 48000, frames: 1000, start: 0, end: 1000 }, 'a loop past the sound: the whole file');
|
||||
assert.deepStrictEqual(wavLoop(makeWav(1000, [1000, 1000])), { rate: 48000, frames: 1000, start: 0, end: 1000 }, 'a loop that is none: the whole file');
|
||||
assert.deepStrictEqual(wavLoop(makeWav(1000, [300, 1000], 44100)), { rate: 44100, frames: 1000, start: 300, end: 1000 }, 'another rate');
|
||||
assert.strictEqual(wavLoop(new ArrayBuffer(8)), null, 'too short');
|
||||
assert.strictEqual(wavLoop(new TextEncoder().encode('<html>not found</html>').buffer), null, 'not a WAV');
|
||||
const cut = makeWav(1000, [300, 1000]).slice(0, 44 + 4000 + 40);
|
||||
assert.deepStrictEqual(wavLoop(cut), { rate: 48000, frames: 1000, start: 0, end: 1000 }, 'a smpl chunk cut off');
|
||||
|
||||
FAKE.files['audio/fairy.wav'] = makeWav(1000, [300, 1000]);
|
||||
FAKE.files['audio/temple.wav'] = makeWav(1000, [10, 1000]);
|
||||
FAKE.files['audio/saria.wav'] = makeWav(1000, null);
|
||||
FAKE.files['audio/itemget.wav'] = makeWav(1000, null);
|
||||
|
||||
// ---- a track loops between its loop points, sample for sample, at the game's rate ----
|
||||
music('fairy');
|
||||
assert.strictEqual(FAKE.ctxs.length, 1, 'one AudioContext');
|
||||
const ctx = FAKE.ctxs[0];
|
||||
assert.deepStrictEqual(ctx.opts, { sampleRate: 48000 }, 'the context at the game\'s rate');
|
||||
play(.5); // (still being read: the fade-in waits for it)
|
||||
await settle();
|
||||
assert.strictEqual(ctx.sources.length, 1, 'one source');
|
||||
let src = ctx.sources[0];
|
||||
assert.strictEqual(src.starts, 1, 'started once');
|
||||
assert.strictEqual(src.loop, true, 'looping');
|
||||
near(src.loopStart, 300 / 48000, 'loop start');
|
||||
near(src.loopEnd, 1000 / 48000, 'loop end');
|
||||
const fairy = live.find(m => m.name === 'fairy');
|
||||
assert.strictEqual(fairy.k, 0, 'the fade-in starts when the music does');
|
||||
assert.deepStrictEqual(src.to.to, [ctx.destination], 'through a gain to the speakers');
|
||||
play(1.5);
|
||||
near(fairy.g.gain.value, .4, 'faded in to the music volume (1.4 s)');
|
||||
S.sound.muted = true; play(.1); near(fairy.g.gain.value, 0, 'muted');
|
||||
S.sound.muted = false; S.sound.music = .8; play(.1); near(fairy.g.gain.value, .8, 'volume follows');
|
||||
S.sound.music = .4; play(.1);
|
||||
assert.strictEqual(FAKE.audios.length, 0, 'no <audio> element');
|
||||
assert.deepStrictEqual(FAKE.fetched, ['audio/fairy.wav'], 'read once');
|
||||
|
||||
// ---- the same track again: nothing restarts; another: the first fades out whole, then stops ----
|
||||
music('fairy'); await settle();
|
||||
assert.strictEqual(ctx.sources.length, 1, 'the same track does not start again');
|
||||
music('temple', true, 1.4); await settle();
|
||||
assert.strictEqual(ctx.sources.length, 2, 'the next track');
|
||||
const temple = ctx.sources[1];
|
||||
near(temple.loopStart, 10 / 48000, 'its own loop');
|
||||
play(1.3);
|
||||
assert.strictEqual(src.stopAt, null, 'not cut during its fade-out');
|
||||
assert.ok(fairy.g.gain.value > 0, 'still sounding');
|
||||
play(.2);
|
||||
assert.ok(src.stopAt !== null, 'stopped once faded out');
|
||||
assert.ok(!live.includes(fairy), 'gone from the live list');
|
||||
assert.ok(!decoded.has('fairy') && decoded.has('temple'), 'its samples let go; the playing track kept');
|
||||
|
||||
// ---- the item fanfare: once, at its full level from its first note, then what comes after it ----
|
||||
music('itemget', false, .3); await settle();
|
||||
const fan = ctx.sources[2];
|
||||
assert.strictEqual(fan.loop, false, 'plays once');
|
||||
const item = live.find(m => m.name === 'itemget');
|
||||
assert.strictEqual(item.k, 1, 'no fade-in on a one-shot');
|
||||
// (before any frame: the gain is set as the source starts, not ramped up from 0 on the next frame)
|
||||
near(item.g.gain.value, .4, 'full level from its first sample');
|
||||
assert.deepStrictEqual(item.g.gain.set, [], 'no ramp to it');
|
||||
play(.02);
|
||||
near(item.g.gain.value, .4, 'and kept');
|
||||
play(.3);
|
||||
assert.ok(temple.stopAt !== null, 'the track before it faded in .3 s');
|
||||
fan.onended(); play(.02); // (played to its end: a source fires ended once, not again when stop() comes after)
|
||||
assert.deepStrictEqual(FAKE.oneShots, ['itemget'], 'what plays after the fanfare is asked for');
|
||||
assert.strictEqual(curTrack, null, 'nothing playing');
|
||||
assert.ok(!live.includes(item), 'the fanfare is gone');
|
||||
assert.strictEqual(item.g.cut, true, 'its gain let go of the speakers');
|
||||
|
||||
// ---- a track faded out before it was read never starts ----
|
||||
music('saria'); music(null); play(.05); await settle();
|
||||
assert.strictEqual(ctx.sources.length, 3, 'never started');
|
||||
// ---- an older WAV, without a loop, loops whole ----
|
||||
music('saria'); await settle();
|
||||
const saria = ctx.sources[3];
|
||||
assert.strictEqual(saria.loop, true, 'loops');
|
||||
near(saria.loopStart, 0, 'from the start');
|
||||
near(saria.loopEnd, 1000 / 48000, 'to the end');
|
||||
play(1.5);
|
||||
music(null, true, 2.2); play(2.1);
|
||||
assert.strictEqual(saria.stopAt, null, 'still fading out (2.2 s, as for the game starting)');
|
||||
play(.2);
|
||||
assert.ok(saria.stopAt !== null && live.length === 0, 'stopped once faded out');
|
||||
|
||||
// ---- a context the browser holds back starts on the first click or key ----
|
||||
actx.state = 'suspended';
|
||||
listeners.pointerdown.forEach(f => f({}));
|
||||
assert.strictEqual(actx.state, 'running', 'resumed by a click');
|
||||
actx.state = 'suspended'; const resumes = actx.resumes; play(.1);
|
||||
assert.strictEqual(actx.state, 'running', 'and again from the frame loop once a click or key has come');
|
||||
assert.strictEqual(actx.resumes, resumes + 1, 'asked once, not every frame');
|
||||
|
||||
// ---- fallback: a file Web Audio cannot decode plays in an <audio> element, as before ----
|
||||
FAKE.decodeFails = true;
|
||||
music('fairy'); await settle();
|
||||
assert.strictEqual(FAKE.audios.length, 1, 'an <audio> element');
|
||||
const el = FAKE.audios[0];
|
||||
assert.strictEqual(el.src, 'audio/fairy.wav');
|
||||
assert.strictEqual(el.loop, true, 'looping whole');
|
||||
assert.ok(el.playing, 'playing');
|
||||
play(1.5); near(el.volume, .4, 'faded in');
|
||||
music(null); play(1.5);
|
||||
assert.ok(!el.playing && el.src === '', 'stopped and let go');
|
||||
FAKE.decodeFails = false;
|
||||
|
||||
// ---- fallback: no Web Audio at all ----
|
||||
actxTried = false; actx = null; FAKE.noWebAudio = true;
|
||||
music('temple'); await settle();
|
||||
assert.strictEqual(FAKE.audios.length, 2, 'an <audio> element without Web Audio');
|
||||
assert.strictEqual(FAKE.audios[1].loop, true);
|
||||
music('itemget', false, .3); await settle();
|
||||
const once = FAKE.audios[2];
|
||||
assert.strictEqual(once.loop, false, 'the fanfare once');
|
||||
near(once.volume, .4, 'at its full level from the start');
|
||||
once.onended();
|
||||
assert.deepStrictEqual(FAKE.oneShots, ['itemget', 'itemget'], 'and what comes after it');
|
||||
|
||||
// ---- music off (no game yet): nothing is read or played ----
|
||||
music(null); play(2);
|
||||
S.media.music = false; const before = FAKE.fetched.length;
|
||||
music('fairy'); await settle();
|
||||
assert.strictEqual(curTrack, null); assert.strictEqual(FAKE.fetched.length, before, 'nothing read without a game');
|
||||
|
||||
console.log('launcher music: all checks passed');
|
||||
})().catch(e => { console.error(e && e.stack || e); process.exit(1); });
|
||||
@@ -560,6 +560,24 @@ static void voices_and_mix(void) {
|
||||
CHECK(active() == 2 && voice_with(CURSOR) == 0 && voice_with(DECIDE) == 1);
|
||||
quiet();
|
||||
}
|
||||
{ /* ((Triforce, 11-19) the system menu's: the mouse onto Mods or Quit and its click in one tick, or a stick's flick and
|
||||
A, is their decide alone, as the options' tick and decision; 50 ms on they both play. Its ticks are not thinned
|
||||
out by the 180 ms gap, as the game's System list does not thin out its own) */
|
||||
install(SYS_CURSOR, 30000, 0.5f, 0.5f), install(SYS_DECIDE, 100, 1.0f, -1.0f);
|
||||
t0 += 10000 * kMs;
|
||||
hos_menu_sound_play(SYS_CURSOR, t0);
|
||||
hos_menu_sound_play(SYS_DECIDE, t0);
|
||||
CHECK(active() == 1 && voice_with(SYS_DECIDE) == 0 && voice_with(SYS_CURSOR) < 0 && voice_pos(0) == 0);
|
||||
quiet();
|
||||
hos_menu_sound_play(SYS_CURSOR, t0 + 1000 * kMs);
|
||||
hos_menu_sound_play(SYS_CURSOR, t0 + 1100 * kMs); /* (100 ms on: heard, restarted) */
|
||||
CHECK(active() == 1 && voice_with(SYS_CURSOR) == 0 && voice_pos(0) == 0);
|
||||
for (int k = 0; k < 10; k++) block(1.0f, 0.0f, 0.0f);
|
||||
hos_menu_sound_play(SYS_DECIDE, t0 + 1150 * kMs);
|
||||
CHECK(active() == 2 && voice_with(SYS_CURSOR) == 0 && voice_with(SYS_DECIDE) == 1);
|
||||
quiet();
|
||||
sounds[SYS_CURSOR] = sounds[SYS_DECIDE] = (Sound){0};
|
||||
}
|
||||
{ /* a restart inside the mix, between its read of the voice's place and of its sound: the tick is 240 samples in when
|
||||
the decision, 100 samples long, takes its voice. The place is the tick's, the sound the decision's: nothing of
|
||||
it is mixed in this block (240 is past the decision's end, and its samples end where nothing can be read),
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <algorithm>
|
||||
#include <exception>
|
||||
#include <limits>
|
||||
#include <new>
|
||||
@@ -16,7 +17,9 @@
|
||||
#ifdef _WIN32
|
||||
#include <windows.h>
|
||||
#else
|
||||
constexpr int MOVEFILE_REPLACE_EXISTING = 1;
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
constexpr int MOVEFILE_REPLACE_EXISTING = 1, MOVEFILE_WRITE_THROUGH = 8;
|
||||
void Sleep(unsigned ms) { std::this_thread::sleep_for(std::chrono::milliseconds(ms)); }
|
||||
#endif
|
||||
#include "file_whole.h" // ((Triforce, handoff §8) the save's Writing, and its .for file written whole)
|
||||
@@ -42,7 +45,7 @@ void operator delete[](void* p) noexcept { ::operator delete(p); }
|
||||
void operator delete[](void* p, std::size_t) noexcept { ::operator delete(p); }
|
||||
|
||||
using VkResult = int;
|
||||
constexpr VkResult VK_SUCCESS = 0, VK_ERROR_UNKNOWN = -13;
|
||||
constexpr VkResult VK_SUCCESS = 0, VK_INCOMPLETE = 5, VK_ERROR_UNKNOWN = -13;
|
||||
// props: the save in play is left out on Intel; the fixture's card is not one.
|
||||
struct { int device = 1; struct { unsigned vendorID = 0x10DE; } props; } dev;
|
||||
int pcache = 2;
|
||||
@@ -59,6 +62,10 @@ enum Fault { NONE, VECTOR_ALLOC, VECTOR_LENGTH, TMP_ALLOC, QUERY_FAIL, EMPTY, CO
|
||||
std::atomic<Fault> fault{NONE};
|
||||
std::atomic<int> queries{0}, copies{0}, writes{0}, replacements{0}, save_errors{0}, start_errors{0};
|
||||
std::atomic<bool> copy_blocked{false}, allow_copy{false};
|
||||
// ((Triforce) the workers building while a checkpoint fetches (warm_checkpoint.h): the cache grows by this between the size
|
||||
// asked and each copy, up to grow_until)
|
||||
std::atomic<std::size_t> grow_on_copy{0}, grow_until{0};
|
||||
std::atomic<int> incompletes{0};
|
||||
|
||||
#define CHECK(c) do { if (!(c)) { std::fprintf(stderr, "FAIL line %d: %s\n", __LINE__, #c); return 1; } } while (0)
|
||||
|
||||
@@ -81,14 +88,25 @@ VkResult vkGetPipelineCacheData(int device, int cache, std::size_t* n, void* dat
|
||||
*n = fault == VECTOR_LENGTH ? (std::numeric_limits<std::size_t>::max)() : fault == EMPTY ? 0 : cache_size.load();
|
||||
if (fault == VECTOR_ALLOC) fail_next_new = true;
|
||||
} else {
|
||||
// (the data as the call found it: taken in by a pipeline built after it began, it need not be in this copy. Read
|
||||
// before the copy is counted, which a case waits for before it grows the cache)
|
||||
if (grow_on_copy && cache_size < grow_until) cache_size = std::min(cache_size + grow_on_copy, grow_until.load());
|
||||
const std::size_t has = cache_size.load();
|
||||
++copies;
|
||||
if (fault == COPY_FAIL) return VK_ERROR_UNKNOWN;
|
||||
if (fault == BLOCK_COPY) {
|
||||
copy_blocked = true;
|
||||
while (!allow_copy.load()) Sleep(1);
|
||||
}
|
||||
std::memset(data, 'N', *n);
|
||||
// (as the Vulkan rule has it: at most *n written, VK_INCOMPLETE when the data is larger, *n what was written)
|
||||
const std::size_t put = std::min(*n, has);
|
||||
std::memset(data, 'N', put);
|
||||
*n = put;
|
||||
if (fault == TMP_ALLOC) fail_next_new = true;
|
||||
if (put < has) {
|
||||
++incompletes;
|
||||
return VK_INCOMPLETE;
|
||||
}
|
||||
}
|
||||
return VK_SUCCESS;
|
||||
}
|
||||
@@ -100,8 +118,10 @@ std::size_t save_fwrite(const void* p, std::size_t size, std::size_t n, FILE* f)
|
||||
if (fault == SHORT_WRITE) return 0;
|
||||
return std::fwrite(p, size, n, f);
|
||||
}
|
||||
std::atomic<int> write_through{0};
|
||||
int save_replace(const char* from, const char* to, unsigned flags) {
|
||||
if (flags != MOVEFILE_REPLACE_EXISTING || to != pcache_path) std::abort();
|
||||
if ((flags & ~(unsigned)MOVEFILE_WRITE_THROUGH) != (unsigned)MOVEFILE_REPLACE_EXISTING || to != pcache_path) std::abort();
|
||||
if (flags & MOVEFILE_WRITE_THROUGH) ++write_through;
|
||||
++replacements;
|
||||
if (fault == REPLACE_FAIL) return 0;
|
||||
#ifdef _WIN32
|
||||
@@ -123,19 +143,60 @@ bool memory_ram_fits(std::uint64_t bytes) {
|
||||
++fit_asks;
|
||||
return bytes && ram_fits;
|
||||
}
|
||||
// ((Triforce) and the same looked at now, for the preparation's checkpoint saves: vk_memory.cpp memory_ram_fits_now)
|
||||
bool memory_ram_fits_now(std::uint64_t bytes) {
|
||||
++fit_asks;
|
||||
return bytes && ram_fits;
|
||||
}
|
||||
|
||||
// ((Triforce) A checkpoint's (vk_draw.cpp, warm_checkpoint.h): the flag on its thread, a stop asked, the file flushed, the disk's
|
||||
// room. And whether the cache began from the file, and the stamp the file's .own names (pcache_own_mark)
|
||||
#include "warm_checkpoint.h"
|
||||
thread_local bool pcache_checkpoint_now = false;
|
||||
std::atomic<bool> stop_asked{false}, disk_room{true};
|
||||
std::atomic<int> flushes{0}, disk_asks{0}, stop_asks{0};
|
||||
// (a stop asked once this many stop asks were made: the first, before the fetch; the next, between the parts of the write)
|
||||
std::atomic<int> stop_after{-1};
|
||||
bool prepare_stopped() {
|
||||
const int k = ++stop_asks;
|
||||
return stop_asked || (stop_after >= 0 && k > stop_after);
|
||||
}
|
||||
bool pcache_file_flush(FILE* f) {
|
||||
++flushes;
|
||||
return std::fflush(f) == 0;
|
||||
}
|
||||
bool pcache_disk_fits(std::uint64_t) {
|
||||
++disk_asks;
|
||||
return disk_room;
|
||||
}
|
||||
bool pcache_from_file = false;
|
||||
std::uint64_t pcache_own_stamp() { return 0xabcdef0123456789ull; }
|
||||
|
||||
// (Triforce) The play file (vk_draw.cpp pcache_play_save, pcache_play.h; tests/test_pcache_play.py): no play cache here, so the
|
||||
// main file is saved as before
|
||||
std::atomic<int64_t> pcache_main_built{0};
|
||||
std::atomic<int> pcache_preparing{0};
|
||||
bool pcache_play_save(int64_t) { return true; }
|
||||
int pcache_play_cache = 0;
|
||||
std::atomic<std::size_t> pcache_play_saved{0};
|
||||
void pcache_main_written(int64_t) {}
|
||||
|
||||
// (Triforce) The carry over a stamp change (pcache_carry.h, tests/test_pcache_carry.py): vk_draw.cpp's own part, as it is
|
||||
// (pcache_carry_past, pcache_carry_save_ok, pcache_carry_check, pcache_carry_held, pcache_carry_early, pcache_carry_saved, cut
|
||||
// out by tests/test_pipeline_cache_save.py):
|
||||
// a carried session writes only up to its cap or the bound where lower, past it names the stamp in <file>.nocarry, and each
|
||||
// save in place writes the history beside the file
|
||||
#include <mutex>
|
||||
#include "pcache_carry.h"
|
||||
#include "pcache_carry_part.inc"
|
||||
|
||||
#define fwrite save_fwrite
|
||||
#define MoveFileExA save_replace
|
||||
#include "pipeline_cache_save.inc"
|
||||
#undef MoveFileExA
|
||||
#undef fwrite
|
||||
// ((Triforce) the preparation's checkpoint save, vk_draw.cpp's as it is (warm_checkpoint.h), through the save above
|
||||
#include "pcache_checkpoint_save.inc"
|
||||
|
||||
bool wait_until(const std::atomic<int>& n, int target) {
|
||||
const auto end = std::chrono::steady_clock::now() + std::chrono::seconds(3);
|
||||
@@ -150,6 +211,47 @@ bool old_file() {
|
||||
std::fclose(f);
|
||||
return n == 3 && std::memcmp(data, "old", 3) == 0;
|
||||
}
|
||||
bool side_file(std::uint64_t base, std::uint32_t carried) {
|
||||
FILE* f = std::fopen((pcache_path + ".base").c_str(), "rb");
|
||||
if (!f) return false;
|
||||
std::uint8_t raw[pcache_carry::kSideBytes]{};
|
||||
const auto n = std::fread(raw, 1, sizeof raw, f);
|
||||
std::fclose(f);
|
||||
pcache_carry::Side s;
|
||||
return pcache_carry::get(raw, n, &s) && s.base == base && s.carried == carried && !std::memcmp(s.stamp, "1122334455667788", 16);
|
||||
}
|
||||
// The side file's open word (pcache_carry.h Side::open), -1 when there is no side file
|
||||
int side_open() {
|
||||
FILE* f = std::fopen((pcache_path + ".base").c_str(), "rb");
|
||||
if (!f) return -1;
|
||||
std::uint8_t raw[pcache_carry::kSideBytes]{};
|
||||
const auto n = std::fread(raw, 1, sizeof raw, f);
|
||||
std::fclose(f);
|
||||
pcache_carry::Side s;
|
||||
return pcache_carry::get(raw, n, &s) ? (int)s.open : -1;
|
||||
}
|
||||
// The 16 digits a side file of the pipeline cache's has ("" when there is none)
|
||||
std::string sixteen(const std::string& path) {
|
||||
FILE* f = std::fopen(path.c_str(), "rb");
|
||||
if (!f) return "";
|
||||
char data[17]{};
|
||||
const auto n = std::fread(data, 1, 16, f);
|
||||
std::fclose(f);
|
||||
return n == 16 ? std::string(data, 16) : "";
|
||||
}
|
||||
bool tmp_left() {
|
||||
FILE* f = std::fopen((pcache_path + ".tmp").c_str(), "rb");
|
||||
if (f) std::fclose(f);
|
||||
return f != nullptr;
|
||||
}
|
||||
bool nocarry_file() {
|
||||
FILE* f = std::fopen((pcache_path + ".nocarry").c_str(), "rb");
|
||||
if (!f) return false;
|
||||
char data[17]{};
|
||||
const auto n = std::fread(data, 1, sizeof data, f);
|
||||
std::fclose(f);
|
||||
return n == 16 && !std::memcmp(data, "1122334455667788", 16);
|
||||
}
|
||||
bool new_file() {
|
||||
FILE* f = std::fopen(pcache_path.c_str(), "rb");
|
||||
if (!f) return false;
|
||||
@@ -271,6 +373,332 @@ int run(const std::string& name) {
|
||||
pipeline_cache_save(true);
|
||||
CHECK(new_file() && copies == 3 && replacements == 3 && pcache_saved_size == 96);
|
||||
CHECK(save_errors == 0 && start_errors == 0);
|
||||
} else if (name == "carry-cap") {
|
||||
// (Triforce) Carried over a stamp change with a base of 64 bytes: written up to 80 (1.25 x), its history with it.
|
||||
pcache_carried = true;
|
||||
pcache_side.base = 64, pcache_side.carried = 1;
|
||||
pipeline_cache_save(true);
|
||||
CHECK(new_file() && replacements == 1 && side_file(64, 1) && pcache_side.base == 64 && pcache_side.carried == 1);
|
||||
CHECK(std::memcmp(pcache_side.stamp, "1122334455667788", 16) == 0);
|
||||
cache_size = 80; // At the cap: still written, the base kept (a carried file's growth is not a new base).
|
||||
pipeline_cache_save(true);
|
||||
CHECK(new_file() && replacements == 2 && side_file(64, 1) && pcache_saved_size == 80);
|
||||
CHECK(!pcache_carry_over && !nocarry_file());
|
||||
cache_size = 96; // Past it: the size asked, nothing fetched or written, the file keeps its last save.
|
||||
pipeline_cache_save(true);
|
||||
CHECK(queries == 3 && copies == 2 && writes == 2 && replacements == 2 && pcache_saved_size == 80);
|
||||
CHECK(pcache_carry_over && nocarry_file()); // Over: the rebuild is due, and a preparation begun again starts fresh.
|
||||
cache_size = 80;
|
||||
CHECK(new_file() && side_file(64, 1));
|
||||
cache_size = 96; // Asked again: refused again.
|
||||
pipeline_cache_save(true);
|
||||
CHECK(copies == 2 && replacements == 2);
|
||||
// A fresh cache in its place (pcache_carry_rebuild): no carry, its saves written and the base follows them.
|
||||
pcache_carried = false;
|
||||
pcache_carry_over = false;
|
||||
pcache_side = pcache_carry::session(pcache_carry::Start::Fresh, pcache_side);
|
||||
pipeline_cache_save(true);
|
||||
CHECK(new_file() && replacements == 3 && pcache_side.base == 96 && pcache_side.carried == 0 && side_file(96, 0));
|
||||
CHECK(!pcache_carry_over && save_errors == 0 && start_errors == 0);
|
||||
} else if (name == "carry-bound") {
|
||||
// (Triforce) Carried with a base of 64 bytes (cap 80) and a bound of 72: past the bound, under the cap, is past what it
|
||||
// may hold (never left over the bound unwritten with no rebuild), and the bound's own refusal is not reached.
|
||||
pcache_carried = true;
|
||||
pcache_side.base = 64, pcache_side.carried = 1;
|
||||
pcache_bound_bytes = 72;
|
||||
cache_size = 72; // At the bound: written.
|
||||
pipeline_cache_save(true);
|
||||
CHECK(new_file() && replacements == 1 && !pcache_carry_over && !nocarry_file());
|
||||
cache_size = 76; // Over the bound, under the cap.
|
||||
pipeline_cache_save(true);
|
||||
CHECK(copies == 1 && replacements == 1 && pcache_carry_over && nocarry_file() && pcache_saved_size == 72);
|
||||
cache_size = 72;
|
||||
CHECK(new_file());
|
||||
// Not carried, the same size over the bound: the bound's rule as before, no rebuild asked.
|
||||
pcache_carried = false;
|
||||
pcache_carry_over = false;
|
||||
cache_size = 76;
|
||||
pipeline_cache_save(true);
|
||||
CHECK(copies == 1 && replacements == 1 && !pcache_carry_over);
|
||||
CHECK(save_errors == 0 && start_errors == 0);
|
||||
} else if (name == "carry-done") {
|
||||
// (Triforce) A carried session's history is open (pcache_carry.h Side::open) until its preparation goes through to
|
||||
// its end (pcache_carry_close): a stopped one's save is read as carried by the preparation begun again.
|
||||
pcache_carried = true;
|
||||
pcache_side.base = 64;
|
||||
std::memcpy(pcache_side.stamp, "aaaaaaaaaaaaaaaa", 16); // (the old stamp's file)
|
||||
pcache_side = pcache_carry::session(pcache_carry::Start::Carried, pcache_side);
|
||||
CHECK(pcache_side.open == 1 && pcache_side.carried == 1);
|
||||
pcache_carry_close(); // Nothing saved under these shaders yet: no side file written, the next save writes it.
|
||||
CHECK(side_open() == -1 && pcache_side.open == 0);
|
||||
pcache_side.open = 1;
|
||||
pipeline_cache_save(true); // Saved (a stop's last save): these shaders' stamp, the history open.
|
||||
CHECK(new_file() && side_file(64, 1) && side_open() == 1);
|
||||
pcache_carry_close(); // Gone through: no longer open, beside the file at once.
|
||||
CHECK(side_file(64, 1) && side_open() == 0 && pcache_side.open == 0 && replacements == 1);
|
||||
pcache_side.open = 1;
|
||||
cache_size = 80;
|
||||
pipeline_cache_save(true);
|
||||
CHECK(replacements == 2 && side_open() == 1);
|
||||
cache_size = 96; // Past what it may hold: not written, and not done: the file's history stays open.
|
||||
pipeline_cache_save(true);
|
||||
CHECK(replacements == 2 && pcache_carry_over && nocarry_file());
|
||||
pcache_carry_close();
|
||||
CHECK(side_open() == 1 && pcache_side.open == 1);
|
||||
// Not carried (a fresh cache, pcache_carry_rebuild): nothing to do.
|
||||
pcache_carried = false;
|
||||
pcache_carry_over = false;
|
||||
pcache_side = pcache_carry::session(pcache_carry::Start::Fresh, pcache_side);
|
||||
pipeline_cache_save(true);
|
||||
CHECK(replacements == 3 && side_file(96, 0) && side_open() == 0);
|
||||
pcache_carry_close();
|
||||
CHECK(side_open() == 0 && save_errors == 0 && start_errors == 0);
|
||||
} else if (name == "checkpoint") {
|
||||
// (Triforce) A checkpoint mid-warm (warm_checkpoint.h) in a session that carried the file over a stamp change (base
|
||||
// 64, cap 80): saved under these shaders' stamp with the history open, as a stopped run's save. The start after a
|
||||
// crash there reads it as carried still (pcache_carry::resumed), capped as this run was, and past the cap rebuilds.
|
||||
pcache_carried = true;
|
||||
pcache_side.base = 64;
|
||||
std::memcpy(pcache_side.stamp, "aaaaaaaaaaaaaaaa", 16); // (the old stamp's file)
|
||||
pcache_side = pcache_carry::session(pcache_carry::Start::Carried, pcache_side);
|
||||
cache_size = 72;
|
||||
ram_fits = false; // The RAM short: nothing fetched, nothing written, the old file kept.
|
||||
CHECK(pcache_checkpoint_save() == 0 && fit_asks == 1 && copies == 0 && replacements == 0 && old_file());
|
||||
ram_fits = true;
|
||||
CHECK(pcache_checkpoint_save() == 72 && copies == 1 && replacements == 1 && new_file());
|
||||
CHECK(side_file(64, 1) && side_open() == 1 && !pcache_carry_over);
|
||||
{ // (the .for names these shaders now: the next start finds the file the same stamp's)
|
||||
FILE* f = std::fopen((pcache_path + ".for").c_str(), "rb");
|
||||
CHECK(f);
|
||||
char had[17]{};
|
||||
const auto got = std::fread(had, 1, 16, f);
|
||||
std::fclose(f);
|
||||
CHECK(got == 16 && !std::memcmp(had, "1122334455667788", 16));
|
||||
}
|
||||
CHECK(pcache_checkpoint_save() == 0 && copies == 1 && replacements == 1); // Nothing new: nothing written.
|
||||
{ // The start after a crash here, as pcache_init reads the files: the same stamp, its history open, an update's
|
||||
// preparation: carried still, no carry counted again, capped at 80 as this run was.
|
||||
FILE* f = std::fopen((pcache_path + ".base").c_str(), "rb");
|
||||
CHECK(f);
|
||||
std::uint8_t raw[pcache_carry::kSideBytes]{};
|
||||
const auto got = std::fread(raw, 1, sizeof raw, f);
|
||||
std::fclose(f);
|
||||
pcache_carry::Side had;
|
||||
CHECK(pcache_carry::get(raw, got, &had));
|
||||
const pcache_carry::Side history = pcache_carry::history(true, had, "1122334455667788", 72);
|
||||
CHECK(pcache_carry::resumed(true, true, true, history));
|
||||
const pcache_carry::Side again = pcache_carry::session(pcache_carry::Start::Same, history);
|
||||
CHECK(again.open == 1 && again.carried == 1 && again.base == 64);
|
||||
CHECK(!pcache_carry::over(true, 80, again, 0) && pcache_carry::over(true, 81, again, 0));
|
||||
}
|
||||
cache_size = 96; // Past the cap at a checkpoint: not written, the rebuild asked, the file as the last checkpoint left it.
|
||||
CHECK(pcache_checkpoint_save() == 0 && copies == 1 && replacements == 1 && pcache_carry_over && nocarry_file());
|
||||
cache_size = 72;
|
||||
CHECK(new_file() && side_open() == 1);
|
||||
// Not carried (a fresh cache): a checkpoint writes it, its history not open.
|
||||
pcache_carried = false;
|
||||
pcache_carry_over = false;
|
||||
pcache_side = pcache_carry::session(pcache_carry::Start::Fresh, pcache_side);
|
||||
cache_size = 88;
|
||||
CHECK(pcache_checkpoint_save() == 88 && replacements == 2 && side_file(88, 0) && side_open() == 0);
|
||||
let_go = true; // The cache let go: not asked.
|
||||
const int asked = queries.load();
|
||||
CHECK(pcache_checkpoint_save() == 0 && queries == asked && replacements == 2);
|
||||
CHECK(save_errors == 0 && start_errors == 0);
|
||||
} else if (name == "checkpoint-grow") {
|
||||
// (Triforce) A checkpoint while the workers build (warm_checkpoint.h): the cache grows between the size asked and the
|
||||
// copy. A save of the other kind (the size asked, no room) gets VK_INCOMPLETE and writes nothing, as before; a
|
||||
// checkpoint fetches with room, writes what the driver gave, on the disk before it takes the old file's place.
|
||||
grow_on_copy = 8, grow_until = 1u << 30;
|
||||
pipeline_cache_save(true);
|
||||
CHECK(incompletes == 1 && copies == 1 && replacements == 0 && old_file() && !tmp_left());
|
||||
CHECK(pcache_checkpoint_save() == 80 && incompletes == 1 && copies == 2 && replacements == 1 && new_file());
|
||||
CHECK(flushes == 1 && write_through == 1 && disk_asks == 1 && pcache_saved_size == 80);
|
||||
// The other saves: no flush, no write-through, the disk not asked (nothing changed for them).
|
||||
grow_on_copy = 0;
|
||||
cache_size = 96;
|
||||
pipeline_cache_save(true);
|
||||
CHECK(replacements == 2 && new_file() && flushes == 1 && write_through == 1 && disk_asks == 1);
|
||||
// Carried (base 64, cap 80): asked at 76, fetched at 84, past the cap. Looked at again on what was fetched: not written,
|
||||
// the rebuild asked.
|
||||
pcache_carried = true;
|
||||
pcache_side.base = 64, pcache_side.carried = 1;
|
||||
cache_size = 76, grow_on_copy = 8;
|
||||
CHECK(pcache_checkpoint_save() == 0 && copies == 4 && replacements == 2 && pcache_carry_over && nocarry_file());
|
||||
pcache_carried = false;
|
||||
pcache_carry_over = false;
|
||||
// The bound (88): asked at 84, fetched at 92, over it: not written.
|
||||
pcache_bound_bytes = 88;
|
||||
cache_size = 84;
|
||||
CHECK(pcache_checkpoint_save() == 0 && copies == 5 && replacements == 2);
|
||||
pcache_bound_bytes = 0;
|
||||
// Growing past the room at every try: kFetchTries copies, the size asked again before each, nothing written.
|
||||
grow_on_copy = warm_checkpoint::kRoomMin + 8;
|
||||
const int had = copies.load(), asked = queries.load();
|
||||
CHECK(pcache_checkpoint_save() == 0 && copies == had + warm_checkpoint::kFetchTries && replacements == 2);
|
||||
CHECK(queries == asked + 1 + warm_checkpoint::kFetchTries && incompletes == 1 + warm_checkpoint::kFetchTries);
|
||||
CHECK(save_errors == 0 && start_errors == 0);
|
||||
} else if (name == "checkpoint-stop") {
|
||||
// (Triforce) A stop asked (warm_checkpoint.h): a checkpoint gives up, before the fetch or in the write, and leaves no
|
||||
// .tmp; the stop's own save (not a checkpoint) writes the cache as ever.
|
||||
stop_asked = true;
|
||||
CHECK(pcache_checkpoint_save() == 0 && copies == 0 && replacements == 0 && old_file());
|
||||
stop_asked = false;
|
||||
stop_after = stop_asks.load() + 1; // (the look before the fetch says not stopped, the one in the write says stopped)
|
||||
CHECK(pcache_checkpoint_save() == 0 && copies == 1 && writes == 0 && replacements == 0 && old_file() && !tmp_left());
|
||||
stop_after = -1;
|
||||
stop_asked = true;
|
||||
pipeline_cache_save(true);
|
||||
CHECK(replacements == 1 && new_file() && flushes == 0);
|
||||
stop_asked = false;
|
||||
cache_size = 72;
|
||||
CHECK(pcache_checkpoint_save() == 72 && replacements == 2 && new_file());
|
||||
// The disk short of room for the .tmp beside the old file: not fetched, asked again later.
|
||||
disk_room = false;
|
||||
cache_size = 80;
|
||||
CHECK(pcache_checkpoint_save() == 0 && copies == 3 && replacements == 2);
|
||||
disk_room = true;
|
||||
CHECK(pcache_checkpoint_save() == 80 && replacements == 3 && new_file());
|
||||
// A write that fails leaves no .tmp to fill the disk.
|
||||
cache_size = 88;
|
||||
fault = SHORT_WRITE;
|
||||
CHECK(pcache_checkpoint_save() == 0 && replacements == 3 && !tmp_left());
|
||||
fault = NONE;
|
||||
CHECK(save_errors == 0 && start_errors == 0);
|
||||
} else if (name == "carry-begun") {
|
||||
// (Triforce) pcache_carry.h begun: a carried session's save writes its history (these shaders' stamp, open) before the
|
||||
// data takes the old file's place, and the .for after. Cut between them (here: the data not put in place), the start
|
||||
// after reads the session's own history, capped, not one fresh set of the file's size, uncapped.
|
||||
CHECK(file_writers::write_whole(pcache_path + ".for", "aaaaaaaaaaaaaaaa", 16));
|
||||
pcache_carried = true;
|
||||
pcache_side.base = 64;
|
||||
std::memcpy(pcache_side.stamp, "aaaaaaaaaaaaaaaa", 16);
|
||||
pcache_side = pcache_carry::session(pcache_carry::Start::Carried, pcache_side);
|
||||
cache_size = 72;
|
||||
fault = REPLACE_FAIL;
|
||||
CHECK(pcache_checkpoint_save() == 0 && replacements == 1 && old_file() && !tmp_left());
|
||||
CHECK(side_file(64, 1) && side_open() == 1 && sixteen(pcache_path + ".for") == "aaaaaaaaaaaaaaaa");
|
||||
{
|
||||
FILE* f = std::fopen((pcache_path + ".base").c_str(), "rb");
|
||||
CHECK(f);
|
||||
std::uint8_t raw[pcache_carry::kSideBytes]{};
|
||||
const auto got = std::fread(raw, 1, sizeof raw, f);
|
||||
std::fclose(f);
|
||||
pcache_carry::Side had;
|
||||
CHECK(pcache_carry::get(raw, got, &had));
|
||||
CHECK(pcache_carry::begun(true, had, "1122334455667788", "aaaaaaaaaaaaaaaa"));
|
||||
CHECK(pcache_carry::resumed(true, true, true, had));
|
||||
const pcache_carry::Side again = pcache_carry::session(pcache_carry::Start::Same, had);
|
||||
CHECK(again.open == 1 && again.carried == 1 && again.base == 64 && pcache_carry::over(true, 81, again, 0));
|
||||
// (by the history's own rule the side file is not that file's: one fresh set of its size, never capped)
|
||||
CHECK(pcache_carry::history(true, had, "aaaaaaaaaaaaaaaa", 3).open == 0);
|
||||
}
|
||||
// The history cannot be written: the data is not put in place, the old file and its .for stay.
|
||||
fault = NONE;
|
||||
std::remove((pcache_path + ".base").c_str());
|
||||
#ifdef _WIN32
|
||||
CHECK(CreateDirectoryA((pcache_path + ".base").c_str(), nullptr));
|
||||
#else
|
||||
CHECK(mkdir((pcache_path + ".base").c_str(), 0700) == 0);
|
||||
#endif
|
||||
CHECK(pcache_checkpoint_save() == 0 && replacements == 1 && old_file() && !tmp_left());
|
||||
CHECK(sixteen(pcache_path + ".for") == "aaaaaaaaaaaaaaaa");
|
||||
#ifdef _WIN32
|
||||
CHECK(RemoveDirectoryA((pcache_path + ".base").c_str()));
|
||||
#else
|
||||
CHECK(rmdir((pcache_path + ".base").c_str()) == 0);
|
||||
#endif
|
||||
CHECK(pcache_checkpoint_save() == 72 && replacements == 2 && new_file() && side_file(64, 1) && side_open() == 1);
|
||||
CHECK(sixteen(pcache_path + ".for") == "1122334455667788");
|
||||
// Not carried: no history written before the data (as before), a cut save leaves none.
|
||||
pcache_carried = false;
|
||||
pcache_side = pcache_carry::session(pcache_carry::Start::Fresh, pcache_side);
|
||||
std::remove((pcache_path + ".base").c_str());
|
||||
cache_size = 80;
|
||||
fault = REPLACE_FAIL;
|
||||
CHECK(pcache_checkpoint_save() == 0 && replacements == 3 && side_open() == -1);
|
||||
fault = NONE;
|
||||
CHECK(save_errors == 0 && start_errors == 0);
|
||||
} else if (name == "own") {
|
||||
// (Triforce) <file>.own (pcache_own_mark): written beside the saves of a session that began with no file or with such a
|
||||
// file, removed by those of a session that began with another file's data or carried one.
|
||||
const std::string own = pcache_path + ".own";
|
||||
pipeline_cache_save(true);
|
||||
CHECK(new_file() && sixteen(own) == "abcdef0123456789" && pcache_own_named()); // (read so at the next start)
|
||||
pcache_from_file = true; // (a file not of that kind: an older build's, after an update that kept the stamp)
|
||||
cache_size = 72;
|
||||
pipeline_cache_save(true);
|
||||
CHECK(new_file() && sixteen(own).empty() && !pcache_own_named());
|
||||
pcache_from_own = true; // (one of that kind: a checkpoint's before a crash)
|
||||
cache_size = 80;
|
||||
CHECK(pcache_checkpoint_save() == 80 && sixteen(own) == "abcdef0123456789");
|
||||
pcache_carried = true; // (carried over a stamp change)
|
||||
pcache_side.base = 80;
|
||||
cache_size = 88;
|
||||
pipeline_cache_save(true);
|
||||
CHECK(new_file() && sixteen(own).empty() && replacements == 4);
|
||||
CHECK(save_errors == 0 && start_errors == 0);
|
||||
} else if (name == "carry-check") {
|
||||
// (Triforce) The preparation's look at the size (prepare_run, warm_libraries): not carried, the driver is not asked.
|
||||
CHECK(!pcache_carry_check(false) && !pcache_carry_check(true) && queries == 0);
|
||||
pcache_carried = true;
|
||||
pcache_side.base = 64;
|
||||
pcache_bound_bytes = 0;
|
||||
cache_size = 80; // At the cap: not past.
|
||||
CHECK(!pcache_carry_check(true) && queries == 1 && !pcache_carry_over);
|
||||
cache_size = 96;
|
||||
dev.props.vendorID = 0x8086; // Intel: not asked while workers build into the cache, asked once they are joined.
|
||||
CHECK(!pcache_carry_check(true) && queries == 1);
|
||||
CHECK(pcache_carry_check(false) && queries == 2 && pcache_carry_over && nocarry_file());
|
||||
CHECK(pcache_carry_check(true) && queries == 2); // Once past, it stays so without asking.
|
||||
pcache_carry_over = false;
|
||||
dev.props.vendorID = 0x10DE;
|
||||
CHECK(pcache_carry_check(true) && queries == 3);
|
||||
pcache_carry_over = false;
|
||||
let_go = true; // The cache let go: nothing asked.
|
||||
CHECK(!pcache_carry_check(false) && queries == 3);
|
||||
CHECK(copies == 0 && writes == 0 && old_file());
|
||||
} else if (name == "carry-early") {
|
||||
// (Triforce) The early drop (warm_libraries, pcache_carry_early): not carried, nothing asked and nothing projected.
|
||||
std::size_t from = 1;
|
||||
CHECK(!pcache_carry_held(&from) && from == 0 && !pcache_carry_early(64, 100, 1000, 1500) && queries == 0);
|
||||
pcache_carried = true;
|
||||
pcache_side.base = 64; // (its limit 80: the room from 64 is 16, the margin 32 of projected growth)
|
||||
pcache_bound_bytes = 0;
|
||||
CHECK(pcache_carry_held(&from) && from == 64 && queries == 1);
|
||||
cache_size = 68; // 4 bytes for a sample of 100 of 1000 programs: 40 over the warm at this rate, past the margin.
|
||||
CHECK(!pcache_carry_early(from, 100, 1000, 1499));
|
||||
CHECK(queries == 2 && !pcache_carry_over && !nocarry_file()); // (the sample too small: asked, not dropped)
|
||||
cache_size = 65; // 1 byte for 100 of 1000: 10, under the margin.
|
||||
CHECK(!pcache_carry_early(from, 100, 1000, 1500) && queries == 3 && !pcache_carry_over);
|
||||
cache_size = 96; // Past already: left to pcache_carry_check, which says so.
|
||||
CHECK(!pcache_carry_early(from, 100, 1000, 1500) && queries == 4 && !pcache_carry_over);
|
||||
cache_size = 68;
|
||||
dev.props.vendorID = 0x8086; // Intel: not asked while workers build, and no projection made (the warm's own order).
|
||||
from = 1;
|
||||
CHECK(!pcache_carry_held(&from) && from == 0 && !pcache_carry_early(64, 100, 1000, 1500) && queries == 4);
|
||||
dev.props.vendorID = 0x10DE;
|
||||
#ifdef _WIN32
|
||||
_putenv("RX_VK_PCACHE_CARRY_PROJECT=0");
|
||||
#else
|
||||
setenv("RX_VK_PCACHE_CARRY_PROJECT", "0", 1);
|
||||
#endif
|
||||
// Off: past alone, and no projection made (the warm's own order).
|
||||
CHECK(!pcache_carry_held(&from) && from == 0 && queries == 4);
|
||||
CHECK(!pcache_carry_early(64, 100, 1000, 1500) && queries == 4 && !pcache_carry_over);
|
||||
#ifdef _WIN32
|
||||
_putenv("RX_VK_PCACHE_CARRY_PROJECT=");
|
||||
#else
|
||||
unsetenv("RX_VK_PCACHE_CARRY_PROJECT");
|
||||
#endif
|
||||
CHECK(pcache_carry_held(&from) && from == 68 && queries == 5);
|
||||
from = 64;
|
||||
// Dropped: as past what it may hold, the carry refused for these shaders, and the look past it says so without asking.
|
||||
CHECK(pcache_carry_early(from, 100, 1000, 1500) && queries == 6 && pcache_carry_over && nocarry_file());
|
||||
CHECK(pcache_carry_check(true) && queries == 6 && !pcache_carry_early(from, 100, 1000, 1500) && queries == 6);
|
||||
// Not written: a carried cache dropped is not saved, and the file keeps what it was.
|
||||
pipeline_cache_save(true);
|
||||
CHECK(copies == 0 && writes == 0 && replacements == 0 && old_file());
|
||||
} else if (name == "ram-short") {
|
||||
ram_fits = false; // In play, a copy of the data would not fit in the RAM available: it waits, nothing fetched.
|
||||
pcache_built_since_save = 32;
|
||||
|
||||
@@ -133,13 +133,20 @@ void check(uint32_t sw, uint32_t sh, const int* crop, uint32_t x, uint32_t y, ui
|
||||
fsr4_result = framegen_rows::SKIP;
|
||||
CHECK(framegen_record(nullptr, 1, sw, sh, crop) && fsr4_calls == 2 && fg.recorded->made == 0);
|
||||
CHECK(dispatches == 13 && copies == 5);
|
||||
// ((Triforce, FG-2) no picture without the HUD, or HDR Native: the game's frame alone, never the shared interpolation's
|
||||
// frame in place of AMD's; the present's source handed on for the picture without the HUD's cut)
|
||||
shown();
|
||||
fsr4_result = framegen_rows::GAME;
|
||||
CHECK(framegen_record(nullptr, 1, sw, sh, crop) && fsr4_calls == 3 && fg.recorded->made == 0);
|
||||
CHECK(dispatches == 15 && copies == 6);
|
||||
CHECK(fg.src_w == sw && fg.src_h == sh && fg.source.x == x && fg.source.y == y && fg.source.w == w && fg.source.h == h);
|
||||
fsr4_result = framegen_rows::OWN;
|
||||
CHECK(framegen_record(nullptr, 1, sw, sh, crop) && fsr4_calls == 3 && fg.recorded->made == 1);
|
||||
CHECK(dispatches == 18 && copies == 6);
|
||||
CHECK(framegen_record(nullptr, 1, sw, sh, crop) && fsr4_calls == 4 && fg.recorded->made == 1);
|
||||
CHECK(dispatches == 20 && copies == 7);
|
||||
shown();
|
||||
fg.have_prev = false; // (nothing before this frame: still handed over, as a frame with nothing to blend from)
|
||||
CHECK(framegen_record(nullptr, 1, sw, sh, crop) && fsr4_calls == 4 && !fsr4_blend && fg.recorded->made == 0);
|
||||
CHECK(dispatches == 20 && copies == 7);
|
||||
CHECK(framegen_record(nullptr, 1, sw, sh, crop) && fsr4_calls == 5 && !fsr4_blend && fg.recorded->made == 0);
|
||||
CHECK(dispatches == 22 && copies == 8);
|
||||
opts.framegen = 2;
|
||||
// ((Triforce) the fine vectors (vk_framegen.cpp fine_vectors), their pipelines made: a 2x frame is the copy, the
|
||||
// quarter- and half-size luma, the coarse vectors and their median, the fine vectors, two picks and one made frame)
|
||||
@@ -147,7 +154,7 @@ void check(uint32_t sw, uint32_t sh, const int* crop, uint32_t x, uint32_t y, ui
|
||||
fg.have_prev = true;
|
||||
fg.half.pipe = fg.fine_flow.pipe = fg.fine_pick.pipe = fg.fine_synth.pipe = 1;
|
||||
CHECK(framegen_record(nullptr, 1, sw, sh, crop) && fg.recorded->made == 1);
|
||||
CHECK(dispatches == 29 && copies == 8);
|
||||
CHECK(dispatches == 31 && copies == 9);
|
||||
fg.half.pipe = fg.fine_flow.pipe = fg.fine_pick.pipe = fg.fine_synth.pipe = VK_NULL_HANDLE;
|
||||
} else {
|
||||
CHECK(dispatches == 0 && copies == 0 && !fg.recorded);
|
||||
|
||||
@@ -59,7 +59,13 @@ struct Info {
|
||||
#include "spv_store.h" // (Triforce: the store a packed stage has in its module's place, gpu/vk; Stage names it)
|
||||
#include "cache_types.inc"
|
||||
|
||||
struct { uintptr_t device = 123; } dev;
|
||||
// ((Triforce) dev.fixes.nan_bits: AMD's older shader compiler, whose modules make_module gives selects of the bits
|
||||
// (spv_nan_select.h). Off here, as on every other card: every module is made of the record's words as they are.
|
||||
// tests/test_spv_nan_select.py has the selects)
|
||||
struct {
|
||||
uintptr_t device = 123;
|
||||
struct { bool nan_bits = false; } fixes;
|
||||
} dev;
|
||||
std::map<VkShaderModule, unsigned> destroyed;
|
||||
unsigned attempts = 0, created = 0, releases = 0, fail_at = 0;
|
||||
int vkCreateShaderModule(uintptr_t device, const VkShaderModuleCreateInfo* info, const void* allocator,
|
||||
@@ -95,6 +101,10 @@ void dropped_note(uint64_t) {}
|
||||
// (local, RenoDX port: vk_renodx.h's, which make_module asks for a fragment module's replacement. None here: every module
|
||||
// is the cache's own, so the counts below are of what the loader made)
|
||||
const std::vector<uint32_t>* renodx_replacement(uint32_t) { return nullptr; }
|
||||
// ((Triforce) the fog's froxels, gpu/vk/spv_fog.h, which make_module asks of each module it makes: none here is the fog's, so
|
||||
// every module is made of the record's words as they are. tests/test_spv_fog.py has the fog)
|
||||
#include "spv_fog.h"
|
||||
#include "spv_nan_select.h"
|
||||
#define PROF_EXACT() // (vk_prof.h's exact-timing scope, since #989: nothing to time here)
|
||||
// (local, texture detail: vk_shader.cpp's note of which bindings a module reads by exact texel. Nothing to note here)
|
||||
void exact_note(VkShaderModule, const std::vector<uint32_t>&) {}
|
||||
|
||||
@@ -167,6 +167,7 @@ static void L(const VkImageSubresourceRange& r) { put(r.aspectMask), put(r.baseM
|
||||
static void L(const VkImageSubresourceLayers& r) { put(r.aspectMask), put(r.mipLevel), put(r.baseArrayLayer), put(r.layerCount); }
|
||||
static void L(const VkOffset3D& o) { put(o.x), put(o.y), put(o.z); }
|
||||
static void L(const VkExtent3D& e) { put(e.width), put(e.height), put(e.depth); }
|
||||
static void L(const VkExtent2D& e) { put(e.width), put(e.height); }
|
||||
static void L(const VkRect2D& r) { put(r.offset.x), put(r.offset.y), put(r.extent.width), put(r.extent.height); }
|
||||
static void L(const VkViewport& v) { put(v.x), put(v.y), put(v.width), put(v.height), put(v.minDepth), put(v.maxDepth); }
|
||||
static void L(const VkClearValue& v) { raw(&v, sizeof v); } // (a union of 16 bytes, no padding)
|
||||
@@ -398,6 +399,8 @@ F(vkCmdSetColorBlendEnableEXT, (VkCommandBuffer cb, uint32_t first, uint32_t n,
|
||||
F(vkCmdSetColorBlendEquationEXT, (VkCommandBuffer cb, uint32_t first, uint32_t n, const VkColorBlendEquationEXT* v), handle(cb), put(first); A(v, n);)
|
||||
F(vkCmdSetColorWriteMaskEXT, (VkCommandBuffer cb, uint32_t first, uint32_t n, const VkColorComponentFlags* v), handle(cb), put(first);
|
||||
each(v, n, [](VkColorComponentFlags x) { put(x); });)
|
||||
F(vkCmdSetFragmentShadingRateKHR, (VkCommandBuffer cb, const VkExtent2D* e, const VkFragmentShadingRateCombinerOpKHR ops[2]), handle(cb);
|
||||
opt(e, [](const VkExtent2D& v) { L(v); }); each(ops, 2, [](VkFragmentShadingRateCombinerOpKHR x) { put(x); });)
|
||||
F(vkCmdWriteBufferMarkerAMD, (VkCommandBuffer cb, VkPipelineStageFlagBits s, VkBuffer b, VkDeviceSize o, uint32_t m),
|
||||
handle(cb), put(s), handle(b), put(o), put(m);)
|
||||
F(vkCmdSetCheckpointNV, (VkCommandBuffer cb, const void* m), handle(cb), handle(m); fx(cb, 2, (uint64_t)(uintptr_t)m);) // (an opaque value: the pointer is the datum)
|
||||
@@ -606,6 +609,8 @@ struct DynState { // (vk_draw.cpp's DynState: the arrays the dynamic state cal
|
||||
VkBool32 en[8];
|
||||
VkColorBlendEquationEXT eq[8];
|
||||
VkColorComponentFlags wm[8];
|
||||
VkExtent2D rate; // ((Triforce) draw_rate's, foliage_shadow.h)
|
||||
VkFragmentShadingRateCombinerOpKHR keep[2];
|
||||
};
|
||||
static void dynamic_state(VkCommandBuffer cmd, int d) {
|
||||
DynState s{};
|
||||
@@ -645,6 +650,9 @@ static void dynamic_state(VkCommandBuffer cmd, int d) {
|
||||
vkCmdSetColorBlendEnableEXT(cmd, 0, 3, s.en);
|
||||
vkCmdSetColorBlendEquationEXT(cmd, 0, 3, s.eq);
|
||||
vkCmdSetColorWriteMaskEXT(cmd, 0, 3, s.wm);
|
||||
s.rate = {1u + (uint32_t)(d & 1), 1u + (uint32_t)(d & 1)};
|
||||
s.keep[0] = s.keep[1] = VK_FRAGMENT_SHADING_RATE_COMBINER_OP_KEEP_KHR;
|
||||
vkCmdSetFragmentShadingRateKHR(cmd, &s.rate, s.keep);
|
||||
if (g_mutate) poison(&s);
|
||||
}
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ no arguments and its own defaults.
|
||||
RUN_ALL_SKIP = {"windows": "needs spirv-val: checked on Linux"} # OS ("linux", "windows") -> why it is skipped
|
||||
|
||||
{name} in an argument is a tool or folder find_tools looks for (cxx, vulkan_headers, spirv_headers, spirv_val, glslang,
|
||||
dotnet); a check whose tool, compiler (the word after --cc or --cxx) or module is missing here is skipped, or fails
|
||||
dotnet, node); a check whose tool, compiler (the word after --cc or --cxx) or module is missing here is skipped, or fails
|
||||
with --strict. A check skipped on both OSes (a GPU, the game) names both. A declaration that is not a plain literal of
|
||||
that shape, names an unknown placeholder or OS, or any other RUN_ALL_ name, stops the run with the file and line; so
|
||||
does one set or changed anywhere but its own top-level line (inside an if or a try, .append(...), +=, a subscript).
|
||||
@@ -82,6 +82,7 @@ def find_tools():
|
||||
"spirv_val": which("spirv-val"),
|
||||
"glslang": which("glslangValidator", "glslang"),
|
||||
"dotnet": which("dotnet"),
|
||||
"node": which("node"),
|
||||
"cxx": which(os.environ.get("CXX", ""), "clang++", "g++", "c++"),
|
||||
}
|
||||
|
||||
|
||||
@@ -79,6 +79,8 @@ bool sampler_of(int id, nvn_samp_par* p) {
|
||||
// a clamped one that stays as the game has it)
|
||||
if (policy == "anisotropy") p->ws = NVN_WRAP_MODE_REPEAT, p->wt = NVN_WRAP_MODE_MIRRORED_REPEAT;
|
||||
if (policy == "lod-clamp") p->lod_bias = 100, p->lod_min = -3, p->lod_max = -1;
|
||||
// ((Triforce, v0.5.2) the anisotropy only where U and V repeat: a clamped one (anisotropy-clamped) reads a screen buffer
|
||||
if (policy == "anisotropy") p->ws = NVN_WRAP_MODE_REPEAT, p->wt = NVN_WRAP_MODE_MIRRORED_REPEAT;
|
||||
return true;
|
||||
}
|
||||
const char* getenv(const char* name) {
|
||||
@@ -86,7 +88,7 @@ const char* getenv(const char* name) {
|
||||
if (!std::strcmp(name, "RX_VK_PUSH_ALL") && descriptor_policy == "descriptor-whole") return "1";
|
||||
if (!std::strcmp(name, "RX_VK_SAMPLER_CACHE") && cache_off) return "0";
|
||||
if (!std::strcmp(name, "RX_VK_SHADOW_PCF") && policy == "compare-pcf-off") return "0";
|
||||
if (!std::strcmp(name, "RX_VK_ANISO") && (policy == "anisotropy" || policy == "anisotropy-clamped")) return "16";
|
||||
if (!std::strcmp(name, "RX_VK_ANISO") && policy.find("anisotropy") == 0) return "16";
|
||||
if (!std::strcmp(name, "RX_VK_FORCE_LINEAR") && policy == "force-linear") return "1";
|
||||
return nullptr;
|
||||
}
|
||||
@@ -171,8 +173,8 @@ void vkCmdBindDescriptorSets(VkCommandBuffer, VkPipelineBindPoint, VkPipelineLay
|
||||
std::array<Pushed, 2>& pushed() { static std::array<Pushed, 2> state; return state; }
|
||||
|
||||
std::string route;
|
||||
VkSampler get(int id = 0, bool compare = false) {
|
||||
return route == "make" ? sampler_make(id, compare) : sampler_for(id, compare);
|
||||
VkSampler get(int id = 0, bool compare = false, bool scene = false) {
|
||||
return route == "make" ? sampler_make(id, compare, scene) : sampler_for(id, compare, scene);
|
||||
}
|
||||
void valid(VkSampler sampler) { assert(sampler && live.count(sampler)); }
|
||||
void retry(const std::string& test) {
|
||||
@@ -246,14 +248,14 @@ void run(const std::string& test) {
|
||||
// A distinct ID forces the parameter acceleration insertion.
|
||||
// Use sampler_make directly to test this cache even when the outer ID table is bypassed.
|
||||
if (!cache_off) {
|
||||
fail_cache = Seen; auto next = sampler_make(1, false); valid(next); assert(allocation_faults == 1);
|
||||
fail_cache = Seen; auto next = sampler_make(1, false, false); valid(next); assert(allocation_faults == 1);
|
||||
assert(live.at(next).ci.mipLodBias == 0.25f && live.at(next).ci.maxLod == 8);
|
||||
} else valid(get(1));
|
||||
assert(destroyed == 0); return;
|
||||
}
|
||||
if (test == "mine-commit") {
|
||||
auto first = sampler_make(0, false); valid(first);
|
||||
fail_cache = Mine; assert(sampler_make(0, false) == first);
|
||||
auto first = sampler_make(0, false, false); valid(first);
|
||||
fail_cache = Mine; assert(sampler_make(0, false, false) == first);
|
||||
assert(allocation_faults == 1 && creates == 1 && destroyed == 0 && live.size() == 1); return;
|
||||
}
|
||||
if (test == "valid-after-failure" || test == "failure-commit") {
|
||||
@@ -268,6 +270,23 @@ void run(const std::string& test) {
|
||||
auto first = get(); valid(first); generation++; registration_lod_max = 3;
|
||||
auto second = get(); valid(second); assert(second != first && creates == 2 && live.at(second).ci.maxLod == 3); return;
|
||||
}
|
||||
// ((Triforce, S8) the upscaler's texture LOD bias: added only for a draw into the jittered scene (scene), on a wrapping,
|
||||
// trilinear sampler; the other passes' sampler of the same id is its own, unbiased, and neither is taken for the other)
|
||||
if (test == "scene-bias" || test == "scene-clamped" || test == "scene-off") {
|
||||
policy = test == "scene-bias" ? "wrap" : "";
|
||||
upscale_lod_bias = test == "scene-off" ? 0.0f : -1.5f;
|
||||
const VkSampler other = get(4), scene = get(4, false, true); // (id 4: the game's own bias 1)
|
||||
valid(other); valid(scene);
|
||||
assert(live.at(other).ci.mipLodBias == 1.0f);
|
||||
if (test == "scene-bias") {
|
||||
assert(scene != other && creates == 2 && live.at(scene).ci.mipLodBias == -0.5f);
|
||||
assert(get(4, false, true) == scene && get(4) == other && creates == 2); // (each kept apart)
|
||||
assert(get(4, true, true) != scene); // (a depth compare: never biased, another sampler)
|
||||
assert(live.at(get(4, true, true)).ci.mipLodBias == 1.0f && live.at(get(4, true)).ci.mipLodBias == 1.0f);
|
||||
} else // (clamped, or no bias in use: the same sampler for both)
|
||||
assert(scene == other && creates == 1 && live.at(scene).ci.mipLodBias == 1.0f);
|
||||
return;
|
||||
}
|
||||
if (test == "shared-thread") {
|
||||
auto first = get(); valid(first); VkSampler other{};
|
||||
std::thread worker([&] { other = get(); }); worker.join();
|
||||
|
||||
@@ -77,6 +77,8 @@ void logf(const char* fmt, ...) {
|
||||
}
|
||||
static int upscaling = 0; // (upscaler_rows.h: what the temporal chain draws with)
|
||||
int temporal_mode() { return upscaling; }
|
||||
static bool before_bloom = false; // (the Upscale before bloom row: the upscaler takes the scene, before the SMAA)
|
||||
bool temporal_before_bloom() { return before_bloom; }
|
||||
bool fsr3_wanted() { return false; }
|
||||
bool fsr3_native() { return false; }
|
||||
static uint64_t frame_no = 10;
|
||||
@@ -154,7 +156,7 @@ static int logic(const char* env) {
|
||||
CHECK(aa_asked() && aa_mode() == ar::FXAA);
|
||||
}
|
||||
upscaling = ur::DLAA, frame_no++;
|
||||
CHECK(aa_mode() == ar::GAME); // (an upscaler's own anti-aliasing goes over the switch too)
|
||||
CHECK(aa_mode() == ar::FXAA); // (the switch over an upscaler too: a lab's A/B of the game's SMAA under it)
|
||||
std::puts("aa passes: RX_VK_AA is the run's choice");
|
||||
return 0;
|
||||
}
|
||||
@@ -206,10 +208,16 @@ static int logic(const char* env) {
|
||||
CHECK(said.size() == 3); // (replaced again: said again)
|
||||
frame_no++;
|
||||
CHECK(aa_leave_out(ar::kEdgesKey));
|
||||
// DLSS comes on: the game's own SMAA whole again, at once; and off again: Off's first frame runs the two passes
|
||||
// DLSS comes on after the bloom: the game's SMAA stays out (Off under it: AMD and NVIDIA want jittered frames no other
|
||||
// anti-aliasing has been over); with Upscale before bloom the game's own whole again, at once; and off again: Off's first
|
||||
// frame runs the two passes
|
||||
aa_composed(true, nullptr);
|
||||
upscaling = ur::DLSS, frame_no++;
|
||||
CHECK(aa_asked() && aa_mode() == ar::OFF && aa_leave_out(ar::kEdgesKey) && aa_leave_out(ar::kWeightsKey));
|
||||
aa_composed(true, nullptr);
|
||||
before_bloom = true, frame_no++;
|
||||
CHECK(aa_asked() && aa_mode() == ar::GAME && !aa_leave_out(ar::kEdgesKey) && !aa_leave_out(ar::kWeightsKey) && aa_state() == ar::QUIET);
|
||||
before_bloom = false;
|
||||
upscaling = ur::GAME, frame_no++;
|
||||
CHECK(aa_mode() == ar::OFF && !aa_leave_out(ar::kEdgesKey));
|
||||
aa_composed(true, nullptr);
|
||||
|
||||
@@ -88,11 +88,17 @@ int main() {
|
||||
CHECK(chosen(row, 4) == GAME && chosen(row, 99) == GAME);
|
||||
}
|
||||
CHECK(chosen(-1, -1) == GAME && chosen(4, -1) == GAME && chosen(1000, -1) == GAME);
|
||||
/* with the Upscaler row: the choice with the game's own upscaler, the game's own SMAA (the frame as before the row) while
|
||||
DLSS, DLAA, FSR 3.1, FSR 4 or a native AA draws; the row then has nothing to choose, nor with RX_VK_AA set */
|
||||
/* with the Upscaler row: the choice with the game's own upscaler; while DLSS, DLAA, FSR 3.1, FSR 4 or a native AA draws
|
||||
from the tone mapped picture none, the game's SMAA left out of the jittered frames they gather (FSR3-06, FSR4-5); before
|
||||
the bloom the game's own SMAA (the upscaler took the scene before it), and RX_VK_AA's choice over them for an A/B; the
|
||||
row then has nothing to choose, nor with RX_VK_AA set */
|
||||
for (int up = 0; up < ur::kUpscalers; up++) {
|
||||
CHECK(upscaler_own(up) == (up != ur::GAME));
|
||||
for (int v = 0; v < kValues; v++) CHECK(effective(v, up) == (up == ur::GAME ? v : GAME));
|
||||
for (int v = 0; v < kValues; v++) {
|
||||
CHECK(effective(v, up) == (up == ur::GAME ? v : OFF));
|
||||
CHECK(effective(v, up, false) == effective(v, up) && effective(v, up, true) == (up == ur::GAME ? v : GAME));
|
||||
CHECK(effective(v, up, false, true) == v && effective(v, up, true, true) == v);
|
||||
}
|
||||
CHECK(fixed(up, false) == (up != ur::GAME) && fixed(up, true));
|
||||
}
|
||||
CHECK(upscaler_own(ur::DLSS) && upscaler_own(ur::DLAA) && upscaler_own(ur::FSR3) && upscaler_own(ur::FSR3_AA) &&
|
||||
@@ -205,9 +211,12 @@ int main() {
|
||||
/* back to the game's own, then Off again: what was replaced before does not count, the passes run first */
|
||||
CHECK(!t.begin(10005, GAME) && !t.last_replaced && t.state == QUIET);
|
||||
CHECK(!t.begin(10006, OFF) && !t.last_replaced && !leave_out(EDGES, OFF, t.last_replaced, false));
|
||||
/* an upscaler with its own anti-aliasing comes on (the choice in effect is the game's own): the same */
|
||||
/* an upscaler with its own anti-aliasing comes on after the bloom: Off goes on in effect under it, the passes left out;
|
||||
before the bloom the choice in effect is the game's own: the same as back to the game's own */
|
||||
t.composed(10006, true);
|
||||
CHECK(!t.begin(10007, effective(OFF, ur::DLSS)) && !t.last_replaced);
|
||||
CHECK(!t.begin(10007, effective(OFF, ur::DLSS)) && t.last_replaced && leave_out(EDGES, OFF, t.last_replaced, false));
|
||||
CHECK(!t.begin(10008, effective(OFF, ur::DLSS, true)) && !t.last_replaced);
|
||||
CHECK(!t.begin(10009, effective(GAME, ur::FSR4)) && !t.last_replaced && !leave_out(EDGES, OFF, t.last_replaced, false));
|
||||
}
|
||||
/* a choice in effect and no composition replaced for a minute (another game version, a long screen without the 3D):
|
||||
said once, and again only after one was replaced or the choice changed */
|
||||
@@ -344,9 +353,10 @@ int main() {
|
||||
state_now = aa_rows::MISSING;
|
||||
CHECK(hn_aa(v, -1) == hn_aa(v, env == aa_rows::GAME ? 3 : 4));
|
||||
}
|
||||
/* the other rows' fixing is theirs: the row's own value does not fix another */
|
||||
/* the other rows' fixing is theirs: the row's own value does not fix another. ((Triforce, options_version 7) DLAA is the
|
||||
Render resolution's Native (100%) step: that row has its steps) */
|
||||
up_now = ur::DLAA, env_now = -1;
|
||||
CHECK(row_fixed(&opts.aa) && row_fixed(&opts.resolution) && !row_fixed(&opts.sharpness));
|
||||
CHECK(row_fixed(&opts.aa) && !row_fixed(&opts.resolution) && !row_fixed(&opts.sharpness));
|
||||
std::puts("aa row: its entry, its saved line, its text with each Upscaler: all checks passed");
|
||||
return 0;
|
||||
}
|
||||
@@ -362,20 +372,21 @@ def main():
|
||||
draw = (VK / "vk_draw.cpp").read_text(encoding="utf-8")
|
||||
aa = (VK / "vk_aa.cpp").read_text(encoding="utf-8")
|
||||
|
||||
# the row: with the scaling rows on the Graphics tab ((Triforce) 11-17: the tab in sections; Upscaling and edges holds the
|
||||
# upscaler, the anti-aliasing, the sharpness and the window's filter, after the 3D's size in Quality)
|
||||
order = ['"Render resolution", &opts.resolution', '"Upscaling and edges", nullptr', '"Upscaler", &opts.dlss',
|
||||
'"Anti-aliasing", &opts.aa', '"Sharpness", &opts.sharpness', '"Window scaling filter", &opts.upscale']
|
||||
# the row: on the Graphics tab, (Triforce, options_version 7) in its own group after the Upscaling group's rows (it shows
|
||||
# only with the game's own upscaler, row_shown), the window's filter gone
|
||||
order = ['"Upscaler", &opts.dlss', '"Render resolution", &opts.resolution', '"Sharpness", &opts.sharpness',
|
||||
'MENU_HEADING(TAB_GRAPHICS, "Anti-aliasing")', '"Anti-aliasing", &opts.aa']
|
||||
at = [menu.find(row) for row in order]
|
||||
check(-1 not in at and at == sorted(at), "vk_menu.cpp: the Anti-aliasing row is not in Upscaling and edges, after the upscaler")
|
||||
# ((Triforce) rows, not every text: the Full overlay's settings say "Anti-aliasing" too, as NX2navi's)
|
||||
check(len(re.findall(r'\{TAB_\w+, "Anti-aliasing",', menu)) == 1, "vk_menu.cpp: more than one Anti-aliasing row")
|
||||
entry = block(menu, menu.rindex("{TAB_GRAPHICS,", 0, at[3])) # (the Anti-aliasing row's entry)
|
||||
check(-1 not in at and at == sorted(at), "vk_menu.cpp: the Anti-aliasing row is not in its group after the Upscaling group")
|
||||
check(menu.count('"Anti-aliasing", &opts.aa') == 1, "vk_menu.cpp: more than one Anti-aliasing row")
|
||||
check("(rows[i].value != &opts.aa || up == ur::GAME)" in definition(menu, "bool row_shown"),
|
||||
"vk_menu.cpp: the Anti-aliasing row shows while DLSS or FSR smooths the edges itself")
|
||||
entry = block(menu, menu.rindex("{TAB_GRAPHICS,", 0, at[4]))
|
||||
check(re.search(r"\bint aa = 0;", header), "vk_menu.h: Anti-aliasing is not the game's own by default")
|
||||
# a press on a row with nothing to choose changes and saves nothing, and a Quality preset does not set the row
|
||||
check(definition(menu, "void set_row").split("{", 1)[1].lstrip().startswith("// (nothing else to choose") and
|
||||
"if (row_fixed(r.value)) return;" in definition(menu, "void set_row"), "set_row no longer leaves a fixed row alone")
|
||||
check("opts.aa" not in definition(menu, "void apply_preset"), "a Quality preset sets the Anti-aliasing row")
|
||||
check("void apply_preset" not in menu, "a Quality preset is back, and could set the Anti-aliasing row")
|
||||
read = menu[menu.index(" for (Row& r : rows) {\n if (!ini_row(r) || strcmp(line, ini_key(r))) continue;"):]
|
||||
read = block(read, 0)
|
||||
check("std::min(std::max(v, r.lo), r.hi)" in read, "menu_init no longer clamps a saved value to its row")
|
||||
@@ -384,7 +395,7 @@ def main():
|
||||
|
||||
# the renderer's side: what is in effect is the row's rule, asked with what upscales as the menu's Upscaler row shows it
|
||||
mode = definition(aa, "int aa_mode")
|
||||
check("ar::chosen(opts.aa, env_choice())" in mode and "ar::effective(choice, upscaler_now())" in mode,
|
||||
check("ar::chosen(opts.aa, env_choice())" in mode and "ar::effective(choice, upscaler_now(), temporal_before_bloom(), env_choice() >= 0)" in mode,
|
||||
"aa_mode does not take the row's choice (RX_VK_AA over it) through aa_rows.h's effective")
|
||||
check("frame_read.load(std::memory_order_acquire) == frame" in mode and "std::lock_guard lk(s.mu);" in mode,
|
||||
"aa_mode no longer takes the choice once a frame")
|
||||
@@ -396,8 +407,12 @@ def main():
|
||||
check('getenv("RX_VK_AA")' in aa and 'getenv("RX_VK_AA_KEEP")' in aa, "vk_aa.cpp no longer reads its two switches")
|
||||
# the game's own chosen and nothing left to free: a dispatch asks a comparison and nothing else
|
||||
check(re.sub(r"\s+", " ", definition(aa, "bool aa_asked")) ==
|
||||
"bool aa_asked() { return ar::chosen(opts.aa, env_choice()) != ar::GAME || engaged.load(std::memory_order_relaxed); }",
|
||||
"aa_asked is no longer the row's choice and whether anything is left to free")
|
||||
"bool aa_asked() { return ar::chosen(opts.aa, env_choice()) != ar::GAME || engaged.load(std::memory_order_relaxed) || upscaler_asks(); }",
|
||||
"aa_asked is no longer the row's choice, whether anything is left to free and whether an upscaler leaves the SMAA out")
|
||||
asks = definition(aa, "bool upscaler_asks")
|
||||
check("ar::effective(ar::GAME, upscaler_now(), temporal_before_bloom(), env_choice() >= 0) != ar::GAME" in asks and
|
||||
"frame.load(std::memory_order_acquire) != now" in asks,
|
||||
"upscaler_asks does not ask aa_rows.h's effective once a frame whether an upscaler leaves the game's SMAA out")
|
||||
leave = definition(aa, "bool aa_leave_out")
|
||||
check(leave.split("{", 1)[1].lstrip().startswith("if (!aa_asked()) return false;") and
|
||||
"ar::leave_out(ar::role(key), mode, last_replaced.load(std::memory_order_acquire), keep_passes())" in leave,
|
||||
@@ -452,7 +467,7 @@ def main():
|
||||
("@HINT@", definition(menu, "const char* hn_aa")),
|
||||
("@FIXED@", definition(menu, "bool row_fixed")),
|
||||
("@KEY@", definition(menu, "const char* ini_key")),
|
||||
("@INI_ROW@", definition(menu, "bool ini_row")),
|
||||
("@INI_ROW@", "bool is_merged(const int*) { return false; } /* ((Triforce, options_version 7) no merged row here */\n" + definition(menu, "bool ini_row")),
|
||||
("@ENTRY@", entry + ","),
|
||||
("@READ@", read)):
|
||||
fixture = fixture.replace(mark, text)
|
||||
|
||||
@@ -19,6 +19,7 @@ WANT = {
|
||||
"licenses/zstd/PROVENANCE.md": "third_party/zstd/PROVENANCE.md",
|
||||
"licenses/libertinus/OFL.txt": "third_party/fonts/libertinus/OFL.txt",
|
||||
"licenses/libertinus/PROVENANCE.md": "third_party/fonts/PROVENANCE.md",
|
||||
"licenses/fidelityfx/LICENSE.md": "third_party/fidelityfx/LICENSE.md", # ((Triforce) 11-20: FSR 4's headers in the image)
|
||||
}
|
||||
|
||||
|
||||
|
||||
276
tests/test_async_rules.py
Normal file
276
tests/test_async_rules.py
Normal file
@@ -0,0 +1,276 @@
|
||||
"""The replay thread's rules (gpu/vk/async_rules.h, RX_VK_ASYNC=1; no game, no GPU).
|
||||
|
||||
With the replay on a thread of its own a signal of the CPU's takes its capture on the game's thread only when a submission handed
|
||||
over before it may still wait for that event; a present forces nothing but what was already stopped at the present before; the
|
||||
submit's capture shares its copies with the copy helpers and has them made before the hand-over; the game's submit keeps its
|
||||
virtual core; the present poll waits for the replay thread asleep. Compiles and runs the header's rules (the notes of the
|
||||
submissions handed over: told and not told, done, the bound; the capture's rule; the present's drain from its switch; the look
|
||||
before the thread sleeps). Each rule of the header taken out in turn (a mutation) must make the header's test fail. Then reads
|
||||
the sources for where the rules are used: the notes made at the hand-over and taken away where a submission is replayed whole, the
|
||||
capture's rule at the signal, the copies done before the hand-over, the host's wait ops told before its submit, the two calls
|
||||
found by name, and the switches' row in the development guide.
|
||||
|
||||
python -I -B tests/test_async_rules.py [--cxx g++]
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
import subprocess
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
RUN_ALL_ARGS = ["--cxx", "{cxx}"]
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
VK = ROOT / "gpu" / "vk"
|
||||
HOST = ROOT / "host"
|
||||
|
||||
|
||||
def block(text, marker):
|
||||
start = text.index(marker)
|
||||
end = text.index("{", start) + 1
|
||||
depth = 1
|
||||
while depth:
|
||||
depth += (text[end] == "{") - (text[end] == "}")
|
||||
end += 1
|
||||
return text[start:end]
|
||||
|
||||
|
||||
def in_order(text, parts, where):
|
||||
at = 0
|
||||
for part in parts:
|
||||
found = text.find(part, at)
|
||||
if found < 0:
|
||||
raise SystemExit("%s: %r is missing, or not after the part before it (update the test with the code)" % (where, part))
|
||||
at = found + len(part)
|
||||
|
||||
|
||||
HEADER_TEST = r'''
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include "async_rules.h"
|
||||
#define CHECK(x) do { if (!(x)) { std::fprintf(stderr, "FAIL:%d %s\n", __LINE__, #x); std::exit(1); } } while (0)
|
||||
using namespace mkwvk::async_rules;
|
||||
int main() {
|
||||
// (the switches that are on unless 0)
|
||||
CHECK(on_unless_zero(nullptr) && on_unless_zero("") && on_unless_zero("1") && on_unless_zero("2") && !on_unless_zero("0"));
|
||||
const uint64_t A = 0x1000, B = 0x2000, C = 0x3000;
|
||||
{ // (told its waits: noted for those events only, until it is replayed whole)
|
||||
Notes n;
|
||||
const uint64_t ev[] = {A, B, A};
|
||||
n.add(7, true, ev, 3);
|
||||
CHECK(n.pending.size() == 1 && n.pending[0].events.size() == 2); // (A once)
|
||||
CHECK(n.waits_for(A) && n.waits_for(B) && !n.waits_for(C));
|
||||
CHECK(capture_at_signal(true, true, n, A) && !capture_at_signal(true, true, n, C));
|
||||
CHECK(!capture_at_signal(false, true, n, A)); // (the thread has nothing: the next submit's capture has it all)
|
||||
CHECK(capture_at_signal(true, false, n, C)); // (the notes off: every signal with the thread behind, as before)
|
||||
CHECK(!capture_at_signal(false, false, n, C));
|
||||
n.done(8); // (another submission's: this one stays)
|
||||
CHECK(n.waits_for(A));
|
||||
n.done(7);
|
||||
CHECK(n.pending.empty() && !n.waits_for(A) && !n.waits_for(B));
|
||||
CHECK(!capture_at_signal(true, true, n, A));
|
||||
}
|
||||
{ // (told that it waits for nothing: not noted)
|
||||
Notes n;
|
||||
n.add(1, true, nullptr, 0);
|
||||
CHECK(n.pending.empty() && !n.waits_for(A));
|
||||
}
|
||||
{ // (not told: it may wait for any event)
|
||||
Notes n;
|
||||
n.add(3, false, nullptr, 0);
|
||||
CHECK(n.pending.size() == 1 && n.waits_for(A) && n.waits_for(C));
|
||||
n.done(3);
|
||||
CHECK(!n.waits_for(A));
|
||||
}
|
||||
{ // (two submissions wait for the same event: the second still does when the first is done)
|
||||
Notes n;
|
||||
n.add(1, true, &A, 1);
|
||||
n.add(2, true, &A, 1);
|
||||
n.add(3, true, &B, 1);
|
||||
n.done(1);
|
||||
CHECK(n.waits_for(A) && n.waits_for(B));
|
||||
n.done(2);
|
||||
CHECK(!n.waits_for(A) && n.waits_for(B));
|
||||
n.done(3);
|
||||
CHECK(n.pending.empty());
|
||||
}
|
||||
{ // (the bound: past it every signal takes its capture, until none is pending)
|
||||
Notes n;
|
||||
for (uint64_t v = 1; v <= kMaxNotes; v++) n.add(v, true, &A, 1);
|
||||
CHECK(n.pending.size() == kMaxNotes && !n.over && !n.waits_for(C));
|
||||
n.add(kMaxNotes + 1, true, &B, 1); // (not noted: its event must not be missed all the same)
|
||||
CHECK(n.pending.size() == kMaxNotes && n.over);
|
||||
CHECK(n.waits_for(B) && n.waits_for(C));
|
||||
for (uint64_t v = 1; v < kMaxNotes; v++) n.done(v);
|
||||
CHECK(n.over && n.waits_for(C)); // (one is still pending)
|
||||
n.done(kMaxNotes);
|
||||
CHECK(n.over && n.pending.empty() && n.waits_for(B)); // (the one past the bound is not done: its event still counts)
|
||||
n.done(kMaxNotes + 1);
|
||||
CHECK(!n.over && n.pending.empty() && !n.waits_for(B));
|
||||
}
|
||||
// (the present's drain: the stale way unless the switch says otherwise)
|
||||
CHECK(present_drain(nullptr) == PresentDrain::Stale && present_drain("") == PresentDrain::Stale);
|
||||
CHECK(present_drain("2") == PresentDrain::Stale && present_drain("1") == PresentDrain::Force);
|
||||
CHECK(present_drain("0") == PresentDrain::Keep);
|
||||
// (the look before the thread sleeps)
|
||||
CHECK(spin_ns(nullptr) == 100000 && spin_ns("") == 100000 && spin_ns("0") == 0 && spin_ns("50") == 50000);
|
||||
CHECK(spin_ns("5000") == 1000000 && spin_ns("-3") == 0);
|
||||
std::puts("PASS header: the notes of the submissions handed over, the capture at a signal, the present's drain, the look");
|
||||
return 0;
|
||||
}
|
||||
'''
|
||||
|
||||
# (what, the header's text, its replacement): each must make the header's test fail
|
||||
MUTATIONS = [
|
||||
("a submission told to wait for nothing is left out", " if (told && n <= 0) return;\n", ""),
|
||||
("a submission not told may wait for any event", " if (!told) note.events.push_back(kAnyEvent);\n else\n",
|
||||
" if (told)\n"),
|
||||
("an event is noted once", "if (std::find(note.events.begin(), note.events.end(), events[i]) == note.events.end()) ", ""),
|
||||
("the bound raises its flag", " over = true;\n unnoted.push_back(value);", " unnoted.push_back(value);"),
|
||||
("a submission past the bound is remembered", " unnoted.push_back(value);\n", ""),
|
||||
("a submission replayed whole leaves the notes", " pending.erase(it);\n", ""),
|
||||
("only the submission of that value leaves", " if (it->value == value) {", " if (it->value <= value) {"),
|
||||
("the flag falls when every one past the bound is done", " if (unnoted.empty()) over = false;\n", ""),
|
||||
("the flag stays while one past the bound is not done", " if (unnoted.empty()) over = false;", " if (pending.empty()) over = false;"),
|
||||
("past the bound every event counts", " if (over) return true;\n", ""),
|
||||
("any event stands for every event", "if (e == event || e == kAnyEvent) return true;", "if (e == event) return true;"),
|
||||
("no capture when the thread has nothing", " if (!behind) return false;\n", ""),
|
||||
("the notes decide when they are on", " return !notes_on || notes.waits_for(event);", " return true;"),
|
||||
("the stale way unless set", " if (!env || !*env) return PresentDrain::Stale;", " if (!env || !*env) return PresentDrain::Force;"),
|
||||
("0 keeps, 1 forces", " return v == 0 ? PresentDrain::Keep : v == 1 ? PresentDrain::Force : PresentDrain::Stale;",
|
||||
" return v == 0 ? PresentDrain::Keep : PresentDrain::Stale;"),
|
||||
("the look's bound", "std::clamp(std::atoi(env), 0, 1000)", "std::atoi(env)"),
|
||||
]
|
||||
|
||||
|
||||
def check_source(replay, native, backend, thread, dev):
|
||||
if '#include "async_rules.h"' not in replay:
|
||||
raise SystemExit("vk_replay.cpp does not include async_rules.h")
|
||||
# (the notes: made at the hand-over, under the queue's lock, with the value the hand-over gave)
|
||||
enq = block(replay, "void enqueue(Job&& j) {")
|
||||
in_order(enq, ["std::unique_lock lk(q_mu);", "j.value = ++q_values;", "if (j.kind == JOB_SUBMIT && wait_notes_on()) {",
|
||||
"wait_notes.add(j.value, j.waits_told, j.waits.data(), (int)j.waits.size());", "q_jobs.push_back(std::move(j));",
|
||||
"q_count.fetch_add(1"], "vk_replay.cpp enqueue")
|
||||
# (taken away only where a submission is replayed whole: run_submit returned true)
|
||||
job = block(replay, "void submit_job(std::vector<uint64_t>& handles, uint64_t value, uint64_t queue) {")
|
||||
if "if (run_submit(handles.data(), (int)handles.size(), value, queue, true, 0, nullptr, may_stop)) async_wait_done(value);" not in job:
|
||||
raise SystemExit("vk_replay.cpp submit_job: a submission replayed whole does not leave the notes, or one that stopped does")
|
||||
res = block(replay, "void resume_queue(uint64_t queue, bool forced) {")
|
||||
in_order(res, ["const uint64_t resumed = q.value;",
|
||||
"if (!run_submit(handles.data(), (int)handles.size(), resumed, queue, false, q.cb, from, true)) return;",
|
||||
"async_wait_done(resumed);",
|
||||
"if (!run_submit(s.handles.data(), (int)s.handles.size(), s.value, queue, false, 0, nullptr, true)) return;",
|
||||
"async_wait_done(s.value);"], "vk_replay.cpp resume_queue")
|
||||
if replay.count("async_wait_done(") != 5: # (its declaration, its definition, and the three places above)
|
||||
raise SystemExit("vk_replay.cpp: async_wait_done is called in a place this test does not know")
|
||||
done = block(replay, "void async_wait_done(uint64_t value) {")
|
||||
in_order(done, ["if (!wait_notes_n.load(", "std::lock_guard lk(q_mu);", "wait_notes.done(value);", "wait_notes_n.store("],
|
||||
"vk_replay.cpp async_wait_done")
|
||||
# (the capture at a signal: the rule's, on the game's thread, and in order with the jobs)
|
||||
sig = block(replay, "void event_signal_queued(uint64_t gpu, uint32_t value) {")
|
||||
in_order(sig, ["if (capture && async_unforced()) {", "std::lock_guard order(submit_order_mu);", "const bool behind = replay_behind();",
|
||||
"if (behind && wait_notes_on()) {", "std::lock_guard nk(q_mu);",
|
||||
"take = async_rules::capture_at_signal(true, true, wait_notes, gpu);", "if (take) {",
|
||||
"j.ev_capture = memory_capture_submit();", "enqueue(std::move(j));", "return;"],
|
||||
"vk_replay.cpp event_signal_queued")
|
||||
# ((Triforce, 11-20) the look at the notes under the hand-overs' lock: a submission between its capture and its enqueue is
|
||||
# seen, and the signal's job is queued in order with it; one lock_guard of it, taken before the look)
|
||||
if sig.count("(submit_order_mu)") != 1 or sig.index("std::lock_guard order(submit_order_mu);") > sig.index("const bool behind = replay_behind();"):
|
||||
raise SystemExit("vk_replay.cpp event_signal_queued: the look at the notes is not under submit_order_mu")
|
||||
# (the submit's capture: its copies shared, and all made before the hand-over)
|
||||
sub = block(replay, "void submit_q(const uint64_t* handles, int n, uint64_t queue) {")
|
||||
own = sub[sub.index("std::lock_guard lk(submit_order_mu);"):]
|
||||
in_order(own, ['async_rules::on_unless_zero(getenv("RX_VK_ASYNC_CAPTURE_BEHIND"))', "memory_capture_submit(true);",
|
||||
"memory_capture_copies_done();", "} else {", "memory_capture_submit();", "if (tl_submit_waits_told) {",
|
||||
"j.waits_told = true;", "tl_submit_waits_told = false;", "enqueue(std::move(j));"], "vk_replay.cpp submit_q")
|
||||
# (the present: the rule from its switch; the thread's look)
|
||||
run = block(replay, "void run_job(Job& j) {")
|
||||
in_order(run, ['async_rules::present_drain(getenv("RX_VK_PRESENT_DRAIN"))', "way == async_rules::PresentDrain::Keep",
|
||||
"way == async_rules::PresentDrain::Stale", "drain_stale();", "drain(0);", "do_present("], "vk_replay.cpp run_job")
|
||||
main_ = block(replay, "void replay_thread_main() {")
|
||||
in_order(main_, ['async_rules::spin_ns(getenv("RX_VK_ASYNC_SPIN_US"))', "while (!q_count.load(", "std::unique_lock lk(q_mu);",
|
||||
"q_jobs.pop_front(), have = true, q_count.fetch_sub(1"], "vk_replay.cpp replay_thread_main")
|
||||
if replay.count("q_jobs.pop_front()") != replay.count("q_count.fetch_sub(1"):
|
||||
raise SystemExit("vk_replay.cpp: a job is taken from the queue without its count")
|
||||
# (the two diagnostics for the black frames after a tour stay behind their switches)
|
||||
for name in ('getenv("RX_VK_LOG_READBACK_ZERO")', 'getenv("RX_VK_REGION_TRAP")'):
|
||||
if replay.count(name) != 1:
|
||||
raise SystemExit("vk_replay.cpp: the diagnostic %s is not read in one place" % name)
|
||||
idle = block(replay, "bool replay_idle_wait(uint64_t timeout_ns) {")
|
||||
in_order(idle, ["if (!async_on()) return true;", "std::unique_lock lk(q_mu);", "q_done.wait_for(lk,",
|
||||
"return q_jobs.empty() && !q_busy;"], "vk_replay.cpp replay_idle_wait")
|
||||
for name in ("void mkwvk_submit_waits(const uint64_t* events, int n) {", "int mkwvk_replay_idle_wait(uint64_t timeout_ns) {"):
|
||||
if name not in replay:
|
||||
raise SystemExit("vk_replay.cpp: %s is not exported" % name.split("(")[0])
|
||||
# (the host: the wait ops of a submit's recordings, told before its hand-over; the core kept; the poll's wait)
|
||||
res_d = block(native, "static void resolve_deferred(uint8_t *p, uint64_t *waits, int *nwaits) {")
|
||||
in_order(res_d, ["if (h.op == NOP_END) return;", "if (h.op == NOP_WAIT_EVENT && waits && *nwaits >= 0) {",
|
||||
"if (*nwaits == SUBMIT_WAITS_MAX) *nwaits = -1;", "waits[(*nwaits)++] = ((const nvn_p_wait_event *)(p + 8))->gpu;",
|
||||
"p += h.size;"], "nvn_native.c resolve_deferred")
|
||||
q = block(native, "NV(nvnQueueSubmitCommands) {")
|
||||
in_order(q, ["const int async = rx_async_replay();", "resolve_deferred((uint8_t *)(uintptr_t)h[i], async ? waits : NULL, &nwaits);",
|
||||
'getenv("HOS_ASYNC_KEEP_CORE")', "const int away = keep_core ? 0 : hos_vcore_away();",
|
||||
"if (async && nwaits >= 0) rx_nvn_submit_waits(waits, nwaits);", "rx_nvn_submit_q(h, n, (uint64_t)(uintptr_t)q);",
|
||||
"if (away) hos_vcore_back();"], "nvn_native.c nvnQueueSubmitCommands")
|
||||
for name in ('GetProcAddress(vk_module, "mkwvk_submit_waits")', 'GetProcAddress(vk_module, "mkwvk_replay_idle_wait")',
|
||||
"int rx_async_replay(void) {", "return fn ? fn(timeout_ns) : 1;"):
|
||||
if name not in backend:
|
||||
raise SystemExit("rx_backend.c: %r is missing" % name)
|
||||
poll = block(thread, "static int present_poll(Ctx *c, int64_t ns) {")
|
||||
in_order(poll, ["async = rx_async_replay();", "on = e ? atoi(e) != 0 : async;", "const int away = hos_vcore_away();",
|
||||
"if (async && v != 1) {", "rx_nvn_replay_idle_wait((uint64_t)ns);", "hos_nvn_event_value(ev, &v);",
|
||||
"while (v != 1 && hos_now_ns() < end) {"], "hos_thread.c present_poll")
|
||||
for name in ("RX_VK_ASYNC_EVENT_NOTES", "RX_VK_ASYNC_CAPTURE_BEHIND", "HOS_ASYNC_KEEP_CORE", "HOS_PRESENT_POLL", "RX_VK_PRESENT_DRAIN",
|
||||
"RX_VK_ASYNC_SPIN_US", "RX_VK_LOG_READBACK_ZERO", "RX_VK_REGION_TRAP"):
|
||||
if name not in dev:
|
||||
raise SystemExit("docs/development.md: %s is not in the switches table" % name)
|
||||
|
||||
|
||||
def build(cxx, d, name, src, include):
|
||||
cpp, exe = d / (name + ".cpp"), d / (name + ".exe")
|
||||
cpp.write_text(src, encoding="utf-8")
|
||||
r = subprocess.run([cxx, "-std=c++20", "-O1", "-Wall", "-Wextra", "-Werror", "-Wno-unused-function", "-I" + str(include), str(cpp),
|
||||
"-o", str(exe)], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
|
||||
if r.returncode:
|
||||
return None, r.stdout
|
||||
return exe, ""
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--cxx", default=os.environ.get("CXX", "g++"))
|
||||
a = ap.parse_args()
|
||||
check_source((VK / "vk_replay.cpp").read_text(encoding="utf-8"), (HOST / "nvn_native.c").read_text(encoding="utf-8"),
|
||||
(HOST / "rx_backend.c").read_text(encoding="utf-8"), (HOST / "hos_thread.c").read_text(encoding="utf-8"),
|
||||
(ROOT / "docs" / "development.md").read_text(encoding="utf-8"))
|
||||
print("PASS sources: the notes at the hand-over and where a submission is replayed whole, the capture at a signal, the copies "
|
||||
"before the hand-over, the host's waits and calls, the switches' row")
|
||||
header = (VK / "async_rules.h").read_text(encoding="utf-8")
|
||||
with tempfile.TemporaryDirectory(prefix="async-rules-") as tmp:
|
||||
d = Path(tmp)
|
||||
exe, out = build(a.cxx, d, "header", HEADER_TEST, VK)
|
||||
if not exe:
|
||||
raise SystemExit("header: the build failed:\n" + out)
|
||||
r = subprocess.run([str(exe)], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, timeout=60)
|
||||
if r.returncode:
|
||||
raise SystemExit("the header test failed:\n" + r.stdout)
|
||||
print(r.stdout.strip())
|
||||
for i, (what, old, new) in enumerate(MUTATIONS):
|
||||
if header.count(old) != 1:
|
||||
raise SystemExit("mutation %r: its text is not once in async_rules.h (update the test with the header)" % what)
|
||||
inc = d / ("mutant%d" % i)
|
||||
inc.mkdir()
|
||||
(inc / "async_rules.h").write_text(header.replace(old, new), encoding="utf-8")
|
||||
exe, out = build(a.cxx, d, "mutant%d" % i, HEADER_TEST, inc)
|
||||
if exe: # (a mutant that does not build has failed too: an unused name under -Werror)
|
||||
r = subprocess.run([str(exe)], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, timeout=60)
|
||||
if r.returncode == 0:
|
||||
raise SystemExit("mutation %r: the header test still passed without it" % what)
|
||||
out = r.stdout
|
||||
last = out.strip().splitlines()[-1] if out.strip() else "it did not pass"
|
||||
print("PASS mutation: without %s the test fails (%s)" % (what, last[:120]))
|
||||
print("ALL PASS")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
589
tests/test_cache_set.py
Normal file
589
tests/test_cache_set.py
Normal file
@@ -0,0 +1,589 @@
|
||||
"""One earlier set of the shader caches is kept for a change of a setting, and put back when the setting goes back
|
||||
(gpu/vk/cache_set.h the rule, gpu/vk/cache_set_files.h the files, gpu/vk/vk_cache_set.cpp this start's; no game/GPU).
|
||||
|
||||
The header is compiled and run as it is: the decision for each start (the set there this stamp's: nothing; a stamp that
|
||||
changed by a setting, the build the same: kept when the disk has twice the set and 10 GB free, counting what deleting the
|
||||
old kept set frees; the kept set this stamp's and whole: put back, the set there kept in its place when it is this build's;
|
||||
a kept set with a piece missing: refused and deleted; another build: the kept set deleted, nothing kept; off: nothing
|
||||
renamed, a kept set deleted for another build or RX_VK_CACHE_SET=0), the kept pieces' names, the record's text read back,
|
||||
the program cache's head. Then cache_set_files.h runs on folders of the test's own: kept, put back with and without the
|
||||
set there kept, the player's pipeline list gone through when it changed since, a refused set, a rename that fails rolled
|
||||
back, a swap cut short and an unreadable record swept, the off switches. Then the source: the set is decided once, right
|
||||
after the device is made and before anything opens a cache; its pieces are the files the caches have by the stamp; a set
|
||||
put back has the state lists gone through before the title; the build part is outside the translation stamp, and the
|
||||
translation stamp's text is what it was; the Robust buffers row says what changing it costs, by the card.
|
||||
python -I -B tests/test_cache_set.py --cxx clang++
|
||||
"""
|
||||
import argparse
|
||||
import ast
|
||||
import re
|
||||
import subprocess
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
RUN_ALL_ARGS = ["--cxx", "{cxx}"]
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
VK = ROOT / "gpu" / "vk"
|
||||
|
||||
FIXTURE = r"""
|
||||
#include <cstdio>
|
||||
#include "cache_set.h"
|
||||
#define CHECK(x) do { if (!(x)) { std::printf("line %d: %s\n", __LINE__, #x); return 1; } } while (0)
|
||||
using namespace cache_set;
|
||||
static const uint64_t GB = 1ull << 30;
|
||||
static const uint64_t A = 0xA0A0A0A0A0A0A0A0ull, B = 0xB0B0B0B0B0B0B0B0ull, C = 0xC0C0C0C0C0C0C0C0ull;
|
||||
static const uint64_t X = 0x1111ull, Y = 0x2222ull; // (two builds)
|
||||
// (a start of stamp B, build X, over the set of stamp A that build X made: the Robust buffers row switched)
|
||||
static Facts toggled(uint64_t free_gb, uint64_t set_gb) {
|
||||
Facts f;
|
||||
f.on = true, f.stamp = B, f.build = X;
|
||||
f.live = true, f.live_stamp = A, f.live_named = true, f.live_build = X, f.live_bytes = set_gb * GB;
|
||||
f.space_known = true, f.free_bytes = free_gb * GB;
|
||||
return f;
|
||||
}
|
||||
int main() {
|
||||
// (the set there is this stamp's: nothing renamed, whatever there is room for)
|
||||
{
|
||||
Facts f = toggled(500, 6);
|
||||
f.stamp = A;
|
||||
Plan p = decide(f);
|
||||
CHECK(p.what == Do::Same && !p.forget);
|
||||
f.kept = true, f.kept_stamp = B, f.kept_build = X, f.kept_whole = true; // (kept for the other setting: stays)
|
||||
p = decide(f);
|
||||
CHECK(p.what == Do::Same && !p.forget);
|
||||
f.kept_build = Y; // (another build's kept set: deleted)
|
||||
p = decide(f);
|
||||
CHECK(p.what == Do::Same && p.forget);
|
||||
f.kept_build = X, f.kept_stamp = A, f.kept_whole = false; // (a kept set naming the set there: a swap cut short)
|
||||
p = decide(f);
|
||||
CHECK(p.what == Do::Same && p.forget);
|
||||
}
|
||||
// (a setting changed: kept with twice the set and 10 GB free, 22 GB for a 6 GB set; a byte less is not room)
|
||||
CHECK(decide(toggled(50, 6)).what == Do::Keep && !decide(toggled(50, 6)).forget);
|
||||
CHECK(decide(toggled(22, 6)).what == Do::Keep);
|
||||
{
|
||||
Facts f = toggled(22, 6);
|
||||
f.free_bytes -= 1;
|
||||
CHECK(decide(f).what == Do::Drop && !decide(f).forget);
|
||||
// (an old kept set of a third stamp: deleting it frees its bytes, and the one there takes its place)
|
||||
f.kept = true, f.kept_stamp = C, f.kept_build = X, f.kept_bytes = 6 * GB, f.kept_whole = true;
|
||||
f.free_bytes = 16 * GB;
|
||||
Plan p = decide(f);
|
||||
CHECK(p.what == Do::Keep && p.forget);
|
||||
f.free_bytes = 16 * GB - 1; // (no room even so: the old kept set stays, the set there is dropped as before)
|
||||
p = decide(f);
|
||||
CHECK(p.what == Do::Drop && !p.forget);
|
||||
}
|
||||
CHECK(decide(toggled(0, 0)).what == Do::Drop); // (10 GB are wanted beyond any set)
|
||||
CHECK(decide(toggled(10, 0)).what == Do::Keep);
|
||||
{
|
||||
Facts f = toggled(500, 6);
|
||||
f.space_known = false; // (the disk's free space not known: not kept)
|
||||
CHECK(decide(f).what == Do::Drop);
|
||||
f = toggled(500, 6);
|
||||
f.live_named = false; // (no record of what the set there was made for: a build before the rule. Not kept)
|
||||
CHECK(decide(f).what == Do::Drop);
|
||||
f = toggled(500, 6);
|
||||
f.live = false; // (no program cache there: nothing to keep)
|
||||
CHECK(decide(f).what == Do::Drop);
|
||||
}
|
||||
// (the translator changed: the set there is no use again, and the kept one neither)
|
||||
{
|
||||
Facts f = toggled(500, 6);
|
||||
f.build = Y;
|
||||
f.kept = true, f.kept_stamp = B, f.kept_build = X, f.kept_bytes = 6 * GB, f.kept_whole = true;
|
||||
Plan p = decide(f);
|
||||
CHECK(p.what == Do::Drop && p.forget);
|
||||
}
|
||||
// (switched back: the kept set is this stamp's and whole: put back, the set there kept in its place)
|
||||
{
|
||||
Facts f = toggled(0, 6); // (no free space wanted for that: renames)
|
||||
f.kept = true, f.kept_stamp = B, f.kept_build = X, f.kept_bytes = 6 * GB, f.kept_whole = true;
|
||||
Plan p = decide(f);
|
||||
CHECK(p.what == Do::Restore && p.keep_live && !p.forget);
|
||||
f.live_named = false; // (the set there of a build not known: put back over it, and it is not kept)
|
||||
p = decide(f);
|
||||
CHECK(p.what == Do::Restore && !p.keep_live && !p.forget);
|
||||
f.live = false; // (no set there at all)
|
||||
p = decide(f);
|
||||
CHECK(p.what == Do::Restore && !p.keep_live);
|
||||
// (a piece missing or not its size: refused and deleted; the set there is then kept if there is room)
|
||||
f = toggled(500, 6);
|
||||
f.kept = true, f.kept_stamp = B, f.kept_build = X, f.kept_bytes = 6 * GB, f.kept_whole = false;
|
||||
p = decide(f);
|
||||
CHECK(p.what == Do::Keep && p.forget);
|
||||
f.free_bytes = 0;
|
||||
p = decide(f);
|
||||
CHECK(p.what == Do::Drop && p.forget);
|
||||
// (the kept set of this stamp, but of another build: never put back)
|
||||
f = toggled(500, 6);
|
||||
f.build = Y, f.kept = true, f.kept_stamp = B, f.kept_build = X, f.kept_whole = true;
|
||||
p = decide(f);
|
||||
CHECK(p.what == Do::Drop && p.forget);
|
||||
}
|
||||
// (off: nothing renamed; a kept set of this build stays, but for RX_VK_CACHE_SET=0's off; another build's is deleted)
|
||||
{
|
||||
Facts f = toggled(500, 6);
|
||||
f.on = false;
|
||||
f.kept = true, f.kept_stamp = B, f.kept_build = X, f.kept_whole = true;
|
||||
Plan p = decide(f);
|
||||
CHECK(p.what == Do::Drop && !p.forget);
|
||||
f.stamp = A;
|
||||
CHECK(decide(f).what == Do::Same && !decide(f).forget);
|
||||
f.off_forgets = true;
|
||||
CHECK(decide(f).what == Do::Same && decide(f).forget);
|
||||
f.off_forgets = false, f.kept_build = Y; // (a translator update while it is off: of no use to any build again)
|
||||
CHECK(decide(f).what == Do::Same && decide(f).forget);
|
||||
f.stamp = B;
|
||||
CHECK(decide(f).what == Do::Drop && decide(f).forget);
|
||||
}
|
||||
CHECK(room(22 * GB, 0, 6 * GB) && !room(22 * GB - 1, 0, 6 * GB) && room(16 * GB, 6 * GB, 6 * GB));
|
||||
CHECK(!room(~0ull, ~0ull, ~0ull / 2) && room(~0ull, ~0ull, 0)); // (no sum wraps)
|
||||
CHECK(on(nullptr) && on("1") && on("") && on("00") && !on("0"));
|
||||
|
||||
CHECK(kept_name("mkw_vk_pipelines.bin.for", 0x0123456789abcdefull) == "mkw_vk_pipelines.0123456789abcdef.bin.for");
|
||||
CHECK(kept_name("triforce_prepared.bin.warming.skip", 1) == "triforce_prepared.0000000000000001.bin.warming.skip");
|
||||
CHECK(kept_name("triforce_programs.idx", B) == "triforce_programs.b0b0b0b0b0b0b0b0.idx");
|
||||
for (size_t i = 0; i < kPieceCount; i++)
|
||||
for (size_t j = 0; j < kPieceCount; j++) CHECK(i == j || kept_name(kPieces[i], A) != kept_name(kPieces[j], A));
|
||||
CHECK(kept_name(kPieces[0], A) != kept_name(kPieces[0], B));
|
||||
// (a kept piece's name read back, and nothing else taken for one)
|
||||
for (size_t i = 0; i < kPieceCount; i++) {
|
||||
uint64_t st = 0;
|
||||
CHECK(kept_piece_of(kept_name(kPieces[i], A), &st) && st == A);
|
||||
CHECK(!kept_piece_of(kPieces[i], &st));
|
||||
}
|
||||
{
|
||||
uint64_t st = 0;
|
||||
CHECK(kept_piece_of("triforce_programs.0123456789abcdef.idx", &st) && st == 0x0123456789abcdefull);
|
||||
CHECK(!kept_piece_of("triforce_programs.0123456789ABCDEF.idx", &st)); // (kept_name writes lower case)
|
||||
CHECK(!kept_piece_of("triforce_programs.0123456789abcde.idx", &st));
|
||||
CHECK(!kept_piece_of("triforce_programs.0123456789abcdef.idx.part", &st));
|
||||
CHECK(!kept_piece_of("triforce_shaders.0123456789abcdef.bin", &st));
|
||||
CHECK(!kept_piece_of(kKept, &st) && !kept_piece_of(kRecord, &st) && !kept_piece_of(kStates, &st));
|
||||
}
|
||||
|
||||
uint8_t head[16] = {0x48, 0x53, 0x50, 0x31, 9, 9, 9, 9};
|
||||
std::memcpy(head + 8, &B, 8);
|
||||
uint64_t s = 0;
|
||||
CHECK(programs_head(head, 16, &s) && s == B);
|
||||
CHECK(!programs_head(head, 15, &s));
|
||||
head[0] ^= 1;
|
||||
CHECK(!programs_head(head, 16, &s));
|
||||
|
||||
Record r;
|
||||
r.stamp = A, r.build = X;
|
||||
r.parts = {{"depth", 1}, {"robust", 0}, {"env", 77}};
|
||||
r.env = "RX_VK_MESH_AHEAD,EDEN_X";
|
||||
r.pieces = {{"triforce_programs.bin", 5ull * GB}, {"mkw_vk_pipelines.bin.for", 16}};
|
||||
r.states = C;
|
||||
Record back;
|
||||
CHECK(parse(format(r), &back));
|
||||
CHECK(back.stamp == A && back.build == X && back.parts == r.parts && back.env == r.env && back.pieces == r.pieces);
|
||||
CHECK(back.states == C);
|
||||
CHECK(back.bytes() == 5ull * GB + 16);
|
||||
std::string crlf;
|
||||
for (char ch : format(r)) {
|
||||
if (ch == '\n') crlf += '\r';
|
||||
crlf += ch;
|
||||
}
|
||||
CHECK(parse(crlf, &back) && back.pieces == r.pieces);
|
||||
Record none;
|
||||
CHECK(parse(format(none), &back) && back.env.empty() && back.pieces.empty() && !back.states);
|
||||
CHECK(!parse("", &back) && !parse("triforce-cache-set 2\nstamp 1\nbuild 2\n", &back));
|
||||
CHECK(!parse("triforce-cache-set 1\nstamp 1\n", &back)); // (no build part: not a record)
|
||||
CHECK(!parse("triforce-cache-set 1\nstamp 1\nbuild 2\npiece ..\\triforce_options.ini 3\n", &back)); // (not a piece)
|
||||
|
||||
Record now = r;
|
||||
now.stamp = B;
|
||||
now.parts[1].second = 1;
|
||||
CHECK(changed(r, now) == std::vector<std::string>{"robust"});
|
||||
now.build = Y;
|
||||
now.parts.push_back({"gpu", 3});
|
||||
CHECK((changed(r, now) == std::vector<std::string>{"build", "robust", "gpu"}));
|
||||
CHECK(changed(r, r).empty());
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
FILES = r"""
|
||||
#include <cstdarg>
|
||||
#include <cstdio>
|
||||
#include <filesystem>
|
||||
#include <string>
|
||||
#include "cache_set_files.h"
|
||||
#define CHECK(x) do { if (!(x)) { std::printf("%s line %d: %s\n", where, __LINE__, #x); return 1; } } while (0)
|
||||
using namespace cache_set;
|
||||
namespace fs = std::filesystem;
|
||||
static const uint64_t GB = 1ull << 30;
|
||||
static const uint64_t A = 0xA0A0A0A0A0A0A0A0ull, B = 0xB0B0B0B0B0B0B0B0ull, C = 0xC0C0C0C0C0C0C0C0ull;
|
||||
static const uint64_t X = 0x1111ull, Y = 0x2222ull;
|
||||
static const char* where = "";
|
||||
static void log_(const char* fmt, ...) {
|
||||
va_list a;
|
||||
va_start(a, fmt);
|
||||
std::vfprintf(stderr, fmt, a);
|
||||
va_end(a);
|
||||
std::fputc('\n', stderr);
|
||||
}
|
||||
static std::string base;
|
||||
static std::string folder(const char* name) {
|
||||
where = name;
|
||||
const std::string d = base + "/" + name + "/";
|
||||
fs::create_directories(d);
|
||||
return d;
|
||||
}
|
||||
// (n bytes; a program cache's head naming stamp when it is not 0)
|
||||
static void put(const std::string& path, size_t n, uint64_t stamp = 0) {
|
||||
std::string b(n, 'x');
|
||||
if (stamp && n >= 16) {
|
||||
const uint32_t magic = kProgramsMagic, build = 7;
|
||||
std::memcpy(&b[0], &magic, 4), std::memcpy(&b[4], &build, 4), std::memcpy(&b[8], &stamp, 8);
|
||||
}
|
||||
FILE* f = std::fopen(path.c_str(), "wb");
|
||||
std::fwrite(b.data(), 1, b.size(), f);
|
||||
std::fclose(f);
|
||||
}
|
||||
static uint64_t size(const std::string& path) {
|
||||
std::error_code ec;
|
||||
if (!fs::is_regular_file(path, ec)) return ~0ull;
|
||||
const auto n = fs::file_size(path, ec);
|
||||
return ec ? ~0ull : (uint64_t)n;
|
||||
}
|
||||
static bool has(const std::string& path) { return fs::exists(path); }
|
||||
static uint64_t head(const std::string& path) {
|
||||
uint64_t s = 0;
|
||||
return head_of(path, &s) ? s : 0;
|
||||
}
|
||||
static Record rec(uint64_t stamp, uint64_t build) {
|
||||
Record r;
|
||||
r.stamp = stamp, r.build = build;
|
||||
r.parts = {{"robust", stamp == A ? 0u : 1u}};
|
||||
return r;
|
||||
}
|
||||
static void record(const std::string& d, const Record& r) { file_writers::write_whole(d + kRecord, format(r)); }
|
||||
static void kept_record(const std::string& d, const Record& r) { file_writers::write_whole(d + kKept, format(r)); }
|
||||
// (the files in the folder, but for the record of what the set there is for)
|
||||
static size_t count(const std::string& d) {
|
||||
size_t n = 0;
|
||||
for (const auto& e : fs::directory_iterator(d)) n += e.path().filename() != kRecord;
|
||||
return n;
|
||||
}
|
||||
static Switches room_for(bool on = true) {
|
||||
Switches s;
|
||||
s.on = on, s.space_given = true, s.free_bytes = 20 * GB;
|
||||
return s;
|
||||
}
|
||||
static const std::string P = "triforce_programs.bin", M = "mkw_vk_pipelines.bin", R = "triforce_prepared.bin";
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
if (argc < 2) return 2;
|
||||
base = argv[1];
|
||||
const std::string a = folder("swap");
|
||||
// (a setting changed: the set for A kept by its names, its record first, the player's list unmoved; the record says B)
|
||||
{
|
||||
put(a + P, 100, A), put(a + M, 50), put(a + kStates, 40);
|
||||
record(a, rec(A, X));
|
||||
const Plan p = run(a, rec(B, X), room_for(), log_);
|
||||
CHECK(p.what == Do::Keep);
|
||||
CHECK(!has(a + P) && !has(a + M) && size(a + kept_name(P, A)) == 100 && size(a + kept_name(M, A)) == 50);
|
||||
CHECK(head(a + kept_name(P, A)) == A && size(a + kStates) == 40);
|
||||
Record k, now;
|
||||
CHECK(read_record(a + kKept, &k) && k.stamp == A && k.build == X && k.states == states_id(a) && k.states);
|
||||
CHECK((k.pieces == std::vector<std::pair<std::string, uint64_t>>{{P, 100}, {M, 50}}));
|
||||
CHECK(read_record(a + kRecord, &now) && now.stamp == B);
|
||||
CHECK(!has(a + kStatesPending) && count(a) == 4);
|
||||
}
|
||||
// (switched back after play under B, the player's list longer: A put back, B kept in its place with a piece A lacks,
|
||||
// and the lists are gone through before the title)
|
||||
{
|
||||
put(a + P, 70, B), put(a + M, 30), put(a + R, 9), put(a + kStates, 60);
|
||||
const Plan p = run(a, rec(A, X), room_for(), log_);
|
||||
CHECK(p.what == Do::Restore && p.keep_live && !p.forget);
|
||||
CHECK(head(a + P) == A && size(a + P) == 100 && size(a + M) == 50 && !has(a + R));
|
||||
CHECK(head(a + kept_name(P, B)) == B && size(a + kept_name(P, B)) == 70 && size(a + kept_name(M, B)) == 30);
|
||||
CHECK(size(a + kept_name(R, B)) == 9 && !has(a + kept_name(P, A)) && !has(a + kept_name(M, A)));
|
||||
Record k;
|
||||
CHECK(read_record(a + kKept, &k) && k.stamp == B && k.pieces.size() == 3 && k.states == states_id(a));
|
||||
CHECK(has(a + kStatesPending) && size(a + kStates) == 60);
|
||||
CHECK(count(a) == 8); // (P M, the three of B, the kept record, the list, the marker)
|
||||
}
|
||||
// (and to B again, the list as B was kept with: put back, no lists to go through for it)
|
||||
{
|
||||
fs::remove(a + kStatesPending);
|
||||
const Plan p = run(a, rec(B, X), room_for(), log_);
|
||||
CHECK(p.what == Do::Restore && p.keep_live);
|
||||
CHECK(head(a + P) == B && size(a + P) == 70 && size(a + M) == 30 && size(a + R) == 9);
|
||||
CHECK(size(a + kept_name(P, A)) == 100 && size(a + kept_name(M, A)) == 50 && !has(a + kept_name(R, A)));
|
||||
CHECK(!has(a + kStatesPending) && count(a) == 7);
|
||||
// (the same start again: nothing moves)
|
||||
CHECK(run(a, rec(B, X), room_for(), log_).what == Do::Same && count(a) == 7 && size(a + kept_name(P, A)) == 100);
|
||||
}
|
||||
// (a new translator: the kept set deleted, nothing kept)
|
||||
{
|
||||
const Plan p = run(a, rec(C, Y), room_for(), log_);
|
||||
CHECK(p.what == Do::Drop && p.forget);
|
||||
CHECK(!has(a + kKept) && !has(a + kept_name(P, A)) && !has(a + kept_name(M, A)) && size(a + P) == 70);
|
||||
}
|
||||
// (put back over a set nothing says what it was made for: it is not kept, and its pieces the kept set lacks are deleted)
|
||||
{
|
||||
const std::string d = folder("restore-unnamed");
|
||||
put(d + kept_name(P, A), 100, A), put(d + kept_name(M, A), 50);
|
||||
Record k = rec(A, X);
|
||||
k.pieces = {{P, 100}, {M, 50}};
|
||||
kept_record(d, k);
|
||||
put(d + P, 70, C), put(d + M, 30), put(d + R, 9);
|
||||
const Plan p = run(d, rec(A, X), room_for(), log_);
|
||||
CHECK(p.what == Do::Restore && !p.keep_live);
|
||||
CHECK(head(d + P) == A && size(d + P) == 100 && size(d + M) == 50 && !has(d + R) && !has(d + kKept));
|
||||
CHECK(!has(d + kStatesPending) && count(d) == 2); // (no list: none to go through)
|
||||
}
|
||||
// (a kept set with a piece not its size: refused and deleted, and the set there kept in its place)
|
||||
{
|
||||
const std::string d = folder("refused");
|
||||
put(d + kept_name(P, B), 70, B), put(d + kept_name(M, B), 29);
|
||||
Record k = rec(B, X);
|
||||
k.pieces = {{P, 70}, {M, 30}};
|
||||
kept_record(d, k);
|
||||
put(d + P, 100, A), put(d + M, 50);
|
||||
record(d, rec(A, X));
|
||||
const Plan p = run(d, rec(B, X), room_for(), log_);
|
||||
CHECK(p.what == Do::Keep && p.forget);
|
||||
CHECK(!has(d + kept_name(P, B)) && !has(d + kept_name(M, B)) && !has(d + P) && !has(d + M));
|
||||
CHECK(size(d + kept_name(P, A)) == 100 && size(d + kept_name(M, A)) == 50);
|
||||
CHECK(read_record(d + kKept, &k) && k.stamp == A && count(d) == 3);
|
||||
}
|
||||
// (a rename that cannot be made: those made are renamed back, and nothing is kept)
|
||||
{
|
||||
const std::string d = folder("rollback-keep");
|
||||
put(d + P, 100, A), put(d + M, 50);
|
||||
record(d, rec(A, X));
|
||||
fs::create_directories(d + kept_name(M, A));
|
||||
put(d + kept_name(M, A) + "/in-the-way", 1);
|
||||
run(d, rec(B, X), room_for(), log_);
|
||||
CHECK(head(d + P) == A && size(d + P) == 100 && size(d + M) == 50 && !has(d + kept_name(P, A)));
|
||||
CHECK(!has(d + kKept));
|
||||
}
|
||||
{
|
||||
const std::string d = folder("rollback-restore");
|
||||
put(d + kept_name(P, A), 100, A), put(d + kept_name(M, A), 50), put(d + kept_name(R, A), 9);
|
||||
Record k = rec(A, X);
|
||||
k.pieces = {{P, 100}, {M, 50}, {R, 9}};
|
||||
kept_record(d, k);
|
||||
put(d + P, 70, B), put(d + M, 30);
|
||||
record(d, rec(B, X));
|
||||
fs::create_directories(d + R);
|
||||
put(d + R + "/in-the-way", 1);
|
||||
const Plan p = run(d, rec(A, X), room_for(), log_);
|
||||
CHECK(p.what == Do::Restore && p.keep_live);
|
||||
CHECK(head(d + P) == B && size(d + P) == 70 && size(d + M) == 30);
|
||||
CHECK(size(d + kept_name(P, A)) == 100 && size(d + kept_name(M, A)) == 50 && size(d + kept_name(R, A)) == 9);
|
||||
CHECK(!has(d + kept_name(P, B)) && !has(d + kept_name(M, B)));
|
||||
CHECK(read_record(d + kKept, &k) && k.stamp == A);
|
||||
}
|
||||
// (a start that ended in a swap, after the set for B was renamed aside and A put back, before the record said so: the
|
||||
// record names A, which is there; B's pieces, which nothing names, are deleted, and nothing else)
|
||||
{
|
||||
const std::string d = folder("cut-swap");
|
||||
put(d + P, 100, A), put(d + M, 50);
|
||||
record(d, rec(A, X));
|
||||
Record k = rec(A, X);
|
||||
k.pieces = {{P, 100}, {M, 50}};
|
||||
kept_record(d, k);
|
||||
put(d + kept_name(P, B), 70, B), put(d + kept_name(M + ".for", B), 3), put(d + kept_name(R, B), 9);
|
||||
put(d + "notes.0123456789abcdef.txt", 5), put(d + P + ".part", 5), put(d + "triforce_shaders.bin", 5);
|
||||
const Plan p = run(d, rec(A, X), room_for(), log_);
|
||||
CHECK(p.what == Do::Same && p.forget);
|
||||
CHECK(size(d + P) == 100 && size(d + M) == 50 && !has(d + kKept));
|
||||
CHECK(!has(d + kept_name(P, B)) && !has(d + kept_name(M + ".for", B)) && !has(d + kept_name(R, B)));
|
||||
CHECK(has(d + "notes.0123456789abcdef.txt") && has(d + P + ".part") && has(d + "triforce_shaders.bin") && count(d) == 5);
|
||||
}
|
||||
// (a kept record that cannot be read: its pieces, which nothing names now, are deleted)
|
||||
{
|
||||
const std::string d = folder("unreadable");
|
||||
put(d + kept_name(P, B), 70, B), put(d + kept_name(M, B), 30);
|
||||
file_writers::write_whole(d + kKept, std::string("triforce-cache-set 9\n"));
|
||||
put(d + P, 100, A);
|
||||
record(d, rec(A, X));
|
||||
run(d, rec(A, X), room_for(), log_);
|
||||
CHECK(!has(d + kept_name(P, B)) && !has(d + kept_name(M, B)) && size(d + P) == 100);
|
||||
}
|
||||
// (off: RX_VK_CACHE_SET=0 deletes the kept set; RX_VK_PCACHE_KEEP_OLD leaves this build's, and deletes another's)
|
||||
{
|
||||
const auto kept_at = [](const std::string& d, uint64_t build) {
|
||||
put(d + kept_name(P, B), 70, B);
|
||||
Record k = rec(B, build);
|
||||
k.pieces = {{P, 70}};
|
||||
kept_record(d, k);
|
||||
put(d + P, 100, A);
|
||||
record(d, rec(A, X));
|
||||
};
|
||||
std::string d = folder("off-0");
|
||||
kept_at(d, X);
|
||||
Switches s = room_for(false);
|
||||
s.off_forgets = true;
|
||||
CHECK(run(d, rec(A, X), s, log_).what == Do::Same && !has(d + kept_name(P, B)) && !has(d + kKept));
|
||||
d = folder("off-keep-old");
|
||||
kept_at(d, X);
|
||||
CHECK(run(d, rec(C, X), room_for(false), log_).what == Do::Drop && size(d + kept_name(P, B)) == 70 && has(d + kKept));
|
||||
CHECK(size(d + P) == 100); // (nothing renamed: the caches drop it themselves)
|
||||
d = folder("off-update");
|
||||
kept_at(d, Y);
|
||||
run(d, rec(A, X), room_for(false), log_);
|
||||
CHECK(!has(d + kept_name(P, B)) && !has(d + kKept));
|
||||
// (RX_VK_NO_PROGRAM_CACHE: the same, without a decision)
|
||||
d = folder("tidy");
|
||||
kept_at(d, Y);
|
||||
put(d + kept_name(M, C), 4);
|
||||
tidy(d, X, log_);
|
||||
CHECK(!has(d + kept_name(P, B)) && !has(d + kKept) && !has(d + kept_name(M, C)) && size(d + P) == 100);
|
||||
d = folder("tidy-ours");
|
||||
kept_at(d, X);
|
||||
tidy(d, X, log_);
|
||||
CHECK(size(d + kept_name(P, B)) == 70 && has(d + kKept));
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def between(text, start, end):
|
||||
a = text.index(start)
|
||||
return text[a:text.index(end, a)]
|
||||
|
||||
|
||||
def function(text, head):
|
||||
a = text.index(head)
|
||||
return text[a:text.index("\n}\n", a) + 2]
|
||||
|
||||
|
||||
def check(ok, why):
|
||||
if not ok:
|
||||
raise SystemExit(why)
|
||||
|
||||
|
||||
def stamped_shader():
|
||||
"""vk_shader.cpp as nx2/build.py's translation_text takes it for the translation stamp"""
|
||||
tree = ast.parse((ROOT / "nx2" / "build.py").read_text(encoding="utf-8"))
|
||||
functions = [n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name in ("strip_comments", "translation_text")]
|
||||
ns = {}
|
||||
exec(compile(ast.Module(body=functions, type_ignores=[]), "build.py", "exec"), ns)
|
||||
return ns["translation_text"]("vk_shader.cpp", (VK / "vk_shader.cpp").read_bytes()).decode("utf-8")
|
||||
|
||||
|
||||
def check_source():
|
||||
shader = (VK / "vk_shader.cpp").read_text(encoding="utf-8")
|
||||
draw = (VK / "vk_draw.cpp").read_text(encoding="utf-8")
|
||||
main = (VK / "vk_main.cpp").read_text(encoding="utf-8")
|
||||
files = (VK / "vk_cache_set.cpp").read_text(encoding="utf-8")
|
||||
rule = (VK / "cache_set.h").read_text(encoding="utf-8")
|
||||
steps = (VK / "cache_set_files.h").read_text(encoding="utf-8")
|
||||
|
||||
# (once the device is made, before anything opens a cache: mkwvk_init, right after create_device)
|
||||
init = function(main, "const MkwVkRenderer* mkwvk_init(const MkwVkHost* h) {")
|
||||
made = "if (!create_instance() || !pick_device() || !create_device()) return nullptr;"
|
||||
check(made in init and "cache_set_init();" in init, "mkwvk_init does not decide the caches' kept set")
|
||||
check(init.index(made) < init.index("cache_set_init();") < init.index("table.version"),
|
||||
"the kept set is not decided right after the device is made")
|
||||
run = function(files, "void cache_set_run() {")
|
||||
check("std::call_once(once, [] { cache_set_run(); });" in files, "the kept set is not decided once")
|
||||
check(run.index("other_triforce(") < run.index('getenv("RX_VK_NO_PROGRAM_CACHE")') < run.index("this_start()") <
|
||||
run.index("cache_set::run(dir, now, sw, logf);"),
|
||||
"the set is decided before it is known that no other Triforce has the caches")
|
||||
check('getenv("RX_VK_PCACHE_KEEP_OLD")' in run and 'cache_set::on(getenv("RX_VK_CACHE_SET"))' in run and
|
||||
'sw.off_forgets = !cache_set::on(getenv("RX_VK_CACHE_SET"));' in run and
|
||||
"cache_set::tidy(dir, program_cache_build_part(), logf)" in run, "the switches that leave the kept set off are not read")
|
||||
check("r.stamp = program_cache_stamp();" in files and "r.build = program_cache_build_part();" in files,
|
||||
"the decision is not made by the caches' own stamp")
|
||||
# (the files' run, which the FILES fixture runs: the folder swept and measured, then decided, then a piece moved)
|
||||
steps_run = function(steps, "inline Plan run(const std::string& dir, const Record& now, const Switches& sw, Log log) {")
|
||||
check("f.stamp = now.stamp, f.build = now.build;" in steps_run and
|
||||
steps_run.index("sweep(") < steps_run.index("std::filesystem::space(") < steps_run.index("decide(f)") <
|
||||
steps_run.index("move_all("), "the folder is not swept and measured before the decision, or a piece moves before it")
|
||||
# (a set put back whose notes are older than the player's list: the prepare before the title goes through the lists)
|
||||
prep = function(draw, "bool prepare_run(void (*progress)(size_t done, size_t total), bool background) {")
|
||||
check("const bool put_back = !background && cache_set_states_pending();" in prep and "if (shipped_new || put_back) {" in prep,
|
||||
"prepare_run does not go through the state lists for a kept set put back")
|
||||
lists = function(draw, "void state_list_prepare(void (*progress)(size_t done, size_t total)) {")
|
||||
check("if (!stopped) cache_set_states_done();" in lists, "state_list_prepare does not clear the put-back marker")
|
||||
# (a stop leaves the marker: the lists are gone through again at the next start, the set put back's notes with them)
|
||||
stop = lists[lists.index("const auto stopped = [&] {"):]
|
||||
check("lists_done.stopped = true;" in stop[:stop.index("};")], "state_list_prepare clears the put-back marker after a stop")
|
||||
check('state_list_path("triforce_pipeline_states.bin")' in draw and 'kStates = "triforce_pipeline_states.bin";' in rule,
|
||||
"cache_set.h kStates is not vk_draw.cpp's state list")
|
||||
|
||||
# (the pieces: the files the caches keep by the stamp, by the names the game folder has them)
|
||||
pieces = re.findall(r'"([a-z_]+(?:\.[a-z]+)+)"', between(rule, "inline constexpr const char* kPieces[] = {", "};"))
|
||||
check(len(pieces) == len(set(pieces)) == 17 and pieces[0] == "triforce_programs.bin", "cache_set.h kPieces: %r" % pieces)
|
||||
check('"triforce_programs.bin"' in function(shader, "void disk_init() {") and
|
||||
'path.substr(0, path.size() - 4) + ".idx"' in shader, "vk_shader.cpp no longer names the program cache's files so")
|
||||
for needle in ('pcache_path = dir + "mkw_vk_pipelines.bin";', 'pcache_path + ".for"', 'pcache_path + ".base"',
|
||||
'pcache_path + ".own"', '+ "_play.bin";',
|
||||
'pcache_play_path + ".for"', '+ "triforce_prepared.bin";', 'prepared + ".check"', 'path + ".warming";',
|
||||
'warming + ".skip"', '+ "triforce_pipelines.bin";', 'pipe_notes_path() + ".predicted"',
|
||||
'pipe_notes_path() + ".plan"', '(pipe_notes_path() + ".built")', 'state_list_path("triforce_states_applied.bin")'):
|
||||
check(needle in draw, "vk_draw.cpp no longer names a cache's file as cache_set.h does: " + needle)
|
||||
magic = re.search(r"constexpr uint32_t kDiskMagic = (0x[0-9A-Fa-f]+);", shader)
|
||||
check(magic and ("kProgramsMagic = %s;" % magic.group(1)) in rule, "cache_set.h's program cache head is not vk_shader.cpp's")
|
||||
# (the switches the log names are disk_stamp's)
|
||||
lists = [re.search(r'for \(const char\* pre : \{([^}]*)\}\)', t).group(1) for t in (function(shader, "uint64_t disk_stamp() {"), files)]
|
||||
check(lists[0] == lists[1], "vk_cache_set.cpp's list of the stamp's switches is not disk_stamp's")
|
||||
|
||||
# (the build part: outside the translation stamp, and the stamp's text has nothing of it; the translator's words as
|
||||
# disk_stamp takes them)
|
||||
stamped = stamped_shader()
|
||||
check("program_cache_build_part" not in stamped and "uint64_t program_cache_build_part() {" in shader,
|
||||
"program_cache_build_part is in the translation stamp: the program cache would be translated again")
|
||||
words = "program_carry::translator_words(carry_on(), kTranslationStamp, HOOKSHOT_SHADER_STAMP, translator);"
|
||||
check(words in function(shader, "uint64_t program_cache_build_part() {") and words in function(shader, "uint64_t disk_stamp() {"),
|
||||
"the build part does not take the translator's words as disk_stamp does")
|
||||
for name in ("cache_set", "vk_cache_set", "cache_set_files"):
|
||||
check(name not in stamped, "the translation stamp's text names " + name)
|
||||
|
||||
# (the Robust buffers row says what changing it costs, and that switching back is quick with a kept set)
|
||||
menu = (VK / "vk_menu.cpp").read_text(encoding="utf-8")
|
||||
row = between(menu, '{TAB_DEBUG, "Robust buffers", &opts.robust,', "hn_robust, true},")
|
||||
text = "".join(re.findall(r'"((?:[^"\\]|\\.)*)"', row))
|
||||
check("prepares every shader again" in text and "long first start on AMD" in text and "Switching back is quick" in text
|
||||
and "on NVIDIA cards it does not" in text, "the Robust buffers row does not say what changing it costs: " + text)
|
||||
# (the cost is the translation's, by the card: fetch_bounds_buffers depends on the row only where fetch_bounds is on,
|
||||
# which it is not on NVIDIA)
|
||||
coop = (VK / "vk_coopmat.cpp").read_text(encoding="utf-8")
|
||||
vendor = (VK / "vk_vendor.h").read_text(encoding="utf-8")
|
||||
check("fetch_bounds_buffers = dev.fixes.fetch_bounds && !dev.features.robustBufferAccess;" in coop and
|
||||
"x.fetch_bounds = f.vendor_id != 0x10DE;" in vendor, "the Robust buffers row's cost is no longer by the card")
|
||||
dev_md = (ROOT / "docs/development.md").read_text(encoding="utf-8")
|
||||
check("`RX_VK_CACHE_SET=0`" in dev_md, "RX_VK_CACHE_SET is not in docs/development.md's switches")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--cxx", default="g++")
|
||||
args = parser.parse_args()
|
||||
check_source()
|
||||
with tempfile.TemporaryDirectory(prefix="cache-set-") as tmp:
|
||||
tmp = Path(tmp)
|
||||
(tmp / "t.cpp").write_text(FIXTURE, encoding="utf-8")
|
||||
exe = tmp / "cache-set"
|
||||
subprocess.run([args.cxx, "-std=c++20", "-Wall", "-Wextra", "-Werror", "-I" + str(VK), str(tmp / "t.cpp"), "-o", str(exe)],
|
||||
check=True)
|
||||
r = subprocess.run([str(exe)], capture_output=True, text=True)
|
||||
if r.returncode:
|
||||
raise SystemExit(f"cache_set.h: {r.stdout.strip()}")
|
||||
# (the files: each start's renames, deletes and records, on folders of the test's own)
|
||||
(tmp / "f.cpp").write_text(FILES, encoding="utf-8")
|
||||
exe = tmp / "cache-set-files"
|
||||
subprocess.run([args.cxx, "-std=c++20", "-Wall", "-Wextra", "-Werror", "-I" + str(VK), str(tmp / "f.cpp"), "-o", str(exe)],
|
||||
check=True)
|
||||
(tmp / "folders").mkdir()
|
||||
r = subprocess.run([str(exe), str(tmp / "folders")], capture_output=True, text=True)
|
||||
if r.returncode:
|
||||
raise SystemExit(f"cache_set_files.h: {r.stdout.strip()}\n{r.stderr.strip()}")
|
||||
print("PASS: a set of the shader caches is kept for a change of a setting, put back whole when it goes back (the state "
|
||||
"lists gone through when the player's grew), and deleted at a change of the translator, by RX_VK_CACHE_SET=0, or "
|
||||
"when no record names it")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -410,17 +410,40 @@ def check_source(mem, replay, texture, dev):
|
||||
seg = replay[replay.index("seg_cv.wait(l, [j] { return j->done.load(); });"):]
|
||||
check(seg.index("seg_cv.wait(l, [j] { return j->done.load(); });") < seg.index("vkQueueSubmit2(dev.queue, 1, &si, j->r->fence)"),
|
||||
"a parallel replay's segment is submitted before it is done")
|
||||
check(replay.count("vkQueueSubmit2(") == 4, "vk_replay.cpp submits in a place this test does not know: check that the copies "
|
||||
# ((Triforce) the early segments' path (replay_handle_early, RX_VK_SEG_EARLY) submits its segments as replay_handle does: two
|
||||
# segment submits, each after its job's wait, and each job flushes its uploads (run_job: texture_uploads_recorded) before it is done)
|
||||
seg_submit = "vkQueueSubmit2(dev.queue, 1, &si, j->r->fence)"
|
||||
seg_wait = "seg_cv.wait(l, [j] { return j->done.load(); });"
|
||||
check(replay.count(seg_submit) == 2 and replay.count(seg_wait) == 2 and
|
||||
replay.count("j->uploads = texture_uploads_recorded();") == 2,
|
||||
"the parallel replay's two segment paths no longer submit as this test knows")
|
||||
at = 0
|
||||
for _ in range(2):
|
||||
w = replay.index(seg_wait, at)
|
||||
s = replay.index(seg_submit, at)
|
||||
check(w < s, "a parallel replay's segment (one of the two paths) is submitted before it is done")
|
||||
at = s + 1
|
||||
check(replay.count("vkQueueSubmit2(") == 5, "vk_replay.cpp submits in a place this test does not know: check that the copies "
|
||||
"behind are done before it")
|
||||
# (the submitting thread: only the synchronous replay leaves copies behind, and it finishes them before it returns)
|
||||
# (the submitting thread: the synchronous replay leaves copies behind, and it finishes them before it returns)
|
||||
q = block(replay, "void submit_q(")
|
||||
sync = q[:q.index("std::lock_guard lk(submit_order_mu);")]
|
||||
before(sync, "memory_capture_submit(true);", "~CopiesDone() { memory_capture_copies_done(); }",
|
||||
# ((Triforce) a held submit's capture (HOS_NVN_HOLD=2: its game thread already runs again either way) leaves its copies
|
||||
# behind too unless RX_VK_HELD_BEHIND=0: the synchronous path's call is memory_capture_submit(!tl_submit_held || held_behind))
|
||||
sync_call = "memory_capture_submit(!tl_submit_held || held_behind);"
|
||||
before(sync, sync_call, "~CopiesDone() { memory_capture_copies_done(); }",
|
||||
"submit_q: the copies behind are not done before the game's thread returns")
|
||||
before(sync, "} copies_done;", "return do_submit(handles, n);", "submit_q: the replay runs after the copies are done")
|
||||
check("memory_capture_submit(true)" not in q[q.index("std::lock_guard lk(submit_order_mu);"):],
|
||||
"submit_q: the replay thread's capture leaves copies behind while the game goes on")
|
||||
check(replay.count("memory_capture_submit(true)") == 1, "a capture other than the synchronous replay's leaves copies behind")
|
||||
# ((Triforce, async_rules.h 2) the replay thread's capture shares its copies with the helpers too, and has every one of them
|
||||
# made before the hand-over: the game goes on once the submit returns, and nothing is left behind it)
|
||||
own = q[q.index("std::lock_guard lk(submit_order_mu);"):]
|
||||
check(own.count("memory_capture_submit(true);") == 1, "submit_q: the replay thread's capture is not the one this test knows")
|
||||
before(own, "memory_capture_submit(true);", "memory_capture_copies_done();",
|
||||
"submit_q: the replay thread's capture leaves copies behind while the game goes on")
|
||||
before(own, "memory_capture_copies_done();", "enqueue(std::move(j));",
|
||||
"submit_q: the replay thread's capture is handed over before its copies are made")
|
||||
check(replay.count("memory_capture_submit(true)") == 1 and replay.count(sync_call) == 1,
|
||||
"a capture other than the two submits' leaves copies behind")
|
||||
# (the figures and the switch)
|
||||
check("vk: a frame's captures at the game's submits:" in replay, "no 120-present line of the captures on the game's threads")
|
||||
check("RX_VK_CAPTURE_BEHIND" in dev, "docs/development.md: RX_VK_CAPTURE_BEHIND is not in the switches table")
|
||||
|
||||
285
tests/test_crash_threads.py
Normal file
285
tests/test_crash_threads.py
Normal file
@@ -0,0 +1,285 @@
|
||||
"""A crash report says what the other threads were doing (host/crash_threads.h and .c, HOS_CRASH_THREADS; no game).
|
||||
|
||||
A crash report had the faulting thread alone. The crash while a save loads reads an object whose memory holds something
|
||||
else, and its reports could not say which thread had freed it. A report now starts by taking every other thread's host
|
||||
stack on a helper thread and ends with a line a thread.
|
||||
|
||||
The header's rules, compiled and run: on unless the switch is 0; a thread whose top frame is in a system library is a
|
||||
waiting one, any other a running one; a running thread's line has every frame kept and a waiting one's twelve. Each rule
|
||||
taken out in turn (a mutation) must make the test fail, and each mutant must build.
|
||||
|
||||
On Windows host/crash_threads.c itself is compiled and run beside a thread that spins in a function of its own and one
|
||||
that sleeps: the report has a "running" line for the spinner with a frame inside the test's own program and its name, a
|
||||
"waiting" line for the sleeper, the running ones first, no line for the reporting thread, and the count; with the switch
|
||||
at 0 nothing is taken or written; a second begin takes nothing again.
|
||||
|
||||
The sources: nothing is allocated, logged or locked between a thread's SuspendThread and its ResumeThread; the crash
|
||||
report and the fatal error's begin the snapshot before their own lines and write it after them, with the lines so far
|
||||
flushed first; the switch's row is in the development guide.
|
||||
|
||||
python -I -B tests/test_crash_threads.py [--cc gcc]
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
RUN_ALL_ARGS = ["--cc", "gcc"]
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
HOST = ROOT / "host"
|
||||
|
||||
|
||||
def block(text, marker):
|
||||
start = text.index(marker)
|
||||
end = text.index("{", start) + 1
|
||||
depth = 1
|
||||
while depth:
|
||||
depth += (text[end] == "{") - (text[end] == "}")
|
||||
end += 1
|
||||
return text[start:end]
|
||||
|
||||
|
||||
def in_order(text, parts, where):
|
||||
at = 0
|
||||
for part in parts:
|
||||
found = text.find(part, at)
|
||||
if found < 0:
|
||||
raise SystemExit("%s: %r is missing, or not after the part before it (update the test with the code)" % (where, part))
|
||||
at = found + len(part)
|
||||
|
||||
|
||||
HEADER_TEST = r'''
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include "crash_threads.h"
|
||||
#define CHECK(x) do { if (!(x)) { fprintf(stderr, "FAIL:%d %s\n", __LINE__, #x); exit(1); } } while (0)
|
||||
int main(void) {
|
||||
/* (on unless the switch is 0) */
|
||||
CHECK(crash_threads_on(NULL) && crash_threads_on("") && crash_threads_on("1") && crash_threads_on("00") && !crash_threads_on("0"));
|
||||
/* (a top frame in a system library: waiting; in the game, the back end, a driver, or no module: running) */
|
||||
CHECK(crash_threads_waiting("ntdll.dll") && crash_threads_waiting("NTDLL.DLL") && crash_threads_waiting("KERNELBASE.dll"));
|
||||
CHECK(crash_threads_waiting("kernel32.dll") && crash_threads_waiting("win32u.dll") && crash_threads_waiting("USER32.dll"));
|
||||
CHECK(!crash_threads_waiting("Triforce.exe") && !crash_threads_waiting("triforce_vk.dll") && !crash_threads_waiting("nvoglv64.dll"));
|
||||
CHECK(!crash_threads_waiting("?") && !crash_threads_waiting("") && !crash_threads_waiting("nt") && !crash_threads_waiting("kernel"));
|
||||
/* (a line's frames: all kept of a running thread, twelve of a waiting one, never more than there are) */
|
||||
CHECK(crash_threads_shown(CRASH_THREADS_FRAMES, 0) == CRASH_THREADS_FRAMES && crash_threads_shown(3, 0) == 3);
|
||||
CHECK(crash_threads_shown(CRASH_THREADS_FRAMES, 1) == 12 && crash_threads_shown(2, 1) == 2 && crash_threads_shown(0, 0) == 0);
|
||||
CHECK(crash_threads_shown(-1, 0) == 0 && crash_threads_shown(100, 0) == CRASH_THREADS_FRAMES);
|
||||
CHECK(CRASH_THREADS_MAX >= 256 && CRASH_THREADS_FRAMES > 12 && CRASH_THREADS_FRAMES <= 40);
|
||||
/* (a stopped thread's walk reads only inside its stack [lo, hi)) */
|
||||
CHECK(crash_threads_in_stack(0x1000, 8, 0x1000, 0x2000) && crash_threads_in_stack(0x1ff8, 8, 0x1000, 0x2000));
|
||||
CHECK(!crash_threads_in_stack(0xff8, 8, 0x1000, 0x2000) && !crash_threads_in_stack(0x1ffc, 8, 0x1000, 0x2000));
|
||||
CHECK(!crash_threads_in_stack(0x3000, 8, 0x1000, 0x2000) && !crash_threads_in_stack(0x1800, 0x900, 0x1000, 0x2000));
|
||||
CHECK(!crash_threads_in_stack(0x1000, 8, 0x2000, 0x1000) && !crash_threads_in_stack(0x1000, ~0ull, 0x1000, 0x2000));
|
||||
CHECK(CRASH_THREADS_WAIT_MS >= 500 && CRASH_THREADS_WAIT_MS <= 5000);
|
||||
puts("PASS header: the switch, waiting or running, a line's frames");
|
||||
return 0;
|
||||
}
|
||||
'''
|
||||
|
||||
MUTATIONS = [
|
||||
("off at 0", "return !(env && env[0] == '0' && !env[1]);", "return 1 + 0 * (env != 0);"),
|
||||
("on when unset", "return !(env && env[0] == '0' && !env[1]);", "return env && env[0] == '1';"),
|
||||
("0 alone is off", "return !(env && env[0] == '0' && !env[1]);", "return !(env && env[0] == '0');"),
|
||||
("ntdll waits", 'crash_threads_prefix(top_module, "ntdll") || ', ""),
|
||||
("kernelbase waits", 'crash_threads_prefix(top_module, "kernelbase") ||', ""),
|
||||
("win32u waits", 'crash_threads_prefix(top_module, "win32u") ||', ""),
|
||||
("whatever its case", "return ch >= 'A' && ch <= 'Z' ? ch + 32 : ch;", "return ch;"),
|
||||
("the whole prefix", "if (crash_threads_lower((unsigned char)*s) != *lower_prefix) return 0;",
|
||||
"if (crash_threads_lower((unsigned char)*s) != *lower_prefix) return s[0] == 'n';"),
|
||||
("a waiting thread's line is short", "const int most = waiting ? 12 : CRASH_THREADS_FRAMES;", "const int most = CRASH_THREADS_FRAMES + 0 * waiting;"),
|
||||
("a running thread's line is whole", "const int most = waiting ? 12 : CRASH_THREADS_FRAMES;", "const int most = 12 + 0 * waiting;"),
|
||||
("no more frames than there are", "return frames < 0 ? 0 : frames < most ? frames : most;", "return frames < 0 ? 0 : most;"),
|
||||
("the stack's bottom", "return sp >= lo && sp <= hi && need <= hi - sp;", "return (int)(0 * lo) + (sp <= hi && need <= hi - sp);"),
|
||||
("the stack's top", "return sp >= lo && sp <= hi && need <= hi - sp;", "return sp >= lo && sp <= hi + 0 * need;"),
|
||||
("past the top by the read", "return sp >= lo && sp <= hi && need <= hi - sp;", "return sp >= lo && sp < hi + 0 * need;"),
|
||||
]
|
||||
|
||||
# (Windows: crash_threads.c as it is, with the log's lines kept for the checks)
|
||||
RUNTIME_TEST = r'''
|
||||
#include <stdarg.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <windows.h>
|
||||
static char lines[64][1024];
|
||||
static int nlines;
|
||||
void hos_log(const char *fmt, ...) {
|
||||
va_list ap;
|
||||
va_start(ap, fmt);
|
||||
if (nlines < 64) vsnprintf(lines[nlines++], sizeof lines[0], fmt, ap);
|
||||
va_end(ap);
|
||||
}
|
||||
#include "@SOURCE@"
|
||||
#define CHECK(x) do { if (!(x)) { fprintf(stderr, "FAIL:%d %s\n", __LINE__, #x); for (int i = 0; i < nlines; i++) fprintf(stderr, " %s\n", lines[i]); exit(1); } } while (0)
|
||||
static volatile LONG stop, spinning;
|
||||
__declspec(noinline) static DWORD spin_here(void) {
|
||||
volatile unsigned n = 0;
|
||||
InterlockedExchange(&spinning, 1);
|
||||
while (!stop) n++;
|
||||
return n;
|
||||
}
|
||||
static DWORD WINAPI spinner(void *p) { (void)p; SetThreadDescription(GetCurrentThread(), L"the spinner"); return spin_here() + 1; }
|
||||
static DWORD WINAPI sleeper(void *p) { (void)p; SetThreadDescription(GetCurrentThread(), L"the sleeper"); Sleep(60000); return 0; }
|
||||
static int find(const char *what) {
|
||||
for (int i = 0; i < nlines; i++)
|
||||
if (strstr(lines[i], what)) return i;
|
||||
return -1;
|
||||
}
|
||||
int main(int argc, char **argv) {
|
||||
(void)argv;
|
||||
HANDLE a = CreateThread(NULL, 0, spinner, NULL, 0, NULL), b = CreateThread(NULL, 0, sleeper, NULL, 0, NULL);
|
||||
CHECK(a && b);
|
||||
while (!spinning) Sleep(1);
|
||||
Sleep(100); /* (the sleeper is in its sleep by now) */
|
||||
if (argc > 1) { /* (the switch at 0, set by the test: nothing taken, nothing written) */
|
||||
hos_crash_threads_begin();
|
||||
hos_crash_threads_end();
|
||||
CHECK(nlines == 0);
|
||||
puts("PASS run (Windows), HOS_CRASH_THREADS=0: nothing taken");
|
||||
return 0;
|
||||
}
|
||||
SetThreadDescription(GetCurrentThread(), L"the reporter");
|
||||
hos_crash_threads_begin();
|
||||
hos_crash_threads_begin(); /* (once a process) */
|
||||
hos_crash_threads_end();
|
||||
const int run = find("thread \"the spinner\""), wait = find("thread \"the sleeper\""), total = find("other threads,");
|
||||
CHECK(run >= 0 && wait >= 0 && total >= 0);
|
||||
CHECK(strstr(lines[run], ") running:") && strstr(lines[wait], ") waiting:"));
|
||||
CHECK(run < wait && wait < total && total == nlines - 1); /* (the running ones first, the count last) */
|
||||
char self[MAX_PATH];
|
||||
GetModuleFileNameA(NULL, self, sizeof self);
|
||||
const char *base = strrchr(self, '\\') ? strrchr(self, '\\') + 1 : self;
|
||||
CHECK(strstr(lines[run], base)); /* (a frame in this program: the spin) */
|
||||
CHECK(strstr(lines[wait], "ntdll") || strstr(lines[wait], "KERNELBASE") || strstr(lines[wait], "kernel"));
|
||||
CHECK(find("the reporter") < 0); /* (the reporting thread has its own report) */
|
||||
CHECK(find("not taken within") < 0);
|
||||
int spaces = 0; /* (a waiting line: twelve frames at most) */
|
||||
for (const char *q = strstr(lines[wait], "waiting:"); q && *q; q++) spaces += *q == ' ';
|
||||
CHECK(spaces >= 1 && spaces <= 12);
|
||||
const int before = nlines;
|
||||
hos_crash_threads_end(); /* (one report) */
|
||||
CHECK(nlines == before);
|
||||
InterlockedExchange(&stop, 1);
|
||||
puts("PASS run (Windows): a running line for the spinner, a waiting line for the sleeper, none for the reporter");
|
||||
return 0;
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
def check_source(cfile, glue, thread, dev):
|
||||
take = block(cfile, "static DWORD WINAPI crash_take(void *unused) {")
|
||||
a, b = take.index("if (SuspendThread(h) != (DWORD)-1) {"), take.index("ResumeThread(h);")
|
||||
held = take[a:b]
|
||||
for bad in ("hos_log", "malloc", "calloc", "printf", "fopen", "OpenThread", "CloseHandle", "CreateToolhelp32Snapshot", "Acquire"):
|
||||
if bad in held:
|
||||
raise SystemExit("crash_threads.c: %s between a thread's SuspendThread and its ResumeThread (it may hold that lock)" % bad)
|
||||
if "s->frames = crash_unwind(h, s->pc);" not in held:
|
||||
raise SystemExit("crash_threads.c: the unwind is not between SuspendThread and ResumeThread")
|
||||
in_order(take, ["te.th32ThreadID == me || te.th32ThreadID == crash_self", "SuspendThread(h)", "ResumeThread(h);",
|
||||
"InterlockedExchange(&crash_count, count);"], "crash_threads.c crash_take")
|
||||
unwind = block(cfile, "static int crash_unwind(HANDLE h, DWORD64 *out) {")
|
||||
for bad in ("hos_log", "malloc", "printf", "IsBadReadPtr", "GetProcAddress"):
|
||||
if bad in unwind:
|
||||
raise SystemExit("crash_threads.c crash_unwind: %s while the thread is stopped" % bad)
|
||||
# (nothing read outside the stopped thread's own stack: the bounds first, each step checked before it reads)
|
||||
in_order(unwind, ["if (!crash_stack_bounds(h, &lo, &hi)) {", "for (; n < CRASH_THREADS_FRAMES && ctx.Rip; n++) {",
|
||||
"if (!crash_threads_in_stack(ctx.Rsp, 8, lo, hi)) break;", "ctx.Rip = *(DWORD64 *)ctx.Rsp;",
|
||||
"RtlVirtualUnwind("], "crash_threads.c crash_unwind")
|
||||
in_order(take, ['crash_query = (CrashQueryThread)(void *)GetProcAddress(', "for (BOOL ok = Thread32First(", "SuspendThread(h)"],
|
||||
"crash_threads.c crash_take: NtQueryInformationThread found before any thread is stopped")
|
||||
begin = block(cfile, "void hos_crash_threads_begin(void) {")
|
||||
in_order(begin, ['if (!crash_threads_on(getenv("HOS_CRASH_THREADS")) || InterlockedExchange(&crash_begun, 1)) return;',
|
||||
"crash_self = GetCurrentThreadId();", "crash_helper = CreateThread(NULL, 0, crash_take, NULL, 0, NULL);"],
|
||||
"crash_threads.c hos_crash_threads_begin")
|
||||
end = block(cfile, "void hos_crash_threads_end(void) {")
|
||||
in_order(end, ["if (!crash_helper) return;", "WaitForSingleObject(helper, CRASH_THREADS_WAIT_MS);",
|
||||
"if (waited != WAIT_OBJECT_0 || count < 0) {", "return;", "for (int pass = 0; pass < 2; pass++)",
|
||||
"const int waiting = crash_threads_waiting(mod);", "if (waiting != pass) continue;",
|
||||
"const int shown = crash_threads_shown(s->frames, waiting);"], "crash_threads.c hos_crash_threads_end")
|
||||
# (the crash report: the snapshot begun before its first line, written after its last, the lines so far flushed first)
|
||||
crash = block(glue, "static LONG WINAPI report_crash(EXCEPTION_POINTERS *info) {")
|
||||
in_order(crash, ["if (!hos_ending_enter()) return EXCEPTION_CONTINUE_SEARCH;", "hos_crash_threads_begin();",
|
||||
'hos_log("CRASH: exception %#lx', 'hos_log("CRASH: [x%d+%#05x]', "hos_log_flush();",
|
||||
"hos_crash_threads_end();", "hos_log_flush();", "return EXCEPTION_CONTINUE_SEARCH;"], "mkw_glue.c report_crash")
|
||||
fatal = block(thread, "void hos_fatal(Ctx *c, const char *fmt, ...) {")
|
||||
in_order(fatal, ["if (!hos_ending_enter()) {", "hos_crash_threads_begin();", 'FATAL: %s"', "hos_backtrace();",
|
||||
"hos_crash_threads_end();", "log_flush();", "TerminateProcess(GetCurrentProcess(), 3);"], "hos_thread.c hos_fatal")
|
||||
for name, text in (("mkw_glue.c", glue), ("hos_thread.c", thread)):
|
||||
if text.count("hos_crash_threads_begin();") != 1 or text.count("hos_crash_threads_end();") != 1:
|
||||
raise SystemExit("%s: the snapshot is begun or written in a place this test does not know" % name)
|
||||
in_order(glue, ["static DWORD WINAPI crash_test_after(void *p) {", 'getenv("HOS_CRASH_TEST_S")'], "mkw_glue.c the test crash")
|
||||
if "| `HOS_CRASH_THREADS=0` |" not in dev:
|
||||
raise SystemExit("docs/development.md: HOS_CRASH_THREADS is not in the switches table")
|
||||
|
||||
|
||||
def build(cc, d, name, src, include, extra=()):
|
||||
c, exe = d / (name + ".c"), d / (name + ".exe")
|
||||
c.write_text(src, encoding="utf-8")
|
||||
r = subprocess.run([cc, "-std=gnu11", "-O1", "-Wall", "-Wextra", "-Werror", "-Wno-unused-function", *extra, "-I" + str(include), str(c),
|
||||
"-o", str(exe)], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
|
||||
if r.returncode:
|
||||
return None, r.stdout
|
||||
return exe, ""
|
||||
|
||||
|
||||
def run(exe, args=(), env=None):
|
||||
return subprocess.run([str(exe), *args], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, timeout=60, env=env)
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--cc", default=os.environ.get("CC", "gcc"))
|
||||
a = ap.parse_args()
|
||||
cfile = (HOST / "crash_threads.c").read_text(encoding="utf-8")
|
||||
header = (HOST / "crash_threads.h").read_text(encoding="utf-8")
|
||||
check_source(cfile, (HOST / "mkw_glue.c").read_text(encoding="utf-8"), (HOST / "hos_thread.c").read_text(encoding="utf-8"),
|
||||
(ROOT / "docs" / "development.md").read_text(encoding="utf-8"))
|
||||
print("PASS sources: nothing allocated or logged while a thread is stopped; the crash report and the fatal error's begin "
|
||||
"the snapshot first and write it last; the switch's row")
|
||||
with tempfile.TemporaryDirectory(prefix="crash-threads-") as tmp:
|
||||
d = Path(tmp)
|
||||
exe, out = build(a.cc, d, "header", HEADER_TEST, HOST)
|
||||
if not exe:
|
||||
raise SystemExit("header: the build failed:\n" + out)
|
||||
r = run(exe)
|
||||
if r.returncode:
|
||||
raise SystemExit("the header test failed:\n" + r.stdout)
|
||||
print(r.stdout.strip())
|
||||
for i, (what, old, new) in enumerate(MUTATIONS):
|
||||
if header.count(old) != 1:
|
||||
raise SystemExit("mutation %r: its text is not once in crash_threads.h (update the test with the header)" % what)
|
||||
inc = d / ("mutant%d" % i)
|
||||
inc.mkdir()
|
||||
(inc / "crash_threads.h").write_text(header.replace(old, new), encoding="utf-8")
|
||||
exe, out = build(a.cc, d, "mutant%d" % i, HEADER_TEST, inc)
|
||||
if not exe:
|
||||
raise SystemExit("mutation %r: the mutant does not build (a mutant must fail the test, not the compiler):\n%s" % (what, out))
|
||||
if run(exe).returncode == 0:
|
||||
raise SystemExit("mutation %r: the header test still passed without it" % what)
|
||||
print("PASS mutations: %d rules of crash_threads.h, each taken out, fail the header's test" % len(MUTATIONS))
|
||||
if sys.platform != "win32":
|
||||
print("SKIP run: the other threads' stacks are taken on Windows only")
|
||||
return
|
||||
src = RUNTIME_TEST.replace("@SOURCE@", str(HOST / "crash_threads.c").replace("\\", "/"))
|
||||
exe, out = build(a.cc, d, "run", src, HOST)
|
||||
if not exe:
|
||||
raise SystemExit("the Windows run: the build failed:\n" + out)
|
||||
env = dict(os.environ)
|
||||
env.pop("HOS_CRASH_THREADS", None)
|
||||
r = run(exe, env=env)
|
||||
if r.returncode:
|
||||
raise SystemExit("the Windows run failed:\n" + r.stdout)
|
||||
print(r.stdout.strip())
|
||||
env["HOS_CRASH_THREADS"] = "0"
|
||||
r = run(exe, ["off"], env=env)
|
||||
if r.returncode:
|
||||
raise SystemExit("the Windows run with HOS_CRASH_THREADS=0 failed:\n" + r.stdout)
|
||||
print(r.stdout.strip())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -57,9 +57,8 @@ def main():
|
||||
check(at == len(order), "the groups do not cover the tools")
|
||||
story = [g for g in groups if g[0] == "Story & amiibo"]
|
||||
check(story and order[int(story[0][1]):int(story[0][2])] == [11, 12, 13], "the three rows are not one group of the tab")
|
||||
second = int(re.search(r"constexpr int kDebugSecondColumn = (\d+);", menu).group(1))
|
||||
check(0 < second < len(groups) and "g >= kDebugSecondColumn ? 1 : 0" in menu and "debug_groups[kDebugSecondColumn].from ? 1 : 0" in menu,
|
||||
"the two columns of the tab are not told apart by the group")
|
||||
# ((Triforce, 11-17) one list as every tab's, each group under its heading: tests/test_debug_tab_layout.py)
|
||||
check("out[head] = -1 - g;" in function(menu, "int debug_list("), "the groups do not stand under their headings")
|
||||
|
||||
# confirm opens the page; it is drawn, takes the keys and the mouse, and goes back to the tab
|
||||
cheats = menu[menu.index("void cheat_press(int i,"):menu.index("void menu_tick() {")]
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
"""The Debug tab's layout (gpu/vk/debug_tab_layout.h, gpu/vk/vk_menu.cpp draw_debug_rows; no game).
|
||||
"""The Debug tab drawn as every other tab of the options (gpu/vk/vk_menu.cpp debug_list, draw_options; no game).
|
||||
|
||||
Looked at in pictures (tests/ui_preview.cpp), the tab had three faults. Its rows were cut off in the middle of the column
|
||||
where they scrolled past the first or the last whole row, while every other tab lets them go under the header and toward
|
||||
the guides. The Developer row with more than two values (Replay helper threads) had a wider cell than the rows around
|
||||
it, so the cells' left edges did not line up. And a still (a headless shot, the preview) drew every list at its top
|
||||
whatever was selected, because only a window's frames stepped the scroll's easing.
|
||||
The lab's playtest (11-17) showed the Debug tab styled apart from the rest: its headings ("Player", "Story & amiibo") a
|
||||
plain gold line instead of the game's separator with its mark, a blank row's room between its groups, its own column
|
||||
geometry (names further left, value cells wider than on every other tab), and its buttons orange without an arrow where
|
||||
the System tab's were the dark panel with one. Before that it had its own layout (debug_tab_layout.h, gone now) for two
|
||||
columns that fitted at no window size.
|
||||
|
||||
Compiles and runs tests/debug_tab_layout_test.cpp: the cells' widths with the tab's own measures (one column, every cell
|
||||
the width the widest asks, the Developer row's among them), the same at 1, 1.5, 2 and 3 times the size (the layout scales
|
||||
with the window's height: two columns fit at no window size), a long name that takes the room, a column wide enough for
|
||||
two, and never a cell under its narrowest.
|
||||
|
||||
Reads the source for the rest: draw_debug_rows takes its widths from that function, clips and culls its rows by the
|
||||
column's own clip (not by the first and last whole row), and gives the mouse the same; a still is drawn settled.
|
||||
Now the tab is a list as the others are: draw_options draws it with the same rows, cells, headings and scroll, in the
|
||||
order debug_list gives (the Debug tools switch, each group of tools under its heading, the Developer heading and its
|
||||
rows). This compiles debug_list and debug_step from the source with a made-up table of rows and checks: no blank entry,
|
||||
a group with no row shown has no heading, every heading has a row under it, the tools gone with the switch off leave the
|
||||
switch and the Developer rows, and Up and Down walk the rows over the headings. The rest is read in the source: one
|
||||
drawing loop for every tab, the headings ui::heading's, one action-button style (action_cell: the orange plate with its
|
||||
arrow) on every tab, and a still drawn settled.
|
||||
|
||||
python -I -B tests/test_debug_tab_layout.py [--cxx g++]
|
||||
"""
|
||||
@@ -21,7 +21,7 @@ import subprocess
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
RUN_ALL_ARGS = ["--cxx", "g++"]
|
||||
RUN_ALL_ARGS = ["--cxx", "{cxx}"]
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
@@ -41,37 +41,156 @@ def function(text, head):
|
||||
return text[start:end]
|
||||
|
||||
|
||||
FIXTURE = r'''#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <initializer_list>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
#define CHECK(x) do { if (!(x)) { std::fprintf(stderr, "FAIL:%d %s\n", __LINE__, #x); std::exit(1); } } while (0)
|
||||
enum MenuTab { TAB_DISPLAY = 0, TAB_DEBUG = 5 };
|
||||
struct { int debug_tools, reuse, robust; } opts;
|
||||
struct Row { MenuTab tab; const char* name; int* value; signed char cheat; bool heading; };
|
||||
// (the tab's rows in the table's order, as vk_menu.cpp has them: the switch, the tools by their number, Developer)
|
||||
Row rows[] = {{TAB_DISPLAY, "Elsewhere", &opts.reuse, -1, false}, {TAB_DEBUG, "Debug tools", &opts.debug_tools, -1, false},
|
||||
{TAB_DEBUG, "Heart protection", nullptr, 0, false}, {TAB_DEBUG, "No-clip flight", nullptr, 1, false},
|
||||
{TAB_DEBUG, "Mark position", nullptr, 2, false}, {TAB_DEBUG, "Return to mark", nullptr, 3, false},
|
||||
{TAB_DEBUG, "Set time", nullptr, 4, false}, {TAB_DEBUG, "Inventory item", nullptr, 5, false},
|
||||
{TAB_DEBUG, "Change quantity", nullptr, 6, false}, {TAB_DEBUG, "Free camera", nullptr, 7, false},
|
||||
{TAB_DEBUG, "Teleport", nullptr, 8, false}, {TAB_DEBUG, "Switch age", nullptr, 9, false},
|
||||
{TAB_DEBUG, "Inventory", nullptr, 10, false}, {TAB_DEBUG, "Game flags", nullptr, 11, false},
|
||||
{TAB_DEBUG, "Cutscenes", nullptr, 12, false}, {TAB_DEBUG, "Scan amiibo", nullptr, 13, false},
|
||||
{TAB_DEBUG, "Developer", nullptr, -1, true}, {TAB_DEBUG, "Descriptor reuse", &opts.reuse, -1, false},
|
||||
{TAB_DEBUG, "Robust buffers", &opts.robust, -1, false}};
|
||||
constexpr int kRows = sizeof rows / sizeof rows[0];
|
||||
static bool hidden[kRows];
|
||||
static bool row_shown(int i) { return !hidden[i]; }
|
||||
int tab_row_count(int t) {
|
||||
int c = 0;
|
||||
for (int i = 0; i < kRows; i++) if (rows[i].tab == (MenuTab)t && row_shown(i)) c++;
|
||||
return c;
|
||||
}
|
||||
int tab_row_to_global(int t, int local_idx) {
|
||||
int count = 0;
|
||||
for (int i = 0; i < kRows; i++)
|
||||
if (rows[i].tab == (MenuTab)t && row_shown(i)) {
|
||||
if (count == local_idx) return i;
|
||||
count++;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@DEBUG@
|
||||
static std::vector<const char*> names() { // (the list as drawn: a heading's title or a row's name)
|
||||
int list[kDebugList];
|
||||
const int n = debug_list(list);
|
||||
std::vector<const char*> out;
|
||||
for (int j = 0; j < n; j++) out.push_back(list[j] < 0 ? debug_groups[-1 - list[j]].title : rows[tab_row_to_global(TAB_DEBUG, list[j])].name);
|
||||
return out;
|
||||
}
|
||||
static bool same(const std::vector<const char*>& got, std::initializer_list<const char*> want) {
|
||||
if (got.size() != want.size()) return false;
|
||||
size_t i = 0;
|
||||
for (const char* w : want) {
|
||||
if (std::string_view(got[i]) != w) return false;
|
||||
i++;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
static void show(const std::vector<const char*>& v) { for (const char* s : v) std::fprintf(stderr, " %s\n", s); }
|
||||
static int local(const char* name) { // (a row's number on the tab)
|
||||
const int n = tab_row_count(TAB_DEBUG);
|
||||
for (int k = 0; k < n; k++) if (std::string_view(rows[tab_row_to_global(TAB_DEBUG, k)].name) == name) return k;
|
||||
return -1;
|
||||
}
|
||||
int main() {
|
||||
hidden[7] = hidden[8] = true; // (Inventory item and Change quantity: never on the tab)
|
||||
std::vector<const char*> v = names();
|
||||
if (!same(v, {"Debug tools", "Player", "Heart protection", "No-clip flight", "Switch age", "Inventory", "Story & amiibo",
|
||||
"Game flags", "Cutscenes", "Scan amiibo", "Travel", "Teleport", "Mark position", "Return to mark",
|
||||
"Camera & world", "Free camera", "Set time", "Developer", "Descriptor reuse", "Robust buffers"})) {
|
||||
show(v);
|
||||
CHECK(!"the tab's list with every tool");
|
||||
}
|
||||
// (the tools off: they are not shown, nor their headings)
|
||||
for (int i = 2; i <= 15; i++) hidden[i] = true;
|
||||
v = names();
|
||||
if (!same(v, {"Debug tools", "Developer", "Descriptor reuse", "Robust buffers"})) {
|
||||
show(v);
|
||||
CHECK(!"the tab's list with the tools off");
|
||||
}
|
||||
// (a group none of whose rows is shown: no heading, no room)
|
||||
for (int i = 2; i <= 15; i++) hidden[i] = i == 7 || i == 8 || i == 4 || i == 5 || i == 10;
|
||||
v = names();
|
||||
if (!same(v, {"Debug tools", "Player", "Heart protection", "No-clip flight", "Switch age", "Inventory", "Story & amiibo",
|
||||
"Game flags", "Cutscenes", "Scan amiibo", "Camera & world", "Free camera", "Set time", "Developer",
|
||||
"Descriptor reuse", "Robust buffers"})) {
|
||||
show(v);
|
||||
CHECK(!"the tab's list without the Travel rows");
|
||||
}
|
||||
// Up and Down: the rows in the list's order, over the headings, round at the ends
|
||||
CHECK(debug_step(local("Debug tools"), 1) == local("Heart protection"));
|
||||
CHECK(debug_step(local("Inventory"), 1) == local("Game flags"));
|
||||
CHECK(debug_step(local("Set time"), 1) == local("Descriptor reuse"));
|
||||
CHECK(debug_step(local("Robust buffers"), 1) == local("Debug tools"));
|
||||
CHECK(debug_step(local("Debug tools"), -1) == local("Robust buffers"));
|
||||
CHECK(debug_step(local("Game flags"), -1) == local("Inventory"));
|
||||
std::puts("ok");
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument("--cxx", default="g++")
|
||||
a = p.parse_args()
|
||||
menu = (ROOT / "gpu/vk/vk_menu.cpp").read_text(encoding="utf-8")
|
||||
draw = function(menu, "void draw_debug_rows(")
|
||||
check("void draw_debug_rows(ui::Ctx& c, float cx0, float cx1, float top, float bottom, float clip0, float clip1, int sel) {" in draw
|
||||
and "draw_debug_rows(c, cx0, cx1, top, bottom, clip0, clip1, sel);" in function(menu, "void draw_options(ui::Ctx& c) {"),
|
||||
"the Debug tab is not given the column's clip")
|
||||
check("c.d->PushClipRect(ImVec2(cx0, clip0), ImVec2(cx1, std::max(clip0, clip1)), true);" in draw, "the Debug tab's rows are not clipped as the other tabs'")
|
||||
check(draw.count("if (y + pitch <= clip0 || y >= clip1)") == 2 and "<= top || y >= bottom" not in draw,
|
||||
"a row or a heading is left out, or cut, at the first or last whole row")
|
||||
check("hits.add(x0, std::max(y, clip0), x1, std::min(y + rh, clip1), menu_hit::kRow, k, va.x, vb.x, 0, 0, 0, vm);" in draw,
|
||||
"the mouse's rows are not what shows of them") # ((Triforce) vm: where a toggle's halves meet, tests/test_menu_hit.py)
|
||||
check("scroll_rows(TAB_DEBUG, visual_count, sel_at, top, bottom, pitch, &shown)" in draw, "the scroll no longer counts whole rows between top and bottom")
|
||||
check("debug_tab::widths(col_w, right - left, name_need, cell_full, cell_tight, span_need)" in draw
|
||||
and "if (i == 0 || i >= dev) span_need = std::max(span_need, need(" in draw, "the cells' widths are not debug_tab_layout.h's")
|
||||
check("const float width = in_tools ? cell_w[vcol[i]] : span_w;" in draw, "the switch's and the Developer rows' cells are not one width")
|
||||
ui = (ROOT / "gpu/vk/vk_ui.h").read_text(encoding="utf-8")
|
||||
check("draw_debug_rows" not in menu and not (ROOT / "gpu/vk/debug_tab_layout.h").exists(),
|
||||
"the Debug tab still has a layout of its own")
|
||||
draw = function(menu, "void draw_options(ui::Ctx& c) {")
|
||||
# one list, one loop, for every tab: the Debug tab's entries are debug_list's
|
||||
check("if (cur_tab == TAB_DEBUG) listed = debug_list(list);" in draw and "return;" not in draw[:draw.index("PushClipRect")],
|
||||
"the Debug tab is not drawn by the tabs' own loop")
|
||||
check("scroll_rows(cur_tab, listed, sel_at, top, bottom, pitch, &shown)" in draw, "the Debug tab's list does not scroll as the others")
|
||||
# its headings the game's separator and title, as the others'
|
||||
check("ui::heading(c, ImVec2(rx0, y), ImVec2(rx1, y + rh), rx0 + ui::lu(c, 72), i < 0 ? debug_groups[-1 - i].title : r.name);" in draw
|
||||
and "AddLine(" not in draw, "a Debug group's heading is not the game's separator and title")
|
||||
check("separator(c, " in function(ui, "inline void heading("), "ui::heading has no separator")
|
||||
# its rows the same cells: the tools' toggles, Link's age, choices and buttons
|
||||
check("} else if (r.cheat >= 0) {" in draw and 'halves_cell(c, va, vb, "On", "Off", cheat_value(r.cheat) != "On", selected, false);' in draw
|
||||
and 'halves_cell(c, va, vb, "Kid", "Adult", link_age.load(std::memory_order_relaxed) == 1, selected, false);' in draw,
|
||||
"the debug tools' toggles are not the tabs' halves")
|
||||
# one action-button style: the orange plate with its arrow, on the System tab's rows as on the Debug tab's
|
||||
action = function(menu, "void action_cell(")
|
||||
check("choice_cell(c, a, b, word, sel, false, !fixed, fixed);" in action, "action_cell is not the orange plate with its arrow")
|
||||
check("else action_cell(c, va, vb, v.empty() ? buttons[r.cheat] : v, selected, r.cheat == 9);" in draw
|
||||
and 'else action_cell(c, va, vb, ends ? r.name : share_row(r) ? share_label(share_row(r)) : "Open", selected);' in draw,
|
||||
"the Debug tab's buttons and the page, save, Restart and Quit rows are not one style")
|
||||
check(", false, true, false, true)" not in draw, "a row still draws its button as the dark panel")
|
||||
# the rows clipped as the other tabs': none under the header
|
||||
check("if (y < clip0 || y > clip1) continue;" in draw, "a row is drawn with its top under the header")
|
||||
check("hits.add(rx0, std::max(y, clip0), rx1, std::min(y + rh, clip1), menu_hit::kRow, i, va.x, vb.x, t0, t1, 0, vm);" in draw,
|
||||
"the mouse's rows are not what shows of them")
|
||||
# Up and Down on the tab walk debug_list's order
|
||||
tick = function(menu, "void menu_tick() {")
|
||||
check("selected = debug_step(selected, press[2] ? 1 : -1);" in tick, "Up and Down do not walk the Debug tab's order")
|
||||
# a still is drawn settled: only menu_record, a window's frames, steps the easing
|
||||
image = function(menu, "void menu_record_image(")
|
||||
record = function(menu, "void menu_record(VkCommandBuffer cmd, uint32_t index")
|
||||
check("if (!ease_live) ease_step = 1.0f;" in image and image.index("if (!ease_live) ease_step = 1.0f;") < image.index("draw_menu(c"),
|
||||
"a still does not draw the lists where the selection asks")
|
||||
check("ease_live = true;" in record and "ease_live = true" not in image, "the window's frames do not keep their easing")
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
exe = Path(tmp) / "debug_tab_layout_test.exe"
|
||||
subprocess.run([a.cxx, "-std=c++20", "-O1", "-Wall", "-Wextra", "-Werror", str(ROOT / "tests/debug_tab_layout_test.cpp"), "-o", str(exe)], check=True)
|
||||
|
||||
start = menu.index("struct DebugGroup {")
|
||||
debug = menu[start:menu.index("/// (Triforce) A row that does something or opens a page")]
|
||||
fixture = FIXTURE.replace("@DEBUG@", debug)
|
||||
with tempfile.TemporaryDirectory(prefix="debug-tab-") as tmp:
|
||||
cpp, exe = Path(tmp) / "fixture.cpp", Path(tmp) / "fixture.exe"
|
||||
cpp.write_text(fixture, encoding="utf-8")
|
||||
subprocess.run([a.cxx, "-std=c++20", "-O1", "-Wall", "-Wextra", "-Werror", str(cpp), "-o", str(exe)], check=True)
|
||||
run = subprocess.run([str(exe)], capture_output=True, text=True)
|
||||
if run.returncode or run.stdout.strip() != "ok":
|
||||
raise SystemExit("FAIL: tests/debug_tab_layout_test.cpp (exit %d)\n%s%s" % (run.returncode, run.stdout, run.stderr))
|
||||
print("PASS: the Debug tab's cells line up, its rows are clipped as the other tabs', and a still is drawn settled")
|
||||
raise SystemExit("FAIL: the Debug tab's list (exit %d)\n%s%s" % (run.returncode, run.stdout, run.stderr))
|
||||
print("PASS: the Debug tab is a list as the other tabs are: their rows, headings, buttons and scroll, no blank rows")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -8,8 +8,8 @@ and stamp it was resolved from is the same.
|
||||
out of the source and run against stand-ins for texture_view_of, sampler_for, uniform_range and the generations
|
||||
(tests/desc_keep_test.cpp), which count their calls: a texture is looked up again when its slot is registered anew, a sampler
|
||||
registration changed, a texture was destroyed or made again (issue 1126), a frame left a texture for later, or the submission
|
||||
is a new one; a uniform buffer when an inline update came, a pool moved or a mirror was made (gpu_bind_stamp), or the recording
|
||||
is another; c1 within its recording; never a failed one, a copy in the recording's stream, or a driver bank. A generation that
|
||||
is a new one, or the draw is the jittered scene where the last was not (its own, biased sampler); a uniform buffer when an
|
||||
inline update came, a pool moved or a mirror was made (gpu_bind_stamp), or the recording is another; c1 within its recording; never a failed one, a copy in the recording's stream, or a driver bank. A generation that
|
||||
moves while its lookup runs makes the next one look again. RX_VK_DESC_KEEP=check resolves every time and counts and logs one
|
||||
that comes out otherwise; =0, RX_VK_NO_DESC_REUSE, RX_VK_SAMPLER_CACHE=0 and RX_VK_LATE_DEFER turn it off.
|
||||
3. build_descriptors itself (source): only a draw's build keeps (not a dispatch's, a dump's or the temporal upscaler's second
|
||||
@@ -28,7 +28,7 @@ RUN_ALL_ARGS = ["--cxx", "{cxx}", "--headers", "{vulkan_headers}"]
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
CASES = ["header", "on", "off", "no-reuse", "sampler-cache-off", "late-defer", "texture", "compute", "texture-moved", "texture-dummy", "texture-dummy-redrawn",
|
||||
"texture-no-sampler", "uniform", "uniform-stream", "uniform-moved", "c1", "storage", "check", "check-bad"]
|
||||
"texture-scene", "texture-no-sampler", "uniform", "uniform-stream", "uniform-moved", "c1", "storage", "check", "check-bad"]
|
||||
|
||||
|
||||
def block(text, marker):
|
||||
@@ -50,11 +50,13 @@ def check_build(source):
|
||||
build = block(source, "void build_descriptors(")
|
||||
need("desc_keep::Prog* const kp = keep && desc_keep_mode() && !dump_on() && !pre_retarget_on" in build,
|
||||
"build_descriptors keeps descriptors outside a draw's own build")
|
||||
need("build_descriptors(s, p, true);" in block(source, "void draw(VkCommandBuffer"), "a draw does not keep its descriptors")
|
||||
need(source.count("build_descriptors(s, p, true)") == 1, "something other than a draw keeps descriptors")
|
||||
need("build_descriptors(s, p, true, scene);" in block(source, "void draw(VkCommandBuffer"), "a draw does not keep its descriptors")
|
||||
need(source.count("build_descriptors(s, p, true") == 1, "something other than a draw keeps descriptors")
|
||||
need(build.count("jn += d.count;") == 5, "a descriptor kind does not move the place counter: kept results would be another's")
|
||||
need("kept_uniform(kp, jb + k, s, st, d.index + k)" in build, "the uniform buffers do not go through kept_uniform")
|
||||
need("kept_texture(kp, jb + k, handle, vt, d.is_depth" in build, "the sampled textures do not go through kept_texture")
|
||||
need("st.vk_stage == VK_SHADER_STAGE_COMPUTE_BIT,\n scene, &view, &tex);" in build,
|
||||
"the sampled textures are not given the draw's scene flag (the upscaler's texture LOD bias)")
|
||||
need("sampler_for(" not in build and "texture_view_of(handle, vt, ViewUse::Sample" not in build,
|
||||
"a sampled texture is looked up past kept_texture")
|
||||
ssbo = build[build.index("for (const auto& d : info.storage_buffers_descriptors)"):build.index("auto texel_views")]
|
||||
|
||||
@@ -91,8 +91,8 @@ def check_source(source):
|
||||
fails)
|
||||
need("const bool same_desc = same_gens || (sig_hit && sig_mode == 1);" in draw, "a checked hit is not built", fails)
|
||||
build = draw[draw.index("if (!same_desc) {"):]
|
||||
before(build, "const int64_t drops = desc_drops", "build_descriptors(s, p, true);", "the drops are not read before the build", fails)
|
||||
before(build, "build_descriptors(s, p, true);", "sig_armed = desc_drops == drops;", "the signature is armed before the build", fails)
|
||||
before(build, "const int64_t drops = desc_drops", "build_descriptors(s, p, true, scene);", "the drops are not read before the build", fails)
|
||||
before(build, "build_descriptors(s, p, true, scene);", "sig_armed = desc_drops == drops;", "the signature is armed before the build", fails)
|
||||
need("sig_armed &= b.buffer != VK_NULL_HANDLE;" in build, "a bank not made arms the signature", fails)
|
||||
need("sig.tex.assign(built_textures().begin(), built_textures().end());" in build, "the build's textures are not kept", fails)
|
||||
bind = draw[draw.index("FINE_SCOPE(FT_BINDDESC);"):]
|
||||
|
||||
160
tests/test_dialog_dim.py
Normal file
160
tests/test_dialog_dim.py
Normal file
@@ -0,0 +1,160 @@
|
||||
"""Our dialogs' dim leaves the black bars beside or above the game's picture black, the Full panel bright over it
|
||||
(gpu/vk/game_grid.h dim_parts, vk_menu.cpp dim_window, dim_page, draw_quit_ask, draw_menu; no game).
|
||||
|
||||
(Triforce, 11-20) The lab's check 3 of 26670c0: under our dialogs (Quit, and the restart question's and the Mods dialogs'
|
||||
dim through dim_page, which dim the whole window since 26670c0) "the black bars turn a dark brown": luminance 0 before,
|
||||
8.6 to 8.9 settled (the dim rgba(8, 5, 2, a) is lighter than black). Over the picture the dim's look is to stay as it is.
|
||||
And the stats panel: the game's own dialogs never dim our overlay, and over Quit's dialog the panel stayed bright, but the
|
||||
restart question's, the Mods dialogs' and the keyboard's dim went over it (26670c0): our dialogs dimmed it partly. Now it
|
||||
is over the dim under all of ours (test_options_tabs_grid.py checks the draw list's order).
|
||||
|
||||
1. game_grid.h alone: the dim's parts for the lab's shapes and others: the picture first (the dim's colour), then the
|
||||
bars (black), none overlapping, together exactly the window; with no picture known, the window in one part.
|
||||
2. The blend: a black bar pixel under each dim (alpha 110, 120, 220) stays 0 in the bars' part; over the picture the
|
||||
result is the same as with the old one rectangle.
|
||||
3. The source: dim_window draws the bars black at the dim's alpha, the picture in its colour; dim_page and Quit's dialog
|
||||
dim through it; draw_ask, mods_dialog and mods_keyboard through dim_page. ((11-20, a review of 408e2dc) dim_page cuts
|
||||
the bars black only inside the game's Options screen; over play our own background is under the bars, one rectangle.
|
||||
|
||||
python -I -B tests/test_dialog_dim.py [--cxx clang++]
|
||||
"""
|
||||
import argparse
|
||||
import subprocess
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
VK = ROOT / "gpu" / "vk"
|
||||
RUN_ALL_ARGS = ["--cxx", "{cxx}"]
|
||||
|
||||
|
||||
def check(ok, why):
|
||||
if not ok:
|
||||
raise SystemExit("FAIL: " + why)
|
||||
|
||||
|
||||
def block(text, head):
|
||||
start = text.index(head)
|
||||
end = text.index("{", start) + 1
|
||||
depth = 1
|
||||
while depth:
|
||||
depth += (text[end] == "{") - (text[end] == "}")
|
||||
end += 1
|
||||
return text[start:end]
|
||||
|
||||
|
||||
GRID = r"""
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdint>
|
||||
#include "game_grid.h"
|
||||
using namespace mkwvk;
|
||||
static int fails = 0;
|
||||
#define CHECK(x) do { if (!(x)) { std::printf("FAIL:%d %s\n", __LINE__, #x); fails++; } } while (0)
|
||||
static float area(const game_grid::Rect& r) { return (r.x1 - r.x0) * (r.y1 - r.y0); }
|
||||
static bool overlap(const game_grid::Rect& a, const game_grid::Rect& b) {
|
||||
return std::fmin(a.x1, b.x1) > std::fmax(a.x0, b.x0) && std::fmin(a.y1, b.y1) > std::fmax(a.y0, b.y0);
|
||||
}
|
||||
// (the source-over blend of one 8-bit channel, as the overlay's pipeline: dst (1 - a) + src a)
|
||||
static float over(float dst, float src, float a) { return dst * (1 - a) + src * a; }
|
||||
int main() {
|
||||
const double r21 = 64.0 / 27.0, r1610 = 16.0 / 10.0, r32 = 32.0 / 9.0;
|
||||
const struct { uint32_t pw, ph, ww, wh; double r; int bars; const char* what; } cases[] = {
|
||||
{3416, 1440, 1600, 900, r21, 2, "1600 x 900, 21:9 picture (bars above and below: the lab's)"},
|
||||
{3416, 1440, 3440, 1440, r21, 2, "fullscreen 3440 x 1440, 21:9 (64:27 a little narrower: bars at the sides)"},
|
||||
{3416, 1440, 1720, 720, r21, 2, "1720 x 720, 21:9"},
|
||||
{2304, 1440, 1680, 1050, r1610, 0, "1680 x 1050, 16:10 (the picture the whole window)"},
|
||||
{2560, 1440, 1920, 1080, 0, 0, "16:9"},
|
||||
{5120, 1440, 1920, 1080, r32, 2, "32:9 picture in a 16:9 window"},
|
||||
{1600, 1200, 1920, 1080, 0, 2, "4:3 picture in a 16:9 window"},
|
||||
{2560, 1440, 1601, 901, 0, -1, "an odd 16:9 window"},
|
||||
};
|
||||
for (const auto& k : cases) {
|
||||
const game_grid::Place g = game_grid::of(k.pw, k.ph, k.ww, k.wh, k.r);
|
||||
game_grid::Rect r[5];
|
||||
const int n = game_grid::dim_parts(g, (float)k.ww, (float)k.wh, r);
|
||||
float sum = 0;
|
||||
for (int i = 0; i < n; i++) {
|
||||
sum += area(r[i]);
|
||||
CHECK(area(r[i]) > 0);
|
||||
for (int j = 0; j < i; j++) CHECK(!overlap(r[i], r[j]));
|
||||
}
|
||||
std::printf("%-70s picture %g,%g %gx%g, %d bars\n", k.what, g.pic_x, g.pic_y, g.pic_w, g.pic_h, n - 1);
|
||||
CHECK(std::fabs(sum - (float)k.ww * k.wh) < 0.5f); // (the window exactly)
|
||||
CHECK(r[0].x0 == g.pic_x && r[0].y0 == g.pic_y && r[0].x1 == g.pic_x + g.pic_w && r[0].y1 == g.pic_y + g.pic_h);
|
||||
if (k.bars >= 0) CHECK(n - 1 == k.bars);
|
||||
}
|
||||
// the lab's window: the picture 1600 x 675 from 112 down, the bars above (112) and below (113) it
|
||||
{
|
||||
game_grid::Rect r[5];
|
||||
CHECK(game_grid::dim_parts(game_grid::of(3416, 1440, 1600, 900, r21), 1600, 900, r) == 3);
|
||||
CHECK(r[0].x0 == 0 && r[0].y0 == 112 && r[0].x1 == 1600 && r[0].y1 == 787);
|
||||
CHECK(r[1].y0 == 0 && r[1].y1 == 112 && r[1].x0 == 0 && r[1].x1 == 1600);
|
||||
CHECK(r[2].y0 == 787 && r[2].y1 == 900 && r[2].x0 == 0 && r[2].x1 == 1600);
|
||||
}
|
||||
// no picture known yet: the whole window, one part
|
||||
{
|
||||
game_grid::Rect r[5];
|
||||
CHECK(game_grid::dim_parts(game_grid::of(0, 0, 1600, 900, 0), 1600, 900, r) == 1 && area(r[0]) == 1600.0f * 900);
|
||||
}
|
||||
// the blend: a bar's black under each of our dims, before (rgba(8, 5, 2, a): lifted) and now (black at a: still 0); over
|
||||
// the picture the dim's colour as it was, the same result
|
||||
for (int a8 : {110, 120, 220}) {
|
||||
const float a = a8 / 255.0f;
|
||||
CHECK(over(0, 8, a) > 3); // (was: the bar's red channel lifted, 3.5 to 6.9 of 255)
|
||||
CHECK(over(0, 0, a) == 0); // (now: black)
|
||||
for (float p : {0.0f, 20.0f, 140.0f, 255.0f}) CHECK(over(p, 0, a) <= p); // (black never lightens)
|
||||
}
|
||||
if (!fails) std::puts("the dim's parts: the picture in its colour, the bars black, the window exactly");
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--cxx", default="clang++")
|
||||
args = parser.parse_args()
|
||||
menu = (VK / "vk_menu.cpp").read_text(encoding="utf-8")
|
||||
|
||||
dw = block(menu, "void dim_window(ImDrawList* d, const game_grid::Map& m, const game_grid::Place& g, float w, float h, ImU32 col) {")
|
||||
check("const int n = game_grid::dim_parts(g, w, h, r);" in dw and "i ? (col & IM_COL32_A_MASK) : col" in dw,
|
||||
"dim_window: the bars are not black under the dim, or the picture not in its colour")
|
||||
check("m.back_x(r[i].x0), m.back_y(r[i].y0)" in dw, "dim_window: the parts are not in the drawing's pixels")
|
||||
dp = block(menu, "void dim_page(ui::Ctx& c, ImU32 col) {")
|
||||
check("dim_window(c.d, menu_map, game_black ? menu_grid(w, h) : game_grid::Place{}, w, h, col);" in dp and "AddRectFilled" not in dp,
|
||||
"dim_page: its dim is one rectangle over the whole window inside the game's Options screen, the bars lifted")
|
||||
# ((11-20, a review of 408e2dc) the bars black only where the game's own black is under the dim: inside its Options screen
|
||||
# (and the Mods entry's row); over play draw_menu covered them with our own background, one rectangle there)
|
||||
check("const bool game_black = embed_open || page == kModsRowPage;" in dp,
|
||||
"dim_page: over play (our own background over the bars) the dim is cut black at the picture's edges")
|
||||
dm = block(menu, "void draw_menu(ui::Ctx& c, bool perf_under) {")
|
||||
check("if (!embed_open && !row && !ui::system_bg(c)) c.d->AddRectFilled(ImVec2(0, 0), ImVec2(c.w, c.h), ui::rgba(8, 5, 2, ui::kDimAlpha));" in dm,
|
||||
"draw_menu: over play our background no longer covers the whole window (dim_page's one rectangle there is for it)")
|
||||
ask = block(menu, "void draw_quit_ask(ui::Ctx& c) {")
|
||||
check("dim_window(c.d, menu_map, menu_grid(menu_window_w, menu_window_h), menu_window_w, menu_window_h, ui::rgba(8, 5, 2, 220));" in ask and
|
||||
"ui::rgba(8, 5, 2, 220));" not in ask.replace("menu_window_h, ui::rgba(8, 5, 2, 220));", ""),
|
||||
"Quit's dialog: its dim is one rectangle over the whole window, the bars lifted")
|
||||
for head, dim in (("void draw_ask(ui::Ctx& c) {", "dim_page(c, ui::rgba(8, 5, 2, 110));"),
|
||||
("void mods_dialog(ui::Ctx& c, const char* title,", "dim_page(c, ui::rgba(8, 5, 2, 120));"),
|
||||
("void mods_keyboard(ui::Ctx& c) {", "dim_page(c, ui::rgba(8, 5, 2, 120));")):
|
||||
check(dim in block(menu, head), head + " its dim is not dim_page's")
|
||||
# (the Full panel over our dialogs' dim: waiting on every page but the Mods entry's, drawn after the dim)
|
||||
check(dp.index("panel_merge(c.d);") < dp.index("dim_window(") < dp.index("panel_over(c.d);"),
|
||||
"dim_page: the Full panel is under our dialog's dim (the game's own dialogs never dim the overlay)")
|
||||
check("const bool perf_between = perf_under && !row;" in block(menu, "void draw_menu(ui::Ctx& c, bool perf_under) {"),
|
||||
"draw_menu: the Full panel is drawn under the restart question's dim, or under the page over play")
|
||||
|
||||
with tempfile.TemporaryDirectory(prefix="dialog-dim-") as tmp:
|
||||
tmp = Path(tmp)
|
||||
src, exe = tmp / "grid.cpp", tmp / "grid.exe"
|
||||
src.write_text(GRID, encoding="utf-8")
|
||||
subprocess.run([args.cxx, "-std=c++20", "-O1", "-Wall", "-Wextra", "-Werror", "-I" + str(VK), str(src), "-o", str(exe)], check=True)
|
||||
r = subprocess.run([str(exe)], capture_output=True, text=True)
|
||||
print(r.stdout.strip())
|
||||
check(r.returncode == 0, "the dim's parts:\n" + r.stdout)
|
||||
print("PASS: our dialogs' dim leaves the bars black, the Full panel bright over it")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,9 +1,9 @@
|
||||
"""Who holds the frame limit while NVIDIA DLSS frame generation runs: Reflex's sleep or the game's own wait (no game, no GPU).
|
||||
|
||||
With DLSS frame generation the game's frame waited twice: the host's wait where the frame starts (host/nn_vi.c) and Reflex's
|
||||
sleep on the replay's thread after a present. With the Display tab's Reflex frame limit row on, Reflex's sleep holds the
|
||||
frame rate cap and the host's wait steps aside (gpu/vk/vk_dlssg.cpp pace, after NX2navi's vk_dlssg_pace). The rule is
|
||||
gpu/vk/dlssg_pace.h.
|
||||
sleep on the replay's thread after a present. With the Reflex frame limit on ((Triforce, options_version 7) no row:
|
||||
RX_VK_REFLEX_LIMIT=1, off otherwise until it has been played), Reflex's sleep holds the frame rate cap and the host's wait
|
||||
steps aside (gpu/vk/vk_dlssg.cpp pace, after NX2navi's vk_dlssg_pace). The rule is gpu/vk/dlssg_pace.h.
|
||||
|
||||
Compiles and runs the rule (tests/test_dlssg_pace.c, as C and as C++: vk_dlssg.cpp includes it), and reads the source for
|
||||
what cannot run without the game and NVIDIA's files: that the row is off by default and pace() does nothing then, that
|
||||
@@ -43,12 +43,20 @@ def check_source():
|
||||
real = src[src.index("#else", src.index("#ifndef HOOKSHOT_DLSSG")):]
|
||||
stubs = src[src.index("#ifndef HOOKSHOT_DLSSG"):src.index("#else", src.index("#ifndef HOOKSHOT_DLSSG"))]
|
||||
check("bool pace(int64_t) { return false; }" in stubs, "a build without Streamline no longer answers that the host waits")
|
||||
# ((Triforce, options_version 7) the Reflex frame limit row is gone and an older file's line is dropped. Its value stays
|
||||
# off, the old row's default and what nearly every file held, until Reflex holding the cap with DLSS frame generation has
|
||||
# been played on an RTX 40/50 card; RX_VK_REFLEX_LIMIT=1 turns it on for a run, as it does Reflex's hold without it)
|
||||
menu_h = (ROOT / "gpu/vk/vk_menu.h").read_text(encoding="utf-8")
|
||||
check("int reflex_limit = 0;" in menu_h, "the Reflex frame limit row is not off by default")
|
||||
check("int reflex_limit = 0;" in menu_h, "the Reflex frame limit is on although nobody has played it")
|
||||
menu = (ROOT / "gpu/vk/vk_menu.cpp").read_text(encoding="utf-8")
|
||||
check('{TAB_DISPLAY, "Reflex frame limit", &opts.reflex_limit, 0, 1, 1, tx_onoff,' in menu, "the row is not on the Display tab")
|
||||
check(menu.index('"Game frame rate cap"') < menu.index('"Reflex frame limit"') < menu.index('{TAB_DISPLAY, "VSync"'),
|
||||
"the row is not beside the Game frame rate cap")
|
||||
check('"Reflex frame limit"' not in menu, "the Reflex frame limit row is still there")
|
||||
check([line.strip() for line in menu.splitlines() if "opts.reflex_limit" in line and not line.strip().startswith("//")] ==
|
||||
['if (const char* e = getenv("RX_VK_REFLEX_LIMIT")) opts.reflex_limit = atoi(e) != 0;'],
|
||||
"the menu sets the Reflex frame limit other than from RX_VK_REFLEX_LIMIT")
|
||||
init = menu[menu.index("void menu_init() {"):]
|
||||
check('opts.reflex_limit = atoi(e) != 0;' in init[:init.index("\n}\n")], "RX_VK_REFLEX_LIMIT is not read at menu_init")
|
||||
merged = (ROOT / "gpu/vk/merged_rows.h").read_text(encoding="utf-8")
|
||||
check('"reflex_frame_limit"' in merged[merged.index("constexpr const char* kDropped[]"):], "an old reflex_frame_limit= line is kept")
|
||||
|
||||
pace = block(real, "bool pace(int64_t period_ns) {")
|
||||
# (the row off, and nothing of it left over: nothing decided, nothing asked of Streamline)
|
||||
@@ -91,7 +99,8 @@ def check_source():
|
||||
replay = (ROOT / "gpu/vk/vk_replay.cpp").read_text(encoding="utf-8")
|
||||
check("if (id == HOS_OPT_PACE_START) return pace::frame_start();" in replay and
|
||||
"if (id == HOS_OPT_PACE_PERIOD) return pace::set_period_ns(value);" in replay, "the renderer no longer answers the host")
|
||||
for doc, needle in (("readme.md", "| Reflex frame limit |"), ("docs/development.md", "`HOS_PACE_HANDOFF=0`")):
|
||||
for doc, needle in (("readme.md", "holds the frame rate cap where each frame starts in place of the game's own wait"),
|
||||
("docs/development.md", "`HOS_PACE_HANDOFF=0`")):
|
||||
check(needle in (ROOT / doc).read_text(encoding="utf-8"), doc + " does not say " + needle)
|
||||
|
||||
|
||||
|
||||
@@ -1,15 +1,20 @@
|
||||
"""The foliage in the sun's far shadow cascades drawn with one face culled (gpu/vk/foliage_shadow.h, vk_draw.cpp draw_cull;
|
||||
RX_VK_FOLIAGE_SHADOW_CULL, off unless set; no game, no GPU).
|
||||
"""The foliage in the sun's far shadow cascades made cheaper (gpu/vk/foliage_shadow.h; vk_draw.cpp draw_cull, pipeline_rate,
|
||||
draw_rate; after NX2navi's 754ded9; no game, no GPU).
|
||||
|
||||
The game draws its foliage cards double-sided with mesh programs, into the shadow cascades too, where the stacked cards seen
|
||||
from the sun cover the same texels many times over. With the switch a mesh program's draw into a cascade from the given layer
|
||||
on that culls neither face is drawn with its back (or front) faces culled. Compiles and runs the header's rule (the switch's
|
||||
values; which draws it takes: mesh programs only, no colour target, a depth target square and wider than 768, the layer, the
|
||||
game's own cull mode kept where it has one), then draw_cull cut out of vk_draw.cpp against stand-ins, in a process each for
|
||||
the switch's values (native mesh programs and the compute fallback's, the log). Reads the source for what needs the game:
|
||||
that the face goes through the packed dynamic state, so a draw into another layer with the same state is not taken for the
|
||||
same, that dynamic_state sets the cull mode from it, that the cull mode is dynamic state (no other pipeline), and that the
|
||||
switch is in the development guide.
|
||||
from the sun cover the same texels many times over. RX_VK_FOLIAGE_SHADOW_CULL (on from layer 1 unless off): a mesh program's
|
||||
draw into a cascade from that layer on that culls neither face is drawn with its back (or front) faces culled.
|
||||
RX_VK_FOLIAGE_SHADOW_VRS (on from layer 2 unless off, where the device has pipelineFragmentShadingRate): the same draws of
|
||||
native mesh programs from that layer on shade one fragment per 2 x 2 pixels, the rate dynamic state in those pipelines alone.
|
||||
|
||||
Compiles and runs the header's rules (the switches' values and defaults; which draws they take: mesh programs only, no colour
|
||||
target, a depth target square and wider than 768, the layer, the game's own cull mode kept where it has one; which pipelines
|
||||
have the rate), then draw_cull, pipeline_rate and draw_rate cut out of vk_draw.cpp against stand-ins, in a process each for the
|
||||
switches' values (native mesh programs and the compute fallback's, the log, when the rate is set again). Reads the source for
|
||||
what needs the game: that the face goes through the packed dynamic state, that the cull mode is dynamic state (no other
|
||||
pipeline), that the rate is dynamic state in pipeline_rate's pipelines alone (whole or their two shader libraries, those keyed
|
||||
apart) and set right after their bind, that the device asks for the extension only where it can be used, and that the switches
|
||||
are in the development guide.
|
||||
|
||||
python -I -B tests/test_foliage_shadow.py [--cxx g++]
|
||||
"""
|
||||
@@ -35,7 +40,7 @@ def block(text, marker):
|
||||
return text[start:end]
|
||||
|
||||
|
||||
def check_source(draw):
|
||||
def check_source(draw, main):
|
||||
if '#include "foliage_shadow.h"' not in draw:
|
||||
raise SystemExit("vk_draw.cpp does not include foliage_shadow.h")
|
||||
if "constexpr int kDynCull = 23;" not in draw:
|
||||
@@ -59,9 +64,55 @@ def check_source(draw):
|
||||
raise SystemExit("vk_draw.cpp: the cull mode is no longer dynamic state: the rule would need other pipelines")
|
||||
if draw.index("uint32_t draw_cull(") > draw.index("int dyn_pack("):
|
||||
raise SystemExit("vk_draw.cpp: draw_cull is not before dyn_pack")
|
||||
# (the shading rate: dynamic state in pipeline_rate's pipelines alone, whole or their two shader libraries)
|
||||
rate_line = ("if (pipeline_rate(p, at) && (part < 0 || part == 1 || part == 2)) "
|
||||
"dyn.push_back(VK_DYNAMIC_STATE_FRAGMENT_SHADING_RATE_KHR);")
|
||||
build = block(draw, "VkPipeline build_graphics(const Program& p, const NvnState& s, const Targets& at, VkPrimitiveTopology topo, int part, bool* cold)")
|
||||
if rate_line not in build:
|
||||
raise SystemExit("vk_draw.cpp build_graphics: the shading rate is not dynamic state in pipeline_rate's pipelines alone")
|
||||
if draw.count("VK_DYNAMIC_STATE_FRAGMENT_SHADING_RATE_KHR") != 1:
|
||||
raise SystemExit("vk_draw.cpp: the shading rate's dynamic state is named outside build_graphics's one line (every pipeline's key?)")
|
||||
if build.index(rate_line) > build.index("dy.dynamicStateCount = (uint32_t)dyn.size();"):
|
||||
raise SystemExit("vk_draw.cpp build_graphics: the shading rate is pushed after the dynamic state's count was taken")
|
||||
keys = block(draw, "void gpl_keys(")
|
||||
if "pipeline_rate(p, at) ? mix(program, kRateLibrary) : program" not in keys or \
|
||||
"keys[1] = shaders, keys[2] = mix(shaders, (uint64_t)at.samples)" not in keys:
|
||||
raise SystemExit("vk_draw.cpp gpl_keys: the shader libraries of pipelines with the rate are not keyed apart (or the others changed)")
|
||||
# (the light precompile: a depth-only note is built once more for the rate (built_key), but once its program is read one
|
||||
# whose program has no rate is left as the earlier start built it, before the workers take the notes)
|
||||
pre = draw[draw.index("const uint64_t built_stamp = warmed_stamp(gpl_wanted());"):]
|
||||
drop = "return p && !pipeline_rate(*p, note_targets(*n));"
|
||||
if "if (light && dev.foliage_rate) {" not in pre or drop not in pre or \
|
||||
not pre.index("program_cache_load_some(wanted,") < pre.index(drop) < pre.index("pre->notes = std::move(notes)"):
|
||||
raise SystemExit("vk_draw.cpp precompile_run: the depth-only notes of programs without the rate are built again (or "
|
||||
"dropped before their programs are read)")
|
||||
if "if (built_key(*n) == n->key || !built.count(n->key)) return false;" not in pre:
|
||||
raise SystemExit("vk_draw.cpp precompile_run: a note not built before, or with no rate key, is dropped by the program test")
|
||||
if "rate" in block(draw, "uint64_t pipeline_key(const Program& p, const NvnState& s, const Targets& at, VkPrimitiveTopology topo) {"):
|
||||
raise SystemExit("vk_draw.cpp pipeline_key: the rate changed the pipelines' keys (the notes and the precompile would not find them)")
|
||||
bind = draw.index("vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pl), last_pipeline = pl;")
|
||||
call = draw.index("if (pipeline_rate(p, at)) draw_rate(cmd, s, at, bound);")
|
||||
if not bind < call < draw.index("if (!bind_descriptors(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, p)) SKIP_HERE();", bind):
|
||||
raise SystemExit("vk_draw.cpp draw: the rate is not set right after the pipeline's bind (a draw left out between would leave it unset)")
|
||||
if "const bool bound = pl != last_pipeline;" not in draw[bind - 400:bind]:
|
||||
raise SystemExit("vk_draw.cpp draw: draw_rate is not told whether the pipeline was bound for this draw")
|
||||
# (the device: the extension only where it is of use, the rate per draw only)
|
||||
for needle in ("if (dev.mesh_shader && rate_from >= 0) optional(VK_KHR_FRAGMENT_SHADING_RATE_EXTENSION_NAME, rate_ext);",
|
||||
"rate.attachmentFragmentShadingRate = rate.primitiveFragmentShadingRate = VK_FALSE;",
|
||||
"dev.foliage_rate = rate_ext && rate.pipelineFragmentShadingRate && dev.mesh_shader;",
|
||||
"*rate_at = rate.pNext;"):
|
||||
if needle not in main:
|
||||
raise SystemExit("vk_main.cpp create_device lacks %r" % needle)
|
||||
if not main.index("dev.mesh_shader = dev.mesh_shader && mesh.meshShader && mesh.taskShader;") < \
|
||||
main.index("dev.foliage_rate = rate_ext") < main.index("VkResult made = vkCreateDevice("):
|
||||
raise SystemExit("vk_main.cpp create_device: dev.foliage_rate is not decided between the mesh shaders' and the device's creation")
|
||||
rec = (ROOT / "gpu/vk/vk_recorder.h").read_text(encoding="utf-8")
|
||||
if "A(vkCmdSetFragmentShadingRateKHR)" not in rec or "pk_vkCmdSetFragmentShadingRateKHR" not in rec:
|
||||
raise SystemExit("vk_recorder.h does not carry vkCmdSetFragmentShadingRateKHR (RX_VK_RECORDER would make it out of order)")
|
||||
dev = (ROOT / "docs/development.md").read_text(encoding="utf-8")
|
||||
if "`RX_VK_FOLIAGE_SHADOW_CULL=<layer>[f]`" not in dev:
|
||||
raise SystemExit("docs/development.md: RX_VK_FOLIAGE_SHADOW_CULL is not in the switches table")
|
||||
for switch in ("`RX_VK_FOLIAGE_SHADOW_CULL=<layer>[f]`", "`RX_VK_FOLIAGE_SHADOW_VRS=<layer>`"):
|
||||
if switch not in dev:
|
||||
raise SystemExit("docs/development.md: %s is not in the switches table" % switch)
|
||||
|
||||
|
||||
HEADER_TEST = r'''
|
||||
@@ -71,8 +122,9 @@ HEADER_TEST = r'''
|
||||
#define CHECK(x) do { if (!(x)) { std::fprintf(stderr, "FAIL:%d %s\n", __LINE__, #x); std::exit(1); } } while (0)
|
||||
using namespace mkwvk::foliage_shadow;
|
||||
int main() {
|
||||
CHECK(parse(nullptr).from == -1);
|
||||
CHECK(parse("").from == -1);
|
||||
// (the cull: on from layer 1 unless off, NX2navi's)
|
||||
CHECK(parse(nullptr).from == 1 && !parse(nullptr).front);
|
||||
CHECK(parse("").from == 1);
|
||||
CHECK(parse("off").from == -1);
|
||||
CHECK(parse("-1").from == -1);
|
||||
CHECK(parse("f").from == -1);
|
||||
@@ -81,7 +133,7 @@ int main() {
|
||||
CHECK(parse("0").from == 0 && !parse("0").front);
|
||||
CHECK(parse("2f").from == 2 && parse("2f").front);
|
||||
CHECK(parse("3").from == 3);
|
||||
const Rule off = parse(nullptr), one = parse("1"), one_front = parse("1f"), zero = parse("0"), three = parse("3");
|
||||
const Rule off = parse("off"), one = parse(nullptr), one_front = parse("1f"), zero = parse("0"), three = parse("3");
|
||||
// (off: the game's face, whatever the draw)
|
||||
for (int game = 0; game < 4; game++) CHECK(cull(off, game, true, 0, true, 1600, 1600, 2) == game);
|
||||
// (the far cascades of the sun's three, 1600 x 1600: from layer 1 on)
|
||||
@@ -106,7 +158,31 @@ int main() {
|
||||
CHECK(cull(one, kNone, true, 0, true, 260, 260, 5) == kNone);
|
||||
CHECK(cull(one, kNone, true, 0, true, 1600, 900, 1) == kNone);
|
||||
CHECK(cull(one, kNone, true, 0, true, 1600, 1601, 1) == kNone);
|
||||
std::printf("PASS: the rule: the switch's values, the draws it takes and the ones it leaves\n");
|
||||
// (the rate: on from layer 2 unless off, NX2navi's)
|
||||
CHECK(parse_rate(nullptr) == 2 && parse_rate("") == 2);
|
||||
CHECK(parse_rate("off") == -1 && parse_rate("-1") == -1 && parse_rate("x") == -1);
|
||||
CHECK(parse_rate("1") == 1 && parse_rate("0") == 0 && parse_rate("3") == 3);
|
||||
const int r2 = parse_rate(nullptr), r_off = parse_rate("off"), r3 = parse_rate("3");
|
||||
CHECK(rate(r2, kNone, true, 0, true, 1600, 1600, 2) == 2); // (the far cascade's foliage: 2 x 2)
|
||||
CHECK(rate(r2, kNone, true, 0, true, 1600, 1600, 1) == 1); // (the middle and near ones: as the game draws them)
|
||||
CHECK(rate(r2, kNone, true, 0, true, 1600, 1600, 0) == 1);
|
||||
CHECK(rate(parse_rate("1"), kNone, true, 0, true, 1600, 1600, 1) == 2);
|
||||
CHECK(rate(r_off, kNone, true, 0, true, 1600, 1600, 2) == 1);
|
||||
CHECK(rate(r3, kNone, true, 0, true, 1600, 1600, 2) == 1);
|
||||
CHECK(rate(r2, kBack, true, 0, true, 1600, 1600, 2) == 1); // (single-sided as the game draws it: not the cards)
|
||||
CHECK(rate(r2, kFront, true, 0, true, 1600, 1600, 2) == 1);
|
||||
CHECK(rate(r2, kNone, false, 0, true, 1600, 1600, 2) == 1);
|
||||
CHECK(rate(r2, kNone, true, 1, true, 1600, 1600, 2) == 1);
|
||||
CHECK(rate(r2, kNone, true, 0, false, 1600, 1600, 2) == 1);
|
||||
CHECK(rate(r2, kNone, true, 0, true, 768, 768, 2) == 1); // (a character's own shadow map)
|
||||
CHECK(rate(r2, kNone, true, 0, true, 1600, 900, 2) == 1);
|
||||
// (the pipelines with the rate dynamic: native mesh programs, no colour target, a depth one, the rate on the device)
|
||||
CHECK(pipeline_rate(true, true, 0, true));
|
||||
CHECK(!pipeline_rate(false, true, 0, true));
|
||||
CHECK(!pipeline_rate(true, false, 0, true));
|
||||
CHECK(!pipeline_rate(true, true, 1, true));
|
||||
CHECK(!pipeline_rate(true, true, 0, false));
|
||||
std::printf("PASS: the rules: the switches' values, the draws they take and the ones they leave, the pipelines with the rate\n");
|
||||
}
|
||||
'''
|
||||
|
||||
@@ -118,9 +194,20 @@ FUNCTION_TEST = r'''
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include "foliage_shadow.h"
|
||||
#define CHECK(x) do { if (!(x)) { std::fprintf(stderr, "FAIL:%d %s\n", __LINE__, #x); std::exit(1); } } while (0)
|
||||
enum { NVN_FACE_NONE = 0, NVN_FACE_FRONT = 1, NVN_FACE_BACK = 2, NVN_FACE_FRONT_AND_BACK = 3 };
|
||||
typedef struct Cmd_T* VkCommandBuffer;
|
||||
#define VK_NULL_HANDLE nullptr
|
||||
enum VkFormat { VK_FORMAT_UNDEFINED = 0, VK_FORMAT_D32_SFLOAT = 126, VK_FORMAT_S8_UINT = 127 };
|
||||
struct VkExtent2D { uint32_t width, height; };
|
||||
enum VkFragmentShadingRateCombinerOpKHR { VK_FRAGMENT_SHADING_RATE_COMBINER_OP_KEEP_KHR = 0, VK_FRAGMENT_SHADING_RATE_COMBINER_OP_MAX_KHR = 3 };
|
||||
struct RateCall { VkCommandBuffer cmd; uint32_t w, h; int op0, op1; };
|
||||
std::vector<RateCall> rate_calls;
|
||||
void vkCmdSetFragmentShadingRateKHR(VkCommandBuffer cmd, const VkExtent2D* e, const VkFragmentShadingRateCombinerOpKHR ops[2]) {
|
||||
rate_calls.push_back({cmd, e->width, e->height, (int)ops[0], (int)ops[1]});
|
||||
}
|
||||
namespace mkwvk {
|
||||
std::string logged;
|
||||
void logf(const char* fmt, ...) {
|
||||
@@ -134,22 +221,27 @@ void logf(const char* fmt, ...) {
|
||||
}
|
||||
struct NvnState { struct { uint32_t cull : 2, front : 1, mode : 2, offset_en : 3; } poly{}; };
|
||||
struct Texture { int id; };
|
||||
struct Targets { int n = 0; Texture* depth = nullptr; uint32_t width = 0, height = 0, depth_layer = 0; };
|
||||
struct Targets { int n = 0; Texture* depth = nullptr; uint32_t width = 0, height = 0, depth_layer = 0; VkFormat depth_format = VK_FORMAT_UNDEFINED; };
|
||||
struct Program { bool mesh = false, fallback = false; uint64_t key = 0; };
|
||||
struct Device { bool foliage_rate = false; } dev;
|
||||
bool depth_aspect(VkFormat f) { return f == VK_FORMAT_D32_SFLOAT; }
|
||||
thread_local const Program* cur_program = nullptr;
|
||||
/* FUNCTION */
|
||||
thread_local VkCommandBuffer rate_cmd = VK_NULL_HANDLE;
|
||||
thread_local uint32_t rate_size = 0;
|
||||
/* FUNCTIONS */
|
||||
} // namespace mkwvk
|
||||
using namespace mkwvk;
|
||||
int main(int argc, char** argv) {
|
||||
CHECK(argc == 3);
|
||||
const int want = std::atoi(argv[1]); // (the face the far cascades' foliage gets: 0 the game's none, 1 front, 2 back)
|
||||
CHECK(argc == 4);
|
||||
const int want = std::atoi(argv[1]); // (the face the far cascades' foliage gets: 0 the game's none, 1 front, 2 back)
|
||||
const int near_face = std::atoi(argv[2]); // (and the near cascade's, layer 0)
|
||||
const int rate_from = std::atoi(argv[3]); // (the first layer at 2 x 2; -1 none)
|
||||
Texture cascades{1};
|
||||
Program native{true, false, 0x1111}, fallback{false, true, 0x2222}, vertex{false, false, 0x3333};
|
||||
NvnState s;
|
||||
s.poly.cull = NVN_FACE_NONE;
|
||||
Targets at;
|
||||
at.depth = &cascades, at.width = at.height = 1600, at.depth_layer = 2;
|
||||
at.depth = &cascades, at.width = at.height = 1600, at.depth_layer = 2, at.depth_format = VK_FORMAT_D32_SFLOAT;
|
||||
cur_program = &native;
|
||||
CHECK((int)draw_cull(s, at) == want);
|
||||
cur_program = &fallback; // (the compute fallback's draw of a mesh program: the same)
|
||||
@@ -171,17 +263,69 @@ int main(int argc, char** argv) {
|
||||
at.n = 0, at.width = at.height = 768; // (a character's own shadow map)
|
||||
CHECK(draw_cull(s, at) == NVN_FACE_NONE);
|
||||
const bool on = want != 0;
|
||||
CHECK((logged.find("vk: RX_VK_FOLIAGE_SHADOW_CULL=") != std::string::npos) == on);
|
||||
CHECK((logged.find("faces culled (=off: as the game draws them)") != std::string::npos) == on);
|
||||
CHECK((logged.find("cull as the game asks") != std::string::npos) == !on);
|
||||
CHECK((logged.find("vk: foliage shadow cull: program 0000000000001111") != std::string::npos) == on);
|
||||
CHECK((logged.find("vk: foliage shadow cull: program 0000000000002222") != std::string::npos) == on);
|
||||
CHECK(logged.find("0000000000003333") == std::string::npos);
|
||||
std::printf("PASS: RX_VK_FOLIAGE_SHADOW_CULL=%s: the far cascades' foliage culls %s\n", std::getenv("RX_VK_FOLIAGE_SHADOW_CULL") ?
|
||||
std::getenv("RX_VK_FOLIAGE_SHADOW_CULL") : "(unset)", want == 2 ? "its back faces" : want == 1 ? "its front faces" : "as the game asks");
|
||||
|
||||
// the pipelines with the rate dynamic: the device's flag, native mesh programs, no colour target, a depth format
|
||||
Targets cascade;
|
||||
cascade.depth = &cascades, cascade.width = cascade.height = 1600, cascade.depth_format = VK_FORMAT_D32_SFLOAT;
|
||||
CHECK(!pipeline_rate(native, cascade)); // (no device flag: none, whatever else)
|
||||
dev.foliage_rate = true;
|
||||
CHECK(pipeline_rate(native, cascade));
|
||||
CHECK(!pipeline_rate(fallback, cascade) && !pipeline_rate(vertex, cascade));
|
||||
Targets colour = cascade;
|
||||
colour.n = 1;
|
||||
CHECK(!pipeline_rate(native, colour));
|
||||
Targets stencil = cascade;
|
||||
stencil.depth_format = VK_FORMAT_S8_UINT;
|
||||
CHECK(!pipeline_rate(native, stencil));
|
||||
Targets none = cascade;
|
||||
none.depth_format = VK_FORMAT_UNDEFINED; // (by the depth format, the pipeline's key, not by the depth texture)
|
||||
CHECK(!pipeline_rate(native, none));
|
||||
|
||||
// the draws through them: 2 x 2 into the far cascades from the switch's layer, 1 x 1 else; set at each bind, once a size
|
||||
const uint32_t far_size = rate_from >= 0 && rate_from <= 2 ? 2u : 1u;
|
||||
VkCommandBuffer a = (VkCommandBuffer)(uintptr_t)0x10, b = (VkCommandBuffer)(uintptr_t)0x20;
|
||||
cur_program = &native;
|
||||
cascade.depth_layer = 2;
|
||||
draw_rate(a, s, cascade, true);
|
||||
CHECK(rate_calls.size() == 1 && rate_calls[0].cmd == a && rate_calls[0].w == far_size && rate_calls[0].h == far_size);
|
||||
CHECK(rate_calls[0].op0 == VK_FRAGMENT_SHADING_RATE_COMBINER_OP_KEEP_KHR && rate_calls[0].op1 == VK_FRAGMENT_SHADING_RATE_COMBINER_OP_KEEP_KHR);
|
||||
draw_rate(a, s, cascade, false); // (the same pipeline, the same size: the command buffer has it)
|
||||
CHECK(rate_calls.size() == 1);
|
||||
draw_rate(a, s, cascade, true); // (bound again: another pipeline was bound between, the state undefined)
|
||||
CHECK(rate_calls.size() == 2);
|
||||
draw_rate(b, s, cascade, false); // (another command buffer)
|
||||
CHECK(rate_calls.size() == 3 && rate_calls[2].cmd == b);
|
||||
cascade.depth_layer = 0; // (the near cascade: 1 x 1, set when it differs)
|
||||
draw_rate(b, s, cascade, false);
|
||||
CHECK(rate_calls.size() == (far_size == 2 ? 4u : 3u) && rate_calls.back().w == 1 && rate_calls.back().h == 1);
|
||||
cascade.depth_layer = 2;
|
||||
s.poly.cull = NVN_FACE_BACK; // (drawn single-sided by the game: not the cards, 1 x 1)
|
||||
draw_rate(b, s, cascade, true);
|
||||
CHECK(rate_calls.back().w == 1);
|
||||
s.poly.cull = NVN_FACE_NONE;
|
||||
Targets small = cascade;
|
||||
small.width = small.height = 768; // (a character's own shadow map)
|
||||
draw_rate(b, s, small, true);
|
||||
CHECK(rate_calls.back().w == 1);
|
||||
CHECK((logged.find("vk: foliage shadow 2 x 2: program 0000000000001111's draw into the cascade layer 2 (1600x1600)") !=
|
||||
std::string::npos) == (far_size == 2));
|
||||
std::printf("PASS: RX_VK_FOLIAGE_SHADOW_CULL=%s: the far cascades' foliage culls %s; RX_VK_FOLIAGE_SHADOW_VRS=%s: %s\n",
|
||||
std::getenv("RX_VK_FOLIAGE_SHADOW_CULL") ? std::getenv("RX_VK_FOLIAGE_SHADOW_CULL") : "(unset)",
|
||||
want == 2 ? "its back faces" : want == 1 ? "its front faces" : "as the game asks",
|
||||
std::getenv("RX_VK_FOLIAGE_SHADOW_VRS") ? std::getenv("RX_VK_FOLIAGE_SHADOW_VRS") : "(unset)",
|
||||
far_size == 2 ? "the far cascade at 2 x 2" : "1 x 1 everywhere");
|
||||
}
|
||||
'''
|
||||
|
||||
# the switch -> the face the far cascades' foliage gets, and the near cascade's (NVN's: 0 none, 1 front, 2 back)
|
||||
RUNS = [(None, 0, 0), ("1", 2, 0), ("1f", 1, 0), ("0", 2, 2), ("off", 0, 0)]
|
||||
# (cull switch, vrs switch) -> the face the far cascades' foliage gets, the near cascade's (NVN's: 0 none, 1 front, 2 back),
|
||||
# and the first layer at 2 x 2 (-1 none)
|
||||
RUNS = [(None, None, 2, 0, 2), ("1", "2", 2, 0, 2), ("1f", None, 1, 0, 2), ("0", "1", 2, 2, 1), ("off", "off", 0, 0, -1),
|
||||
("", "", 2, 0, 2), (None, "3", 2, 0, 3)]
|
||||
|
||||
|
||||
def main():
|
||||
@@ -189,21 +333,25 @@ def main():
|
||||
p.add_argument("--cxx", default="g++")
|
||||
a = p.parse_args()
|
||||
draw = (ROOT / "gpu/vk/vk_draw.cpp").read_text(encoding="utf-8")
|
||||
check_source(draw)
|
||||
function = block(draw, "uint32_t draw_cull(")
|
||||
main_cpp = (ROOT / "gpu/vk/vk_main.cpp").read_text(encoding="utf-8")
|
||||
check_source(draw, main_cpp)
|
||||
functions = "\n".join(block(draw, m) for m in ("bool pipeline_rate(const Program& p, const Targets& at)", "uint32_t draw_cull(",
|
||||
"void draw_rate("))
|
||||
vk = str(ROOT / "gpu" / "vk")
|
||||
with tempfile.TemporaryDirectory(prefix="foliage-shadow-") as tmp:
|
||||
tmp = Path(tmp)
|
||||
for name, text in (("header", HEADER_TEST), ("function", FUNCTION_TEST.replace("/* FUNCTION */", function))):
|
||||
for name, text in (("header", HEADER_TEST), ("function", FUNCTION_TEST.replace("/* FUNCTIONS */", functions))):
|
||||
cpp, exe = tmp / (name + ".cpp"), tmp / (name + ".exe")
|
||||
cpp.write_text(text, encoding="utf-8")
|
||||
subprocess.run([a.cxx, "-std=c++20", "-Wall", "-Wextra", "-Werror", "-I" + vk, str(cpp), "-o", str(exe)], check=True)
|
||||
subprocess.run([str(tmp / "header.exe")], check=True)
|
||||
for switch, want, near in RUNS:
|
||||
env = {k: v for k, v in os.environ.items() if k != "RX_VK_FOLIAGE_SHADOW_CULL"}
|
||||
if switch is not None:
|
||||
env["RX_VK_FOLIAGE_SHADOW_CULL"] = switch
|
||||
subprocess.run([str(tmp / "function.exe"), str(want), str(near)], env=env, check=True, timeout=30)
|
||||
for cull, vrs, want, near, rate_from in RUNS:
|
||||
env = {k: v for k, v in os.environ.items() if k not in ("RX_VK_FOLIAGE_SHADOW_CULL", "RX_VK_FOLIAGE_SHADOW_VRS")}
|
||||
if cull is not None:
|
||||
env["RX_VK_FOLIAGE_SHADOW_CULL"] = cull
|
||||
if vrs is not None:
|
||||
env["RX_VK_FOLIAGE_SHADOW_VRS"] = vrs
|
||||
subprocess.run([str(tmp / "function.exe"), str(want), str(near), str(rate_from)], env=env, check=True, timeout=30)
|
||||
print("PASS: the foliage in the far shadow cascades")
|
||||
|
||||
|
||||
|
||||
@@ -149,8 +149,9 @@ def main():
|
||||
check("if (id == HOS_OPT_DISPLAY_CAP) return fps_cap::of_display(display_refresh_mhz());" in replay,
|
||||
"the renderer does not answer HOS_OPT_DISPLAY_CAP with fps_cap.h's rule for the window's display")
|
||||
menu = (ROOT / "gpu/vk/vk_menu.cpp").read_text(encoding="utf-8")
|
||||
check(re.search(r'\{TAB_DISPLAY, "Game frame rate cap", &opts\.fps_cap, -3, 6, 1, tx_fps_cap,', menu),
|
||||
"the Game frame rate cap row does not go from 30 (-3) to Monitor's rate (6)")
|
||||
# ((Triforce, options_version 7) the Graphics tab's Frame rate & latency group: Frame rate cap)
|
||||
check(re.search(r'\{TAB_GRAPHICS, "Frame rate cap", &opts\.fps_cap, -3, 6, 1, tx_fps_cap,', menu),
|
||||
"the Frame rate cap row does not go from 30 (-3) to Monitor's rate (6)")
|
||||
label = block(menu, "const char* tx_fps_cap(int v) {")
|
||||
check("fps_cap::of_display(display_refresh_mhz())" in label and '"Monitor\'s rate (%d)"' in label,
|
||||
"the row does not say what Monitor's rate gives on this display")
|
||||
@@ -164,8 +165,8 @@ def main():
|
||||
check("const int interval = fps_max() < 60 ? 1 : present_interval;" in presented and "fps_max() * interval" in presented,
|
||||
"a cap under 60 that settles late is paced with the game's own interval on top")
|
||||
readme = (ROOT / "readme.md").read_text(encoding="utf-8")
|
||||
check("| Game frame rate cap | 30, 40, 45, 60, 90, 120, 144, 165, 240, Monitor's rate" in readme,
|
||||
"readme.md's settings table has no Game frame rate cap row with Monitor's rate")
|
||||
check("| Frame rate cap | 30, 40, 45, 60, 90, 120, 144, 165, 240, Monitor's rate" in readme,
|
||||
"readme.md's settings table has no Frame rate cap row with Monitor's rate")
|
||||
guide = (ROOT / "docs/development.md").read_text(encoding="utf-8")
|
||||
check("| `frame_rate_cap` | 0 60, 1 90, 2 120, 3 144, 4 165, 5 240, 6 the monitor's refresh rate; -1 45, -2 40, -3 30 |" in guide,
|
||||
"docs/development.md's options table has no frame_rate_cap")
|
||||
|
||||
196
tests/test_fps_counter_grid.py
Normal file
196
tests/test_fps_counter_grid.py
Normal file
@@ -0,0 +1,196 @@
|
||||
"""The FPS counter over play, the title and the pause menu on the game's grid, at its 16:9 place among the game's header items
|
||||
in every window and picture shape (vk_menu.cpp draw_fps, gpu/vk/game_grid.h column_of; no game).
|
||||
|
||||
(Triforce, 11-20) The lab's check 3 of 26670c0, a 1680 x 1050 window with a 16:10 picture (fps_counter=1): "on the title
|
||||
and the pause menu the counter ends at x about 1445, about 235 px in from the right edge; on the pause menu it sits on the
|
||||
game's header between RB and the rupee counter" (16x10_02_title_down_mods.png, 16x10_31_sys_down_mods.png). Between the
|
||||
pause menu's R and its rupees is the counter's place at 16:9 (draw_fps: its right end 500 units left of the screen's right
|
||||
edge, 60 units down, measured on the game's own 1920 x 1080 screens). Over play the counter was laid out on the window's
|
||||
16:9 column of its whole height: at 16:10 the game's layouts are squeezed across (x 0.9, the grid the whole picture) and the
|
||||
counter was not, so it ended 500 window units (243 px) in from the edge where the game's items had moved 10% toward the
|
||||
edge, toward the middle of the gap; in a window with bars above and below the picture it was at the window's top, in the bar.
|
||||
|
||||
1. game_grid.h alone: the counter's right end and middle as draw_fps places them on column_of(..., true): its right end
|
||||
1420 units right of the grid's middle (the game's units: 3840 across the grid) and its middle 60 units under the grid's
|
||||
top in every shape, so the same distance from the pause menu's R (its right end 1044 units right of the middle,
|
||||
MenuOverlay_00's T_BtnR_00) and its rupees as at 16:9; unchanged where the picture fills a 16:9 or wider window's
|
||||
height; inside the picture with bars above and below. The old place at 16:10 is checked to be off by the lab's amount.
|
||||
2. The source: draw_fps over play on the grid (on_game unless under our header), put there through put_on_grid.
|
||||
3. ((11-20, a review of ca33bee) Under our header the counter is on the column draw_menu lays the page and its header on,
|
||||
on every page, the restart question (page 5, under our "Restart Needed" banner) too: draw_fps's and draw_menu's own
|
||||
on_game expressions, compiled and run for each page over play and inside the game's Options screen. ca33bee had put
|
||||
page 5 on the grid always: over play (F1) in a 1600 x 900 window with a 21:9 picture the counter left the banner it
|
||||
sat over at (1392, 25) for (1244, 131), over the dimmed page.
|
||||
|
||||
python -I -B tests/test_fps_counter_grid.py [--cxx clang++]
|
||||
"""
|
||||
import argparse
|
||||
import subprocess
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
VK = ROOT / "gpu" / "vk"
|
||||
RUN_ALL_ARGS = ["--cxx", "{cxx}"]
|
||||
|
||||
|
||||
def check(ok, why):
|
||||
if not ok:
|
||||
raise SystemExit("FAIL: " + why)
|
||||
|
||||
|
||||
def block(text, head):
|
||||
start = text.index(head)
|
||||
end = text.index("{", start) + 1
|
||||
depth = 1
|
||||
while depth:
|
||||
depth += (text[end] == "{") - (text[end] == "}")
|
||||
end += 1
|
||||
return text[start:end]
|
||||
|
||||
|
||||
GRID = r"""
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdint>
|
||||
#include "game_grid.h"
|
||||
using namespace mkwvk;
|
||||
static int fails = 0;
|
||||
#define CHECK(x) do { if (!(x)) { std::printf("FAIL:%d %s\n", __LINE__, #x); fails++; } } while (0)
|
||||
static bool near(float a, float b, float tol) { return std::fabs(a - b) <= tol; }
|
||||
struct Spot { float x1, my, kx, units_x1, units_my; game_grid::Place g; };
|
||||
// (as draw_fps over play: the column (pages_column(w, h, true)), on it the HUD's 16:9 width (the column's), the right end
|
||||
// lu(500) left of it and the middle lu(60) down, lu = h / 2160; put through the map. In the game's units on the grid too)
|
||||
static Spot counter(uint32_t pw, uint32_t ph, uint32_t ww, uint32_t wh, double r) {
|
||||
Spot s;
|
||||
s.g = game_grid::of(pw, ph, ww, wh, r);
|
||||
const game_grid::Column c = game_grid::column_of(s.g, (float)ww, (float)wh, true);
|
||||
const float lu = c.h / 2160.0f, hud_w = std::min(c.w, std::floor(c.h * 16.0f / 9.0f + 0.5f)), hud_x1 = (c.w + hud_w) * 0.5f;
|
||||
s.x1 = c.map.x(hud_x1 - 500 * lu), s.my = c.map.y(60 * lu), s.kx = c.map.kx;
|
||||
s.units_x1 = (s.x1 - (s.g.x + s.g.w * 0.5f)) * 3840 / s.g.w, s.units_my = (s.my - s.g.y) * 2160 / s.g.h;
|
||||
return s;
|
||||
}
|
||||
// (as it was over play: the window's own context, the HUD the window's middle 16:9 of its whole height)
|
||||
static float old_x1(float ww, float wh) {
|
||||
const float lu = wh / 2160.0f, hud_w = std::min(ww, std::floor(wh * 16.0f / 9.0f + 0.5f));
|
||||
return (ww + hud_w) * 0.5f - 500 * lu;
|
||||
}
|
||||
int main() {
|
||||
const double r21 = 64.0 / 27.0, r1610 = 16.0 / 10.0, r32 = 32.0 / 9.0;
|
||||
const struct { uint32_t pw, ph, ww, wh; double r; const char* what; } cases[] = {
|
||||
{2560, 1440, 1920, 1080, 0, "16:9"},
|
||||
{2304, 1440, 1680, 1050, r1610, "the lab's 1680 x 1050 window, 16:10 picture"},
|
||||
{3416, 1440, 1600, 900, r21, "1600 x 900 window, 21:9 picture between bars"},
|
||||
{3416, 1440, 1720, 720, r21, "1720 x 720 window, 21:9"},
|
||||
{3416, 1440, 3440, 1440, r21, "fullscreen 3440 x 1440, 21:9"},
|
||||
{5120, 1440, 5120, 1440, r32, "32:9"},
|
||||
{2560, 1440, 1600, 1200, 0, "4:3 window, 16:9 picture between bars"},
|
||||
{1600, 1200, 1600, 1200, 0, "4:3 window and picture"},
|
||||
};
|
||||
for (const auto& k : cases) {
|
||||
const Spot s = counter(k.pw, k.ph, k.ww, k.wh, k.r);
|
||||
std::printf("%-46s right end %7.1f, middle %6.1f (units: %6.1f right of the middle, %5.1f down), x %.3f\n", k.what, s.x1, s.my,
|
||||
s.units_x1, s.units_my, s.kx);
|
||||
// (its 16:9 place on the game's grid: 1420 units right of the middle (500 in from the grid's edge), 60 down)
|
||||
CHECK(near(s.units_x1, 1420, 2) && near(s.units_my, 60, 2)); // (the column on whole pixels: half a pixel)
|
||||
// (inside the picture, right of the pause menu's R (to 1044 units) by as much as at 16:9)
|
||||
CHECK(s.my > s.g.pic_y && s.x1 < s.g.pic_x + s.g.pic_w && s.units_x1 - 1044 > 300);
|
||||
}
|
||||
// where the picture fills a 16:9 or wider window's height: where it was
|
||||
{
|
||||
CHECK(near(counter(2560, 1440, 1920, 1080, 0).x1, old_x1(1920, 1080), 0.5f));
|
||||
CHECK(near(counter(3416, 1440, 1720, 720, r21).x1, old_x1(1720, 720), 0.5f));
|
||||
CHECK(near(counter(3416, 1440, 3440, 1440, r21).x1, old_x1(3440, 1440), 0.5f));
|
||||
CHECK(near(counter(2560, 1440, 1920, 1080, 0).my, 30, 0.01f));
|
||||
}
|
||||
// the lab's 16:10 window: it was 243 px in from the right edge (1437; the lab saw it end at about 1445), 1365 units right
|
||||
// of the middle on the squeezed grid where the game's items are at their 16:9 units; now 1420 units, 218 px in (500
|
||||
// units squeezed x 0.9), squeezed across with the game's header
|
||||
{
|
||||
const Spot s = counter(2304, 1440, 1680, 1050, r1610);
|
||||
const float was = old_x1(1680, 1050), was_units = (was - 840) * 3840 / 1680;
|
||||
CHECK(near(was, 1437, 1) && near(was_units, 1365, 2));
|
||||
CHECK(near(s.x1, 1461.5f, 1) && near(1680 - s.x1, 500 * 1050 / 2160.0f * 0.9f, 1) && near(s.kx, 0.9f, 0.001f));
|
||||
}
|
||||
// bars above and below: it was at the window's top, in the bar (25 px down where the picture starts at 113)
|
||||
{
|
||||
const Spot s = counter(3416, 1440, 1600, 900, r21);
|
||||
CHECK(60 * 900 / 2160.0f < s.g.pic_y && s.my > s.g.pic_y);
|
||||
}
|
||||
if (!fails) std::puts("the FPS counter at its 16:9 place on the game's grid in every shape");
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
PAGES = r"""
|
||||
#include <cstdio>
|
||||
#include <initializer_list>
|
||||
static int fails = 0;
|
||||
static int page = 0;
|
||||
static bool inside = false; // (pages_on_game: our tabs inside the game's Options screen)
|
||||
#define CHECK(x) do { if (!(x)) { std::printf("FAIL:%d %s (page %d, inside %d)\n", __LINE__, #x, page, (int)inside); fails++; } } while (0)
|
||||
static bool pages_on_game() { return inside; }
|
||||
static bool fps_on_game(bool under_banner) { return %FPS%; }
|
||||
static bool menu_on_game(bool row) { return %MENU%; }
|
||||
int main() {
|
||||
for (bool in : {false, true})
|
||||
for (int p : {0, 1, 3, 4, 5, 6, 8}) { // (8: the Mods page, kModsPage)
|
||||
inside = in, page = p;
|
||||
CHECK(fps_on_game(true) == menu_on_game(false)); // (under our header: on the page's column, its banner's)
|
||||
CHECK(fps_on_game(true) == in);
|
||||
CHECK(fps_on_game(false)); // (over play, the title, the pause menu: the game's grid)
|
||||
}
|
||||
if (!fails) std::puts("the counter under our header on the page's own column, the restart question's too");
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--cxx", default="clang++")
|
||||
args = parser.parse_args()
|
||||
menu = (VK / "vk_menu.cpp").read_text(encoding="utf-8")
|
||||
|
||||
fps = block(menu, "void draw_fps(ui::Ctx& window, bool under_banner) {")
|
||||
check("const bool on_game = under_banner ? pages_on_game() : true;" in fps,
|
||||
"draw_fps: over play, the title and the pause menu the counter is on the window's column, not the game's grid")
|
||||
dm = block(menu, "void draw_menu(ui::Ctx& c, bool perf_under) {")
|
||||
|
||||
def on_game_of(body, what):
|
||||
lines = [l.strip() for l in body.splitlines() if l.strip().startswith("const bool on_game = ")]
|
||||
check(len(lines) == 1, what + ": not one on_game")
|
||||
return lines[0][len("const bool on_game = "):].rstrip(";")
|
||||
check("const game_grid::Column col = pages_column(window.w, window.h, on_game);" in fps and
|
||||
"ui::Ctx c = on_game ? column_ctx(window, col) : window;" in fps and
|
||||
"if (on_game) c.d->PopClipRect(), put_on_grid(c.d, vtx0, cmd0, col.map, window_clip);" in fps,
|
||||
"draw_fps: the counter is not put on the grid it is laid out on")
|
||||
check("const float x1 = below ? hud_x1 - ui::lu(c, 80) : hud_x1 - ui::lu(c, 500);" in fps and
|
||||
"const float my = below ? banner_h(c) + ui::lu(c, 50) : ui::lu(c, 60);" in fps,
|
||||
"draw_fps: the counter's place on its column changed (the test's model is draw_fps's)")
|
||||
|
||||
# 3. the counter's column against the page's: draw_fps's on_game (under_banner: our options open, not the Mods entry's
|
||||
# row) and draw_menu's (row: the Mods entry's row), for each page, over play and inside the game's Options screen
|
||||
pages = PAGES.replace("%FPS%", on_game_of(fps, "draw_fps")).replace("%MENU%", on_game_of(dm, "draw_menu"))
|
||||
|
||||
with tempfile.TemporaryDirectory(prefix="fps-counter-grid-") as tmp:
|
||||
tmp = Path(tmp)
|
||||
src, exe = tmp / "grid.cpp", tmp / "grid.exe"
|
||||
src.write_text(GRID, encoding="utf-8")
|
||||
subprocess.run([args.cxx, "-std=c++20", "-O1", "-Wall", "-Wextra", "-Werror", "-I" + str(VK), str(src), "-o", str(exe)], check=True)
|
||||
r = subprocess.run([str(exe)], capture_output=True, text=True)
|
||||
print(r.stdout.strip())
|
||||
check(r.returncode == 0, "the counter's place:\n" + r.stdout)
|
||||
src, exe = tmp / "pages.cpp", tmp / "pages.exe"
|
||||
src.write_text(pages, encoding="utf-8")
|
||||
subprocess.run([args.cxx, "-std=c++20", "-O1", "-Wall", "-Wextra", "-Werror", str(src), "-o", str(exe)], check=True)
|
||||
r = subprocess.run([str(exe)], capture_output=True, text=True)
|
||||
print(r.stdout.strip())
|
||||
check(r.returncode == 0, "the counter's column under our header:\n" + r.stdout)
|
||||
print("PASS: the FPS counter over play on the game's grid at its 16:9 place in every shape")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
256
tests/test_framegen_amd.py
Normal file
256
tests/test_framegen_amd.py
Normal file
@@ -0,0 +1,256 @@
|
||||
"""(Triforce) AMD's frame generation made to make frames: what the lab's fgprobe1 run on the owner's RX 7900 XT showed it never
|
||||
did (AMD's library 3.1.6 taken, no AMD-made frame: the scene's depth and motion were never made where the gameplay network
|
||||
does not translate and the upscaler draws it in its place), the motion of what moves by itself, the picture without the HUD,
|
||||
HDR Native's 10 bits and the lab's pin. No game, no GPU.
|
||||
|
||||
1. Compiled and run: sharpen_rules.h's SPIR-V patches on the real frame generation shaders (fg_copy, fg_synth,
|
||||
fg_fine_synth): their one rgba8 storage image declared Rgb10A2 (A2B10G10R10, HDR Native's) with the capability SPIR-V asks
|
||||
for added once, as the first instruction, or rgba16f; nothing else changed. spirv-val checks the modules where it is
|
||||
installed.
|
||||
2. The source (FG-1..FG-9):
|
||||
- the upscaler chain (DLSS, FSR 4) makes frame generation's inputs from its own frame, before the bloom and in place of
|
||||
the dispatch (the path of a network that does not translate too), and copies its motion, what moves by itself in it,
|
||||
over theirs; the dispatch after it makes none again; RX_VK_FG_OWN_MOTION=0 the camera's alone;
|
||||
- the picture without the HUD is taken where the gameplay upscale's output is written (FSR 3.1, the chain, a network that
|
||||
does not translate, the game's own network and the TAAU pass in the 3/4 one's place), never left from a dispatch skipped;
|
||||
- HDR Native's frames are kept in a 10-bit format, the passes that store them made for it, and the present's retyped
|
||||
copy is what frame generation reads;
|
||||
- FSR 3.1's interpolation only with the row at 2x; RX_VK_FRAMEGEN_MULT takes the row's whole range.
|
||||
The old lines fail.
|
||||
|
||||
python -I -B tests/test_framegen_amd.py [--cxx g++]
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
RUN_ALL_ARGS = ["--cxx", "{cxx}"]
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
VK = ROOT / "gpu" / "vk"
|
||||
|
||||
SPV = r'''
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include "sharpen_rules.h"
|
||||
#include "shaders/fg_copy_comp_spv.h"
|
||||
#include "shaders/fg_synth_comp_spv.h"
|
||||
#include "shaders/fg_fine_synth_comp_spv.h"
|
||||
#define CHECK(x) do { if (!(x)) { std::fprintf(stderr, "FAIL:%d %s\n", __LINE__, #x); std::exit(1); } } while (0)
|
||||
using namespace mkwvk::sharpen_rules;
|
||||
|
||||
static size_t images(const std::vector<uint32_t>& w, uint32_t format) { // (storage images, Sampled 2, of that format)
|
||||
size_t n = 0;
|
||||
for (size_t i = 5; i < w.size();) {
|
||||
const uint32_t op = w[i] & 0xffffu, count = w[i] >> 16;
|
||||
if (op == 25 && count >= 9 && w[i + 7] == 2 && w[i + 8] == format) n++;
|
||||
i += count;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
static size_t capabilities(const std::vector<uint32_t>& w, uint32_t cap, bool* first) {
|
||||
size_t n = 0;
|
||||
bool past = false;
|
||||
*first = true;
|
||||
for (size_t i = 5; i < w.size();) {
|
||||
const uint32_t op = w[i] & 0xffffu, count = w[i] >> 16;
|
||||
if (op != 17) past = true;
|
||||
else if (w[i + 1] == cap) n++, *first = *first && !past;
|
||||
i += count;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
static void write(const char* dir, const char* name, const std::vector<uint32_t>& w) {
|
||||
if (!dir) return;
|
||||
char path[1024];
|
||||
std::snprintf(path, sizeof path, "%s/%s.spv", dir, name);
|
||||
FILE* f = std::fopen(path, "wb");
|
||||
CHECK(f && std::fwrite(w.data(), 4, w.size(), f) == w.size());
|
||||
std::fclose(f);
|
||||
}
|
||||
|
||||
static void one(const char* name, const uint32_t* code, size_t bytes, const char* dir) {
|
||||
const std::vector<uint32_t> before(code, code + bytes / 4);
|
||||
CHECK(images(before, kSpvRgba8) == 1); // (the frame it stores, alone)
|
||||
bool first = false;
|
||||
CHECK(capabilities(before, kSpvCapStorageImageExtendedFormats, &first) == 0);
|
||||
// HDR Native's A2B10G10R10: Rgb10A2, which needs StorageImageExtendedFormats: added once, among the first instructions
|
||||
std::vector<uint32_t> w = before;
|
||||
CHECK(storage_format_patch(w, kSpvRgba8, kSpvRgb10A2) == 1);
|
||||
CHECK(spv_require_capability(w, kSpvCapStorageImageExtendedFormats));
|
||||
CHECK(w.size() == before.size() + 2 && images(w, kSpvRgb10A2) == 1 && images(w, kSpvRgba8) == 0);
|
||||
CHECK(capabilities(w, kSpvCapStorageImageExtendedFormats, &first) == 1 && first);
|
||||
CHECK(spv_require_capability(w, kSpvCapStorageImageExtendedFormats) && w.size() == before.size() + 2); // (twice is once)
|
||||
CHECK(std::memcmp(w.data(), before.data(), 5 * 4) == 0); // (the header as it was)
|
||||
// (every other word as it was: the two inserted, the one format)
|
||||
size_t differ = 0;
|
||||
for (size_t i = 5, j = 7; i < before.size(); i++, j++) differ += before[i] != w[j];
|
||||
CHECK(differ == 1);
|
||||
write(dir, (std::string(name) + "_rgb10a2").c_str(), w);
|
||||
// or RGBA16F, where the card stores no A2B10G10R10: no capability asked
|
||||
std::vector<uint32_t> h = before;
|
||||
CHECK(storage_format_patch(h, kSpvRgba8, kSpvRgba16f) == 1 && h.size() == before.size() && images(h, kSpvRgba16f) == 1);
|
||||
write(dir, (std::string(name) + "_rgba16f").c_str(), h);
|
||||
// not SPIR-V: nothing
|
||||
std::vector<uint32_t> bad(before.begin(), before.begin() + 4);
|
||||
CHECK(!spv_require_capability(bad, kSpvCapStorageImageExtendedFormats) && bad.size() == 4);
|
||||
}
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
const char* dir = argc > 1 ? argv[1] : nullptr;
|
||||
one("fg_copy", FG_COPY_COMP_SPV, sizeof FG_COPY_COMP_SPV, dir);
|
||||
one("fg_synth", FG_SYNTH_COMP_SPV, sizeof FG_SYNTH_COMP_SPV, dir);
|
||||
one("fg_fine_synth", FG_FINE_SYNTH_COMP_SPV, sizeof FG_FINE_SYNTH_COMP_SPV, dir);
|
||||
std::puts("PASS: the frame generation shaders' storage image as A2B10G10R10 (its capability added once) or RGBA16F");
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
def check(cond, what):
|
||||
if not cond:
|
||||
raise SystemExit("FAIL: " + what)
|
||||
|
||||
|
||||
def function(source, head):
|
||||
start = source.index(head)
|
||||
return source[start:source.index("\n}\n", start) + 3]
|
||||
|
||||
|
||||
def checks(t):
|
||||
temporal, fsr3, inputs, inputs_h, draw, fg, replay, fi, menu = (t["temporal"], t["fsr3"], t["inputs"], t["inputs_h"],
|
||||
t["draw"], t["fg"], t["replay"], t["fi"], t["menu"])
|
||||
# FG-4 and the gate: the chain makes frame generation's inputs from its frame, in both placements, with its motion
|
||||
helper = function(temporal, "void fg_inputs_from_chain(VkCommandBuffer cmd, Texture* scene, VkImageView view, bool linear,")
|
||||
check("if (!fsr3_inputs::wanted() || fsr3_wanted() || !scene || !view) return;" in helper,
|
||||
"the chain makes frame generation's inputs while FSR 3.1 upscales, or when nothing asks for them")
|
||||
check(helper.index("if (!fsr3_inputs::made_this_frame()) {") < helper.index("fsr3_inputs::prepare(cmd, scene, view, f, linear)") <
|
||||
helper.index("fsr3_inputs::chain_motion(cmd, s.motion.image, rw, rh)"),
|
||||
"the chain does not make the inputs where none are, then copy its motion over them")
|
||||
up = function(temporal, "bool temporal_upscale(VkCommandBuffer cmd, uint64_t key, bool known, Texture* in, VkImageView in_view,")
|
||||
check("if (!chain(cmd, mode, engine, cam, captures, in_view, rw, rh, ow, oh, out_view, nullptr, in->format, out->format)) return false;"
|
||||
in up and "fg_inputs_from_chain(cmd, in, in_view, in->format == VK_FORMAT_R16G16B16A16_SFLOAT, rw, rh);" in up,
|
||||
"temporal_upscale (a network's dispatch, or one that does not translate) makes no frame generation inputs")
|
||||
pre = function(temporal, "Texture* temporal_pre_tonemap(VkCommandBuffer cmd) {")
|
||||
check(pre.index("if (!chain(cmd, mode, *engine, cam, captures, view") < pre.index("fg_inputs_from_chain(cmd, scene, view, true, rw, rh);"),
|
||||
"before the bloom the chain makes no frame generation inputs")
|
||||
check("VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT" in function(temporal, "VkFormat in_format, VkFormat out_format) {"),
|
||||
"the chain's motion cannot be copied from")
|
||||
motion = function(inputs, "bool chain_motion(VkCommandBuffer cmd, VkImage motion, uint32_t width, uint32_t height) {")
|
||||
for what in ('env_switch("RX_VK_FG_OWN_MOTION") == 0', "s.frame.frame != texture_frame_no()", "s.frame.width != width",
|
||||
"vkCmdCopyImage(cmd, motion, VK_IMAGE_LAYOUT_GENERAL, s.motion.image", "s.frame.chain_motion = true;"):
|
||||
check(what in motion, "chain_motion: missing %r" % what)
|
||||
check("return s.have_frame && s.frame.frame == texture_frame_no();" in function(inputs, "bool made_this_frame() {"),
|
||||
"made_this_frame is not this frame's inputs")
|
||||
check("bool chain_motion(VkCommandBuffer cmd, VkImage motion, uint32_t width, uint32_t height);" in inputs_h and
|
||||
"bool chain_motion = false;" in inputs_h, "vk_fsr3_inputs.h does not declare the chain's motion")
|
||||
up3 = function(fsr3, "bool fsr3_upscale(VkCommandBuffer cmd, uint64_t key, bool known, Texture* in, VkImageView in_view,")
|
||||
check("if (!upscaling && fsr3_inputs::made_this_frame()) return false;" in up3 and
|
||||
up3.index("fsr3_inputs::made_this_frame()") < up3.index("fsr3_inputs::prepare(cmd, in, in_view, f, hdr)"),
|
||||
"the dispatch after the bloom makes the inputs again, the camera's motion alone over the chain's")
|
||||
# FG-2: the picture without the HUD, wherever the upscale's output is written
|
||||
stand3 = function(draw, "bool fsr3_stand_in(VkCommandBuffer cmd, const NvnState& s, const Program& p) {")
|
||||
check(stand3.index("hudless_after = {};") < stand3.index("if (p.stages.empty() || !fsr3_inputs::wanted()) return false;"),
|
||||
"fsr3_stand_in leaves a skipped dispatch's picture to the next")
|
||||
check("if (done && out) framegen_hudless_note(cmd, out, level);" in stand3 and
|
||||
"else if (out && gameplay_network(p.key)) hudless_after = {out, level, p.key};" in stand3,
|
||||
"fsr3_stand_in takes no picture without the HUD")
|
||||
check("framegen_hudless_note(cmd, out, level);" in function(draw, "bool temporal_stand_in(VkCommandBuffer cmd, const NvnState& s, const Program& p) {"),
|
||||
"temporal_stand_in takes no picture without the HUD")
|
||||
rejected = function(draw, "static bool temporal_rejected_network(VkCommandBuffer cmd, uint64_t key, Texture* src, const nvn_tex* in, Texture* dst,\n const nvn_tex* out) {")
|
||||
check("framegen_hudless_note(cmd, dst, 0);" in rejected, "a network that does not translate gives no picture without the HUD")
|
||||
check("if (done) hudless_after_dispatch(cmd, p.key);" in function(draw, "bool taau_stand_in(VkCommandBuffer cmd, const NvnState& s, const Program& p) {"),
|
||||
"the TAAU pass in the 3/4 network's place gives no picture without the HUD")
|
||||
at = draw.index("cw.dispatch_at = work_at(cw);")
|
||||
check(draw.index("hudless_after_dispatch(cmd, p.key);", at) - at < 200, "the game's own network gives no picture without the HUD")
|
||||
after = function(draw, "void hudless_after_dispatch(VkCommandBuffer cmd, uint64_t key) {")
|
||||
check("hudless_after = {};" in after and "h.key == key" in after, "a picture is taken for another dispatch than its own")
|
||||
# FG-5: HDR Native's 10 bits through frame generation
|
||||
ensure = function(fg, "bool ensure_size(VkCommandBuffer cmd, uint32_t w, uint32_t h) {")
|
||||
check("fg.format == format) return true;" in ensure, "a change of HDR mode does not make the frames again")
|
||||
check("make_img(fg.frames[i], w, h, format," in ensure and "make_img(set.frame[k], w, h, format," in ensure,
|
||||
"the frames are RGBA8 whatever the picture is")
|
||||
check("std::swap(fg.copy, fg.alt_copy), std::swap(fg.synth, fg.alt_synth), std::swap(fg.fine_synth, fg.alt_fine_synth);" in ensure,
|
||||
"the passes that store the frames are not the frames' format's")
|
||||
pipes = function(fg, "bool make_format_pipes(VkFormat f) {")
|
||||
check("sharpen_rules::spv_require_capability(w, sharpen_rules::kSpvCapStorageImageExtendedFormats)" in pipes and
|
||||
"storage_format_patch(w, sharpen_rules::kSpvRgba8, rgb10 ? sharpen_rules::kSpvRgb10A2 : sharpen_rules::kSpvRgba16f) != 1" in pipes,
|
||||
"the 10-bit passes are not the patched shaders")
|
||||
check("if (!present_native_pq.load(std::memory_order_relaxed) || fg.hdr_failed) return VK_FORMAT_R8G8B8A8_UNORM;" in
|
||||
function(fg, "VkFormat frames_format() {"), "the frames' format does not follow HDR Native")
|
||||
check("if (fg.format != VK_FORMAT_R8G8B8A8_UNORM) return 0;" in function(fg, "int fsr3fi_frame("),
|
||||
"FSR 3.1's interpolation is given HDR Native's 10-bit frames")
|
||||
check(replay.count("retyped_view ? retyped_view : texture_view(tex, t, nullptr, VK_IMAGE_VIEW_TYPE_2D, ViewUse::Sample)") == 2,
|
||||
"frame generation reads the window texture's own view where the present retyped it")
|
||||
check("retyped_view = rt.view;" in replay, "the retyped copy's view is not handed on")
|
||||
# FG-6, FG-9
|
||||
check("return opts.framegen == 2 && asked() && !dlssg::active() && capable() ? 1u : 0u;" in function(fi, "uint32_t frames_wanted() {"),
|
||||
"FSR 3.1's interpolation runs whatever the row says")
|
||||
check('if (const char* e = getenv("RX_VK_FRAMEGEN_MULT")) opts.framegen = framegen_rows::env_row(e);' in menu,
|
||||
"RX_VK_FRAMEGEN_MULT cannot pin AMD's frame generation")
|
||||
|
||||
|
||||
MUTATIONS = [
|
||||
("no inputs at the chain's dispatch", "temporal",
|
||||
" fg_inputs_from_chain(cmd, in, in_view, in->format == VK_FORMAT_R16G16B16A16_SFLOAT, rw, rh);\n", ""),
|
||||
("no inputs before the bloom", "temporal", " fg_inputs_from_chain(cmd, scene, view, true, rw, rh);\n", ""),
|
||||
("the camera's motion alone", "temporal", " if (s.motion.image) (void)fsr3_inputs::chain_motion(cmd, s.motion.image, rw, rh);\n", ""),
|
||||
("made twice", "fsr3", " if (!upscaling && fsr3_inputs::made_this_frame()) return false;\n", ""),
|
||||
("no picture at a network that does not translate", "draw", " framegen_hudless_note(cmd, dst, 0);\n", ""),
|
||||
("no picture at the TAAU pass", "draw", " if (done) hudless_after_dispatch(cmd, p.key);", " if (done) {}"),
|
||||
("no picture at the game's network", "draw", " hudless_after_dispatch(cmd, p.key); // ((Triforce, FG-2)", " // ("),
|
||||
("a skipped dispatch's picture kept", "draw", " hudless_after = {}; // ((Triforce, FG-2) a dispatch's own", " // ("),
|
||||
("8 bits in HDR Native", "fg", "make_img(fg.frames[i], w, h, format,", "make_img(fg.frames[i], w, h, VK_FORMAT_R8G8B8A8_UNORM,"),
|
||||
("the frames not made again", "fg", " && fg.format == format) return true;", ") return true;"),
|
||||
("the window texture's view", "replay", "retyped_view ? retyped_view : texture_view(tex, t", "texture_view(tex, t"),
|
||||
("FSR 3.1 whatever the row", "fi", "return opts.framegen == 2 && asked()", "return asked()"),
|
||||
("the old pin", "menu", "opts.framegen = framegen_rows::env_row(e);", "opts.framegen = std::min(std::max(atoi(e), 2), 8);"),
|
||||
]
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument("--cxx", default="g++")
|
||||
a = p.parse_args()
|
||||
with tempfile.TemporaryDirectory(prefix="framegen-amd-") as tmp:
|
||||
cpp, exe = Path(tmp) / "spv.cpp", Path(tmp) / ("spv.exe" if os.name == "nt" else "spv")
|
||||
cpp.write_text(SPV, encoding="utf-8")
|
||||
subprocess.run([a.cxx, "-std=c++20", "-Wall", "-Wextra", "-Werror", "-I" + str(VK), str(cpp), "-o", str(exe)], check=True)
|
||||
subprocess.run([str(exe), tmp], check=True, timeout=60)
|
||||
val = shutil.which("spirv-val")
|
||||
if val:
|
||||
for spv in sorted(Path(tmp).glob("*.spv")):
|
||||
subprocess.run([val, "--target-env", "vulkan1.2", str(spv)], check=True, timeout=60)
|
||||
print("spirv-val: the patched modules are valid")
|
||||
else:
|
||||
print("spirv-val is not installed here: the patched modules were not validated")
|
||||
texts = {"temporal": (VK / "vk_temporal.cpp").read_text(encoding="utf-8"),
|
||||
"fsr3": (VK / "vk_fsr3.cpp").read_text(encoding="utf-8"),
|
||||
"inputs": (VK / "vk_fsr3_inputs.cpp").read_text(encoding="utf-8"),
|
||||
"inputs_h": (VK / "vk_fsr3_inputs.h").read_text(encoding="utf-8"),
|
||||
"draw": (VK / "vk_draw.cpp").read_text(encoding="utf-8"),
|
||||
"fg": (VK / "vk_framegen.cpp").read_text(encoding="utf-8"),
|
||||
"replay": (VK / "vk_replay.cpp").read_text(encoding="utf-8"),
|
||||
"fi": (VK / "vk_fsr3fi.cpp").read_text(encoding="utf-8"),
|
||||
"menu": (VK / "vk_menu.cpp").read_text(encoding="utf-8")}
|
||||
checks(texts)
|
||||
for name, which, new, old in MUTATIONS:
|
||||
check(new in texts[which], "the mutation '%s' has nothing to change" % name)
|
||||
t = dict(texts)
|
||||
t[which] = t[which].replace(new, old, 1)
|
||||
try:
|
||||
checks(t)
|
||||
except (SystemExit, ValueError):
|
||||
continue
|
||||
raise SystemExit("FAIL: the mutation '%s' passed" % name)
|
||||
print("PASS: AMD's frame generation gets the scene's depth and motion where the upscaler draws (what moves by itself in "
|
||||
"it), the picture without the HUD, HDR Native's 10 bits, and the lab's pin; the old lines fail")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -2,8 +2,10 @@
|
||||
of AMD's files: AMD's library is a stand-in that notes every call it gets.
|
||||
|
||||
1. gpu/vk/framegen_rows.h, compiled and run: the row's last value by what a build and a card support, the values from before
|
||||
(0 Off, 1 Auto, 2 to 8) meaning what they did, the version taken from AMD's list (the newest FSR 4, never an FSR 3.1
|
||||
under its name), the camera cut, when a context still fits and when it is let go, and the order it is taken down in.
|
||||
(0 Off, 1 Auto, 2 to 8) meaning what they did, the version taken from AMD's list (FSR 4's where listed, else FSR 3.1's, as
|
||||
an RX 7900 XT has alone; FSR 4's alone with RX_VK_FSR4_FG=4) and the row's name for it, RX_VK_FRAMEGEN_MULT's range, the
|
||||
game's frame alone without a picture without the HUD and where that picture is cut, the camera cut, when a context still
|
||||
fits and when it is let go, and the order it is taken down in.
|
||||
2. gpu/vk/vk_menu.cpp's own tx_framegen and hn_framegen_fsr4, cut out and run: the names an options file's values show,
|
||||
a saved AMD FSR 4 where it cannot run, and that the row's table, its end and the menu's opening are wired to them.
|
||||
3. gpu/vk/vk_fsr4.cpp's frame generation section (fsr4fg), cut out and run against the stand-in library (Windows, with
|
||||
@@ -97,17 +99,60 @@ int main() {
|
||||
for (int w = 1; w < FG_WHY_COUNT; w++) CHECK(!fsr4_asked(9, (Why)w, false));
|
||||
CHECK(multiplier(-3, 2) == 1 && multiplier(12, 2) == 8); // (a value outside the row)
|
||||
|
||||
// AMD's list: the newest FSR 4, the first of equal ones; never an FSR 3.1 under FSR 4's name
|
||||
// AMD's list: the newest, the first of equal ones: FSR 4's where it is listed, else ((Triforce, FG-1)) FSR 3.1's, which
|
||||
// RX 6000 and 7000 have alone (3.1.6 on the owner's RX 7900 XT); only_fsr4 (RX_VK_FSR4_FG=4): 4.x or nothing, as before
|
||||
unsigned v[3];
|
||||
CHECK(parse_version("4.0.2", v) && v[0] == 4 && v[1] == 0 && v[2] == 2);
|
||||
CHECK(parse_version("4.1.0*", v) && v[1] == 1); // (a version the graphics driver brings)
|
||||
CHECK(!parse_version("FSR", v) && !parse_version(nullptr, v) && !parse_version("4.0", v));
|
||||
{ const char* n[] = {"4.0.2", "3.1.6"}; CHECK(pick_version(n, 2, false) == 0); }
|
||||
{ const char* n[] = {"4.0.2", "3.1.6"}; CHECK(pick_version(n, 2, false) == 0 && pick_version(n, 2, true) == 0); }
|
||||
{ const char* n[] = {"3.1.6", "4.0.0", "4.0.2*", "4.0.2", "4.0.1"}; CHECK(pick_version(n, 5, false) == 2); }
|
||||
{ const char* n[] = {"3.1.6", "3.1.4"}; CHECK(pick_version(n, 2, false) == -1); CHECK(pick_version(n, 2, true) == 0); }
|
||||
{ const char* n[] = {"3.1.6", "4.0.2"}; CHECK(pick_version(n, 2, true) == 1); } // (any: still the newest)
|
||||
{ const char* n[] = {nullptr, "?", "5.0.0"}; CHECK(pick_version(n, 3, false) == -1); CHECK(pick_version(n, 3, true) == 2); }
|
||||
{ const char* n[] = {"3.1.6", "3.1.4"}; CHECK(pick_version(n, 2, false) == 0); CHECK(pick_version(n, 2, true) == -1); }
|
||||
{ const char* n[] = {"3.1.4", "3.1.6"}; CHECK(pick_version(n, 2, false) == 1); } // (the newest 3.1)
|
||||
{ const char* n[] = {"3.1.6"}; CHECK(pick_version(n, 1, false) == 0); } // (an RX 7900 XT's whole list)
|
||||
{ const char* n[] = {"3.1.6", "4.0.2"}; CHECK(pick_version(n, 2, false) == 1); } // (FSR 4's first wherever it is listed)
|
||||
{ const char* n[] = {nullptr, "?", "5.0.0"}; CHECK(pick_version(n, 3, true) == -1); CHECK(pick_version(n, 3, false) == 2); }
|
||||
{ const char* n[] = {nullptr, "?"}; CHECK(pick_version(n, 2, false) == -1); } // (nothing it can read)
|
||||
CHECK(pick_version(nullptr, 0, false) == -1);
|
||||
// each reason it is not used has words for the log
|
||||
for (int w = 0; w < FG_WHY_COUNT; w++) CHECK(why_name((Why)w) && *why_name((Why)w) && std::strcmp(why_name((Why)w), "?"));
|
||||
// the row's name for it, by the version in use
|
||||
char label[32];
|
||||
CHECK(!std::strcmp(row_label(label, sizeof label, "3.1.6"), "AMD FSR (3.1.6)"));
|
||||
CHECK(!std::strcmp(row_label(label, sizeof label, "4.0.2*"), "AMD FSR (4.0.2)")); // (the driver's star is not shown)
|
||||
CHECK(!std::strcmp(row_label(label, sizeof label, ""), "AMD FSR") && !std::strcmp(row_label(label, sizeof label, nullptr), "AMD FSR"));
|
||||
CHECK(!std::strcmp(row_label(label, 8, "3.1.6"), "AMD FSR")); // (cut to what fits, never past the buffer)
|
||||
// ((Triforce, FG-9) RX_VK_FRAMEGEN_MULT: the row's whole range, AMD's 9 among it; not a number, 2 as before
|
||||
CHECK(env_row("9") == 9 && env_row("0") == 0 && env_row("1") == 1 && env_row("5") == 5);
|
||||
CHECK(env_row("12") == 9 && env_row("-3") == 0 && env_row("x") == 2 && env_row("") == 2 && env_row(nullptr) == 2);
|
||||
// ((Triforce, FG-2) the game's frame alone: a new history, or no picture without the HUD (HDR Native first)
|
||||
CHECK(game_frame_alone(SKIP) && game_frame_alone(GAME) && !game_frame_alone(MADE) && !game_frame_alone(OWN));
|
||||
for (int scene = 0; scene < 2; scene++)
|
||||
for (int hl = 0; hl < 2; hl++) CHECK(held_for(true, scene != 0, hl != 0) == HELD_HDR_NATIVE);
|
||||
CHECK(held_for(false, true, true) == HELD_HDR_SCENE && held_for(false, true, false) == HELD_HDR_SCENE);
|
||||
CHECK(held_for(false, false, false) == HELD_NO_HUDLESS && held_for(false, false, true) == HELD_NONE);
|
||||
// ((Triforce) HDR Native and RenoDX's RGBA16F scene hold for every present: the renderer's own makes the frame, as a saved
|
||||
// 9 ran on an RX 6000 or 7000 before (shown(9, false) == 2); only a frame missing its picture without the HUD is the game's
|
||||
// frame alone
|
||||
CHECK(held_whole_run(HELD_HDR_NATIVE) && held_whole_run(HELD_HDR_SCENE));
|
||||
CHECK(!held_whole_run(HELD_NO_HUDLESS) && !held_whole_run(HELD_NONE));
|
||||
CHECK(held_made(HELD_HDR_NATIVE) == OWN && held_made(HELD_HDR_SCENE) == OWN && held_made(HELD_NO_HUDLESS) == GAME);
|
||||
CHECK(!game_frame_alone(held_made(HELD_HDR_NATIVE)) && !game_frame_alone(held_made(HELD_HDR_SCENE)));
|
||||
// the picture without the HUD, cut as the present is: the same rect at the same size, scaled at another
|
||||
SourceRect r = hudless_source(3416, 1440, 3416, 1440, 0, 0, 3416, 1440);
|
||||
CHECK(r.x0 == 0 && r.y0 == 0 && r.x1 == 3416 && r.y1 == 1440);
|
||||
r = hudless_source(2560, 1440, 2560, 1440, 160, 90, 2240, 1260);
|
||||
CHECK(r.x0 == 160 && r.y0 == 90 && r.x1 == 2400 && r.y1 == 1350);
|
||||
r = hudless_source(1280, 720, 2560, 1440, 160, 90, 2240, 1260); // (an output half the window texture's size)
|
||||
CHECK(r.x0 == 80 && r.y0 == 45 && r.x1 == 1200 && r.y1 == 675);
|
||||
r = hudless_source(2560, 1440, 2560, 1440, 2500, 1400, 100, 100); // (clipped to the picture)
|
||||
CHECK(r.x0 == 2500 && r.y0 == 1400 && r.x1 == 2560 && r.y1 == 1440);
|
||||
r = hudless_source(0, 1440, 2560, 1440, 0, 0, 2560, 1440);
|
||||
CHECK(r.x1 == 0 && r.y1 == 0);
|
||||
r = hudless_source(2560, 1440, 2560, 1440, 2560, 0, 10, 10);
|
||||
CHECK(r.x1 == 0);
|
||||
r = hudless_source(2, 2, 2560, 1440, 0, 0, 1, 1); // (nothing of a pixel left: none)
|
||||
CHECK(r.x1 == 0 && r.y1 == 0);
|
||||
|
||||
// the camera: the view matrix's rows are its axes, the position -R^T t
|
||||
const float still[12] = {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0};
|
||||
@@ -160,7 +205,8 @@ int main() {
|
||||
CHECK((play.did == std::vector<std::string>{"stop", "wait_gpu", "destroy_context", "destroy_images"}));
|
||||
teardown(exit, true);
|
||||
CHECK((exit.did == std::vector<std::string>{"stop"}));
|
||||
std::puts("PASS: the Frame generation row's AMD FSR 4, AMD's version list, camera cuts, context life and teardown order");
|
||||
std::puts("PASS: the Frame generation row's AMD FSR, AMD's version list, its name, the env pin, the picture without the HUD's "
|
||||
"rules, camera cuts, context life and teardown order");
|
||||
}
|
||||
'''
|
||||
|
||||
@@ -171,30 +217,54 @@ MENU = CHECK + r'''
|
||||
namespace framegen_rows = mkwvk::framegen_rows;
|
||||
namespace fsr4fg {
|
||||
framegen_rows::Why now = framegen_rows::FG_OK;
|
||||
const char* in_use = "3.1.6";
|
||||
framegen_rows::Why why() { return now; }
|
||||
bool offered() { return why() == framegen_rows::FG_OK; }
|
||||
framegen_rows::Why why_known() { return now; } // ((Triforce) the menu's rows read the answer as known)
|
||||
bool offered_known() { return why_known() == framegen_rows::FG_OK; }
|
||||
const char* version() { return now == framegen_rows::FG_OK ? in_use : ""; }
|
||||
// ((Triforce) what holds AMD's library from every present: HDR Native's picture (present_native_pq), RenoDX's RGBA16F scene
|
||||
framegen_rows::Held held_now = framegen_rows::HELD_NONE;
|
||||
framegen_rows::Held held() { return held_now; }
|
||||
}
|
||||
struct { int hdr = 0; } opts; // ((Triforce, FG-5) the HDR row: 2 Native, which alone is no pause (no HDR display, say)
|
||||
/* TX */
|
||||
/* HN */
|
||||
int main() {
|
||||
static const char* const before[] = {"Off", "Auto", "2x", "3x", "4x", "5x", "6x", "7x", "8x"};
|
||||
for (int w = 0; w < framegen_rows::FG_WHY_COUNT; w++) {
|
||||
fsr4fg::now = (framegen_rows::Why)w;
|
||||
for (int v = 0; v <= 8; v++) CHECK(!std::strcmp(tx_framegen(v), before[v])); // (an options file from before)
|
||||
CHECK(!std::strcmp(tx_framegen(9), w == framegen_rows::FG_OK ? "AMD FSR 4" : "2x")); // (a saved choice shows what runs)
|
||||
const char* line = hn_framegen_fsr4(-1);
|
||||
CHECK(line && *line);
|
||||
CHECK((std::strstr(line, "AMD's FSR 4 library") != nullptr) == (w == framegen_rows::FG_OK));
|
||||
if (w != framegen_rows::FG_OK && w != framegen_rows::FG_NOT_YET) CHECK(std::strstr(line, "the renderer's own makes"));
|
||||
bool listed = false; // (the menu measures every line a value can show: the one shown now is among them)
|
||||
int k = 0;
|
||||
for (; const char* t = hn_framegen_fsr4(k); k++) listed |= t == line;
|
||||
CHECK(listed && k == framegen_rows::FG_WHY_COUNT);
|
||||
}
|
||||
CHECK(std::strstr(hn_framegen_fsr4(0), "HUD")); // (said to the player: the HUD is in the picture it works from)
|
||||
std::puts("PASS: the row's names for an options file's values, and what a saved AMD FSR 4 shows where it cannot run");
|
||||
static const framegen_rows::Held holds[] = {framegen_rows::HELD_NONE, framegen_rows::HELD_NO_HUDLESS, framegen_rows::HELD_HDR_NATIVE,
|
||||
framegen_rows::HELD_HDR_SCENE};
|
||||
for (int hdr = 0; hdr <= 2; hdr++)
|
||||
for (framegen_rows::Held held : holds)
|
||||
for (int w = 0; w < framegen_rows::FG_WHY_COUNT; w++) {
|
||||
fsr4fg::now = (framegen_rows::Why)w;
|
||||
fsr4fg::held_now = held;
|
||||
opts.hdr = hdr;
|
||||
const bool paused = framegen_rows::held_whole_run(held); // (HDR Native's picture, or RenoDX's scene, in any HDR mode)
|
||||
for (int v = 0; v <= 8; v++) CHECK(!std::strcmp(tx_framegen(v), before[v])); // (an options file from before)
|
||||
// (a saved choice shows what runs: AMD's, by the version AMD's library makes the frames with, or 2x)
|
||||
CHECK(!std::strcmp(tx_framegen(9), w == framegen_rows::FG_OK ? "AMD FSR (3.1.6)" : "2x"));
|
||||
const char* line = hn_framegen_fsr4(-1);
|
||||
CHECK(line && *line);
|
||||
CHECK((std::strstr(line, "AMD's frame generation library (its version") != nullptr) == (w == framegen_rows::FG_OK && !paused));
|
||||
CHECK((std::strstr(line, "Paused with HDR Native or RenoDX") != nullptr) == (w == framegen_rows::FG_OK && paused));
|
||||
// (paused, the frame is still made: by the renderer's own, as a saved 9 ran on a card without AMD's)
|
||||
if (w == framegen_rows::FG_OK && paused) CHECK(std::strstr(line, "renderer's own makes the one frame, as at 2x"));
|
||||
if (w != framegen_rows::FG_OK && w != framegen_rows::FG_NOT_YET) CHECK(std::strstr(line, "the renderer's own makes"));
|
||||
bool listed = false; // (the menu measures every line a value can show: the one shown now is among them)
|
||||
int k = 0;
|
||||
for (; const char* t = hn_framegen_fsr4(k); k++) listed |= t == line;
|
||||
CHECK(listed && k == framegen_rows::FG_WHY_COUNT + 1);
|
||||
}
|
||||
fsr4fg::now = framegen_rows::FG_OK, fsr4fg::in_use = "4.0.2";
|
||||
CHECK(!std::strcmp(tx_framegen(9), "AMD FSR (4.0.2)")); // (an RX 9000's)
|
||||
fsr4fg::in_use = "";
|
||||
CHECK(!std::strcmp(tx_framegen(9), "AMD FSR")); // (offered, its version not read)
|
||||
// (said to the player: the HUD is kept out of what is moved, and HDR Native pauses it)
|
||||
CHECK(std::strstr(hn_framegen_fsr4(0), "HUD kept where the game drew it"));
|
||||
CHECK(std::strstr(hn_framegen_fsr4(framegen_rows::FG_WHY_COUNT), "HDR Native") && !hn_framegen_fsr4(framegen_rows::FG_WHY_COUNT + 1));
|
||||
std::puts("PASS: the row's names for an options file's values, AMD's by its version, what a saved AMD FSR shows where it "
|
||||
"cannot run, and its pause with HDR Native or RenoDX's scene");
|
||||
}
|
||||
'''
|
||||
|
||||
@@ -326,6 +396,9 @@ framegen_rows::Why why();
|
||||
inline bool offered() { return why() == framegen_rows::FG_OK; } // (as vk_fsr4.h has it)
|
||||
framegen_rows::Why why_known();
|
||||
inline bool offered_known() { return why_known() == framegen_rows::FG_OK; }
|
||||
// ((Triforce) vk_fsr4.cpp's held(), outside the section: HDR Native's picture or RenoDX's RGBA16F scene, set by a scene
|
||||
static framegen_rows::Held held_now = framegen_rows::HELD_NONE;
|
||||
framegen_rows::Held held() { return held_now; }
|
||||
}
|
||||
/* SECTION */
|
||||
} // namespace mkwvk
|
||||
@@ -343,6 +416,7 @@ static bool fail_configure;
|
||||
static uint64_t chosen_id;
|
||||
static VkCommandBuffer const kCmd = (VkCommandBuffer)(uintptr_t)0x77;
|
||||
static VkImage const kColor = (VkImage)(uintptr_t)0xC0, kDepth = (VkImage)(uintptr_t)0xD0, kMotion = (VkImage)(uintptr_t)0xE0;
|
||||
static VkImage const kHudless = (VkImage)(uintptr_t)0xF0; // ((Triforce, FG-2) the picture without the HUD)
|
||||
static uint64_t last_id;
|
||||
static uint32_t made_w, made_h, made_rw, made_rh, made_flags;
|
||||
|
||||
@@ -367,15 +441,18 @@ static ffxReturnCode_t amd_create(ffxContext* context, ffxCreateContextDescHeade
|
||||
amd_calls++;
|
||||
CHECK(d->type == FFX_API_CREATE_CONTEXT_DESC_TYPE_FRAMEGENERATION);
|
||||
const auto* c = (const ffxCreateContextDescFrameGeneration*)d;
|
||||
bool api = false, backend = false, pin = false;
|
||||
bool api = false, backend = false, pin = false, hudless = false;
|
||||
for (const ffxApiHeader* h = d->pNext; h; h = h->pNext) {
|
||||
if (h->type == FFX_API_CREATE_CONTEXT_DESC_TYPE_FRAMEGENERATION_VERSION)
|
||||
api = ((const ffxCreateContextDescFrameGenerationVersion*)h)->version == FFX_FRAMEGENERATION_VERSION;
|
||||
if (h->type == FFX_API_CREATE_CONTEXT_DESC_TYPE_BACKEND_VK)
|
||||
backend = ((const ffxCreateBackendVKDesc*)h)->deviceContext.vkDevice == lib().device_context.vkDevice;
|
||||
if (h->type == FFX_API_DESC_TYPE_OVERRIDE_VERSION) pin = ((const ffxOverrideVersion*)h)->versionId == chosen_id;
|
||||
if (h->type == FFX_API_CREATE_CONTEXT_DESC_TYPE_FRAMEGENERATION_HUDLESS) // ((Triforce, FG-2) its format, the picture's)
|
||||
hudless = ((const ffxCreateContextDescFrameGenerationHudless*)h)->hudlessBackBufferFormat ==
|
||||
ffxApiGetSurfaceFormatVK(VK_FORMAT_R8G8B8A8_UNORM);
|
||||
}
|
||||
CHECK(api && backend && pin); // (the API's version, the device, and the version asked for by its id)
|
||||
CHECK(api && backend && pin && hudless); // (the API's version, the device, the version asked for by its id, the HUD-less format)
|
||||
CHECK(c->backBufferFormat == ffxApiGetSurfaceFormatVK(VK_FORMAT_R8G8B8A8_UNORM));
|
||||
CHECK(c->flags & FFX_FRAMEGENERATION_ENABLE_DEPTH_INVERTED);
|
||||
CHECK(!(c->flags & (FFX_FRAMEGENERATION_ENABLE_ASYNC_WORKLOAD_SUPPORT | FFX_FRAMEGENERATION_ENABLE_DISPLAY_RESOLUTION_MOTION_VECTORS)));
|
||||
@@ -399,7 +476,9 @@ static ffxReturnCode_t amd_configure(ffxContext* context, const ffxConfigureDesc
|
||||
const auto* c = (const ffxConfigureDescFrameGeneration*)d;
|
||||
// (no swapchain of AMD's and none of its callbacks: the frame is asked for, and presented by the renderer)
|
||||
CHECK((c->flags & FFX_FRAMEGENERATION_FLAG_NO_SWAPCHAIN_CONTEXT_NOTIFY) && !c->swapChain && !c->presentCallback && !c->frameGenerationCallback);
|
||||
CHECK(c->frameGenerationEnabled && !c->allowAsyncWorkloads && !c->onlyPresentGenerated && !c->HUDLessColor.resource);
|
||||
// ((Triforce, FG-2) and the picture without the HUD, every frame: the HUD is kept where the game drew it)
|
||||
CHECK(c->frameGenerationEnabled && !c->allowAsyncWorkloads && !c->onlyPresentGenerated && c->HUDLessColor.resource == kHudless);
|
||||
CHECK(c->HUDLessColor.description.width == made_w && c->HUDLessColor.state == FFX_API_RESOURCE_STATE_UNORDERED_ACCESS);
|
||||
CHECK(c->generationRect.left == 0 && c->generationRect.top == 0 && (uint32_t)c->generationRect.width == made_w);
|
||||
CHECK(c->frameID == last_id + 1); // (one more for each frame handed over)
|
||||
last_id = c->frameID;
|
||||
@@ -435,7 +514,7 @@ static ffxReturnCode_t amd_dispatch(ffxContext* context, const ffxDispatchDescHe
|
||||
|
||||
static fsr4fg::Inputs frame(uint64_t sequence, float x = 0.0f, uint32_t w = 2560, uint32_t h = 1440, uint32_t rw = 1920, uint32_t rh = 1080) {
|
||||
fsr4fg::Inputs in;
|
||||
in.color = kColor, in.width = w, in.height = h;
|
||||
in.color = kColor, in.hudless = kHudless, in.width = w, in.height = h;
|
||||
in.depth = kDepth, in.motion = kMotion, in.render_width = rw, in.render_height = rh;
|
||||
in.near_plane = 0.1f, in.far_plane = FLT_MAX, in.fov_y = 1.0f;
|
||||
const float view[12] = {1, 0, 0, -x, 0, 1, 0, 0, 0, 0, 1, 0}; // (the camera at x, looking down -z)
|
||||
@@ -489,20 +568,73 @@ int main(int argc, char** argv) {
|
||||
CHECK(fsr4fg::generate(kCmd, frame(1)) == fgr::OWN && events.empty());
|
||||
return std::puts("PASS no-file"), 0;
|
||||
}
|
||||
if (scene == "no-model" || scene == "any-version" || scene == "none-listed") {
|
||||
listed = {"3.1.6"}; // (a card without FSR 4's frame generation: AMD's library lists FSR 3.1's alone)
|
||||
if (scene == "fsr31" || scene == "any-version" || scene == "only-fsr4" || scene == "none-listed") {
|
||||
// ((Triforce, FG-1) a card without FSR 4's frame generation (RX 6000, 7000): AMD's library lists FSR 3.1's alone, and
|
||||
// it is taken, by default and with RX_VK_FSR4_FG=1; RX_VK_FSR4_FG=4 refuses it, as every run did before
|
||||
listed = {"3.1.6"};
|
||||
if (scene == "none-listed") listed.clear();
|
||||
if (scene == "any-version") env["RX_VK_FSR4_FG"] = 1, chosen_id = kIds[0];
|
||||
if (scene == "any-version") {
|
||||
CHECK(fsr4fg::why() == fgr::FG_OK && !std::strcmp(fsr4fg::version(), "3.1.6"));
|
||||
if (scene == "any-version") env["RX_VK_FSR4_FG"] = 1;
|
||||
if (scene == "only-fsr4") env["RX_VK_FSR4_FG"] = 4;
|
||||
chosen_id = kIds[0];
|
||||
if (scene == "fsr31" || scene == "any-version") {
|
||||
CHECK(fsr4fg::why() == fgr::FG_OK && fsr4fg::offered() && !std::strcmp(fsr4fg::version(), "3.1.6"));
|
||||
CHECK(has_log("using 3.1.6") && has_log("FSR 3.1's frame generation"));
|
||||
CHECK(fsr4fg::generate(kCmd, frame(1)) == fgr::SKIP && fsr4fg::generate(kCmd, frame(2)) == fgr::MADE);
|
||||
} else {
|
||||
CHECK(fsr4fg::why() == fgr::FG_NO_MODEL && !fsr4fg::offered());
|
||||
CHECK(fsr4fg::generate(kCmd, frame(1)) == fgr::OWN && events.empty() && !contexts_made);
|
||||
CHECK(scene == "none-listed" || has_log("3.1.6")); // (the log names what AMD's library has)
|
||||
CHECK(scene == "none-listed" || (has_log("3.1.6") && has_log("RX_VK_FSR4_FG=4"))); // (the log names what AMD's library has)
|
||||
}
|
||||
return std::puts("PASS versions"), 0;
|
||||
}
|
||||
if (scene == "no-hudless" || scene == "hdr-native") {
|
||||
// ((Triforce, FG-2, FG-5) the scene's depth and motion are there, the picture without the HUD is not (or HDR Native's
|
||||
// picture): AMD's library is not given the frame and no context is made for it. Without the picture without the HUD,
|
||||
// the game's frame is shown alone (GAME); HDR Native's picture, which no picture without the HUD can follow, goes to
|
||||
// the renderer's own (OWN: it makes the frame, as at 2x). Each reason said once. Then with it: a new history (the
|
||||
// frames in between were not given), and on from there
|
||||
CHECK(fsr4fg::why() == fgr::FG_OK);
|
||||
const int calls = amd_calls;
|
||||
for (uint64_t i = 1; i <= 3; i++) {
|
||||
fsr4fg::Inputs in = frame(i);
|
||||
if (scene == "no-hudless") in.hudless = VK_NULL_HANDLE;
|
||||
else in.pq = true; // (with the picture without the HUD too: HDR Native first)
|
||||
CHECK(fsr4fg::generate(kCmd, in) == (scene == "no-hudless" ? fgr::GAME : fgr::OWN) && fsr4fg::made_image() == VK_NULL_HANDLE);
|
||||
}
|
||||
CHECK(amd_calls == calls && !contexts_made && events.empty());
|
||||
CHECK(has_log(scene == "no-hudless" ? "no picture without the HUD this frame" : "paused with HDR Native"));
|
||||
int said = 0;
|
||||
for (const std::string& l : logged)
|
||||
said += l.find(scene == "no-hudless" ? "the game's frame alone" : "the renderer's own makes the frame, as at 2x") != std::string::npos;
|
||||
CHECK(said == 1);
|
||||
CHECK(fsr4fg::generate(kCmd, frame(4)) == fgr::SKIP && fsr4fg::generate(kCmd, frame(5)) == fgr::MADE);
|
||||
return std::puts("PASS held"), 0;
|
||||
}
|
||||
if (scene == "fsr31-hdr-native" || scene == "fsr31-hdr-scene" || scene == "hdr-scene") {
|
||||
// ((Triforce) a saved 9 on an RX 6000 or 7000 (AMD's library lists 3.1.6 alone) with HDR Native's picture, or in a
|
||||
// run with RenoDX's RGBA16F scene (the owner's: RX 7900 XT, HDR Native and RenoDX). Before AMD's FSR 3.1 frame
|
||||
// generation was offered there, the row showed and ran 2x (shown(9, false)). It is offered now and its version on the
|
||||
// row, but these hold it from every present: AMD's library is never asked for the frame, no input is wanted for it,
|
||||
// and the renderer's own makes the one frame (OWN), never the game's frame alone. Gone again, AMD's makes them
|
||||
if (scene != "hdr-scene") listed = {"3.1.6"};
|
||||
const fgr::Held held = scene == "fsr31-hdr-native" ? fgr::HELD_HDR_NATIVE : fgr::HELD_HDR_SCENE;
|
||||
CHECK(fsr4fg::why() == fgr::FG_OK && fsr4fg::offered() && fsr4fg::frames_wanted());
|
||||
CHECK(!std::strcmp(fsr4fg::version(), scene == "hdr-scene" ? "4.0.2" : "3.1.6"));
|
||||
const int calls = amd_calls;
|
||||
fsr4fg::held_now = held;
|
||||
CHECK(!fsr4fg::frames_wanted()); // (vk_fsr3_inputs.cpp wanted() and framegen_hudless_note make nothing for it)
|
||||
for (uint64_t i = 1; i <= 4; i++) {
|
||||
fsr4fg::Inputs in = frame(i);
|
||||
in.pq = held == fgr::HELD_HDR_NATIVE;
|
||||
const fgr::Made m = fsr4fg::generate(kCmd, in);
|
||||
CHECK(m == fgr::OWN && !fgr::game_frame_alone(m) && fsr4fg::made_image() == VK_NULL_HANDLE);
|
||||
}
|
||||
CHECK(amd_calls == calls && !contexts_made && events.empty());
|
||||
fsr4fg::held_now = fgr::HELD_NONE;
|
||||
CHECK(fsr4fg::frames_wanted());
|
||||
CHECK(fsr4fg::generate(kCmd, frame(5)) == fgr::SKIP && fsr4fg::generate(kCmd, frame(6)) == fgr::MADE);
|
||||
return std::puts("PASS held for the run"), 0;
|
||||
}
|
||||
if (scene == "env-off" || scene == "fsr4-off") {
|
||||
env[scene == "env-off" ? "RX_VK_FSR4_FG" : "RX_VK_FSR4"] = 0;
|
||||
CHECK(fsr4fg::why() == fgr::FG_ENV_OFF && !fsr4fg::frames_wanted() && !library_loads && !amd_calls);
|
||||
@@ -611,6 +743,7 @@ int main(int argc, char** argv) {
|
||||
bare.depth = VK_NULL_HANDLE;
|
||||
const int calls = amd_calls;
|
||||
CHECK(fsr4fg::generate(kCmd, bare) == fgr::OWN && amd_calls == calls && take().empty());
|
||||
CHECK(has_log("a present without the scene's depth and motion")); // ((Triforce) said, once: the lab's run had no such line)
|
||||
// another picture size: the GPU idle, AMD's context destroyed, then the image; then both made again, a new history
|
||||
CHECK(fsr4fg::generate(kCmd, frame(12, 40.1f, 1920, 1080, 1920, 1080)) == fgr::SKIP);
|
||||
CHECK(is(take(), {"wait_gpu", "destroy_context", "destroy_image", "create_image 1920x1080", "create_context 1920x1080", "image to GENERAL",
|
||||
@@ -652,9 +785,13 @@ def source_checks():
|
||||
|
||||
# the default stays Off, and the row's table takes an options file's AMD FSR 4 before the graphics card is known
|
||||
need(header, "int framegen = 0;", "vk_menu.h (the Frame generation row's default)")
|
||||
need(menu, '{TAB_GRAPHICS, "Frame generation", &opts.framegen, 0, 9, 1, tx_framegen,', "vk_menu.cpp rows[]")
|
||||
# ((Triforce, options_version 7) the saved value's own row is hidden and ends at AMD FSR 4 (kRowMax, 9), so a file's 9
|
||||
# loads before the card is known; the Graphics tab's Frame generation row is merged_rows.h's, its choices framegen_list)
|
||||
need(menu, '{TAB_HIDDEN, "Frame generation", &opts.framegen, 0, framegen_rows::kRowMax, 1, tx_framegen, nullptr}',
|
||||
"vk_menu.cpp rows[]")
|
||||
sync = function(menu, "void framegen_row_sync() {")
|
||||
need(sync, "r.hi = framegen_rows::row_hi(fsr4fg::offered_known())", "framegen_row_sync") # ((Triforce) as known: menu_ahead)
|
||||
need(sync, "mr7::framegen_choices(framegen_list, fsr4fg::offered_known(), dlssg_offered())",
|
||||
"framegen_row_sync") # ((Triforce) as known: menu_ahead)
|
||||
need(sync, "framegen_rows::kRowMax == 9", "framegen_row_sync")
|
||||
if menu.count("framegen_row_sync();") < 2:
|
||||
raise SystemExit("vk_menu.cpp: the Frame generation row's end is not set at both places the menu opens")
|
||||
@@ -665,15 +802,43 @@ def source_checks():
|
||||
need(function(framegen, "int multiplier() {"), "if (opts.framegen == framegen_rows::FSR4) return 2;", "vk_framegen.cpp multiplier")
|
||||
record = function(framegen, "bool framegen_record(")
|
||||
for what in ("if (opts.framegen == framegen_rows::FSR4) {", "fsr4_frame(cmd, *set, cur, uw, uh, sequence, blend)",
|
||||
"none = by_fsr4 == framegen_rows::SKIP;", "if (set->made == 0 && !none && blend && m > 1) {"):
|
||||
"none = framegen_rows::game_frame_alone(by_fsr4);", "if (set->made == 0 && !none && blend && m > 1) {",
|
||||
"fg.src_w = sw, fg.src_h = sh, fg.source = source;"):
|
||||
need(record, what, "framegen_record")
|
||||
# ((Triforce) the renderer's own vectors are make_vectors')
|
||||
if not record.index("fsr4_frame(") < record.index("fsr3fi_frame(") < record.index("make_vectors(cmd", record.index("fsr4_frame(")):
|
||||
raise SystemExit("framegen_record: AMD FSR 4 is not asked before the renderer's own interpolation")
|
||||
frame = function(framegen, "framegen_rows::Made fsr4_frame(")
|
||||
for what in ("if (!fsr4fg::frames_wanted()) return framegen_rows::OWN;", "fsr3_inputs::take(f)", "in.reset = f.reset || !blend;",
|
||||
"in.sequence = sequence;", "fsr4fg::generate(cmd, in)", "set.frame[0].image"):
|
||||
for what in ("if (!fsr4fg::frames_wanted()) {", "framegen_rows::why_name(", "fsr3_inputs::take(f)", "in.reset = f.reset || !blend;",
|
||||
"in.sequence = sequence;", "fsr4fg::generate(cmd, in)", "set.frame[0].image",
|
||||
# ((Triforce, FG-2) this frame's picture without the HUD, none with HDR Native; what it answered counted
|
||||
"in.hudless = in.pq ? VK_NULL_HANDLE : hudless_for(cmd, f.frame, uw, uh);",
|
||||
"framegen_rows::game_frame_alone(made) ? made : framegen_rows::OWN"):
|
||||
need(frame, what, "fsr4_frame")
|
||||
# ((Triforce, FG-2) the picture without the HUD: this frame's alone, cut as the picture is, its bytes as AMD's library takes them
|
||||
hudless = function(framegen, "VkImage hudless_for(VkCommandBuffer cmd, uint64_t frame, uint32_t w, uint32_t h) {")
|
||||
for what in ("k.valid && k.frame == frame", "framegen_rows::hudless_source(t->w, t->h, fg.src_w, fg.src_h",
|
||||
"VK_FORMAT_R8G8B8A8_SRGB", "vkCmdCopyImage(cmd, hl.srgb.image, VK_IMAGE_LAYOUT_GENERAL, hl.out.image"):
|
||||
need(hudless, what, "vk_framegen.cpp hudless_for")
|
||||
note = function(framegen, "void framegen_hudless_note(VkCommandBuffer cmd, Texture* out, uint32_t level) {")
|
||||
for what in ("fsr4fg::frames_wanted()", "present_native_pq.load", "VK_FORMAT_B10G11R11_UFLOAT_PACK32", "vkCmdBlitImage(",
|
||||
"t.frame = texture_frame_no()"):
|
||||
need(note, what, "vk_framegen.cpp framegen_hudless_note")
|
||||
need(fsr4, "c.HUDLessColor = image_resource(in.hudless,", "vk_fsr4.cpp generate")
|
||||
# ((Triforce) HDR Native and RenoDX's RGBA16F scene hold AMD's library from every present: nothing is wanted for it, the
|
||||
# renderer's own makes the frame, and the menu's line says so by the same rule, not by the HDR row alone
|
||||
need(function(fsr4, "bool frames_wanted() {"), "!fgr::held_whole_run(held())", "vk_fsr4.cpp frames_wanted")
|
||||
held = function(fsr4, "framegen_rows::Held fsr4fg::held() {")
|
||||
for what in ("present_native_pq.load(", "temporal_scene_format(VK_FORMAT_R16G16B16A16_SFLOAT)"):
|
||||
need(held, what, "vk_fsr4.cpp fsr4fg::held")
|
||||
if fsr4.index("framegen_rows::Held fsr4fg::held() {") < fsr4.rindex("#endif"):
|
||||
raise SystemExit("vk_fsr4.cpp: fsr4fg::held is not outside the build's FSR sections (the menu reads it in every build)")
|
||||
need(function(fsr4, "framegen_rows::Made generate("), "return fgr::held_made(held);", "vk_fsr4.cpp generate")
|
||||
hn = function(menu, "const char* hn_framegen_fsr4(int variant) {")
|
||||
need(hn, "framegen_rows::held_whole_run(fsr4fg::held()) ? native : ok", "hn_framegen_fsr4")
|
||||
if "opts.hdr" in hn:
|
||||
raise SystemExit("hn_framegen_fsr4: the pause is read from the HDR row, not from what holds AMD's library (fsr4fg::held)")
|
||||
need(fsr4, "s.desc.header.pNext = &s.hudless.header;", "vk_fsr4.cpp make (the HUD-less format linked)")
|
||||
# its inputs are gathered while it is asked, its context looked after each present, and the exit reaches it
|
||||
need(inputs, "|| fsr4fg::frames_wanted()", "vk_fsr3_inputs.cpp wanted()")
|
||||
need(framegen, "void framegen_present_tick() { fsr4fg::present_tick(); }", "vk_framegen.cpp")
|
||||
@@ -699,13 +864,16 @@ def source_checks():
|
||||
# the rows are documented
|
||||
readme = (ROOT / "readme.md").read_text(encoding="utf-8")
|
||||
row = [line for line in readme.splitlines() if line.startswith("| Frame generation |")]
|
||||
if len(row) != 1 or "AMD FSR 4" not in row[0] or "2x up to 8x" not in row[0]:
|
||||
raise SystemExit("readme.md: the Frame generation row does not list its choices with AMD FSR 4")
|
||||
if len(row) != 1 or "AMD FSR (" not in row[0] or "2x up to 8x" not in row[0] or "3.1.6" not in row[0]:
|
||||
raise SystemExit("readme.md: the Frame generation row does not list its choices with AMD FSR and its version")
|
||||
dev = (ROOT / "docs" / "development.md").read_text(encoding="utf-8")
|
||||
key = [line for line in dev.splitlines() if line.startswith("| `frame_generation` |")]
|
||||
if len(key) != 1 or "9 AMD FSR 4" not in key[0] or "2 to 8 the multiplier" not in key[0]:
|
||||
raise SystemExit("docs/development.md: frame_generation's values do not list 9, AMD FSR 4")
|
||||
need(dev, "`RX_VK_FSR4_FG=0/1`", "docs/development.md (the switches)")
|
||||
if len(key) != 1 or "9 AMD FSR frame generation" not in key[0] or "2 to 8 the multiplier" not in key[0]:
|
||||
raise SystemExit("docs/development.md: frame_generation's values do not list 9, AMD FSR frame generation")
|
||||
need(dev, "`RX_VK_FSR4_FG=0/1/4`", "docs/development.md (the switches)")
|
||||
need(dev, "`RX_VK_FRAMEGEN_MULT=<0..9>`", "docs/development.md (the row's pin, 9 among it)")
|
||||
need(dev, "`RX_VK_FG_OWN_MOTION=0`", "docs/development.md (frame generation's motion)")
|
||||
need(dev, "`RX_VK_FG_HUDLESS=0`", "docs/development.md (the picture without the HUD)")
|
||||
print("PASS: the row, the made frame, the present's tick, the exit and the documents are wired to AMD FSR 4's frame generation")
|
||||
|
||||
|
||||
@@ -733,8 +901,9 @@ def main():
|
||||
there, bare = Path(tmp) / "with", Path(tmp) / "without"
|
||||
there.mkdir(), bare.mkdir()
|
||||
(there / "amd_fidelityfx_framegeneration_vk.dll").write_bytes(b"a stand-in: only looked for by its name")
|
||||
scenes = ["play", "no-device", "no-library", "no-configure", "no-model", "none-listed", "any-version", "env-off", "fsr4-off",
|
||||
"row", "create-fails", "image-fails", "dispatch-fails", "configure-fails", "exit"]
|
||||
scenes = ["play", "no-device", "no-library", "no-configure", "fsr31", "only-fsr4", "none-listed", "any-version", "env-off",
|
||||
"fsr4-off", "row", "no-hudless", "hdr-native", "fsr31-hdr-native", "fsr31-hdr-scene", "hdr-scene", "create-fails", "image-fails", "dispatch-fails", "configure-fails",
|
||||
"exit"]
|
||||
build_and_run(a.cxx, tmp, "fg", text,
|
||||
["-I" + str(a.headers), "-I" + str(ROOT / "third_party" / "fidelityfx"), "-I" + str(VK), "-Wno-unknown-pragmas",
|
||||
"-Wno-unused-function", "-Wno-unused-variable", "-Wno-unused-const-variable", "-Wno-unused-parameter",
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
"""Quality presets preserve the player's frame-generation choice.
|
||||
"""The Insert menu's Frame generation row (Triforce, options_version 7): one row for the renderer's own made frames, AMD FSR 4's
|
||||
and NVIDIA DLSS's, which was a row of its own (gpu/vk/merged_rows.h). Before, this checked that a Quality preset left the
|
||||
row alone; the preset is gone.
|
||||
|
||||
Compile the menu's actual preset and row handlers with small stand-ins.
|
||||
Check that the game FPS cap keeps its saved key when its label changes. No game
|
||||
or GPU is needed.
|
||||
The menu's own set_row, merged_step, merged_store, merged_sync and framegen_row_sync are compiled with small stand-ins and
|
||||
stepped as the arrows step them: the choices offered are those that run here, a DLSS value sets dlss_frame_generation and
|
||||
turns the renderer's own off, and the restart is asked for DLSS's alone. The Frame rate cap keeps its saved key. No game or
|
||||
GPU is needed.
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
@@ -39,23 +42,29 @@ FIXTURE = r"""
|
||||
#include <cctype>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include "@ROOT@/gpu/vk/merged_rows.h"
|
||||
#include "@ROOT@/gpu/vk/framegen_rows.h"
|
||||
|
||||
#define CHECK(x) do { if (!(x)) { std::fprintf(stderr, "FAIL %d: %s\n", __LINE__, #x); return 1; } } while (0)
|
||||
namespace mkwvk {
|
||||
/* OPTIONS */
|
||||
Options opts;
|
||||
/* TABS */
|
||||
/* ROW */
|
||||
namespace mr7 = merged_rows;
|
||||
/* MERGED */
|
||||
int saves = 0;
|
||||
void save() { ++saves; }
|
||||
void apply_pad_layout(int) {}
|
||||
void sync_preset_budgets(int) {}
|
||||
bool row_fixed(const int*) { return false; }
|
||||
int upscaler() { return 0; }
|
||||
unsigned upscalers_available() { return 1; }
|
||||
namespace ur {
|
||||
struct Scaling { int upscaler, resolution; };
|
||||
Scaling step_engine(int, int v, int, unsigned) { return {0, v}; }
|
||||
Scaling step_resolution(int, int v, int dir) { return {0, v + dir}; }
|
||||
int snap(int, int value) { return value; }
|
||||
int step(int, int value, int dir) { return value + dir; }
|
||||
int step_upscaler(int, int dir, unsigned) { return dir; }
|
||||
bool full_scale(int) { return false; }
|
||||
}
|
||||
namespace mr { constexpr int kMax = 8; }
|
||||
void restart_values(int*) {}
|
||||
@@ -63,46 +72,66 @@ struct { void note(const int*) {} } restart_state;
|
||||
bool can_mic() { return false; }
|
||||
void mic_chosen() {}
|
||||
int step_output_choice(int id, int dir) { return id + dir; }
|
||||
const char* tx_framegen(int) { return ""; }
|
||||
const char* hn_framegen(int, int) { return ""; }
|
||||
const char* tx_preset(int) { return ""; }
|
||||
const char* hn_preset(int, int) { return ""; }
|
||||
const char* tx_framegen_row(int) { return ""; }
|
||||
const char* hn_framegen_row(int, int) { return ""; }
|
||||
const char* tx_fps_cap(int) { return ""; }
|
||||
/* (what runs here: AMD FSR 4's frame generation, DLSS frame generation, the card's maker for Low latency) */
|
||||
bool fsr4_here = false, dlssg_here = false;
|
||||
namespace fsr4fg { bool offered_known() { return fsr4_here; } }
|
||||
bool dlssg_offered() { return dlssg_here; }
|
||||
bool renodx_built() { return true; }
|
||||
mr7::Vendor latency_vendor() { return mr7::LATENCY_AMD; }
|
||||
/* LISTS */
|
||||
/* SYNC */
|
||||
/* MERGED_FUNCTIONS */
|
||||
/* INI_KEY */
|
||||
/* STOPS */
|
||||
/* PRESET */
|
||||
/* RESTART_VALUE */
|
||||
/* SET_ROW */
|
||||
} // namespace mkwvk
|
||||
using namespace mkwvk;
|
||||
|
||||
int main() {
|
||||
Row framegen = /* FRAMEGEN_ROW */;
|
||||
Row quality = /* QUALITY_ROW */;
|
||||
Row fps_cap = /* FPS_CAP_ROW */;
|
||||
CHECK(std::strcmp(fps_cap.name, "Game frame rate cap") == 0);
|
||||
CHECK(std::strcmp(fps_cap.name, "Frame rate cap") == 0);
|
||||
CHECK(std::strcmp(ini_key(fps_cap), "frame_rate_cap") == 0);
|
||||
CHECK(std::strstr(fps_cap.help, "Generated frames are additional") != nullptr);
|
||||
CHECK(opts.framegen == 0);
|
||||
for (int previous = 0; previous <= 8; ++previous) {
|
||||
for (int preset = 0; preset <= 5; ++preset) {
|
||||
opts = Options{};
|
||||
opts.framegen = previous;
|
||||
set_row(quality, preset, 1);
|
||||
CHECK(opts.preset == preset);
|
||||
CHECK(opts.framegen == previous);
|
||||
}
|
||||
CHECK(std::strstr(fps_cap.help, "made frames come on top") != nullptr);
|
||||
CHECK(framegen.value == &merged.framegen && framegen.restart && !ini_row(framegen));
|
||||
CHECK(opts.framegen == 0 && opts.dlssg == 0);
|
||||
/* without FSR 4's and DLSS's frame generation here: Off, Auto, 2x to 8x, round */
|
||||
framegen_row_sync();
|
||||
merged_sync();
|
||||
for (int want : {1, 2, 3, 4, 5, 6, 7, 8, 0}) {
|
||||
set_row(framegen, *framegen.value + 1, 1);
|
||||
CHECK(opts.framegen == want && opts.dlssg == 0 && merged.framegen == want && restart_value_of(framegen) == 0);
|
||||
}
|
||||
CHECK(framegen.preset_exempt && !framegen.restart);
|
||||
for (int preset = 1; preset <= 5; ++preset) {
|
||||
opts = Options{};
|
||||
opts.preset = preset;
|
||||
set_row(framegen, 2, 1);
|
||||
CHECK(opts.framegen == 2 && opts.preset == preset);
|
||||
set_row(framegen, 0, -1);
|
||||
CHECK(opts.framegen == 0 && opts.preset == preset);
|
||||
/* with both: 8x, AMD FSR 4, NVIDIA DLSS 2x, 3x, 4x, then Off; DLSS's turn the renderer's own off, and take the restart */
|
||||
fsr4_here = dlssg_here = true;
|
||||
framegen_row_sync();
|
||||
opts.framegen = 8, merged_sync();
|
||||
set_row(framegen, *framegen.value + 1, 1);
|
||||
CHECK(opts.framegen == framegen_rows::FSR4 && opts.dlssg == 0);
|
||||
for (int dlss = 1; dlss <= 3; dlss++) {
|
||||
set_row(framegen, *framegen.value + 1, 1);
|
||||
CHECK(opts.dlssg == dlss && opts.framegen == 0 && merged.framegen == mr7::FG_DLSS + dlss - 1 && restart_value_of(framegen) == dlss);
|
||||
}
|
||||
CHECK(std::strstr(quality.help, "Frame generation") != nullptr);
|
||||
CHECK(std::strstr(quality.help, "stay yours") != nullptr);
|
||||
set_row(framegen, *framegen.value + 1, 1);
|
||||
CHECK(opts.dlssg == 0 && opts.framegen == 0);
|
||||
set_row(framegen, *framegen.value - 1, -1); /* (Left from Off: NVIDIA DLSS 4x) */
|
||||
CHECK(opts.dlssg == 3 && opts.framegen == 0);
|
||||
/* a saved AMD FSR 4 where its library does not run: kept until stepped, the steps from it as from 8x */
|
||||
fsr4_here = false;
|
||||
framegen_row_sync();
|
||||
opts.dlssg = 0, opts.framegen = framegen_rows::FSR4, merged_sync();
|
||||
CHECK(merged.framegen == framegen_rows::FSR4);
|
||||
set_row(framegen, *framegen.value + 1, 1);
|
||||
CHECK(opts.dlssg == 1 && opts.framegen == 0);
|
||||
opts.dlssg = 0, opts.framegen = framegen_rows::FSR4, merged_sync();
|
||||
set_row(framegen, *framegen.value - 1, -1);
|
||||
CHECK(opts.framegen == 8 && opts.dlssg == 0);
|
||||
CHECK(saves > 0);
|
||||
std::puts("PASS: quality presets preserve frame generation and its row preserves the preset");
|
||||
std::puts("PASS: the Frame generation row steps through what runs here, DLSS's values its own, and the cap keeps its key");
|
||||
}
|
||||
"""
|
||||
|
||||
@@ -115,20 +144,35 @@ def fixture(source):
|
||||
row = re.search(r"struct Row \{.*?\n\};", menu, re.S)
|
||||
if not options or not tabs or not row:
|
||||
raise SystemExit("the menu's options, tabs, or row definition is missing")
|
||||
fps_cap = re.search(r'\{TAB_GRAPHICS, "[^"]+", &opts\.fps_cap,', menu)
|
||||
fps_cap = re.search(r'\{TAB_GRAPHICS, "Frame rate cap", &opts\.fps_cap,', menu)
|
||||
if not fps_cap:
|
||||
raise SystemExit("missing game frame rate cap row")
|
||||
raise SystemExit("missing Frame rate cap row")
|
||||
merged = menu[menu.index("struct Merged {"):menu.index("bool is_merged(const int* v)")]
|
||||
merged += menu[menu.index("bool is_merged(const int* v)"):].split("\n", 1)[0] + "\n"
|
||||
lists = menu[menu.index("int framegen_list["):menu.index("bool dlssg_offered() {")]
|
||||
# (the saved values' own rows: no tab shows them, and the merged row takes the restart for DLSS's)
|
||||
for hidden in ('{TAB_HIDDEN, "Frame generation", &opts.framegen, 0, framegen_rows::kRowMax, 1, tx_framegen, nullptr},',
|
||||
'{TAB_HIDDEN, "DLSS frame generation", &opts.dlssg, 0, 3, 1, tx_dlssg, nullptr},'):
|
||||
if hidden not in menu:
|
||||
raise SystemExit("vk_menu.cpp does not keep a merged value under its key: " + hidden)
|
||||
if '"DLSS frame generation", &opts.dlssg, 0, 3, 1, tx_dlssg,\n' in menu:
|
||||
raise SystemExit("DLSS frame generation is still a row of its own")
|
||||
replacements = {
|
||||
"/* OPTIONS */": options.group(0),
|
||||
"/* TABS */": tabs.group(0),
|
||||
"/* ROW */": row.group(0),
|
||||
"/* MERGED */": merged,
|
||||
"/* LISTS */": lists,
|
||||
"/* SYNC */": definition(menu, "void framegen_row_sync"),
|
||||
"/* MERGED_FUNCTIONS */": definition(menu, "void merged_sync") + "\n" + definition(menu, "void merged_store") + "\n" +
|
||||
definition(menu, "int merged_step"),
|
||||
"/* STOPS */": definition(menu, "bool stops_at_ends"),
|
||||
"/* INI_KEY */": definition(menu, "const char* ini_key"),
|
||||
"/* INI_KEY */": definition(menu, "const char* ini_key") + "\n" + definition(menu, "bool ini_row"),
|
||||
"/* RESTART_VALUE */": definition(menu, "int restart_value_of"),
|
||||
"/* FPS_CAP_ROW */": block(menu, fps_cap.start()),
|
||||
"/* PRESET */": definition(menu, "void apply_preset"),
|
||||
"/* SET_ROW */": definition(menu, "void set_row"),
|
||||
"/* FRAMEGEN_ROW */": block(menu, menu.index('{TAB_GRAPHICS, "Frame generation"')),
|
||||
"/* QUALITY_ROW */": block(menu, menu.index('{TAB_GRAPHICS, "Quality preset"')),
|
||||
"@ROOT@": source.as_posix(),
|
||||
}
|
||||
result = FIXTURE
|
||||
for marker, value in replacements.items():
|
||||
|
||||
103
tests/test_fsr3_hdr_scene.py
Normal file
103
tests/test_fsr3_hdr_scene.py
Normal file
@@ -0,0 +1,103 @@
|
||||
"""(Triforce) AMD FSR 3.1 draws in an RGBA16F run (RenoDX's HDR Native: host/nn_vi.c hos_scene_rgba16f), with Upscale before
|
||||
bloom off and on. It never did: at the upscale's dispatch gpu/vk/vk_fsr3.cpp fsr3_upscale returned what the before-bloom
|
||||
dispatch said (false with the row off) for an RGBA16F network and refused any output but B10G11R11, and before the bloom
|
||||
vk_temporal.cpp temporal_pre_tonemap turned an RGBA16F scene away for FSR 3.1, whose pass there wrote B10G11R11 alone. The
|
||||
game's own upscale ran each frame while the menu said AMD FSR 3.1.
|
||||
|
||||
What must hold, read from the source (no game, no GPU):
|
||||
- fsr3_upscale: no early return for an RGBA16F network; its inputs made with the colour unclamped (hdr: the network samples
|
||||
the square root of HDR colour, over 1 where the scene is brighter); an RGBA16F output taken for an RGBA16F input, written
|
||||
through dlss_out.comp's -DHDR layout (dlss_out_hdr_comp_spv.h) squared (linear 2), the B10G11R11 one as before (0);
|
||||
- the shaders it relies on: dlss_out.comp's -DHDR layout declares an rgba16f output and squares at linear 2, fsr3_prep.comp
|
||||
keeps the colour unclamped with flag 4;
|
||||
- before the bloom: temporal_pre_tonemap takes an RGBA16F scene for FSR 3.1, and pre_fsr3 writes FSR's picture back
|
||||
through the -DHDR layout for it, its copy in the scene's own format.
|
||||
The old lines fail.
|
||||
|
||||
python -I -B tests/test_fsr3_hdr_scene.py
|
||||
"""
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
VK = ROOT / "gpu" / "vk"
|
||||
|
||||
|
||||
def check(cond, what):
|
||||
if not cond:
|
||||
raise SystemExit("FAIL: " + what)
|
||||
|
||||
|
||||
def function(source, head):
|
||||
start = source.index(head)
|
||||
return source[start:source.index("\n}\n", start) + 3]
|
||||
|
||||
|
||||
def checks(fsr3, temporal, out_comp, prep_comp):
|
||||
up = function(fsr3, "bool fsr3_upscale(VkCommandBuffer cmd, uint64_t key, bool known, Texture* in, VkImageView in_view, Texture* out,")
|
||||
check("return temporal_pre_dispatch(cmd, in, in_view, out, out_view, out_level, true);" not in up,
|
||||
"fsr3_upscale still leaves an RGBA16F network to the before-bloom dispatch's answer")
|
||||
check("const bool hdr = in->format == VK_FORMAT_R16G16B16A16_SFLOAT;" in up and
|
||||
"fsr3_inputs::prepare(cmd, in, in_view, f, hdr)" in up, "an RGBA16F network's colour is clamped at 1 for FSR")
|
||||
check("const bool out_ok = hdr ? out->format == VK_FORMAT_R16G16B16A16_SFLOAT && temporal_scene_format(in->format)" in up and
|
||||
": out->format == VK_FORMAT_B10G11R11_UFLOAT_PACK32;" in up, "fsr3_upscale does not take an RGBA16F output")
|
||||
check("out->format != VK_FORMAT_B10G11R11_UFLOAT_PACK32 ||" not in up, "fsr3_upscale still refuses any output but B10G11R11")
|
||||
check("make_out_pipeline(hdr)" in up and "hdr ? o.pipe_hdr : o.pipe" in up and "hdr ? 2 : 0" in up,
|
||||
"FSR's picture is not written through the -DHDR output pass, squared, into an RGBA16F output")
|
||||
check(up.index("const bool hdr") < up.index("fsr3_inputs::prepare(cmd, in, in_view, f, hdr)") < up.index("make_out_pipeline(hdr)"),
|
||||
"fsr3_upscale's HDR steps are out of order")
|
||||
made = function(fsr3, "bool make_out_pipeline(bool hdr) {")
|
||||
check("DLSS_OUT_HDR_COMP_SPV" in made and "o.pipe_hdr" in made, "the -DHDR output pass is never made")
|
||||
check('#include "shaders/dlss_out_hdr_comp_spv.h"' in fsr3, "vk_fsr3.cpp does not include the -DHDR output pass")
|
||||
pre = function(fsr3, "bool fsr3_pre(")
|
||||
check("fsr3_inputs::prepare(cmd, scene, scene_view, f, true)" in pre, "before the bloom FSR's colour is not the scene's own")
|
||||
# the shaders: -DHDR writes rgba16f and squares at 2; fsr3_prep's flag 4 does not clamp at 1
|
||||
hdr_part = out_comp[out_comp.index("#ifdef HDR"):]
|
||||
check("layout(binding = 1, rgba16f) uniform writeonly image2D dst;" in hdr_part, "dlss_out.comp's -DHDR layout writes no rgba16f")
|
||||
check("else if (pc.linear == 2) c *= c;" in out_comp, "dlss_out.comp's -DHDR layout no longer squares at linear 2")
|
||||
check("(pc.flags & 4) != 0 ? min(max(c, vec3(0.0)), vec3(64000.0)) : clamp(c, 0.0, 1.0)" in prep_comp,
|
||||
"fsr3_prep.comp no longer keeps the colour unclamped with flag 4")
|
||||
# before the bloom
|
||||
tone = function(temporal, "Texture* temporal_pre_tonemap(VkCommandBuffer cmd) {")
|
||||
check("if (f3 && scene->format != VK_FORMAT_B10G11R11_UFLOAT_PACK32) return nullptr;" not in tone,
|
||||
"temporal_pre_tonemap still turns an RGBA16F scene away for FSR 3.1")
|
||||
pre3 = function(temporal, "bool pre_fsr3(")
|
||||
check("const bool wide = scene->format == VK_FORMAT_R16G16B16A16_SFLOAT;" in pre3 and "make_pipelines(wide)" in pre3 and
|
||||
"make_image(cmd, s.base, scene->format, rw, rh)" in pre3 and "wide ? s.out_hdr : s.out" in pre3,
|
||||
"pre_fsr3 does not write FSR's picture into an RGBA16F scene through the -DHDR layout")
|
||||
check("make_pipelines(false)" not in pre3 and "VK_FORMAT_B10G11R11_UFLOAT_PACK32, rw, rh" not in pre3,
|
||||
"pre_fsr3 still makes the B10G11R11 pass and copy alone")
|
||||
|
||||
|
||||
MUTATIONS = [
|
||||
("the old early return", "fsr3", " // ((Triforce) an RGBA16F run's network (RenoDX's HDR Native)",
|
||||
" if (in->format == VK_FORMAT_R16G16B16A16_SFLOAT) return temporal_pre_dispatch(cmd, in, in_view, out, out_view, out_level, true);\n"
|
||||
" // ((Triforce) an RGBA16F run's network (RenoDX's HDR Native)"),
|
||||
("the old clamped colour", "fsr3", "fsr3_inputs::prepare(cmd, in, in_view, f, hdr)", "fsr3_inputs::prepare(cmd, in, in_view, f)"),
|
||||
("the plain output pass alone", "fsr3", "hdr ? o.pipe_hdr : o.pipe", "o.pipe"),
|
||||
("the old pre guard", "temporal", " // AMD FSR 3.1's too (pre_fsr3))\n",
|
||||
" // AMD FSR 3.1's too (pre_fsr3))\n if (f3 && scene->format != VK_FORMAT_B10G11R11_UFLOAT_PACK32) return nullptr;\n"),
|
||||
("the old pre pass", "temporal", "wide ? s.out_hdr : s.out);\n vkCmdPushDescriptorSetKHR(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, s.out_layout, 0, 2, w);\n vkCmdPushConstants(cmd, s.out_layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof opc, opc);\n vkCmdDispatch(cmd, (rw + 7)",
|
||||
"s.out);\n vkCmdPushDescriptorSetKHR(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, s.out_layout, 0, 2, w);\n vkCmdPushConstants(cmd, s.out_layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof opc, opc);\n vkCmdDispatch(cmd, (rw + 7)"),
|
||||
]
|
||||
|
||||
|
||||
def main():
|
||||
texts = {"fsr3": (VK / "vk_fsr3.cpp").read_text(encoding="utf-8"),
|
||||
"temporal": (VK / "vk_temporal.cpp").read_text(encoding="utf-8"),
|
||||
"out": (VK / "shaders" / "dlss_out.comp").read_text(encoding="utf-8"),
|
||||
"prep": (VK / "shaders" / "fsr3_prep.comp").read_text(encoding="utf-8")}
|
||||
checks(texts["fsr3"], texts["temporal"], texts["out"], texts["prep"])
|
||||
for name, which, new, old in MUTATIONS:
|
||||
check(new in texts[which], "the mutation '%s' has nothing to change" % name)
|
||||
t = dict(texts)
|
||||
t[which] = t[which].replace(new, old, 1)
|
||||
try:
|
||||
checks(t["fsr3"], t["temporal"], t["out"], t["prep"])
|
||||
except SystemExit:
|
||||
continue
|
||||
raise SystemExit("FAIL: the mutation '%s' passed" % name)
|
||||
print("PASS: AMD FSR 3.1 draws in an RGBA16F run, at the upscale's dispatch and before the bloom; the old lines fail")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
227
tests/test_fsr3_history.py
Normal file
227
tests/test_fsr3_history.py
Normal file
@@ -0,0 +1,227 @@
|
||||
"""(Triforce) AMD FSR 3.1's history and jitter (gpu/vk/vk_fsr3.cpp, vk_fsr3_inputs.cpp) and the camera cut the upscalers share
|
||||
(gpu/vk/framegen_rows.h, vk_temporal.cpp's chain). No game, no GPU.
|
||||
|
||||
1. Compiled and run: framegen_rows.h camera_cut with the upscalers' rule (NX2navi's 2495391: a move over 5 m, or a turn over
|
||||
30 degrees with a move over 0.5 m, per 60th of a second, the time scaled 0.25 to 4 times) and frame generation's (10
|
||||
degrees, 1 to 4 times, as before); fsr3_math.h jitter_phases (AMD's ffxFsr3GetJitterPhaseCount: 8 x the width's scale
|
||||
squared, truncated, no cap) and plan_images (one set of images for the game's dynamic resolution: kept for any frame
|
||||
that fits, made again for another output or a larger frame, at the output's size then and with Auto).
|
||||
2. The source: FSR 3.1's inputs start a new history after a held present and at a camera cut, not at another render size;
|
||||
the chain (DLSS, FSR 4) at a cut too; FSR 3.1's passes are given this frame's render size and the images' as the max,
|
||||
the downsampler's dispatch from the frame's size; the exposure snaps after a reset (the previous log-luma at 1e8); the
|
||||
jitter is AMD's length and stops after a few failed frames; the images are let go once FSR 3.1 has not been used for a
|
||||
while (the chain's temporal_idle calls it); the scenes FSR 3.1's inputs keep a camera of follow the output. The old
|
||||
lines fail.
|
||||
|
||||
python -I -B tests/test_fsr3_history.py [--cxx g++]
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
import subprocess
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
RUN_ALL_ARGS = ["--cxx", "{cxx}"]
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
VK = ROOT / "gpu" / "vk"
|
||||
|
||||
CHECK = r'''
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include "framegen_rows.h"
|
||||
#include "fsr3_math.h"
|
||||
|
||||
#define CHECK(c) do { if (!(c)) { std::fprintf(stderr, "FAIL line %d: %s\n", __LINE__, #c); return 1; } } while (0)
|
||||
|
||||
using namespace mkwvk;
|
||||
namespace fgr = mkwvk::framegen_rows;
|
||||
|
||||
// a camera at x metres along +x, turned by deg degrees from looking down -z (view rows: right, up, back; t = -R pos)
|
||||
static fgr::Pose at(float x, float deg) {
|
||||
const float a = deg * 0.017453293f, c = std::cos(a), s = std::sin(a);
|
||||
const float right[3] = {c, 0, -s}, up[3] = {0, 1, 0}, back[3] = {s, 0, c};
|
||||
const float pos[3] = {x, 0, 0};
|
||||
float v[12];
|
||||
const float* rows[3] = {right, up, back};
|
||||
for (int r = 0; r < 3; r++) {
|
||||
for (int i = 0; i < 3; i++) v[r * 4 + i] = rows[r][i];
|
||||
v[r * 4 + 3] = -(rows[r][0] * pos[0] + rows[r][1] * pos[1] + rows[r][2] * pos[2]);
|
||||
}
|
||||
return fgr::pose_of(v);
|
||||
}
|
||||
|
||||
int main() {
|
||||
const fgr::CutRule up = fgr::kUpscalerCut, fg = fgr::kFrameGenCut;
|
||||
CHECK(up.turn_degrees == 30.0f && up.min_scale == 1.0f && fg.turn_degrees == 10.0f && fg.min_scale == 1.0f);
|
||||
// (a quick swing of the orbiting camera: 11 to 18 degrees and 0.9 to 1.4 m a frame. A cut for frame generation as before,
|
||||
// none for the upscalers, whose history it would throw away at every frame of the swing)
|
||||
CHECK(fgr::camera_cut(at(0, 0), at(1.2f, 15), 16.667f, fg) && fgr::camera_cut(at(0, 0), at(1.2f, 15), 16.667f));
|
||||
CHECK(!fgr::camera_cut(at(0, 0), at(1.2f, 15), 16.667f, up));
|
||||
CHECK(!fgr::camera_cut(at(0, 0), at(1.4f, 18), 16.667f, up));
|
||||
// (a turn over 30 degrees with a move is one; a turn in place is none; an area load is one)
|
||||
CHECK(fgr::camera_cut(at(0, 0), at(0.6f, 35), 16.667f, up) && !fgr::camera_cut(at(0, 0), at(0.4f, 90), 16.667f, up));
|
||||
CHECK(fgr::camera_cut(at(0, 0), at(5.1f, 0), 16.667f, up) && !fgr::camera_cut(at(0, 0), at(4.9f, 0), 16.667f, up));
|
||||
CHECK(!fgr::camera_cut(at(0, 0), at(0.05f, 0.08f), 16.667f, up)); // (play: NX2navi's medians)
|
||||
// (the time: a 30 fps frame may move twice as far, four times at the most; never less than one 60th, as frame
|
||||
// generation's rule: the time is the CPU's between two recordings, and frames recorded back to back after a stall are
|
||||
// a few ms apart)
|
||||
CHECK(!fgr::camera_cut(at(0, 0), at(9.0f, 0), 33.333f, up) && fgr::camera_cut(at(0, 0), at(11.0f, 0), 33.333f, up));
|
||||
CHECK(fgr::camera_cut(at(0, 0), at(21.0f, 0), 500.0f, up) && !fgr::camera_cut(at(0, 0), at(19.0f, 0), 500.0f, up));
|
||||
static const float burst[] = {0.0f, 2.0f, 4.1667f, 8.0f, 16.667f};
|
||||
for (float ms : burst) {
|
||||
// ((Triforce) a swing recorded 2 ms after the frame before (the replay catching up) is still a swing, no cut; nor a
|
||||
// 1 m move, nor a 7.5 degree turn with 0.125 m; an area load still is one
|
||||
CHECK(!fgr::camera_cut(at(0, 0), at(1.2f, 15), ms, up) && !fgr::camera_cut(at(0, 0), at(1.4f, 18), ms, up));
|
||||
CHECK(!fgr::camera_cut(at(0, 0), at(1.0f, 0), ms, up) && !fgr::camera_cut(at(0, 0), at(2.0f, 0), ms, up));
|
||||
CHECK(!fgr::camera_cut(at(0, 0), at(0.2f, 8), ms, up));
|
||||
CHECK(fgr::camera_cut(at(0, 0), at(5.1f, 0), ms, up) && fgr::camera_cut(at(0, 0), at(0.6f, 35), ms, up));
|
||||
}
|
||||
fgr::Pose none;
|
||||
CHECK(fgr::camera_cut(none, at(0, 0), 16.667f, up) && fgr::camera_cut(at(0, 0), at(NAN, 0), 16.667f, up));
|
||||
|
||||
// AMD's jitter length: by the width, truncated, no cap
|
||||
CHECK(fsr3_math::jitter_phases(1280, 1920) == 18); // (Quality, 1.5x)
|
||||
CHECK(fsr3_math::jitter_phases(960, 1920) == 32); // (Performance)
|
||||
CHECK(fsr3_math::jitter_phases(640, 1920) == 72); // (Ultra Performance, 3x: NVIDIA's rule stops at 64)
|
||||
CHECK(fsr3_math::jitter_phases(683, 2048) == 71); // (the game's 4/12 of 2048)
|
||||
CHECK(fsr3_math::jitter_phases(1920, 1920) == 8); // (Native AA)
|
||||
CHECK(fsr3_math::jitter_phases(0, 1920) == 8 && fsr3_math::jitter_phases(1920, 0) == 8);
|
||||
|
||||
// one set of images for the dynamic resolution
|
||||
using fsr3_math::plan_images;
|
||||
auto p = plan_images(0, 0, 0, 0, 1280, 720, 1920, 1080, false); // (a fixed share: its own size)
|
||||
CHECK(p.remake && p.width == 1280 && p.height == 720);
|
||||
p = plan_images(1280, 720, 1920, 1080, 1280, 720, 1920, 1080, false);
|
||||
CHECK(!p.remake && p.width == 1280 && p.height == 720);
|
||||
p = plan_images(1280, 720, 1920, 1080, 1104, 621, 1920, 1080, false); // (a step down: kept, the history goes on)
|
||||
CHECK(!p.remake && p.width == 1280 && p.height == 720);
|
||||
p = plan_images(1280, 720, 1920, 1080, 1360, 765, 1920, 1080, false); // (a step up: once, at the output's size)
|
||||
CHECK(p.remake && p.width == 1920 && p.height == 1080);
|
||||
p = plan_images(1920, 1080, 1920, 1080, 1700, 956, 1920, 1080, false);
|
||||
CHECK(!p.remake);
|
||||
p = plan_images(0, 0, 0, 0, 1280, 720, 1920, 1080, true); // (Auto: at the output's size from the start)
|
||||
CHECK(p.remake && p.width == 1920 && p.height == 1080);
|
||||
p = plan_images(1920, 1080, 1920, 1080, 853, 480, 2560, 1440, false); // (another output: made again)
|
||||
CHECK(p.remake && p.width == 853 && p.height == 480);
|
||||
p = plan_images(0, 0, 0, 0, 1920, 1080, 1920, 1080, true); // (Native AA)
|
||||
CHECK(p.remake && p.width == 1920 && p.height == 1080);
|
||||
p = plan_images(0, 0, 0, 0, 2000, 1100, 1920, 1080, true); // (never smaller than the frame)
|
||||
CHECK(p.remake && p.width == 2000 && p.height == 1100);
|
||||
std::puts("ok");
|
||||
return 0;
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
def check(cond, what):
|
||||
if not cond:
|
||||
raise SystemExit("FAIL: " + what)
|
||||
|
||||
|
||||
def function(source, head, last=False):
|
||||
"""A definition from its first line to its closing brace at the start of a line (last: the last one so named, past a
|
||||
declaration ahead of it)"""
|
||||
start = source.rindex(head) if last else source.index(head)
|
||||
return source[start:source.index("\n}\n", start) + 3]
|
||||
|
||||
|
||||
def checks(fsr3, inputs, temporal):
|
||||
prep = function(inputs, "bool prepare(VkCommandBuffer cmd, Texture* in, VkImageView in_view, Frame& out, bool linear) {")
|
||||
# FSR3-04: after a held present and at a camera cut (the upscalers' rule), and no more at another render size (FSR3-02)
|
||||
check("const bool held = !gap && present_held_last();" in prep, "FSR 3.1's inputs start no new history after a held present")
|
||||
check("framegen_rows::camera_cut(s.last_pose, pose, dt, framegen_rows::kUpscalerCut)" in prep,
|
||||
"FSR 3.1's inputs have no camera cut, or not with the upscalers' 30-degree rule")
|
||||
check("const bool reset = gap || held || cut;" in prep, "FSR 3.1's inputs' reset is not the gap, the hold and the cut")
|
||||
check("s.frame.width != rw" not in prep, "FSR 3.1's inputs still start a new history at another render size")
|
||||
check(prep.index("const bool reset = gap || held || cut;") < prep.index("const bool motion = !reset &&"),
|
||||
"the reset is decided after the motion it turns off")
|
||||
chain = function(temporal, "bool chain(VkCommandBuffer cmd, int mode, Engine& engine, const Camera& cam,", last=True)
|
||||
check("framegen_rows::camera_cut(s.last_pose, pose, dt, framegen_rows::kUpscalerCut)" in chain and
|
||||
"const bool reset = !last || now - last > 2 || present_held_last() || cut;" in chain,
|
||||
"the chain (DLSS, FSR 4) starts no new history at a camera cut")
|
||||
# FSR3-02: the frame's render size into the constants and the downsampler, the images' size as the max
|
||||
up = function(fsr3, "bool upscale(VkCommandBuffer cmd, const Inputs& in) {")
|
||||
check("k.max_render_size[0] = (int32_t)g.render_width" in up and "std::clamp(in.render_width, 1u, g.render_width)" in up,
|
||||
"FSR 3.1 is not given the frame's render size within the images' (maxRenderSize)")
|
||||
check("k.max_render_size[0] = rw" not in up, "FSR 3.1's max render size is still the frame's")
|
||||
check("const uint32_t spd_x = ((uint32_t)rw - 1) / 64 + 1;" in up and "spd.render_size[0] = (uint32_t)rw" in up,
|
||||
"the downsampler is not dispatched over the frame's render size")
|
||||
pre = function(fsr3, "bool prepare(uint32_t render_width, uint32_t render_height, uint32_t upscale_width, uint32_t upscale_height, bool dynamic) {")
|
||||
check("fsr3_math::plan_images(" in pre and "if (!plan.remake) return true;" in pre,
|
||||
"FSR 3.1's images are not kept across the dynamic resolution's steps (plan_images)")
|
||||
# FSR3-08: the exposure snaps after a reset
|
||||
check("info.float32[0] = -1.0f, info.float32[1] = 1e8f;" in up, "FSR 3.1's exposure eases in after a reset (log-luma 1)")
|
||||
# FSR3-11 and FSR3-10: AMD's length, and no jitter once FSR 3.1 failed for a few frames
|
||||
done = function(inputs, "void upscaled(uint32_t rw, uint32_t rh, uint32_t dw, uint32_t dh) {")
|
||||
check("fsr3_math::jitter_phases(rw, dw)" in done and "dlss_jitter_phases" not in done,
|
||||
"FSR 3.1's jitter length is not AMD's")
|
||||
check("s.missed_from.store(0" in done, "a frame FSR 3.1 drew does not end a run of failures")
|
||||
jitter = function(inputs, "uint32_t jitter_size(int axis) {")
|
||||
check("now - miss > kMissedFrames) return 0;" in jitter, "the jitter goes on while FSR 3.1 fails to draw")
|
||||
fail = function(fsr3, "bool fail(const char* why, bool real = true) {")
|
||||
check("if (real) fsr3_inputs::missed();" in fail, "FSR 3.1's failures do not stop the jitter")
|
||||
check('fail("its inputs could not be made", false)' in fsr3, "a frame with no scene camera counts as a failure")
|
||||
in_fail = function(inputs, "bool fail(const char* why) {")
|
||||
check("if (why != kNoCamera) missed();" in in_fail, "the inputs' failures (but no camera) do not stop the jitter")
|
||||
# FSR3-09: let go once not used for a while, from the present's idle tick
|
||||
idle = function(fsr3, "bool fsr3_idle() {")
|
||||
check("if (!fsr3_wanted() && now - last > 120) {" in idle and "fsr3::release();" in idle and
|
||||
"fsr3_inputs::release_idle();" in idle, "FSR 3.1's images are never let go")
|
||||
check("if (fsr3_idle()) {" in function(temporal, "void temporal_idle() {"), "temporal_idle does not let FSR 3.1's images go")
|
||||
rel = function(inputs, "void release_idle() {")
|
||||
check("if (now - s.used_frame <= 120) return;" in rel and "later([old] {" in rel, "FSR 3.1's inputs' images are never let go")
|
||||
# FSR3-14: the scene's camera for a scene 1 to 3 times smaller than the output, 640x360 as before
|
||||
note = function(inputs, "void note_scene_draw(const Texture* color0, uint32_t width, uint32_t height, Texture* depth, uint64_t camera,")
|
||||
check("!scene_size(width, height)" in note and "width < 640" not in note,
|
||||
"FSR 3.1's inputs still keep no camera for a scene under 640x360")
|
||||
size = function(inputs, "bool scene_size(uint32_t width, uint32_t height) {")
|
||||
check("if (width >= 640 && height >= 360) return true;" in size and "dlss_checks::scene_size_fits(width, height, ow, oh)" in size,
|
||||
"the scene size rule is not 640x360 or the chain's")
|
||||
check("fsr3_inputs::note_output(" in function(fsr3, "bool fsr3_upscale("), "the output's size is never noted for the inputs")
|
||||
|
||||
|
||||
MUTATIONS = [
|
||||
("the old reset", "inputs", "const bool reset = gap || held || cut;", "const bool reset = gap || cut;"),
|
||||
("the old cut rule", "inputs", "framegen_rows::camera_cut(s.last_pose, pose, dt, framegen_rows::kUpscalerCut)",
|
||||
"framegen_rows::camera_cut(s.last_pose, pose, dt)"),
|
||||
("the old chain reset", "temporal", "const bool reset = !last || now - last > 2 || present_held_last() || cut;",
|
||||
"const bool reset = !last || now - last > 2 || present_held_last();"),
|
||||
("the old max render size", "fsr3", "k.max_render_size[0] = (int32_t)g.render_width", "k.max_render_size[0] = rw"),
|
||||
("the old exposure clear", "fsr3", "info.float32[0] = -1.0f, info.float32[1] = 1e8f;",
|
||||
"info.float32[0] = -1.0f, info.float32[1] = 1.0f;"),
|
||||
("the old jitter length", "inputs", "fsr3_math::jitter_phases(rw, dw)", "(uint32_t)dlss_jitter_phases(rw, rh, dw, dh)"),
|
||||
("the old floor", "inputs", "!scene_size(width, height)", "width < 640 || height < 360"),
|
||||
("no release", "fsr3", "fsr3::release();", "(void)0;"),
|
||||
]
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument("--cxx", default="g++")
|
||||
a = p.parse_args()
|
||||
texts = {"fsr3": (VK / "vk_fsr3.cpp").read_text(encoding="utf-8"),
|
||||
"inputs": (VK / "vk_fsr3_inputs.cpp").read_text(encoding="utf-8"),
|
||||
"temporal": (VK / "vk_temporal.cpp").read_text(encoding="utf-8")}
|
||||
checks(texts["fsr3"], texts["inputs"], texts["temporal"])
|
||||
for name, which, new, old in MUTATIONS:
|
||||
check(new in texts[which], "the mutation '%s' has nothing to change" % name)
|
||||
t = dict(texts)
|
||||
t[which] = t[which].replace(new, old)
|
||||
try:
|
||||
checks(t["fsr3"], t["inputs"], t["temporal"])
|
||||
except SystemExit:
|
||||
continue
|
||||
raise SystemExit("FAIL: the mutation '%s' passed" % name)
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
cpp, exe = Path(tmp) / "fsr3_history.cpp", Path(tmp) / ("fsr3_history" + (".exe" if os.name == "nt" else ""))
|
||||
cpp.write_text(CHECK, encoding="utf-8")
|
||||
subprocess.run([a.cxx, "-std=c++20", "-Wall", "-Wextra", "-Werror", "-I", str(VK), str(cpp), "-o", str(exe)], check=True)
|
||||
subprocess.run([str(exe)], check=True, timeout=60)
|
||||
print("PASS: FSR 3.1's history (held presents, camera cuts, the dynamic resolution, the exposure), its jitter and its "
|
||||
"images' release; the upscalers' camera cut; the old lines fail")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -35,7 +35,8 @@ def checks(inputs, fsr3):
|
||||
"fsr3_upscale still leaves an RGBA16F network before the inputs")
|
||||
# (the inputs are made before the network's own upscale is left to DLSS: prepare comes after the format check and before
|
||||
# the return for frame interpolation's inputs alone)
|
||||
check(up.index("!temporal_scene_format(in->format)") < up.index("fsr3_inputs::prepare(cmd, in, in_view, f)") <
|
||||
# ((Triforce) with hdr: an RGBA16F network's colour unclamped, tests/test_fsr3_hdr_scene.py)
|
||||
check(up.index("!temporal_scene_format(in->format)") < up.index("fsr3_inputs::prepare(cmd, in, in_view, f, hdr)") <
|
||||
up.index("if (!upscaling) return false;"), "fsr3_upscale: the inputs are not made where DLSS upscales")
|
||||
|
||||
|
||||
|
||||
@@ -80,21 +80,28 @@ def main():
|
||||
"the menu does not show FSR 3.1's Native AA when it runs")
|
||||
check("ur::fsr3_bits(fsr3::supported())" in function(menu, "unsigned upscalers_available() {"),
|
||||
"the Upscaler row does not offer both of FSR 3.1's where it runs")
|
||||
# ((Triforce, options_version 7) the Upscaler row names the engine of each of the seven values; a native AA is the Render
|
||||
# resolution row's Native (100%) step, upscaler_rows.h step_resolution)
|
||||
names = function(menu, "const char* tx_upscaler(int) {")
|
||||
table = re.search(r"static const char\* t\[ur::kUpscalers\] = \{(.*?)\};", names, re.S)
|
||||
check(table and [n.strip().strip('"') for n in table.group(1).replace("\n", " ").split(",")] ==
|
||||
["Game", "NVIDIA DLSS", "NVIDIA DLAA", "AMD FSR 3.1", "AMD FSR 4", "AMD FSR 4 Native AA", "AMD FSR 3.1 Native AA"],
|
||||
"tx_upscaler's names are not the seven values' in their saved order")
|
||||
["Game", "NVIDIA DLSS", "NVIDIA DLSS", "AMD FSR 3.1", "AMD FSR 4", "AMD FSR 4", "AMD FSR 3.1"],
|
||||
"tx_upscaler's names are not the seven values' engines in their saved order")
|
||||
# ((Triforce, FSR4-7) FSR 4 by the version AMD's library runs, fsr4_name, the engine's name too)
|
||||
check("const int up = ur::engine(std::clamp(upscaler(), 0, ur::kUpscalers - 1));" in names and "return t[up];" in names,
|
||||
"tx_upscaler does not name what runs by its engine")
|
||||
hints = function(menu, "const char* hn_upscaler(int v, int variant) {")
|
||||
lines = re.search(r"static const char\* const t\[ur::kUpscalers\] = \{(.*?)\n \};", hints, re.S)
|
||||
check(lines and len(re.findall(r'",\n', lines.group(1) + "\n")) == 7, "hn_upscaler has no line for each of the seven values")
|
||||
check('if (up == ur::FSR3_AA) return "Native (FSR 3.1)";' in function(menu, "const char* tx_resolution(int v) {"),
|
||||
"the Render resolution row does not say Native with FSR 3.1's Native AA")
|
||||
check("if (up == ur::FSR3_AA)" in function(menu, "const char* hn_resolution(int v, int variant) {"),
|
||||
"the Render resolution row's help has no line for FSR 3.1's Native AA")
|
||||
check("v = ur::engine(v);" in hints, "hn_upscaler does not say each value's engine")
|
||||
check('if (ur::full_scale(up)) return "Native (100%)";' in function(menu, "const char* tx_resolution(int v) {"),
|
||||
"the Render resolution row does not say Native (100%) with a native AA")
|
||||
check("if (ur::full_scale(up))" in function(menu, "const char* hn_resolution(int v, int variant) {"),
|
||||
"the Render resolution row's help has no line for a native AA")
|
||||
check("ur::step_resolution(upscaler(), *r.value, dir)" in function(menu, "void set_row("),
|
||||
"the Render resolution row does not step through Native (100%)")
|
||||
readme = (ROOT / "readme.md").read_text(encoding="utf-8")
|
||||
check("| Upscaler | Game, NVIDIA DLSS, NVIDIA DLAA, AMD FSR 3.1, AMD FSR 3.1 Native AA, AMD FSR 4, AMD FSR 4 Native AA" in readme,
|
||||
"readme.md's settings table has no Upscaler row with FSR 3.1's Native AA")
|
||||
check("| Upscaler | Game, NVIDIA DLSS, AMD FSR 3.1, AMD FSR 4" in readme and
|
||||
"Native (100%: DLAA, or FSR's native anti-aliasing)" in readme,
|
||||
"readme.md's settings table has no Upscaler row, or no Native (100%) on the Render resolution row")
|
||||
guide = (ROOT / "docs/development.md").read_text(encoding="utf-8")
|
||||
check("6 AMD FSR 3.1 Native AA" in guide and "`=2`: FSR 3.1 as its Native AA" in guide,
|
||||
"docs/development.md does not say the Upscaler's value 6, or RX_VK_FSR=2")
|
||||
|
||||
166
tests/test_fsr3_own_motion.py
Normal file
166
tests/test_fsr3_own_motion.py
Normal file
@@ -0,0 +1,166 @@
|
||||
"""(Triforce, FSR3-03) AMD FSR 3.1 gets the motion of what moves by itself, as NVIDIA DLSS and AMD FSR 4 do. Its inputs
|
||||
(gpu/vk/vk_fsr3_inputs.cpp) had the camera's motion alone (shaders/fsr3_prep.comp): Link, the others and what the game moves
|
||||
got the motion of what is behind them, and FSR trailed or smeared them. The chain's redraws (gpu/vk/vk_temporal.cpp
|
||||
capture_motion, actor_motion) served only its own engines: no draw stored its positions while FSR 3.1 drew
|
||||
(temporal_capture_wanted asked temporal_wanted, false then), and pre_fsr3 took this frame's draws a second time and threw
|
||||
them away.
|
||||
|
||||
What must hold, read from the source (no game, no GPU):
|
||||
- the draws store their positions, and the skinned ones are noted, while FSR 3.1 upscales (temporal_motion_wanted), and the
|
||||
scene's sizes are known to them then (temporal_scene_size asks FSR's own inputs' rule);
|
||||
- the redraws draw into the motion they are given and go by the history they are given (RedrawTarget), not the chain's own
|
||||
alone; the chain gives its own;
|
||||
- FSR 3.1's motion image is a colour attachment, and its Frame carries the camera as drawn and the frame before's;
|
||||
- in place of the upscale's dispatch: fsr3_upscale has the chain draw into FSR's motion after its inputs and before its
|
||||
passes (temporal_fsr3_motion), the frame's draws taken once, let go when the inputs were not made; the draw state set
|
||||
again after (vk_draw.cpp fsr3_stand_in);
|
||||
- before the bloom: temporal_pre_tonemap takes the draws once and gives them to pre_fsr3, which gives them to fsr3_pre's
|
||||
own_motion, called after its inputs and before its passes;
|
||||
- the Upscaler row's hints for FSR 3.1 no longer say that what moves by itself can trail.
|
||||
The old lines fail.
|
||||
|
||||
python -I -B tests/test_fsr3_own_motion.py
|
||||
"""
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
VK = ROOT / "gpu" / "vk"
|
||||
|
||||
|
||||
def check(cond, what):
|
||||
if not cond:
|
||||
raise SystemExit("FAIL: " + what)
|
||||
|
||||
|
||||
def function(source, head):
|
||||
start = source.index(head)
|
||||
return source[start:source.index("\n}\n", start) + 3]
|
||||
|
||||
|
||||
def checks(t):
|
||||
temporal, fsr3, inputs, inputs_h, draw, menu = (t["temporal"], t["fsr3"], t["inputs"], t["inputs_h"], t["draw"],
|
||||
t["menu"])
|
||||
# the gates: FSR 3.1 too
|
||||
check("bool temporal_motion_wanted() { return temporal_wanted() || fsr3_wanted(); }" in temporal,
|
||||
"temporal_motion_wanted does not include AMD FSR 3.1")
|
||||
check("bool temporal_capture_wanted() { return motion_mode() == kMotionCapture && temporal_motion_wanted(); }" in temporal,
|
||||
"the draws store their positions only for the chain's own engines")
|
||||
skinned = function(temporal, "const char* temporal_note_skinned_draw(const SkinnedDraw& k) {")
|
||||
check("!temporal_motion_wanted()) return \"actor motion off\";" in skinned, "the skinned draws are noted only for the chain's engines")
|
||||
skin = function(draw, "static const char* skin_check(const NvnState& s, const Program& p, const DrawArgs& d, const Targets& at) {")
|
||||
check("!temporal_motion_wanted())" in skin and "|| !temporal_wanted())" not in skin,
|
||||
"skin_check takes the skinned draws only for the chain's engines")
|
||||
size = function(temporal, "bool temporal_scene_size(uint32_t width, uint32_t height) {")
|
||||
check("(fsr3_wanted() && fsr3_inputs::scene_size(width, height))" in size,
|
||||
"temporal_scene_size knows no scene while FSR 3.1 upscales in place of the dispatch")
|
||||
# the redraws draw where they are told, by the history they are told
|
||||
begin = function(temporal, "bool begin_redraw(")
|
||||
check("ca.imageView = motion," in begin and "s.motion.view" not in begin, "begin_redraw draws into the chain's motion alone")
|
||||
capture = function(temporal, "int capture_motion(VkCommandBuffer cmd, const Camera& cam,")
|
||||
check("const RedrawTarget& to" in capture and "s.captured_frame == to.last" in capture and
|
||||
"to.jitter_before[i]" in capture and "to.motion)" in capture, "capture_motion does not go by its target")
|
||||
check("s.last_frame" not in capture and "s.last_jitter" not in capture, "capture_motion still goes by the chain's history")
|
||||
actor = function(temporal, "int actor_motion(VkCommandBuffer cmd, const Camera& cam,")
|
||||
check("const RedrawTarget& to" in actor and "it->second.frame != to.last" in actor and "to.motion)" in actor,
|
||||
"actor_motion does not go by its target")
|
||||
check("s.last_frame" not in actor, "actor_motion still goes by the chain's history")
|
||||
chain = function(temporal, "VkFormat in_format, VkFormat out_format) {") # (its definition, not its declaration)
|
||||
check("const RedrawTarget into{s.motion.view, last, s.last_jitter};" in chain and
|
||||
"captures, into)" in chain and "motion, into)" in chain, "the chain does not give its redraws its own motion")
|
||||
# FSR 3.1's inputs: an attachment, and the camera for the redraws
|
||||
prep = function(inputs, "bool prepare(VkCommandBuffer cmd, Texture* in, VkImageView in_view, Frame& out, bool linear) {")
|
||||
# ((Triforce, FG-4) and a copy's destination: the upscaler chain's motion copied over it for frame generation)
|
||||
check("make_image(cmd, s.motion, VK_FORMAT_R16G16_SFLOAT, rw, rh, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT)"
|
||||
in prep, "FSR 3.1's motion image is no colour attachment (nor a copy's destination): the redraws cannot draw into it")
|
||||
check("o.last = s.last_frame;" in prep and prep.index("o.last = s.last_frame;") < prep.index("s.last_frame = now;"),
|
||||
"FSR 3.1's Frame does not carry the frame its history is of")
|
||||
for line in ("std::memcpy(o.current, cam.current, sizeof o.current);", "std::memcpy(o.projection, cam.projection, sizeof o.projection);",
|
||||
"std::memcpy(o.before, previous, sizeof o.before);", "std::memcpy(o.reproject, pc.reproject, sizeof o.reproject);",
|
||||
"o.jitter_before[0] = s.last_jitter[0]", "o.depth = cam.depth;", "o.history = motion;"):
|
||||
check(line in prep, "FSR 3.1's Frame lacks what the redraws take: " + line)
|
||||
check(prep.index("o.jitter_before[0] = s.last_jitter[0]") < prep.index("s.last_jitter[0] = cam.jitter[0]"),
|
||||
"FSR 3.1's Frame carries this frame's jitter as the frame before's")
|
||||
check("struct Own {" in inputs_h and "} own;" in inputs_h, "vk_fsr3_inputs.h's Frame has no camera for the redraws")
|
||||
# fsr3_motion: FSR's motion as the target
|
||||
motion = function(temporal, "int fsr3_motion(VkCommandBuffer cmd, const fsr3_inputs::Frame& f, const std::vector<State::Captured>& captures) {")
|
||||
check("const RedrawTarget into{f.motion, o.last, o.jitter_before};" in motion and
|
||||
"capture_motion(cmd, cam, o.before, o.reproject, f.width, f.height, dview, o.history, captures, into)" in motion and
|
||||
"actor_motion(cmd, cam, o.before, o.reproject, f.width, f.height, dview, o.history, into)" in motion,
|
||||
"fsr3_motion does not draw into FSR 3.1's motion")
|
||||
check("take_captures()" not in motion, "fsr3_motion takes the frame's draws itself (its callers do, once)")
|
||||
check("camera_planes(cam);" in motion and "cam.depth = o.depth;" in motion, "fsr3_motion's camera lacks its planes or depth")
|
||||
# in place of the upscale's dispatch
|
||||
public = function(temporal, "int temporal_fsr3_motion(VkCommandBuffer cmd, const fsr3_inputs::Frame* f) {")
|
||||
check(public.count("take_captures()") == 1 and "return fsr3_motion(cmd, *f, captures);" in public and
|
||||
"std::lock_guard lk(s.mu);" in public, "temporal_fsr3_motion does not take the frame's draws once, under the lock")
|
||||
check("s.asked = texture_frame_no(), s.holding = true;" in public, "the redraws' buffers are not kept while FSR 3.1 draws")
|
||||
up = function(fsr3, "bool fsr3_upscale(VkCommandBuffer cmd, uint64_t key, bool known, Texture* in, VkImageView in_view, Texture* out,")
|
||||
check("const int own = temporal_fsr3_motion(cmd, &f);" in up, "fsr3_upscale gives FSR 3.1 the camera's motion alone")
|
||||
check(up.index("fsr3_inputs::prepare(cmd, in, in_view, f, hdr)") < up.index("temporal_fsr3_motion(cmd, &f)") <
|
||||
up.index("std::lock_guard lk(o.mu);") < up.index("fsr3::upscale(cmd, ai)"),
|
||||
"fsr3_upscale's own motion is not drawn after its inputs, outside its lock and before its passes")
|
||||
check("if (upscaling) (void)temporal_fsr3_motion(cmd, nullptr);" in up, "the frame's draws are kept when FSR 3.1's inputs were not made")
|
||||
stand = function(draw, "bool fsr3_stand_in(VkCommandBuffer cmd, const NvnState& s, const Program& p) {")
|
||||
check("last_pipeline = VK_NULL_HANDLE;" in stand and "vertex_set.on = false" in stand,
|
||||
"fsr3_stand_in does not set the draw state again after the redraws")
|
||||
# before the bloom
|
||||
tone = function(temporal, "Texture* temporal_pre_tonemap(VkCommandBuffer cmd) {")
|
||||
check(tone.count("take_captures()") == 1 and "pre_fsr3(cmd, scene, view, rw, rh, ow, oh, captures)" in tone,
|
||||
"temporal_pre_tonemap does not give FSR 3.1 the draws it took")
|
||||
pre3 = function(temporal, "bool pre_fsr3(")
|
||||
check("take_captures()" not in pre3, "pre_fsr3 takes the frame's draws a second time and throws them away")
|
||||
check("s.skins.clear()" not in pre3, "pre_fsr3 throws the skinned draws away before the redraws")
|
||||
check("fsr3_motion(cmd, f, captures)" in pre3 and "fsr3_pre(cmd, scene, view, ow, oh, &picture, own_motion)" in pre3,
|
||||
"pre_fsr3 does not have the redraws draw into FSR's motion")
|
||||
pre = function(fsr3, "bool fsr3_pre(")
|
||||
check(pre.index("fsr3_inputs::prepare(cmd, scene, scene_view, f, true)") < pre.index("own_motion(f)") <
|
||||
pre.index("fsr3::upscale(cmd, ai)"), "fsr3_pre's own motion is not drawn after its inputs and before its passes")
|
||||
# the hints
|
||||
hints = function(menu, "const char* hn_upscaler(int v, int variant) {")
|
||||
table = hints[:hints.index("};")]
|
||||
entries = [e for e in table.split('",\n') if e.strip()][:7]
|
||||
# ((Triforce, options_version 7) one line per engine: FSR 3.1's Native AA reads as FSR 3.1's, v = ur::engine(v))
|
||||
fsr3_rows = [e for e in entries if "built from AMD's own shaders" in e]
|
||||
check(len(fsr3_rows) == 1 and "v = ur::engine(v);" in hints, "hn_upscaler's FSR 3.1 line is not found")
|
||||
for e in fsr3_rows:
|
||||
check("trail" not in e, "the FSR 3.1 hint still says that what moves by itself can trail")
|
||||
|
||||
|
||||
MUTATIONS = [
|
||||
("the old capture gate", "temporal",
|
||||
"bool temporal_capture_wanted() { return motion_mode() == kMotionCapture && temporal_motion_wanted(); }",
|
||||
"bool temporal_capture_wanted() { return motion_mode() == kMotionCapture && temporal_wanted(); }"),
|
||||
("the old scene size", "temporal", " ||\n (fsr3_wanted() && fsr3_inputs::scene_size(width, height));", ";"),
|
||||
("the second take", "temporal", " s.asked = texture_frame_no(), s.holding = true;\n VkImageView picture = VK_NULL_HANDLE;",
|
||||
" (void)take_captures();\n s.asked = texture_frame_no(), s.holding = true;\n VkImageView picture = VK_NULL_HANDLE;"),
|
||||
("the chain's motion only", "temporal", "ca.imageView = motion,", "ca.imageView = s.motion.view,"),
|
||||
("no attachment", "inputs", "rw, rh, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT)", "rw, rh)"),
|
||||
("the camera's motion alone", "fsr3", " const int own = temporal_fsr3_motion(cmd, &f);\n", " const int own = 0;\n"),
|
||||
("the old hint", "menu", "\"AMD's, on any graphics card, built from AMD's own shaders.\",",
|
||||
"\"AMD's, on any graphics card, built from AMD's own shaders. Things that move by themselves can trail for now.\","),
|
||||
]
|
||||
|
||||
|
||||
def main():
|
||||
texts = {"temporal": (VK / "vk_temporal.cpp").read_text(encoding="utf-8"),
|
||||
"fsr3": (VK / "vk_fsr3.cpp").read_text(encoding="utf-8"),
|
||||
"inputs": (VK / "vk_fsr3_inputs.cpp").read_text(encoding="utf-8"),
|
||||
"inputs_h": (VK / "vk_fsr3_inputs.h").read_text(encoding="utf-8"),
|
||||
"draw": (VK / "vk_draw.cpp").read_text(encoding="utf-8"),
|
||||
"menu": (VK / "vk_menu.cpp").read_text(encoding="utf-8")}
|
||||
checks(texts)
|
||||
for name, which, new, old in MUTATIONS:
|
||||
check(new in texts[which], "the mutation '%s' has nothing to change" % name)
|
||||
t = dict(texts)
|
||||
t[which] = t[which].replace(new, old, 1)
|
||||
try:
|
||||
checks(t)
|
||||
except SystemExit:
|
||||
continue
|
||||
raise SystemExit("FAIL: the mutation '%s' passed" % name)
|
||||
print("PASS: AMD FSR 3.1 gets the motion of what moves by itself, in place of the dispatch and before the bloom; the old "
|
||||
"lines fail")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
224
tests/test_fsr4_upscaler.py
Normal file
224
tests/test_fsr4_upscaler.py
Normal file
@@ -0,0 +1,224 @@
|
||||
"""(Triforce) AMD FSR 4 on the frame chain (gpu/vk/vk_fsr4.cpp, vk_temporal.cpp; gpu/vk/temporal_rules.h). No game, no GPU.
|
||||
|
||||
1. Compiled and run: temporal_rules.h's Retry (a failure leaves the game's upscale for 2 s, then the engine is tried again;
|
||||
the fourth in a row turns it off until the Upscaler row is set again; a good evaluation counts from 0 again), native_at
|
||||
(a native AA anti-aliases at the render size only while the 3D is drawn at the output's size: one chosen in play scales
|
||||
the smaller 3D up), plan_context (a fixed share gets a context of its own render size without the dynamic-resolution
|
||||
flag, the game's dynamic resolution one with it for every size, once the size changes) and frame_ms (under 100 ms, else
|
||||
a 60th).
|
||||
2. The source: a creation or evaluation failure goes through fail_again, not the old latch for good; temporal_mode says the
|
||||
game's own once the engine is off and a fresh Upscaler choice tries it anew; the chain's native AA and the one before
|
||||
the bloom follow native_at and the upscale's output; an RGBA16F (RenoDX HDR Native) picture is no longer refused to
|
||||
FSR 4; FSR 4's context chains ffxCreateContextDescUpscaleVersion, refuses a provider under 4, takes the frame time from
|
||||
frame_ms and the dynamic-resolution flag only with plan_context's drs; FSR 4's jitter is AMD's length; the menu names
|
||||
FSR 4 by the version AMD's library runs and says when the game's own stands in. The old lines fail.
|
||||
|
||||
python -I -B tests/test_fsr4_upscaler.py [--cxx g++]
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
import subprocess
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
RUN_ALL_ARGS = ["--cxx", "{cxx}"]
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
VK = ROOT / "gpu" / "vk"
|
||||
|
||||
CHECK = r'''
|
||||
#include <cstdio>
|
||||
#include "temporal_rules.h"
|
||||
|
||||
#define CHECK(c) do { if (!(c)) { std::fprintf(stderr, "FAIL line %d: %s\n", __LINE__, #c); return 1; } } while (0)
|
||||
|
||||
using namespace mkwvk::temporal_rules;
|
||||
|
||||
int main() {
|
||||
// a failure: the game's upscale for 2 s, then tried again; the fourth in a row: off
|
||||
Retry r;
|
||||
const int64_t s = 1'000'000'000;
|
||||
CHECK(!r.waiting(0) && !r.is_off());
|
||||
CHECK(!r.failed(10 * s) && r.count() == 1 && r.waiting(10 * s) && r.waiting(11 * s) && !r.waiting(12 * s));
|
||||
CHECK(!r.failed(12 * s) && !r.failed(14 * s) && !r.is_off() && r.count() == 3);
|
||||
CHECK(r.failed(16 * s) && r.is_off());
|
||||
// the Upscaler row set again: tried anew, from 0
|
||||
CHECK(r.rearm() && !r.is_off() && r.count() == 0 && !r.waiting(16 * s));
|
||||
CHECK(!r.rearm());
|
||||
// a good evaluation between failures: they are not added up over a session
|
||||
CHECK(!r.failed(20 * s) && !r.failed(22 * s));
|
||||
r.succeeded();
|
||||
CHECK(r.count() == 0 && !r.waiting(22 * s));
|
||||
CHECK(!r.failed(30 * s) && !r.failed(32 * s) && !r.failed(34 * s) && !r.is_off());
|
||||
|
||||
// native AA: only at the output's size. Chosen in play over a 67% 3D: scaled up as FSR 4's upscale
|
||||
CHECK(native_at(true, 2560, 1440, 2560, 1440));
|
||||
CHECK(!native_at(true, 1707, 960, 2560, 1440) && !native_at(true, 2560, 960, 2560, 1440));
|
||||
CHECK(!native_at(false, 2560, 1440, 2560, 1440) && !native_at(false, 854, 480, 2560, 1440));
|
||||
|
||||
// FSR 4's context: the first, a fixed share's own size, no dynamic-resolution flag
|
||||
ContextPlan p = plan_context(false, 0, 0, 0, 0, false, false, 854, 480, 2560, 1440, false, false, false);
|
||||
CHECK(p.remake && !p.drs && !p.dynamic && !p.went_dynamic);
|
||||
p = plan_context(true, 2560, 1440, 854, 480, false, false, 854, 480, 2560, 1440, false, false, false);
|
||||
CHECK(!p.remake);
|
||||
// (HDR colour now, another output: made again, of its own size still)
|
||||
p = plan_context(true, 2560, 1440, 854, 480, false, false, 854, 480, 2560, 1440, true, false, false);
|
||||
CHECK(p.remake && !p.drs);
|
||||
p = plan_context(true, 2560, 1440, 854, 480, false, false, 1280, 720, 3840, 2160, false, false, false);
|
||||
CHECK(p.remake && !p.drs && !p.dynamic);
|
||||
// the render size changes under the output (the game's dynamic resolution): one context for every size from then on
|
||||
p = plan_context(true, 2560, 1440, 1707, 960, false, false, 1600, 900, 2560, 1440, false, false, false);
|
||||
CHECK(p.remake && p.drs && p.dynamic && p.went_dynamic);
|
||||
p = plan_context(true, 2560, 1440, 2560, 1440, true, false, 1500, 844, 2560, 1440, false, true, false);
|
||||
CHECK(!p.remake && p.dynamic && !p.went_dynamic);
|
||||
p = plan_context(true, 2560, 1440, 2560, 1440, true, false, 2560, 1440, 2560, 1440, false, true, false);
|
||||
CHECK(!p.remake); // (up to 100%: the same context, NX2navi's crash was a context without the flag)
|
||||
// RX_VK_FSR4_DRS=1: the flag from the start, as before
|
||||
p = plan_context(false, 0, 0, 0, 0, false, false, 854, 480, 2560, 1440, false, false, true);
|
||||
CHECK(p.remake && p.drs);
|
||||
p = plan_context(true, 2560, 1440, 854, 480, false, false, 854, 480, 2560, 1440, false, false, true);
|
||||
CHECK(p.remake && p.drs);
|
||||
|
||||
// the frame time: under 100 ms, else a 60th
|
||||
CHECK(frame_ms(false, 8.3f) == 8.3f && frame_ms(false, 33.3f) == 33.3f);
|
||||
CHECK(frame_ms(true, 8.3f) == 16.667f && frame_ms(false, 1500.0f) == 16.667f && frame_ms(false, 0.0f) == 16.667f);
|
||||
std::puts("ok");
|
||||
return 0;
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
def check(cond, what):
|
||||
if not cond:
|
||||
raise SystemExit("FAIL: " + what)
|
||||
|
||||
|
||||
def function(source, head, last=False):
|
||||
"""A definition from its first line to its closing brace at the start of a line (last: the last one so named, past a
|
||||
declaration ahead of it)"""
|
||||
start = source.rindex(head) if last else source.index(head)
|
||||
return source[start:source.index("\n}\n", start) + 3]
|
||||
|
||||
|
||||
def checks(temporal, fsr4, menu):
|
||||
# FSR4-1: a failure is tried again, off after four in a row, the row then says the game's own; a new choice re-arms
|
||||
chain = function(temporal, "bool chain(VkCommandBuffer cmd, int mode, Engine& engine, const Camera& cam,", last=True)
|
||||
check('if (ready < 0) return fail_again(engine, why ? why : "it could not be made");' in chain,
|
||||
"a failed creation still turns the engine off for good")
|
||||
check('return fail_again(engine, "its evaluation failed");' in chain and "engine.retry.succeeded();" in chain,
|
||||
"a failed evaluation still turns the engine off for good, or a good one does not count from 0 again")
|
||||
check(chain.count("engine.failed = true;") == 2, "only a missing engine and its shaders are failures for good")
|
||||
again = function(temporal, "bool fail_again(Engine& k, const char* why) {")
|
||||
check("k.e->release();" in again and "drop_image(*im);" in again and "k.retry.failed(now_ns())" in again and
|
||||
"s.last_frame = 0;" in again, "fail_again does not let go what the engine and the chain hold, or count the failure")
|
||||
mode = function(temporal, "int temporal_mode() {")
|
||||
check("rearm_on_choice(v);" in mode and "if (stood_in(v)) return ur::GAME;" in mode,
|
||||
"temporal_mode does not say the game's own for an engine that is off, or a new choice does not try it anew")
|
||||
check(mode.index("rearm_on_choice(v);") < mode.index("if (dlss > 0)"), "the choice is read after the switches")
|
||||
check("if (waiting(engine)) return fail(" in function(temporal, "bool temporal_upscale(VkCommandBuffer cmd,") and
|
||||
"waiting(*engine)" in function(temporal, "Texture* temporal_pre_tonemap(VkCommandBuffer cmd) {"),
|
||||
"the chain does not wait before it tries a failed engine again")
|
||||
check("k.retry.is_off()" in function(temporal, "bool stood_in(int mode) {"), "stood_in does not read the retry state")
|
||||
check("retry.rearm()" in function(temporal, "void rearm_on_choice(int choice) {"), "a new choice does not re-arm")
|
||||
hint = function(menu, "const char* hn_upscaler(int v, int variant) {")
|
||||
check("temporal_stood_in()" in hint and "The game's own stands in: %s failed four times in a row" in hint,
|
||||
"the Upscaler's help does not say when the game's own stands in for FSR 4")
|
||||
# (the FSR 4 it names is the Upscaler row's, by its version: "AMD FSR 4.1")
|
||||
stood = hint[hint.index("static char fsr4_stood_in["):hint.index("const char* const stood_in[2] = {")]
|
||||
check("fsr4_name(false)" in stood, "the stand-in line names FSR 4 without its version")
|
||||
check("else if (variant < DLSS_WHY_COUNT + FSR_WHY_COUNT + 1) return stood_in[" in hint,
|
||||
"the stand-in lines are not among the help's variants (the menu's height)")
|
||||
# FSR4-2: native AA only at the output's size, before the bloom too
|
||||
check("const bool native = temporal_rules::native_at(ur::full_scale(mode), rw, rh, ow, oh);" in chain,
|
||||
"the chain's native AA anti-aliases a smaller 3D and stretches it")
|
||||
pre = function(temporal, "Texture* temporal_pre_tonemap(VkCommandBuffer cmd) {")
|
||||
check("if (!ur::full_scale(mode) || (seen_w && seen_h && (seen_w > rw || seen_h > rh))) {" in pre,
|
||||
"before the bloom a native AA chosen in play does not scale the smaller 3D up to the output")
|
||||
# ((Triforce, options_version 7) an engine's native AA is the Render resolution's Native (100%): that line says it, for
|
||||
# DLAA, FSR 4's and FSR 3.1's alike (ur::full_scale)
|
||||
resolution = function(menu, "const char* hn_resolution(int v, int variant) {")
|
||||
native = resolution[resolution.index("if (ur::full_scale(up))"):resolution.index("const int p = ur::percent(v);")]
|
||||
check("takes its full size at the next start." in native,
|
||||
"the native AA's help (the Render resolution's Native) does not say the 3D takes its full size at the next start")
|
||||
# FSR4-3: an RGBA16F picture goes to FSR 4
|
||||
check("only DLSS takes it" not in chain, "the chain still refuses FSR 4 an RGBA16F (HDR Native) picture")
|
||||
check("const bool hdr = pre != nullptr || in_format == VK_FORMAT_R16G16B16A16_SFLOAT;" in chain,
|
||||
"the chain no longer gives an RGBA16F picture as HDR colour")
|
||||
# FSR4-4, FSR4-8, FSR4-9, FSR4-10: the context and the dispatch
|
||||
make = function(fsr4, "std::shared_ptr<Context> make_context(uint32_t rw, uint32_t rh, uint32_t ow, uint32_t oh, bool drs, bool hdr) {")
|
||||
check("c->built.header.type = FFX_API_CREATE_CONTEXT_DESC_TYPE_UPSCALE_VERSION;" in make and
|
||||
"c->built.version = FFX_UPSCALER_VERSION;" in make and "c->version.header.pNext = &c->built.header;" in make,
|
||||
"the upscale context is made without ffxCreateContextDescUpscaleVersion")
|
||||
check("c->built.header.pNext = &c->legacy_backend.header;" in make, "(linux) the older backend description left the chain")
|
||||
check("if (known && atoi(provider.versionName) < 4) {" in make and "g_why = FSR_NO_MODEL;" in make and
|
||||
"return nullptr;" in make[make.index("atoi(provider.versionName) < 4"):], "a provider under 4 runs under FSR 4's name")
|
||||
check("if (drs) c->upscale.flags |= FFX_UPSCALE_ENABLE_DYNAMIC_RESOLUTION;" in make and
|
||||
make.count("FFX_UPSCALE_ENABLE_DYNAMIC_RESOLUTION") == 1, "the dynamic-resolution flag is set for a fixed share")
|
||||
check("c->upscale.maxRenderSize = drs ? FfxApiDimensions2D{ow, oh} : FfxApiDimensions2D{rw, rh};" in make,
|
||||
"a fixed share's context is not made for its own render size")
|
||||
prep = function(fsr4, "int prepare(VkCommandBuffer, uint32_t rw, uint32_t rh, uint32_t ow, uint32_t oh, bool hdr,")
|
||||
check("temporal_rules::plan_context(" in prep and "make_context(rw, rh, ow, oh, plan.drs, hdr)" in prep,
|
||||
"FSR 4's prepare does not follow plan_context")
|
||||
ev = function(fsr4, "bool evaluate(VkCommandBuffer cmd, const TemporalFrame& f) {")
|
||||
check("temporal_rules::frame_ms(!s.evals," in ev and "d.frameTimeDelta = frame_ms;" in ev, "FSR 4's frame time is not clamped")
|
||||
check("s.jitter_phases = ur::is_fsr4(mode) ? fsr3_math::jitter_phases(rw, dw) : (uint32_t)dlss_jitter_phases(rw, rh, dw, dh);"
|
||||
in chain, "FSR 4's jitter is not AMD's length")
|
||||
# FSR4-7: the name by the version, and the driver in the help
|
||||
load = function(fsr4, "bool load() {")
|
||||
check('snprintf(g_name[0], sizeof g_name[0], "AMD FSR %u.%u", best[0], best[1]);' in load and
|
||||
"g_named.store(true, std::memory_order_release);" in load, "FSR 4's name is not taken from the version AMD's library runs")
|
||||
name = function(fsr4, "const char* fsr4_name(bool native_aa) {")
|
||||
check("g_named.load(std::memory_order_acquire)" in name and "lock" not in name, "fsr4_name waits for the library")
|
||||
tx = function(menu, "const char* tx_upscaler(int) {")
|
||||
check("if (ur::is_fsr4(up)) return fsr4_name(up == ur::FSR4_AA);" in tx, "the Upscaler row always says AMD FSR 4")
|
||||
# ((Triforce, options_version 7) the row names the engine alone: FSR 4's Native AA is the Render resolution's Native)
|
||||
check("const int up = ur::engine(std::clamp(upscaler(), 0, ur::kUpscalers - 1));" in tx,
|
||||
"the Upscaler row names an engine's native AA, which the Render resolution's Native (100%) says")
|
||||
check("driver 26.10.1 or newer" in hint,"the help for no FSR 4 here does not name the driver it needs")
|
||||
|
||||
|
||||
MUTATIONS = [
|
||||
("the old latch", "temporal", 'if (ready < 0) return fail_again(engine, why ? why : "it could not be made");',
|
||||
'if (ready < 0) { engine.failed = true; return fail(why); }'),
|
||||
("no stand-in", "temporal", "if (stood_in(v)) return ur::GAME;", ""),
|
||||
("the old native", "temporal", "const bool native = temporal_rules::native_at(ur::full_scale(mode), rw, rh, ow, oh);",
|
||||
"const bool native = ur::full_scale(mode);"),
|
||||
("the old HDR refusal", "temporal", " if (!engine.started) engine.started = true, engine.ok = engine.e->start();",
|
||||
' if (hdr && !pre && !ur::is_dlss(mode)) return fail("an HDR scene: only DLSS takes it");\n'
|
||||
" if (!engine.started) engine.started = true, engine.ok = engine.e->start();"),
|
||||
("no version struct", "fsr4", "c->version.header.pNext = &c->built.header;", ""),
|
||||
("no provider check", "fsr4", "if (known && atoi(provider.versionName) < 4) {", "if (false) {"),
|
||||
("the old frame time", "fsr4", "temporal_rules::frame_ms(!s.evals,", "(float)(!s.evals) + ("),
|
||||
("the old name", "menu", "if (ur::is_fsr4(up)) return fsr4_name(up == ur::FSR4_AA);", ""),
|
||||
("the stand-in's old name", "menu", "it anew.\", fsr4_name(false));", "it anew.\", \"AMD FSR 4\");"),
|
||||
]
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument("--cxx", default="g++")
|
||||
a = p.parse_args()
|
||||
texts = {"temporal": (VK / "vk_temporal.cpp").read_text(encoding="utf-8"),
|
||||
"fsr4": (VK / "vk_fsr4.cpp").read_text(encoding="utf-8"),
|
||||
"menu": (VK / "vk_menu.cpp").read_text(encoding="utf-8")}
|
||||
checks(texts["temporal"], texts["fsr4"], texts["menu"])
|
||||
for name, which, new, old in MUTATIONS:
|
||||
check(new in texts[which], "the mutation '%s' has nothing to change" % name)
|
||||
t = dict(texts)
|
||||
t[which] = t[which].replace(new, old)
|
||||
try:
|
||||
checks(t["temporal"], t["fsr4"], t["menu"])
|
||||
except SystemExit:
|
||||
continue
|
||||
raise SystemExit("FAIL: the mutation '%s' passed" % name)
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
cpp, exe = Path(tmp) / "fsr4_upscaler.cpp", Path(tmp) / ("fsr4_upscaler" + (".exe" if os.name == "nt" else ""))
|
||||
cpp.write_text(CHECK, encoding="utf-8")
|
||||
subprocess.run([a.cxx, "-std=c++20", "-Wall", "-Wextra", "-Werror", "-I", str(VK), str(cpp), "-o", str(exe)], check=True)
|
||||
subprocess.run([str(exe)], check=True, timeout=60)
|
||||
print("PASS: AMD FSR 4's failures tried again and the stand-in said, native AA in play, RGBA16F colour, its context "
|
||||
"(the version struct, the provider, a fixed share's own size), its frame time, jitter and name; the old lines fail")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -151,6 +151,7 @@ void logf(const char* fmt, ...) { (void)fmt; logged++; }
|
||||
struct { int language = 0, other = 5; } opts;
|
||||
struct Row { int* value; int hi; };
|
||||
Row rows[] = {{&opts.other, 9}, {&opts.language, 0}, {nullptr, 0}};
|
||||
bool is_merged(const int*) { return false; } /* ((Triforce, options_version 7) no merged row here */
|
||||
@STATE@
|
||||
@TEXT@
|
||||
@HINT@
|
||||
|
||||
78
tests/test_game_tab_prompts.py
Normal file
78
tests/test_game_tab_prompts.py
Normal file
@@ -0,0 +1,78 @@
|
||||
"""Our tabs over the game's own Options screen name the buttons in the face the game's own prompts there have
|
||||
(gpu/vk/vk_menu.cpp draw_game_tab, game_prompts_pad; no game).
|
||||
|
||||
(Triforce, 11-19) The lab's "Options screen: the tab strip's ends show LB/RB pad icons while the footer shows the keyboard's
|
||||
Shift (keyboard face active)". On the game's own tab the footer under our tabs is the game's (Default Settings, Back), in the
|
||||
face host/prompts.c gave the game at its start; the strip's ends took the overlay's own device used last (pad_last), which a
|
||||
test's scripted press on the Mods entry sets as a pad's. This compiles game_prompts_pad with a fake host and checks it is a
|
||||
controller's face unless the game has the keys' (the game's own icons, -1, are the Switch's), and reads draw_game_tab for
|
||||
the strip drawn with it.
|
||||
|
||||
python -I -B tests/test_game_tab_prompts.py [--cxx clang++]
|
||||
"""
|
||||
import argparse
|
||||
import subprocess
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
VK = ROOT / "gpu" / "vk"
|
||||
RUN_ALL_ARGS = ["--cxx", "{cxx}"]
|
||||
|
||||
|
||||
def check(ok, why):
|
||||
if not ok:
|
||||
raise SystemExit("FAIL: " + why)
|
||||
|
||||
|
||||
def block(text, head):
|
||||
start = text.index(head)
|
||||
end = text.index("{", start) + 1
|
||||
depth = 1
|
||||
while depth:
|
||||
depth += (text[end] == "{") - (text[end] == "}")
|
||||
end += 1
|
||||
return text[start:end]
|
||||
|
||||
|
||||
PROGRAM = r"""
|
||||
#include <cstdio>
|
||||
#include "vk_api.h"
|
||||
static int face = -1;
|
||||
static int answer() { return face; }
|
||||
struct { int (*prompt_face)(void); } fake{answer}, *host = &fake;
|
||||
%s
|
||||
int main() {
|
||||
int fails = 0;
|
||||
for (int f = -1; f < HOS_PROMPT_N; f++) {
|
||||
face = f;
|
||||
if (game_prompts_pad() != (f != HOS_PROMPT_KEYBOARD)) std::printf("FAIL: face %d\n", f), fails++;
|
||||
}
|
||||
host = nullptr;
|
||||
if (!game_prompts_pad()) std::printf("FAIL: no host\n"), fails++;
|
||||
if (!fails) std::puts("the game's prompts' face");
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--cxx", default="clang++")
|
||||
args = parser.parse_args()
|
||||
menu = (VK / "vk_menu.cpp").read_text(encoding="utf-8")
|
||||
tab = block(menu, "void draw_game_tab(ui::Ctx& c) {")
|
||||
check("k.pad = game_prompts_pad();" in tab and tab.index("k.pad = game_prompts_pad();") < tab.index("draw_tabs(k, -1, true, true);"),
|
||||
"the tab strip over the game's own tab does not name the buttons in the game's prompts' face")
|
||||
with tempfile.TemporaryDirectory(prefix="game-tab-prompts-") as tmp:
|
||||
src, exe = Path(tmp) / "face.cpp", Path(tmp) / "face.exe"
|
||||
src.write_text(PROGRAM.replace("%s", block(menu, "bool game_prompts_pad() {"), 1), encoding="utf-8")
|
||||
subprocess.run([args.cxx, "-std=c++20", "-O1", "-Wall", "-Wextra", "-Werror", "-I" + str(VK), str(src), "-o", str(exe)], check=True)
|
||||
r = subprocess.run([str(exe)], capture_output=True, text=True)
|
||||
check(r.returncode == 0, "the game's prompts' face:\n" + r.stdout)
|
||||
print(r.stdout.strip())
|
||||
print("PASS: the tab strip over the game's Options names the buttons as the game's own footer there")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -43,6 +43,22 @@ def main():
|
||||
"return true;" in warm[:over]:
|
||||
raise SystemExit("the warm pass is taken for done without its libraries on disk, other than for a cache over the bound "
|
||||
"and with a log line that says so")
|
||||
# ((Triforce) over the bound with an older file's data in it (a file carried over an update): that file is not read again,
|
||||
# and the part is not taken for done, so that the next start makes a new file with only these shaders' pipelines; a new file
|
||||
# over the bound too is the way out above. Not with RX_VK_PCACHE_KEEP_OLD (it would be read again at every start), and only
|
||||
# once the .for is gone (else the same file would come back)
|
||||
# ((Triforce) nor for a file of this part's own kind, <file>.own: a checkpoint's before a crash, warm_checkpoint.h)
|
||||
carried = warm.find("if (pcache_from_file && !pcache_from_own && !getenv(\"RX_VK_PCACHE_KEEP_OLD\") && remove((pcache_path + \".for\").c_str()) == 0) {")
|
||||
if carried < over or carried > warm.index("warm_unsaved = true;", over) or \
|
||||
"warm_reset = true;\n return false;\n }" not in warm[carried:warm.index("warm_unsaved = true;", over)]:
|
||||
raise SystemExit("a cache over the bound only by a carried file's old pipelines is kept so for good")
|
||||
init = between(draw, "void pcache_init() {", "\n}\n")
|
||||
if "pcache_from_file = pcache && ci.initialDataSize > 0;" not in init or \
|
||||
init.index("pcache_from_file = pcache && ci.initialDataSize > 0;") < init.rindex("vkCreatePipelineCache("):
|
||||
raise SystemExit("pcache_init does not say whether the cache began from the file")
|
||||
if "if (cold && !prepare_stopped() && !warm_reset && !pcache_carry_over.load()) lib_check_made(path, warmed, false);" not in \
|
||||
between(draw, "bool prepare_run(", "\n}\n"):
|
||||
raise SystemExit("a part to be made again into a new file is recorded as a making that did not stay")
|
||||
if "if (!saved) return false;" not in warm[saved:] or warm.index("return true;", saved) < warm.index("if (!saved) return false;"):
|
||||
raise SystemExit("a warm pass whose libraries are not on disk is taken for done")
|
||||
prep = between(draw, "bool prepare_run(", "\n}\n")
|
||||
@@ -52,7 +68,7 @@ def main():
|
||||
if prep.index("return false;", at) > prep.index("prepared_for.warmed = warmed;", at):
|
||||
raise SystemExit("the warmed stamp is written although the warm pass did not finish")
|
||||
at += 1
|
||||
if "kWarmRecipe = 1;" in draw or "gpl_libs_cached() ? 1u : 3u" not in between(draw, "uint64_t warmed_stamp(", "\n}\n"):
|
||||
if "kWarmRecipe = 1;" in draw or "gpl_libs_cached() ? 1u : 3u" not in between(draw, "uint64_t warmed_stamp_of(", "\n}\n"):
|
||||
raise SystemExit("a folder warmed before the libraries were kept would read as warmed")
|
||||
print("PASS: the stage libraries go into the pipeline cache, and the warm pass counts once they are saved")
|
||||
|
||||
|
||||
@@ -11,7 +11,11 @@ The header is compiled and run as it is:
|
||||
start that died), and tells another driver's journal and an older build's empty marker apart;
|
||||
- the skip list keeps each variant once, for one driver;
|
||||
- starts in a row against a stand-in driver that dies on some programs: the step ends at the next start with those
|
||||
programs left out, and is left out for good only after three starts in a row that did not end it.
|
||||
programs left out, and is left out for good only after three starts in a row that did not end it;
|
||||
- a start counts as one of those three only when it died with the journal's "began" word written: for good from the stage
|
||||
libraries' first driver call, and in the program pass only while a compute warm is in the driver (Journal::Compiling).
|
||||
One that died or was stopped before, or in the translation between or after the compute warms, uses no try, however
|
||||
many there are; one killed in a compute compile does; an older build's journal (no word) counts as it did.
|
||||
Then the source: the link is off unless the row or RX_VK_GPL=1 says so, the entry goes through the header's rules, the
|
||||
link is made under the guard, the journal is marked around each library build, and the row is where the switch reads it.
|
||||
python -I -B tests/test_gpl_rules.py --cxx clang++
|
||||
@@ -28,6 +32,7 @@ ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
FIXTURE = r"""
|
||||
#include <cstdio>
|
||||
#include <memory>
|
||||
#include <set>
|
||||
#include <thread>
|
||||
#include "gpl_rules.h"
|
||||
@@ -47,13 +52,37 @@ static size_t size_of(const std::string& path) {
|
||||
}
|
||||
// A start of the driver's part as vk_draw.cpp makes it (warm_begin, warm_libraries, warm_end), against a driver that dies
|
||||
// with a program of `bad` in its hands: 0 the part was made, 1 the start died, 2 the part was left out.
|
||||
// die: where else the start dies (killed, or a power cut). First comes the program pass, the translation with its compute
|
||||
// warms spread over it (prepare_run's warm_compute, each held by a Journal::Compiling): kEarly, after the journal is opened
|
||||
// and before any of them; kAfterCompute, in the translation after compute warms on several workers came back (an update's
|
||||
// minutes of graphics translation); kInCompute, with one of them in the driver (a hung compile killed)
|
||||
enum Die { kNone, kEarly, kAfterCompute, kInCompute };
|
||||
static int start(const std::string& warming, uint64_t stamp, int programs, const std::set<uint64_t>& bad, int workers,
|
||||
std::vector<Id>* skipped, int* built) {
|
||||
std::vector<Id>* skipped, int* built, Die die = kNone) {
|
||||
const Left left = journal_left(warming, stamp);
|
||||
*skipped = skip_add(warming + ".skip", stamp, left.in_hand);
|
||||
if (left.found && !goes_on(left)) return remove(warming.c_str()), 2;
|
||||
Journal j;
|
||||
if (!j.open(warming, stamp, left.tries + 1)) return 2;
|
||||
if (die == kEarly) return 1;
|
||||
{ // (the compute warms of the program pass: two workers' at once, then one, then none)
|
||||
std::vector<std::unique_ptr<Journal::Compiling>> held;
|
||||
held.push_back(std::make_unique<Journal::Compiling>(j));
|
||||
held.push_back(std::make_unique<Journal::Compiling>(j));
|
||||
if (!j.counts()) return 3;
|
||||
held.erase(held.begin());
|
||||
if (!j.counts()) return 3;
|
||||
if (die == kInCompute) { // (the process is gone: nothing comes back from the driver, no destructor runs)
|
||||
for (auto& h : held) (void)h.release();
|
||||
return 1;
|
||||
}
|
||||
held.clear();
|
||||
if (j.counts()) return 3;
|
||||
Journal::Compiling again(j);
|
||||
if (!j.counts()) return 3;
|
||||
}
|
||||
if (j.counts() || j.has_begun()) return 3;
|
||||
if (die == kAfterCompute) return 1;
|
||||
for (int p = 1; p <= programs; p += workers) { // (the workers take a program each, all in the driver at once)
|
||||
int in_driver = 0;
|
||||
bool dies = false;
|
||||
@@ -62,6 +91,7 @@ static int start(const std::string& warming, uint64_t stamp, int programs, const
|
||||
bool skip = false;
|
||||
for (const Id& s : *skipped) skip = skip || s == id;
|
||||
if (skip) continue;
|
||||
j.began(); // (before each driver call, as vk_draw.cpp warm_libraries: the first one writes the word)
|
||||
j.mark(w, id), in_driver++;
|
||||
dies = dies || bad.count(id.key);
|
||||
}
|
||||
@@ -174,12 +204,32 @@ int main(int, char** argv) {
|
||||
CHECK(!journal_left(path, stamp).found && goes_on(journal_left(path, stamp))); // (no journal: an ordinary start)
|
||||
Journal j;
|
||||
CHECK(j.open(path, stamp, 1));
|
||||
CHECK(size_of(path) == 16 + 16 * (size_t)kSlots);
|
||||
CHECK(size_of(path) == 16 + 16 * (size_t)kSlots + 4 && kBeganAt == 16 + 16 * kSlots);
|
||||
Left l = journal_left(path, stamp);
|
||||
CHECK(l.found && l.tries == 1 && l.in_hand.empty() && goes_on(l)); // (died with nothing in the driver's hands)
|
||||
// (died before its first driver call: found, but no try used)
|
||||
CHECK(l.found && !l.began && l.tries == 0 && l.in_hand.empty() && goes_on(l) && !j.has_begun());
|
||||
{ // ((Triforce, 11-18) a compute warm under way: counted while the driver has it, not once it came back)
|
||||
Journal::Compiling c(j);
|
||||
l = journal_left(path, stamp);
|
||||
CHECK(j.counts() && l.began && l.tries == 1 && !j.has_begun());
|
||||
{
|
||||
Journal::Compiling d(j); // (and another worker's at once: the word stays until both came back)
|
||||
}
|
||||
CHECK(journal_left(path, stamp).began && j.counts());
|
||||
}
|
||||
l = journal_left(path, stamp);
|
||||
CHECK(!j.counts() && !l.began && l.tries == 0 && !j.has_begun());
|
||||
j.began(), j.began();
|
||||
{ // (once the libraries' pass wrote it, a compute warm that comes back does not take it away)
|
||||
Journal::Compiling c(j);
|
||||
}
|
||||
CHECK(j.counts() && journal_left(path, stamp).began);
|
||||
CHECK(j.has_begun() && size_of(path) == 16 + 16 * (size_t)kSlots + 4);
|
||||
l = journal_left(path, stamp);
|
||||
CHECK(l.found && l.began && l.tries == 1 && l.in_hand.empty() && goes_on(l)); // (died with nothing in the driver's hands)
|
||||
j.mark(3, {0xAAAA, 1}), j.mark(5, {0xBBBB, 2}), j.mark(63, {0xCCCC, 0});
|
||||
j.mark(64, {0xDDDD, 4}), j.mark(-1, {0xEEEE, 4}); // (past the slots: no line, and no byte)
|
||||
CHECK(size_of(path) == 16 + 16 * (size_t)kSlots);
|
||||
CHECK(size_of(path) == 16 + 16 * (size_t)kSlots + 4);
|
||||
l = journal_left(path, stamp);
|
||||
CHECK(l.in_hand.size() == 3 && l.in_hand[0] == (Id{0xAAAA, 1}) && l.in_hand[1] == (Id{0xBBBB, 2}) && l.in_hand[2] == (Id{0xCCCC, 0}));
|
||||
j.mark(3, {}); // (it came back from the driver)
|
||||
@@ -191,9 +241,29 @@ int main(int, char** argv) {
|
||||
j.close();
|
||||
CHECK(journal_left(path, stamp).in_hand.size() == 2); // (closing is not ending: only removing the file is)
|
||||
// (the count of starts: the third that did not end it is the last)
|
||||
CHECK(j.open(path, stamp, 2) && journal_left(path, stamp).tries == 2 && goes_on(journal_left(path, stamp)));
|
||||
CHECK(j.open(path, stamp, kTries) && journal_left(path, stamp).tries == kTries && !goes_on(journal_left(path, stamp)));
|
||||
CHECK(j.open(path, stamp, 2) && journal_left(path, stamp).tries == 1); // (not counted until it calls the driver)
|
||||
j.began();
|
||||
CHECK(journal_left(path, stamp).tries == 2 && goes_on(journal_left(path, stamp)));
|
||||
// (the third start, ended before its first driver call: the last try is still there)
|
||||
CHECK(j.open(path, stamp, kTries) && journal_left(path, stamp).tries == kTries - 1 && goes_on(journal_left(path, stamp)));
|
||||
j.began();
|
||||
CHECK(journal_left(path, stamp).tries == kTries && !goes_on(journal_left(path, stamp)));
|
||||
// (a slot named with the word not written, which no build writes: counted, and the variant blamed)
|
||||
CHECK(j.open(path, stamp, 1));
|
||||
j.mark(0, {0xF00D, 1});
|
||||
l = journal_left(path, stamp);
|
||||
CHECK(l.began && l.tries == 1 && l.in_hand.size() == 1);
|
||||
j.close();
|
||||
// (an older build's journal, the slots and no word after them: counted as it was)
|
||||
{
|
||||
FILE* o = fopen(path.c_str(), "wb");
|
||||
const uint32_t head[2] = {kJournalMagic, 2};
|
||||
const uint64_t zero[2 * kSlots]{};
|
||||
CHECK(o && fwrite(head, 4, 2, o) == 2 && fwrite(&stamp, 8, 1, o) == 1 &&
|
||||
fwrite(zero, 8, (size_t)(2 * kSlots), o) == (size_t)(2 * kSlots) && fclose(o) == 0);
|
||||
l = journal_left(path, stamp);
|
||||
CHECK(l.found && l.began && l.tries == 2 && l.in_hand.empty());
|
||||
}
|
||||
// (an older build's marker, an empty file: one start, no variant named)
|
||||
FILE* f = fopen(path.c_str(), "wb");
|
||||
CHECK(f && fclose(f) == 0);
|
||||
@@ -251,6 +321,62 @@ int main(int, char** argv) {
|
||||
CHECK(start(w, stamp, 40, all, 4, &skipped, &built) == 2 && !journal_left(w, stamp).found);
|
||||
CHECK(skipped.size() == 4 * kTries && built == 0);
|
||||
}
|
||||
{
|
||||
const std::string w = dir + "/f.warming";
|
||||
std::vector<Id> skipped;
|
||||
int built = 0;
|
||||
// ((Triforce, 11-18) starts that died before their first driver call use no try, however many: between them, a
|
||||
// driver that dies on everything still gets its three starts, and the fourth leaves the part out)
|
||||
std::set<uint64_t> all;
|
||||
for (int i = 1; i <= 40; i++) all.insert((uint64_t)i);
|
||||
for (int i = 0; i < 5; i++) CHECK(start(w, stamp, 40, all, 4, &skipped, &built, kEarly) == 1);
|
||||
CHECK(journal_left(w, stamp).tries == 0 && skipped.empty());
|
||||
for (uint32_t i = 0; i < kTries; i++) {
|
||||
CHECK(start(w, stamp, 40, all, 4, &skipped, &built) == 1);
|
||||
if (i + 1 < kTries)
|
||||
CHECK(start(w, stamp, 40, all, 4, &skipped, &built, kEarly) == 1 && journal_left(w, stamp).tries == i + 1);
|
||||
}
|
||||
CHECK(start(w, stamp, 40, all, 4, &skipped, &built) == 2 && skipped.size() == 4 * kTries && built == 0);
|
||||
}
|
||||
{
|
||||
const std::string w = dir + "/g.warming";
|
||||
std::vector<Id> skipped;
|
||||
int built = 0;
|
||||
// (an early death after one in the driver: that one's variants stay on the list, and the next start ends the part)
|
||||
CHECK(start(w, stamp, 40, {10}, 4, &skipped, &built) == 1);
|
||||
CHECK(start(w, stamp, 40, {10}, 4, &skipped, &built, kEarly) == 1 && skipped.size() == 4);
|
||||
built = 0;
|
||||
CHECK(start(w, stamp, 40, {10}, 4, &skipped, &built) == 0 && skipped.size() == 4 && built == 36);
|
||||
}
|
||||
{
|
||||
const std::string w = dir + "/h.warming";
|
||||
std::vector<Id> skipped;
|
||||
int built = 0;
|
||||
// ((Triforce, 11-18) killed in the translation after compute warms came back, the minutes after an update: no try,
|
||||
// however many; between them a driver that dies on everything still gets its three starts)
|
||||
std::set<uint64_t> all;
|
||||
for (int i = 1; i <= 40; i++) all.insert((uint64_t)i);
|
||||
for (int i = 0; i < 5; i++) CHECK(start(w, stamp, 40, all, 4, &skipped, &built, kAfterCompute) == 1);
|
||||
CHECK(journal_left(w, stamp).tries == 0 && !journal_left(w, stamp).began && skipped.empty());
|
||||
for (uint32_t i = 0; i < kTries; i++) {
|
||||
CHECK(start(w, stamp, 40, all, 4, &skipped, &built) == 1);
|
||||
if (i + 1 < kTries)
|
||||
CHECK(start(w, stamp, 40, all, 4, &skipped, &built, kAfterCompute) == 1 && journal_left(w, stamp).tries == i + 1);
|
||||
}
|
||||
CHECK(start(w, stamp, 40, all, 4, &skipped, &built) == 2 && skipped.size() == 4 * kTries && built == 0);
|
||||
}
|
||||
{
|
||||
const std::string w = dir + "/i.warming";
|
||||
std::vector<Id> skipped;
|
||||
int built = 0;
|
||||
// (killed with a compute warm in the driver, a hung compile: each such start is a try, and the fourth leaves the
|
||||
// part out; no variant is named, compute warms have no slot)
|
||||
for (uint32_t i = 0; i < kTries; i++) {
|
||||
CHECK(start(w, stamp, 40, {}, 4, &skipped, &built, kInCompute) == 1);
|
||||
CHECK(journal_left(w, stamp).began && journal_left(w, stamp).tries == i + 1);
|
||||
}
|
||||
CHECK(start(w, stamp, 40, {}, 4, &skipped, &built) == 2 && skipped.empty() && built == 0);
|
||||
}
|
||||
{
|
||||
const std::string w = dir + "/e.warming";
|
||||
std::vector<Id> skipped;
|
||||
@@ -284,7 +410,7 @@ def check_source():
|
||||
row = re.search(r'\{TAB_DEBUG, "Fast pipeline link", &opts\.fast_pipeline_link, 0, 1, 1, tx_onoff,(.*?)\},\n', menu, re.S)
|
||||
if not row or not row.group(1).rstrip().endswith("nullptr, true, true"):
|
||||
raise SystemExit("no Fast pipeline link row on the Debug tab (one that applies after a restart and leaves the preset alone)")
|
||||
if menu.index('"Developer", nullptr') > row.start() or row.start() > menu.index('{TAB_SYSTEM, "Restart"'):
|
||||
if menu.index('"Developer", nullptr') > row.start() or row.start() > menu.index('constexpr int kRowsEnd'):
|
||||
raise SystemExit("the Fast pipeline link row is not under the Debug tab's Developer heading")
|
||||
if "int fast_pipeline_link = 1;" not in opts:
|
||||
raise SystemExit("the Fast pipeline link row is not on by default")
|
||||
@@ -324,11 +450,34 @@ def check_source():
|
||||
warm.index("build_graphics(p, *blank, at, VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, part)")
|
||||
if not a < b < c < warm.index("warm_journal.mark(slot, {});"):
|
||||
raise SystemExit("warm_libraries does not skip, then name the variant, then build, then clear its line")
|
||||
# ((Triforce, 11-18) a start is a try from its first driver call: the word is written before the variant is named)
|
||||
if not warm.index("warm_journal.began();") < b:
|
||||
raise SystemExit("warm_libraries names a variant in the driver's hands before the journal says the start called the driver")
|
||||
if "threads.emplace_back(worker, (int)i);" not in warm:
|
||||
raise SystemExit("the workers of the driver's part have no journal slot of their own")
|
||||
prep = between(draw, "bool prepare_run(", "\n}\n")
|
||||
if prep.count("warm_begin(warming, warmed)") != 2 or "remove(warming" in prep or prep.count("warm_end(warming);") < 5:
|
||||
raise SystemExit("prepare_run begins or ends the driver's part past warm_begin and warm_end")
|
||||
# (the program pass's compute warms stay under the journal, opened before the translation, and make the start a try
|
||||
# only while one is in the driver: held by a Journal::Compiling around guarded_compute alone, not the sticky began(),
|
||||
# which would count a death anywhere in the translation after the first of them. The creation is
|
||||
# prepare_compute_pipeline's, which the pipeline cache carry's rebuild shares: pcache_carry.h)
|
||||
cs = between(prep, "const auto warm_compute = [&](Program& p) {", "\n };\n")
|
||||
build = between(draw, "bool prepare_compute_pipeline(Program& p) {", "\n}\n")
|
||||
held = re.search(r"\{\s*const gpl_rules::Journal::Compiling compiling\(warm_journal\);\s*"
|
||||
r"built = guarded_compute\(pcache, &ci, &pl\) == VK_SUCCESS && pl;\s*\}", build)
|
||||
if not held or "prepare_compute_pipeline(p)" not in cs or "guarded_compute(" in cs or \
|
||||
build.count("guarded_compute(") != 1 or "warm_journal.began();" in cs + build:
|
||||
raise SystemExit("prepare_run's compute warms do not hold the journal's word for the driver call alone")
|
||||
# (stopped, the state list is not gone through after the program pass: it held a stop for minutes past the kill)
|
||||
if "if (!background && !prepare_stopped()) state_list_prepare(nullptr);" not in prep:
|
||||
raise SystemExit("prepare_run goes through the state list after a stop")
|
||||
sl = between(draw, "void state_list_prepare(", "\n}\n")
|
||||
if sl.count("if (stopped()) return;") != 2 or "applied.id = 0;" not in between(sl, "const auto stopped = [&] {", "};") or \
|
||||
sl.count("if (prepare_stopped()) return;") != 2:
|
||||
raise SystemExit("state_list_prepare does not stop on a stop, or writes the lists down as gone through when it does")
|
||||
if not prep.index("if (!warm_begin(warming, warmed)) warm = warm_cs = false;") < prep.index("threads.emplace_back(worker);"):
|
||||
raise SystemExit("prepare_run's program pass (its compute warms) is no longer under warm_begin's journal")
|
||||
begin = between(draw, "bool warm_begin(", "\n}\n")
|
||||
for need in ("gpl_rules::journal_left(warming, warmed)", 'gpl_rules::skip_add(warming + ".skip", warmed, left.in_hand)',
|
||||
"if (left.found && !gpl_rules::goes_on(left)) {", "warm_journal.open(warming, warmed, left.tries + 1)"):
|
||||
@@ -336,7 +485,8 @@ def check_source():
|
||||
raise SystemExit("warm_begin: " + need + " is missing")
|
||||
# (and in play: no library of a variant on the skip list is built behind a draw, at any start with the libraries)
|
||||
if "if (gpl_skipped(p)) cold[0] = cold[1] = 0;" not in gp or "gpl_skip_set(warm_skip);" not in begin or \
|
||||
'if (libraries && !background) gpl_skip_set(gpl_rules::skip_read(warming + ".skip", warmed));' not in prep:
|
||||
('if (libraries && !background) {\n warm_skip_carry(warming + ".skip", libraries, warmed);\n'
|
||||
' gpl_skip_set(gpl_rules::skip_read(warming + ".skip", warmed));') not in prep:
|
||||
raise SystemExit("a variant the driver's part leaves out still has its libraries built behind a draw")
|
||||
# (without the libraries the marker is as it was: one start that did not end the compute warm leaves it out)
|
||||
if 'logf("vk: the last start did not finish the driver\'s part of the shaders: left out");' not in prep:
|
||||
|
||||
@@ -11,5 +11,20 @@ int main() {
|
||||
CHECK("a GPU taken out since is Auto", menu_device(2, 1) == -1);
|
||||
CHECK("a negative choice (a hand-edited ini) is Auto", menu_device(-1, 2) == -1);
|
||||
CHECK("no usable GPU: Auto", menu_device(1, 0) == -1);
|
||||
|
||||
// ((Triforce) 11-20) by the saved name first: the launcher numbered the cards in Windows' order before the game's first run
|
||||
using mkwvk::gpu_choice::pick;
|
||||
using mkwvk::gpu_choice::name_key;
|
||||
const std::vector<std::string> laptop = {"NVIDIA GeForce RTX 5060 Laptop GPU", "AMD Radeon(TM) 860M Graphics"};
|
||||
CHECK("the name finds the card the number missed (the ticket's 2 = the 860M here)",
|
||||
pick("NVIDIA GeForce RTX 5060 Laptop GPU", laptop, 2) == 0);
|
||||
CHECK("no name: the number, as before", pick("", laptop, 2) == 1 && pick("", laptop, 1) == 0);
|
||||
CHECK("Auto stays Auto whatever name is left in the file", pick("NVIDIA GeForce RTX 5060 Laptop GPU", laptop, 0) == -1);
|
||||
CHECK("a name no card has (taken out): the number", pick("NVIDIA GeForce RTX 4090", laptop, 1) == 0);
|
||||
CHECK("spaces and case do not matter", pick(" amd radeon(tm) 860m graphics ", laptop, 1) == 1);
|
||||
CHECK("name_key", name_key("AMD Radeon RX 7800 XT\t") == "amd radeon rx 7800 xt");
|
||||
const std::vector<std::string> twins = {"NVIDIA GeForce RTX 3090", "NVIDIA GeForce RTX 3090"};
|
||||
CHECK("two cards of one name: the numbered one when it has that name", pick("NVIDIA GeForce RTX 3090", twins, 2) == 1);
|
||||
CHECK("a number past the list with a name: the first of that name", pick("NVIDIA GeForce RTX 3090", twins, 5) == 0);
|
||||
std::puts("gpu choice: all checks passed");
|
||||
}
|
||||
|
||||
@@ -12,10 +12,11 @@ ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def preset_exempt(menu, value):
|
||||
"""the menu's row for opts.<value> leaves the quality preset alone (Row::preset_exempt, which set_row checks)"""
|
||||
"""the menu has no quality preset that a change of the row's could reset ((Triforce, options_version 7) the Quality preset
|
||||
row is gone, and with it the memory budget it set: the card's own), and the row is on its tab"""
|
||||
start = menu.index("&opts.%s," % value, menu.index("Row rows[] = {"))
|
||||
row = menu[start:menu.index("},", start)]
|
||||
return row.rstrip().endswith(", true") and "if (!r.preset_exempt)" in menu
|
||||
return bool(row) and "opts.preset" not in menu and "void apply_preset" not in menu
|
||||
|
||||
|
||||
def main():
|
||||
@@ -30,12 +31,12 @@ def main():
|
||||
("menu_set_gpu_count((int)valid_gpus.size())", "the row offers only the usable GPUs"),
|
||||
("p.apiVersion >= VK_API_VERSION_1_3", "only Vulkan 1.3 GPUs are listed"),
|
||||
('getenv("RX_VK_DEVICE")', "RX_VK_DEVICE wins over the row"),
|
||||
("gpu_choice::menu_device(opts.gpu_device, (int)valid_gpus.size())", "the row's choice is taken")):
|
||||
("gpu_choice::pick(menu_gpu_name(), gpu_device_names, opts.gpu_device)", "the row's choice is taken, by its saved name first")):
|
||||
if need not in pick:
|
||||
raise SystemExit("pick_device: %s is missing (%s)" % (need, why))
|
||||
if pick.index("menu_init()") > pick.index("gpu_choice::menu_device"):
|
||||
if pick.index("menu_init()") > pick.index("gpu_choice::pick("):
|
||||
raise SystemExit("pick_device reads the GPU row before menu_init")
|
||||
if pick.index('getenv("RX_VK_DEVICE")') > pick.index("gpu_choice::menu_device"):
|
||||
if pick.index('getenv("RX_VK_DEVICE")') > pick.index("gpu_choice::pick("):
|
||||
raise SystemExit("pick_device takes the GPU row before RX_VK_DEVICE")
|
||||
menu = (vk / "vk_menu.cpp").read_text(encoding="utf-8")
|
||||
if not preset_exempt(menu, "gpu_device"):
|
||||
|
||||
@@ -59,10 +59,14 @@ static int fails;
|
||||
@@ENUM@@
|
||||
static GcMap census;
|
||||
static uint64_t census_touched, census_zeroed, census_discarded;
|
||||
static int64_t census_game_bytes; /* (hos_mem_used's count: tests/test_mem_limit.py) */
|
||||
static int locks, unlocks;
|
||||
#define CENSUS_LOCK() (locks++)
|
||||
#define CENSUS_UNLOCK() (unlocks++)
|
||||
int hos_mem_census_on(void) { return 1; }
|
||||
/* ((Triforce) HOS_MEM_LIMIT: the bare region's rule and the discard's core hand-off are only with the limit on) */
|
||||
static int64_t fixture_limit = 1;
|
||||
static int64_t hos_mem_limit(void) { return fixture_limit; }
|
||||
uint64_t hos_large_lo, hos_large_hi;
|
||||
/* (guest addresses: window_lo is at scratch, for the one place that writes there, Linux's zeroing under an import) */
|
||||
static unsigned char scratch[1 << 20];
|
||||
@@ -88,6 +92,10 @@ static int nregions, lock_depth;
|
||||
static int hos_guest_range(uint64_t a, uint64_t n) { (void)a, (void)n; return 1; }
|
||||
static int hos_guest_io_begin(const void *p, uint64_t n) { (void)p, (void)n; return 0; }
|
||||
static void hos_guest_io_end(int io) { (void)io; }
|
||||
/* ((Triforce) the discard's virtual core: given up for the call, taken back after it, once each) */
|
||||
static int cores_away, cores_back, core_away_at_discard;
|
||||
static int hos_vcore_away(void) { cores_away++; return 1; }
|
||||
static void hos_vcore_back(void) { cores_back++; }
|
||||
/* A discard as it happens: whether a listed region still holds its pages (so that hos_region_alloc would not hand them out
|
||||
meanwhile), and whether the regions' lock is held */
|
||||
static int seen, seen_listed, seen_locked;
|
||||
@@ -103,7 +111,7 @@ typedef void *PVOID;
|
||||
#define ERROR_SUCCESS 0
|
||||
#define MEM_RESET 0x80000
|
||||
#define PAGE_READWRITE 4
|
||||
static DWORD fake_discard(PVOID p, SIZE_T n) { discard_seen(guest_of(p), guest_of(p) + n); return ERROR_SUCCESS; }
|
||||
static DWORD fake_discard(PVOID p, SIZE_T n) { core_away_at_discard = cores_away - cores_back; discard_seen(guest_of(p), guest_of(p) + n); return ERROR_SUCCESS; }
|
||||
static void *GetModuleHandleA(const char *name) { (void)name; return (void *)1; }
|
||||
static void *GetProcAddress(void *module, const char *name) { (void)module, (void)name; return (void *)fake_discard; }
|
||||
static void *VirtualAlloc(void *p, SIZE_T n, unsigned type, unsigned protect) {
|
||||
@@ -111,7 +119,7 @@ static void *VirtualAlloc(void *p, SIZE_T n, unsigned type, unsigned protect) {
|
||||
discard_seen(guest_of(p), guest_of(p) + n);
|
||||
return p;
|
||||
}
|
||||
/* (Linux: asked first whether an import holds the pages) */
|
||||
/* (Linux, and Windows since 11-19: asked first whether an import holds the pages) */
|
||||
static int imported_now;
|
||||
int rx_guest_imported(uint64_t lo, uint64_t hi) { discard_seen(lo, hi); return imported_now; }
|
||||
|
||||
@@ -292,6 +300,20 @@ static void test_give_back(void) {
|
||||
/* ---- the production notes and census_release */
|
||||
static void test_production(void) {
|
||||
memset(&census, 0, sizeof census);
|
||||
census_game_bytes = 0;
|
||||
{ /* ((Triforce, 11-19) the budget's count: a page the game maps over one it has already counts once; it goes when let go) */
|
||||
const uint64_t g = 9 * GB;
|
||||
hos_mem_note(HOS_MEM_PAGES, g, 0x10000);
|
||||
hos_mem_note(HOS_MEM_MAPPED, g + 0x8000, 0x10000); /* (half over the pages above) */
|
||||
CHECK(census_game_bytes == 0x18000 && (uint64_t)census_game_bytes == gc_count(&census, GC_GAME, 0, GC_SPACE),
|
||||
"the game's pages counted %lld, the map holds %llu", (long long)census_game_bytes, (unsigned long long)gc_count(&census, GC_GAME, 0, GC_SPACE));
|
||||
hos_mem_note(HOS_MEM_DECOMMITTED, g, 0x8000);
|
||||
hos_mem_note(HOS_MEM_ZEROED, g + 0x8000, 0x4000);
|
||||
hos_mem_note(HOS_MEM_DISCARDED, g + 0xC000, 0x40000); /* (more than is there) */
|
||||
CHECK(census_game_bytes == 0 && !gc_count(&census, GC_GAME, 0, GC_SPACE), "the game's pages let go still counted: %lld", (long long)census_game_bytes);
|
||||
memset(&census, 0, sizeof census);
|
||||
census_game_bytes = 0, census_zeroed = census_discarded = 0;
|
||||
}
|
||||
const uint64_t a = 5 * GB - 0x10000; /* (across a chunk's end) */
|
||||
hos_mem_note(HOS_MEM_COMMITTED, a, 0x30000);
|
||||
CHECK(gc_count(&census, GC_HELD, 0, GC_SPACE) == 0x30000, "committed: %llu held", (unsigned long long)gc_count(&census, GC_HELD, 0, GC_SPACE));
|
||||
@@ -418,10 +440,21 @@ static void test_region_free(void) {
|
||||
const uint64_t discarded = census_discarded, zeroed = census_zeroed;
|
||||
seen = 0, lock_depth = 0;
|
||||
hos_region_free(r);
|
||||
CHECK(seen == 1 && seen_listed && !seen_locked, "a freed region's discard: %d seen, %s, %s", seen,
|
||||
#ifdef FIXTURE_POSIX
|
||||
const int seen_want = 1; /* (the import question; Linux's discard is not a seen one here) */
|
||||
#else
|
||||
const int seen_want = 2; /* (the import question, then the discard) */
|
||||
#endif
|
||||
CHECK(seen == seen_want && seen_listed && !seen_locked, "a freed region's discard: %d seen, %s, %s", seen,
|
||||
seen_listed ? "listed" : "no longer listed (a region asked for meanwhile could be given its pages)",
|
||||
seen_locked ? "under the regions' lock" : "not under the lock");
|
||||
CHECK(nregions == 1 && regions[0].addr == other && lock_depth == 0, "the freed region still listed (%d listed)", nregions);
|
||||
#ifndef FIXTURE_POSIX
|
||||
CHECK(core_away_at_discard == 1 && cores_away == cores_back, "the discard made with the thread's virtual core held (%d away, %d back)",
|
||||
cores_away, cores_back);
|
||||
#else
|
||||
(void)core_away_at_discard; /* (Linux's discard is the memfd's: no virtual core is given up for it) */
|
||||
#endif
|
||||
#ifdef FIXTURE_POSIX
|
||||
CHECK(!gc_count(&census, GC_KEPT, r, r + 0x40000) && !gc_count(&census, GC_HELD, r, r + 0x40000) && census_discarded == discarded,
|
||||
"Linux's discard noted as discarded too: %llu kept, %llu counted discarded",
|
||||
@@ -440,6 +473,23 @@ static void test_region_free(void) {
|
||||
(void)zeroed;
|
||||
CHECK(gc_count(&census, GC_KEPT, r, r + 0x40000) == 0x40000 && census_discarded == discarded + 0x40000 &&
|
||||
!gc_count(&census, GC_HELD, r, r + 0x40000), "a discarded region not kept");
|
||||
/* ((Triforce, 11-19) pages an import holds: zeroed in place and kept as zeroed, not discarded (the discard was slow there and
|
||||
gave nothing back), still while the region is listed and not under the lock) */
|
||||
{
|
||||
const uint64_t discarded2 = census_discarded, zeroed2 = census_zeroed;
|
||||
memset(&list[1], 0, sizeof list[1]);
|
||||
list[1].addr = r, list[1].size = 0x40000, nregions = 2, imported_now = 1, window_lo = r;
|
||||
hos_mem_note(HOS_MEM_COMMITTED, r, 0x40000);
|
||||
seen = 0;
|
||||
hos_region_free(r);
|
||||
CHECK(seen == 1 && seen_listed && !seen_locked && nregions == 1, "Windows' zeroing under an import: %d seen, %s, %s", seen,
|
||||
seen_listed ? "listed" : "no longer listed", seen_locked ? "under the lock" : "not under the lock");
|
||||
CHECK(gc_count(&census, GC_KEPT, r, r + 0x40000) == 0x40000 && census_zeroed == zeroed2 + 0x40000 && census_discarded == discarded2,
|
||||
"Windows' zeroing under an import: %llu kept, %llu counted zeroed, %llu discarded",
|
||||
(unsigned long long)gc_count(&census, GC_KEPT, r, r + 0x40000), (unsigned long long)(census_zeroed - zeroed2),
|
||||
(unsigned long long)(census_discarded - discarded2));
|
||||
imported_now = 0, window_lo = 0;
|
||||
}
|
||||
/* (the heap's large pages are not discarded: left held, not noted) */
|
||||
hos_large_lo = r, hos_large_hi = r + 64 * MB;
|
||||
memset(&list[1], 0, sizeof list[1]);
|
||||
@@ -455,6 +505,58 @@ static void test_region_free(void) {
|
||||
seen = 0;
|
||||
hos_region_free(r); /* (freed already: nothing) */
|
||||
CHECK(seen == 0 && nregions == 1, "a region freed twice discarded twice");
|
||||
/* ((Triforce) a region the game asked for itself, freed with none of its pages in it (it was refused them, HOS_MEM_LIMIT):
|
||||
nothing to discard, and its pages noted let go as a discard notes them) */
|
||||
memset(&census, 0, sizeof census);
|
||||
memset(&list[1], 0, sizeof list[1]);
|
||||
list[1].addr = r, list[1].size = 0x40000, list[1].game = 1, nregions = 2;
|
||||
hos_mem_note(HOS_MEM_COMMITTED, r, 0x40000);
|
||||
const int64_t bare = region_frees_bare;
|
||||
seen = 0, decommits = 0;
|
||||
hos_region_free(r);
|
||||
CHECK(seen == 0 && decommits == 0 && region_frees_bare == bare + 1,
|
||||
"a region of the game's own with none of its pages was discarded (%d discards, %d decommits)", seen, decommits);
|
||||
CHECK(nregions == 1 && regions[0].addr == other && lock_depth == 0, "the bare region still listed (%d listed)", nregions);
|
||||
CHECK(gc_count(&census, GC_KEPT, r, r + 0x40000) == 0x40000 && !gc_count(&census, GC_HELD, r, r + 0x40000),
|
||||
"a bare region's pages not noted let go: %llu kept, %llu held", (unsigned long long)gc_count(&census, GC_KEPT, r, r + 0x40000),
|
||||
(unsigned long long)gc_count(&census, GC_HELD, r, r + 0x40000));
|
||||
{ /* (the same bare region without the limit: discarded, as upstream does) */
|
||||
memset(&census, 0, sizeof census);
|
||||
memset(&list[1], 0, sizeof list[1]);
|
||||
list[1].addr = r, list[1].size = 0x40000, list[1].game = 1, nregions = 2;
|
||||
hos_mem_note(HOS_MEM_COMMITTED, r, 0x40000);
|
||||
fixture_limit = 0, seen = 0, decommits = 0;
|
||||
hos_region_free(r);
|
||||
CHECK((seen || decommits) && region_frees_bare == bare + 1, "without the limit a bare region of the game's was not discarded");
|
||||
fixture_limit = 1;
|
||||
}
|
||||
/* (with one page of the game's in it: discarded whole, as any region) */
|
||||
memset(&census, 0, sizeof census);
|
||||
memset(&list[1], 0, sizeof list[1]);
|
||||
list[1].addr = r, list[1].size = 0x40000, list[1].game = 1, nregions = 2;
|
||||
hos_mem_note(HOS_MEM_COMMITTED, r, 0x40000);
|
||||
hos_mem_note(HOS_MEM_PAGES, r + 0x3000, 0x1000);
|
||||
seen = 0, decommits = 0;
|
||||
hos_region_free(r);
|
||||
CHECK((seen || decommits) && region_frees_bare == bare + 1 && !gc_count(&census, GC_GAME, r, r + 0x40000),
|
||||
"a region with a page of the game's not discarded (%d discards, %d decommits)", seen, decommits);
|
||||
#ifndef FIXTURE_POSIX
|
||||
{ /* (without the limit: upstream's discard, the core kept) */
|
||||
memset(&census, 0, sizeof census);
|
||||
memset(&list[1], 0, sizeof list[1]);
|
||||
list[1].addr = r, list[1].size = 0x40000, nregions = 2;
|
||||
hos_mem_note(HOS_MEM_COMMITTED, r, 0x40000);
|
||||
fixture_limit = 0, cores_away = cores_back = 0, seen = 0;
|
||||
hos_region_free(r);
|
||||
CHECK(seen >= 1 && cores_away == 0, "without the limit the discard gave the core up (%d away)", cores_away); // (>= 1: the import look before it, rx_guest_imported, notes the range too)
|
||||
fixture_limit = 1;
|
||||
}
|
||||
#endif
|
||||
/* (the rule: only the game's own region, only with the census, only with none of its pages) */
|
||||
CHECK(!hos_region_discard_needed(1, 1, 0), "a bare region of the game's is discarded");
|
||||
CHECK(hos_region_discard_needed(0, 1, 0) && hos_region_discard_needed(1, 0, 0) && hos_region_discard_needed(1, 1, 1) &&
|
||||
hos_region_discard_needed(1, 1, 0x40000) && hos_region_discard_needed(0, 0, 0), "a region that needs its discard gets none");
|
||||
memset(&census, 0, sizeof census);
|
||||
regions = NULL, nregions = 0;
|
||||
}
|
||||
|
||||
@@ -483,6 +585,24 @@ MUTATIONS = [
|
||||
("hos_region_free", "regions[i].freeing = 1;",
|
||||
"regions[i].freeing = 1, memmove(®ions[i], ®ions[i + 1], (nregions - i - 1) * sizeof(Range)), nregions--;",
|
||||
"a freed region unlisted before its discard: a region asked for meanwhile may be given the pages it then takes away"),
|
||||
("hos_region_discard_needed", "return !(game_region && census_on && !game_pages);", "return !(game_region && census_on) + 0 * (int)game_pages;",
|
||||
"a region with pages of the game's in it is freed without its discard: the next one there reads what they held"),
|
||||
("hos_region_discard_needed", "return !(game_region && census_on && !game_pages);", "return !(census_on && !game_pages) + 0 * game_region;",
|
||||
"a region the host asked for itself (written without pages) is freed without its discard"),
|
||||
("hos_region_discard_needed", "return !(game_region && census_on && !game_pages);", "return !(game_region && !game_pages) + 0 * census_on;",
|
||||
"without the census nothing says which pages are the game's: every region bare"),
|
||||
("hos_region_discard_needed", "return !(game_region && census_on && !game_pages);", "return 1 + 0 * (game_region + census_on + (int)game_pages);",
|
||||
"every region discarded again: the refused game's stutter (HOS_MEM_LIMIT)"),
|
||||
("hos_region_free", " hos_mem_note(HOS_MEM_DISCARDED, addr, freed_size);\n", "",
|
||||
"a region freed bare stays noted held: counted as handed out for good"),
|
||||
("hos_region_free", "game = regions[i].game;", "game = 0;", "the game's own regions are not known as such: every free a discard"),
|
||||
("hos_region_free", "hos_region_discard_needed(game && hos_mem_limit(),", "hos_region_discard_needed(game,",
|
||||
"a bare region freed without its discard with the limit off: the default path is no longer upstream's"),
|
||||
("discard_pages", " const int away = hos_mem_limit() ? hos_vcore_away() : 0;\n", " const int away = hos_vcore_away();\n",
|
||||
"the discard gives its core up with the limit off: the default path is no longer upstream's"),
|
||||
("discard_pages", " const int away = hos_mem_limit() ? hos_vcore_away() : 0;\n", " const int away = 0;\n",
|
||||
"the discard made with the thread's virtual core held: the threads of its core wait out the kernel's milliseconds"),
|
||||
("discard_pages", " if (away) hos_vcore_back();\n", " (void)away;\n", "the core given up for a discard and never taken back"),
|
||||
("discard_pages", " if (hi <= lo || keep) return;\n", " if (hi <= lo || keep) return;\n hos_mem_note(HOS_MEM_DISCARDED, lo, hi - lo);\n",
|
||||
"the discard noted before the large pages are left alone, and before Linux's own note"),
|
||||
("hos_mem_note", "gc_change(&census, GC_KEPT, lo, hi, 0);\n CENSUS_UNLOCK();", "CENSUS_UNLOCK();",
|
||||
@@ -496,8 +616,8 @@ MUTATIONS = [
|
||||
("census_release", "if (lo < (1ULL << 32)) return 0;", "", "pages below 4 GB, handed out without a commit, are decommitted"),
|
||||
("hos_mem_note", "gc_move(&census, GC_HELD, GC_KEPT, lo, hi)", "gc_change(&census, GC_KEPT, lo, hi, 1)",
|
||||
"a discarded region's pages never committed count as kept"),
|
||||
("hos_mem_note", "gc_change(&census, GC_HELD, lo, hi, 0);\n gc_change(&census, GC_GAME, lo, hi, 0);\n __atomic_add_fetch(&census_zeroed",
|
||||
"gc_change(&census, GC_GAME, lo, hi, 0);\n __atomic_add_fetch(&census_zeroed",
|
||||
("hos_mem_note", "gc_change(&census, GC_HELD, lo, hi, 0);\n __atomic_sub_fetch(&census_game_bytes, (int64_t)gc_change(&census, GC_GAME, lo, hi, 0), __ATOMIC_RELAXED);\n __atomic_add_fetch(&census_zeroed",
|
||||
"__atomic_sub_fetch(&census_game_bytes, (int64_t)gc_change(&census, GC_GAME, lo, hi, 0), __ATOMIC_RELAXED);\n __atomic_add_fetch(&census_zeroed",
|
||||
"zeroed pages stay held: never given back"),
|
||||
]
|
||||
# (and of guest_census.h)
|
||||
@@ -573,7 +693,12 @@ def main():
|
||||
"host/hos_mem.c"),
|
||||
"pages_mark_used_locked": block(mem, "static void pages_mark_used_locked(", "host/hos_mem.c"),
|
||||
"discard_pages": block(mem, "static void discard_pages(", "host/hos_mem.c"),
|
||||
"hos_region_discard_needed": block(mem, "int hos_region_discard_needed(int game_region, int census_on, uint64_t game_pages)",
|
||||
"host/hos_mem.c"),
|
||||
"region_frees_bare": "static int64_t region_frees_bare;",
|
||||
"hos_region_free": block(mem, "void hos_region_free(uint64_t addr)", "host/hos_mem.c")}
|
||||
if mem.count("static int64_t region_frees_bare;") != 1:
|
||||
raise SystemExit("FAIL: host/hos_mem.c's region_frees_bare not found once")
|
||||
range_t = re.findall(r"^typedef struct \{[^}]*\} Range;$", mem, re.M)
|
||||
pages_used = re.findall(r"^static uint64_t pages_used\[[^\n]*\];$", mem, re.M)
|
||||
if len(range_t) != 1 or len(pages_used) != 1:
|
||||
|
||||
172
tests/test_guides_band.py
Normal file
172
tests/test_guides_band.py
Normal file
@@ -0,0 +1,172 @@
|
||||
"""Our guides' plate inside the game's Options screen covers the game's own guides band to its end, past the 16:9 column on
|
||||
a picture wider than the grid (gpu/vk/game_grid.h guide_band_x1, vk_ui.h prompt_bar, vk_menu.cpp draw_menu; no game).
|
||||
|
||||
(Triforce, 11-20) The lab's check 3 of 26670c0: on every Triforce tab inside the game's Options screen "a plain strip of
|
||||
the game's footer band shows to the right of our guides": about 75 px in the 1600 x 900 window (a letterboxed 21:9
|
||||
picture, 16x9_z3_footer_game_vs_ours.png) and about 155 px in fullscreen 3440 x 1440 (fs_10_options_game_tab.png against
|
||||
fs_11_tab1.png, x 3000 to 3155). Our plate ended at the column's right edge (3840 units); the game's band (SystemOverlay_00's
|
||||
N_Footer_00: W_GuideBg_00 and W_GuideBg_01, right-aligned at 2110 and 2174 units right of the middle) goes on past it.
|
||||
Measured on the game's own tab in shots052c, the band is seen to 238 to 240 units past the column's edge in fs, the
|
||||
1720 x 720 window and the 1600 x 900 one (the window pane's last texels clear).
|
||||
|
||||
1. game_grid.h alone: where our plate ends, in the window, for the lab's shapes (within a few pixels of where the game's band
|
||||
was seen to end), never past the picture's right edge (the game draws nothing in the bars), and at the column's edge
|
||||
where the grid is the whole picture's width (16:9, 16:10, 4:3) or over play.
|
||||
2. The source: prompt_bar's plate and its dark texture to guides_x1, the texture's own right end carried on (not stretched,
|
||||
so inside the column it is as it was); draw_menu gives the pages the band's end.
|
||||
|
||||
python -I -B tests/test_guides_band.py [--cxx clang++]
|
||||
"""
|
||||
import argparse
|
||||
import subprocess
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
VK = ROOT / "gpu" / "vk"
|
||||
RUN_ALL_ARGS = ["--cxx", "{cxx}"]
|
||||
|
||||
|
||||
def check(ok, why):
|
||||
if not ok:
|
||||
raise SystemExit("FAIL: " + why)
|
||||
|
||||
|
||||
def block(text, head):
|
||||
start = text.index(head)
|
||||
end = text.index("{", start) + 1
|
||||
depth = 1
|
||||
while depth:
|
||||
depth += (text[end] == "{") - (text[end] == "}")
|
||||
end += 1
|
||||
return text[start:end]
|
||||
|
||||
|
||||
GRID = r"""
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdint>
|
||||
#include "game_grid.h"
|
||||
using namespace mkwvk;
|
||||
static int fails = 0;
|
||||
#define CHECK(x) do { if (!(x)) { std::printf("FAIL:%d %s\n", __LINE__, #x); fails++; } } while (0)
|
||||
static bool near(float a, float b, float tol) { return std::fabs(a - b) <= tol; }
|
||||
// (our plate's right end in the window: guide_band_x1 on the column the pages are drawn on, put through its map)
|
||||
static float plate_end(uint32_t pw, uint32_t ph, uint32_t ww, uint32_t wh, double r, game_grid::Place* gp = nullptr,
|
||||
float band_right = game_grid::kGuideBandRight) {
|
||||
const game_grid::Place g = game_grid::of(pw, ph, ww, wh, r);
|
||||
if (gp) *gp = g;
|
||||
const game_grid::Column c = game_grid::column_of(g, (float)ww, (float)wh, true);
|
||||
return c.map.x(game_grid::guide_band_x1(c, band_right));
|
||||
}
|
||||
int main() {
|
||||
const double r21 = 64.0 / 27.0, r1610 = 16.0 / 10.0, r32 = 32.0 / 9.0;
|
||||
// the lab's shapes, where the game's band was seen to end on its own tab (shots052c *_10_options_game_tab: the last
|
||||
// pixel of the band's fade): the old plate ended at the column's edge, 1399 / 1500 / 3000
|
||||
{
|
||||
game_grid::Place g;
|
||||
const float e = plate_end(3416, 1440, 1600, 900, r21, &g); // (16x9: 674 lines, the column 201 to 1399)
|
||||
std::printf("1600 x 900, 21:9 picture: the plate to %.1f (the game's band seen to 1473 to 1478)\n", e);
|
||||
CHECK(near(e, 1475, 4) && e <= g.pic_x + g.pic_w);
|
||||
const float f = plate_end(3416, 1440, 3440, 1440, r21, &g); // (fs: the column 440 to 3000)
|
||||
std::printf("fullscreen 3440 x 1440: the plate to %.1f (seen to 3150 to 3162)\n", f);
|
||||
CHECK(near(f, 3158, 6));
|
||||
const float h = plate_end(3416, 1440, 1720, 720, r21, &g); // (21x9: the column 220 to 1500)
|
||||
std::printf("1720 x 720: the plate to %.1f (seen to 1577 to 1583)\n", h);
|
||||
CHECK(near(h, 1580, 4));
|
||||
}
|
||||
// where the grid is the picture's whole width the plate ends at the column's edge, as before
|
||||
{
|
||||
CHECK(near(plate_end(2560, 1440, 1920, 1080, 0), 1920, 0.5f)); // (16:9)
|
||||
CHECK(near(plate_end(2304, 1440, 1680, 1050, r1610), 1680, 0.5f)); // (16:10: squeezed, the grid the whole picture)
|
||||
CHECK(near(plate_end(2560, 1440, 1600, 1200, 0), 1600, 0.5f)); // (a 16:9 picture between bars in a 4:3 window)
|
||||
game_grid::Place g;
|
||||
const float e = plate_end(1600, 1200, 1920, 1080, 0, &g); // (a 4:3 picture between bars at its sides)
|
||||
CHECK(near(e, g.pic_x + g.pic_w, 0.5f) && e < 1920 - 100); // (not into the bar)
|
||||
}
|
||||
// a picture only a little wider than 16:9: the band cut at the picture's edge (the game draws nothing past it)
|
||||
{
|
||||
game_grid::Place g;
|
||||
const float e = plate_end(1998, 1080, 1998, 1080, 1998.0 / 1080, &g);
|
||||
const float col_edge = g.x + g.w;
|
||||
CHECK(e > col_edge + 1 && near(e, g.pic_x + g.pic_w, 0.5f));
|
||||
}
|
||||
// a 32:9 picture: the whole band, 240 units past the column, far inside the picture
|
||||
{
|
||||
game_grid::Place g;
|
||||
const float e = plate_end(5120, 1440, 5120, 1440, r32, &g);
|
||||
CHECK(near(e, g.x + g.w + 240 * g.h / 2160, 0.5f) && e < g.pic_x + g.pic_w);
|
||||
}
|
||||
// over play (our options over the game, not its Options screen), and with no picture known: the column's edge
|
||||
{
|
||||
const game_grid::Place g = game_grid::of(3416, 1440, 1600, 900, r21);
|
||||
const game_grid::Column play = game_grid::column_of(g, 1600, 900, false);
|
||||
CHECK(play.game_x1 == 0 && game_grid::guide_band_x1(play) == play.w);
|
||||
const game_grid::Column none = game_grid::column_of(game_grid::of(0, 0, 2560, 1080, 0), 2560, 1080, true);
|
||||
CHECK(none.game_x1 == 0 && game_grid::guide_band_x1(none) == none.w);
|
||||
}
|
||||
// ((Triforce, 11-20, a review of 1104352) the Options screen chosen from the pause menu: its footer may be MenuOverlay_00's,
|
||||
// whose band panes end 2110 units right of the middle (its fade seen out by about 3120 px in the pause menu's own
|
||||
// fs_30_sys_on_title_screen.png, fullscreen 3440 x 1440: (3120 - 1720) x 1.5 = 2100 units). Our plate ends there, not
|
||||
// at the title's 2160 (3160 px: about 33 px of a dark sliver past it over the bars' black)
|
||||
{
|
||||
CHECK(game_grid::kPauseGuideBandRight == 2110 && game_grid::kGuideBandRight == 2160);
|
||||
game_grid::Place g;
|
||||
const float f = plate_end(3416, 1440, 3440, 1440, r21, &g, game_grid::kPauseGuideBandRight);
|
||||
const float title = plate_end(3416, 1440, 3440, 1440, r21);
|
||||
std::printf("fullscreen 3440 x 1440, from the pause menu: the plate to %.1f (the title's %.1f)\n", f, title);
|
||||
CHECK(near(f, 1720 + 2110 / 1.5f, 1) && near(title - f, 33.3f, 1));
|
||||
const float e = plate_end(3416, 1440, 1600, 900, r21, &g, game_grid::kPauseGuideBandRight); // (16x9: 674 lines)
|
||||
CHECK(near(e, 800 + 2110 * g.h / 2160, 1) && e > 1400 && near(plate_end(3416, 1440, 1600, 900, r21) - e, 16, 1));
|
||||
// (over play and on a picture no wider than the grid: the column's edge, whichever band)
|
||||
const game_grid::Column play = game_grid::column_of(game_grid::of(3416, 1440, 1600, 900, r21), 1600, 900, false);
|
||||
CHECK(game_grid::guide_band_x1(play, game_grid::kPauseGuideBandRight) == play.w);
|
||||
CHECK(near(plate_end(2560, 1440, 1920, 1080, 0, nullptr, game_grid::kPauseGuideBandRight), 1920, 0.5f));
|
||||
}
|
||||
if (!fails) std::puts("our guides' plate to the game's band's end in every shape");
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--cxx", default="clang++")
|
||||
args = parser.parse_args()
|
||||
ui = (VK / "vk_ui.h").read_text(encoding="utf-8")
|
||||
menu = (VK / "vk_menu.cpp").read_text(encoding="utf-8")
|
||||
|
||||
# 2. the source
|
||||
pb = block(ui, "inline float prompt_bar(Ctx& c, const Prompt* list, int n) {")
|
||||
check("const float x1 = c.over_game ? std::max(c.w, c.guides_x1) : c.w, past = c.w + lu(c, 4);" in pb,
|
||||
"prompt_bar: the plate still ends at the column's right edge over the game's Options screen")
|
||||
check("ImVec2(x1, c.h), rgba(24, 22, 12));" in pb, "prompt_bar: the plate's dark does not reach the game's band's end")
|
||||
check("image(c, t, ImVec2(band0, top), ImVec2(past, c.h), rgba(0, 0, 0, 215), true);" in pb,
|
||||
"prompt_bar: the band's texture inside the column is not drawn as it was")
|
||||
check("if (x1 > past) c.d->AddImage(t->tex->GetTexRef(), ImVec2(past, top), ImVec2(x1, c.h), ImVec2(u, 0), ImVec2(u, 1), rgba(0, 0, 0, 215));" in pb,
|
||||
"prompt_bar: past the column the band's texture does not go on as its right end is")
|
||||
check("if (x1 > c.w) c.d->AddRectFilled(ImVec2(c.w, top), ImVec2(x1, c.h), kBar);" in pb,
|
||||
"prompt_bar: without the game's texture the plain band stops at the column")
|
||||
dm = block(menu, "void draw_menu(ui::Ctx& c, bool perf_under) {")
|
||||
check("k.guides_x1 = game_grid::guide_band_x1(col, game_options_from_pause.load(std::memory_order_relaxed) ? game_grid::kPauseGuideBandRight" in dm
|
||||
and ": game_grid::kGuideBandRight);" in dm, "draw_menu: the pages do not know where the game's band ends (the title's or the pause menu's)")
|
||||
# ((11-20, a review of 1104352) the host's word 2: the Options chosen from the pause menu)
|
||||
seen = block(menu, "void menu_option_set(int id, int value) {")
|
||||
gop = seen[seen.index("if (id == HOS_OPT_GAME_OPTIONS) {"):]
|
||||
gop = gop[:gop.index("return;")]
|
||||
check("game_options_from_pause.store(value == 2, std::memory_order_relaxed);" in gop,
|
||||
"menu_option_set: the Options screen from the pause menu (the host's 2) is not kept")
|
||||
|
||||
with tempfile.TemporaryDirectory(prefix="guides-band-") as tmp:
|
||||
tmp = Path(tmp)
|
||||
src, exe = tmp / "grid.cpp", tmp / "grid.exe"
|
||||
src.write_text(GRID, encoding="utf-8")
|
||||
subprocess.run([args.cxx, "-std=c++20", "-O1", "-Wall", "-Wextra", "-Werror", "-I" + str(VK), str(src), "-o", str(exe)], check=True)
|
||||
r = subprocess.run([str(exe)], capture_output=True, text=True)
|
||||
print(r.stdout.strip())
|
||||
check(r.returncode == 0, "the band's end:\n" + r.stdout)
|
||||
print("PASS: our guides' plate covers the game's guides band to its end past the column")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -50,6 +50,12 @@ int main() {
|
||||
}
|
||||
CHECK(told == kReports && w.reports == kReports);
|
||||
}
|
||||
{ // ((Triforce) the stacks asked for from outside: served kAsked times a run, then no more)
|
||||
int served = 0, yes = 0;
|
||||
for (int i = 0; i < kAsked + 5; i++) yes += ask(served);
|
||||
CHECK(yes == kAsked && served == kAsked && kAsked >= 4 && kAsked <= 64);
|
||||
CHECK(kAskSuffix[0] == '.' && kAskSuffix[1] == 'n');
|
||||
}
|
||||
std::puts("PASS: the hang watch reports a stall once, only while judged, and a few times a run");
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -31,6 +31,23 @@ def check_source():
|
||||
("pid == GetCurrentProcessId() && !IsIconic(w)", "a minimized window, or another program's, counts as in front")):
|
||||
if needle not in dump:
|
||||
raise SystemExit("gpu/vk/vk_hangdump.cpp: " + why)
|
||||
# ((Triforce) the stacks asked for from outside: looked for every second before the stall's judgement, the file taken away
|
||||
# before the report, the report as a stall's, the log written out, a few a run)
|
||||
loop = dump[dump.index("hangwatch::Watch watch;"):dump.index("}).detach();")]
|
||||
at = 0
|
||||
for part in ("int asked = 0;", "Sleep(1000);", "const std::string ask_path = path + hangwatch::kAskSuffix;", "if (!ask_stuck && game_path_there(ask_path)) {",
|
||||
"if (!ask_take(ask_path)) {", "ask_stuck = true;", "} else if (hangwatch::ask(asked)) {", "dump(path.c_str(), true)", "host->log_flush();",
|
||||
"hangwatch::step(watch, presents, by_name || window_in_front(), sec)"):
|
||||
found = loop.find(part, at)
|
||||
if found < 0:
|
||||
raise SystemExit("gpu/vk/vk_hangdump.cpp: the asked-for stacks: %r is missing or out of order" % part)
|
||||
at = found + len(part)
|
||||
take = dump[dump.index("bool ask_take(const std::string& path) {"):dump.index("/// The game's own window")]
|
||||
if "DeleteFileW(" not in take or "MultiByteToWideChar(CP_UTF8" not in take or "remove(" in take:
|
||||
raise SystemExit("gpu/vk/vk_hangdump.cpp: the ask's file is not taken away by its UTF-8 path with DeleteFileW")
|
||||
header = (ROOT / "gpu/vk/hang_watch.h").read_text(encoding="utf-8")
|
||||
if 'constexpr const char* kAskSuffix = ".now";' not in header:
|
||||
raise SystemExit("gpu/vk/hang_watch.h: the ask's file is no longer the report's name with .now")
|
||||
if "if (presents == 1) hang_watch_start();" not in replay:
|
||||
raise SystemExit("gpu/vk/vk_replay.cpp no longer starts the hang watch at the first present")
|
||||
# (nothing is logged or allocated while a thread is suspended: the log's lines come after every ResumeThread)
|
||||
|
||||
@@ -31,7 +31,7 @@ def nits(y, white, peak, knee=0.6):
|
||||
|
||||
def main():
|
||||
menu = (ROOT / "gpu/vk/vk_menu.cpp").read_text(encoding="utf-8")
|
||||
row = re.search(r'\{TAB_DISPLAY, "HDR peak brightness", &opts\.hdr_peak, (\d+), (\d+), (\d+), tx_nits,', menu)
|
||||
row = re.search(r'\{TAB_DISPLAY, "Peak brightness", &opts\.hdr_peak, (\d+), (\d+), (\d+), tx_nits,', menu)
|
||||
check(row, "vk_menu.cpp: the HDR peak brightness row is missing")
|
||||
lo, hi, step = (int(v) for v in row.groups())
|
||||
check((lo, hi) == (400, PEAK), "the HDR peak brightness row is %d to %d nits, not 400 to 10,000" % (lo, hi))
|
||||
@@ -83,7 +83,7 @@ def main():
|
||||
codes = [pq(v) for v in ys]
|
||||
check(all(a <= b for a, b in zip(codes, codes[1:])) and codes[-1] <= 1.0, "white %d, peak %d: the PQ codes" % (white, peak))
|
||||
readme = (ROOT / "readme.md").read_text(encoding="utf-8")
|
||||
check("peak brightness 400 to 10,000 nits" in readme, "readme.md's settings table does not say the HDR peak's range")
|
||||
check("Peak brightness 400 to 10,000 nits" in readme, "readme.md's settings table does not say the HDR peak's range")
|
||||
guide = (ROOT / "docs/development.md").read_text(encoding="utf-8")
|
||||
check("| `hdr_paper_white`, `hdr_peak_brightness` | nits: 80 to 400, and 400 to 10,000 |" in guide,
|
||||
"docs/development.md's options table does not say the HDR rows' ranges")
|
||||
|
||||
278
tests/test_import_touch.py
Normal file
278
tests/test_import_touch.py
Normal file
@@ -0,0 +1,278 @@
|
||||
"""A range's pages read before the driver imports it (gpu/vk/import_touch.h, RX_VK_IMPORT_TOUCH; no game, no GPU).
|
||||
|
||||
The driver locks an import's pages inside vkAllocateMemory, faulting in the ones nobody touched, and a queue submit from
|
||||
another thread waits for it: 16 to 93 ms beside the large ranges imported ahead. The pages are read first, outside the
|
||||
driver. The rules of the header, compiled and run: on unless the switch is 0; only on the background import thread and
|
||||
only where the range was committed whole; the runs cover a range once and whole; every page of a run is read, one byte
|
||||
each, and nothing past its end. Each rule taken out in turn (a mutation) must make the test fail, and each mutant must
|
||||
build. On Windows the read itself runs: guarded_touch, cut out of vk_memory.cpp, makes freshly committed pages resident
|
||||
(the working set says so before and after), and returns false at a page that cannot be read instead of faulting, with the
|
||||
header's read taken out or its volatile dropped failing that. Then the sources: import_pool reads the pages after the lazy
|
||||
write-back let the range go and after the commit, before the allocate, through a handler that leaves a fault behind (a call
|
||||
through a pointer inside its __try block, to a function that is not inlined), on Windows; the background thread says it is
|
||||
one; the time is kept out of the report's commit part; the switch's row is in the development guide.
|
||||
|
||||
python -I -B tests/test_import_touch.py [--cxx g++]
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
RUN_ALL_ARGS = ["--cxx", "{cxx}"]
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
VK = ROOT / "gpu" / "vk"
|
||||
|
||||
|
||||
def block(text, marker):
|
||||
start = text.index(marker)
|
||||
end = text.index("{", start) + 1
|
||||
depth = 1
|
||||
while depth:
|
||||
depth += (text[end] == "{") - (text[end] == "}")
|
||||
end += 1
|
||||
return text[start:end]
|
||||
|
||||
|
||||
def in_order(text, parts, where):
|
||||
at = 0
|
||||
for part in parts:
|
||||
found = text.find(part, at)
|
||||
if found < 0:
|
||||
raise SystemExit("%s: %r is missing, or not after the part before it (update the test with the code)" % (where, part))
|
||||
at = found + len(part)
|
||||
|
||||
|
||||
HEADER_TEST = r'''
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <vector>
|
||||
#include "import_touch.h"
|
||||
#define CHECK(x) do { if (!(x)) { std::fprintf(stderr, "FAIL:%d %s\n", __LINE__, #x); std::exit(1); } } while (0)
|
||||
using namespace mkwvk::import_touch;
|
||||
int main() {
|
||||
// (on unless the switch is 0)
|
||||
CHECK(on(nullptr) && on("") && on("1") && on("2") && on("00") && !on("0"));
|
||||
// (read first: the switch, the background import thread, the range committed whole; nothing else)
|
||||
CHECK(may(true, true, true));
|
||||
CHECK(!may(false, true, true) && !may(true, false, true) && !may(true, true, false) && !may(false, false, false));
|
||||
CHECK(kLargeMb >= 32 && kLargeMb <= 256);
|
||||
// (the runs of a range: each kRun but the last, none past the end, the range covered once)
|
||||
const uint64_t MB = 1ull << 20;
|
||||
CHECK(kRun % kPage == 0 && kRun >= MB && kRun <= 64 * MB);
|
||||
CHECK(run(816 * MB, 0) == kRun && run(816 * MB, 816 * MB - kRun) == kRun && run(816 * MB, 816 * MB) == 0);
|
||||
CHECK(run(kRun + 3 * kPage, kRun) == 3 * kPage && run(3 * kPage, 0) == 3 * kPage && run(0, 0) == 0 && run(kPage, 2 * kPage) == 0);
|
||||
for (const uint64_t bytes : {uint64_t(kPage), uint64_t(kRun), kRun + kPage, 5 * kRun - kPage, 16 * MB}) {
|
||||
uint64_t sum = 0, n = 0;
|
||||
for (uint64_t off = 0; off < bytes; off += kRun) sum += run(bytes, off), n++;
|
||||
CHECK(sum == bytes && n == (bytes + kRun - 1) / kRun);
|
||||
}
|
||||
// (every page of a run read, none past its end)
|
||||
std::vector<uint8_t> buf(64 * kPage + kPage, 1);
|
||||
CHECK(read_pages(buf.data(), 0) == 0 && read_pages(buf.data(), kPage) == 1 && read_pages(buf.data(), 64 * kPage) == 64);
|
||||
CHECK(read_pages(buf.data() + kPage, 3 * kPage) == 3);
|
||||
std::puts("PASS header: the switch, where the pages are read, a range's runs, a run's pages");
|
||||
return 0;
|
||||
}
|
||||
'''
|
||||
|
||||
# (Windows: guarded_touch as vk_memory.cpp has it, run. Fresh pages are not in the working set until something reads them;
|
||||
# a reserved page cannot be read, and no handler of the host's is here to commit it)
|
||||
RUNTIME_TEST = r'''
|
||||
#include <windows.h>
|
||||
#include <psapi.h>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include "import_touch.h"
|
||||
using namespace mkwvk;
|
||||
#define CHECK(x) do { if (!(x)) { std::fprintf(stderr, "FAIL:%d %s\n", __LINE__, #x); std::exit(1); } } while (0)
|
||||
@GUARDED@
|
||||
static int resident(uint8_t* p, int pages) {
|
||||
int n = 0;
|
||||
for (int i = 0; i < pages; i++) {
|
||||
PSAPI_WORKING_SET_EX_INFORMATION w{};
|
||||
w.VirtualAddress = p + (size_t)i * 4096;
|
||||
CHECK(K32QueryWorkingSetEx(GetCurrentProcess(), &w, sizeof w));
|
||||
n += (int)w.VirtualAttributes.Valid;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
int main() {
|
||||
const int kPages = 256;
|
||||
uint8_t* fresh = (uint8_t*)VirtualAlloc(nullptr, (size_t)kPages * 4096, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
|
||||
CHECK(fresh);
|
||||
CHECK(resident(fresh, kPages) == 0); // (committed, never touched: not in RAM yet)
|
||||
uint64_t pages = 0;
|
||||
CHECK(guarded_touch(fresh, (size_t)kPages * 4096, &pages) && pages == (uint64_t)kPages);
|
||||
CHECK(resident(fresh, kPages) == kPages); // (each page read: each in RAM now, before the driver locks them)
|
||||
// (two pages, the second reserved only: the read leaves through the handler, and the count is not taken)
|
||||
uint8_t* two = (uint8_t*)VirtualAlloc(nullptr, 2 * 4096, MEM_RESERVE, PAGE_NOACCESS);
|
||||
CHECK(two && VirtualAlloc(two, 4096, MEM_COMMIT, PAGE_READWRITE) == two);
|
||||
pages = 0;
|
||||
CHECK(!guarded_touch(two, 2 * 4096, &pages) && pages == 0);
|
||||
CHECK(guarded_touch(two, 4096, &pages) && pages == 1);
|
||||
std::puts("PASS run (Windows): the read brings fresh pages into RAM, and leaves a page it cannot read behind");
|
||||
return 0;
|
||||
}
|
||||
'''
|
||||
|
||||
# (header mutations the Windows run must fail on: the count alone does not see them)
|
||||
RUNTIME_MUTATIONS = [
|
||||
("the pages are read", "for (size_t i = 0; i < n; i += kPage) sink += p[i], pages++;", "for (size_t i = 0; i < n; i += kPage) sink += (unsigned)(size_t)(p + i), pages++;"),
|
||||
("the read is volatile", "inline uint64_t read_pages(const volatile uint8_t* p, size_t n) {", "inline uint64_t read_pages(const uint8_t* p, size_t n) {"),
|
||||
]
|
||||
|
||||
MUTATIONS = [
|
||||
("only with the switch", "return on && background_thread && committed_whole;", "return background_thread && committed_whole + 0 * on;"),
|
||||
("only on the background import thread", "return on && background_thread && committed_whole;", "return on && committed_whole + 0 * background_thread;"),
|
||||
("only where the range was committed whole", "return on && background_thread && committed_whole;", "return on && background_thread + 0 * committed_whole;"),
|
||||
("off at 0", "return !(env && env[0] == '0' && !env[1]);", "return true || env;"),
|
||||
("on when unset", "return !(env && env[0] == '0' && !env[1]);", "return env && env[0] == '1';"),
|
||||
("0 alone is off", "return !(env && env[0] == '0' && !env[1]);", "return !(env && env[0] == '0');"),
|
||||
("the last run ends with the range", "(size_t)(bytes - off < kRun ? bytes - off : kRun)", "kRun"),
|
||||
("no run past the end", "return off >= bytes ? 0 : ", "return "),
|
||||
("every page read", "for (size_t i = 0; i < n; i += kPage) sink += p[i], pages++;",
|
||||
"for (size_t i = 0; i < n; i += 2 * kPage) sink += p[i], pages++;"),
|
||||
("the pages counted", "for (size_t i = 0; i < n; i += kPage) sink += p[i], pages++;", "for (size_t i = 0; i < n; i += kPage) sink += p[i];"),
|
||||
]
|
||||
|
||||
|
||||
TOUCH_SIG = "__declspec(noinline) bool guarded_touch(const uint8_t* p, size_t n, uint64_t* pages) {"
|
||||
TOUCH_PTR = "uint64_t (*volatile touch_read)(const volatile uint8_t*, size_t) = import_touch::read_pages;"
|
||||
|
||||
|
||||
def check_source(memory, header, dev):
|
||||
if '#include "import_touch.h"' not in memory:
|
||||
raise SystemExit("vk_memory.cpp does not include import_touch.h")
|
||||
at = memory.index(TOUCH_SIG)
|
||||
if memory.rfind("#ifdef _WIN32", 0, at) < memory.rfind("#endif", 0, at):
|
||||
raise SystemExit("vk_memory.cpp: guarded_touch is not inside #ifdef _WIN32 (its handler is Windows')")
|
||||
# (the read is a call the compiler cannot see through, to a function it may not inline: a fault leaves through the handler)
|
||||
in_order(memory, [TOUCH_PTR, TOUCH_SIG], "vk_memory.cpp guarded_touch's pointer")
|
||||
touch = block(memory, TOUCH_SIG)
|
||||
in_order(touch, ["__try {", "*pages += touch_read(p, n);",
|
||||
"} __except (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) {",
|
||||
"return false;", "return true;"], "vk_memory.cpp guarded_touch")
|
||||
in_order(header, ["__attribute__((noinline))", "inline uint64_t read_pages(const volatile uint8_t* p, size_t n) {",
|
||||
"for (size_t i = 0; i < n; i += kPage) sink += p[i], pages++;"], "import_touch.h read_pages")
|
||||
pool = block(memory, "bool import_pool(uint64_t lo, uint64_t hi, Pool& p) {")
|
||||
in_order(pool, ["} lazy_io{memory_lazy_io_begin(ptr, bytes)};",
|
||||
"bool committed_whole = false;",
|
||||
"if (page_watches || !(committed_whole = VirtualAlloc(ptr, (SIZE_T)bytes, MEM_COMMIT, PAGE_READWRITE) == ptr))",
|
||||
"#ifdef _WIN32",
|
||||
'static const bool touch = import_touch::on(getenv("RX_VK_IMPORT_TOUCH"));',
|
||||
"if (import_touch::may(touch, import_on_bg_thread, committed_whole)) {",
|
||||
"for (uint64_t off = 0; off < bytes; off += import_touch::kRun) {",
|
||||
"if (bg_waiters.load(std::memory_order_relaxed)) {", "break;",
|
||||
"if (!guarded_touch(ptr + off, import_touch::run(bytes, off), &pages)) faulted++;",
|
||||
"touch_ms = std::chrono::duration<double, std::milli>(clk::now() - a).count();",
|
||||
"#endif",
|
||||
"t1 = clk::now();",
|
||||
"const VkResult allocated = vkAllocateMemory(dev.device, &ai, nullptr, &p.memory);"], "vk_memory.cpp import_pool")
|
||||
if pool.count("guarded_touch(") != 1 or memory.count("touch_read(") != 1 or memory.count("import_touch::read_pages") != 1:
|
||||
raise SystemExit("vk_memory.cpp: the pages are read in a place this test does not know")
|
||||
# (a lookup that waits for an import says so for the whole of its wait, and the read stops while it does)
|
||||
in_order(memory, ["std::atomic<int> bg_waiters{0};", "bg_waiters.fetch_add(1, std::memory_order_relaxed);",
|
||||
"bg_done_cv.wait(lk, [&] { return !under_way(); });", "bg_waiters.fetch_sub(1, std::memory_order_relaxed);"],
|
||||
"vk_memory.cpp pool_lookup's wait")
|
||||
if memory.count("bg_waiters.fetch_add(") != 1 or memory.count("bg_waiters.fetch_sub(") != 1:
|
||||
raise SystemExit("vk_memory.cpp: bg_waiters is changed in a place this test does not know")
|
||||
if pool.count("committed_whole") != 3:
|
||||
raise SystemExit("vk_memory.cpp import_pool: committed_whole is set or read in a place this test does not know")
|
||||
# (the background thread says so, once, before its first import; nothing else does)
|
||||
if memory.count("import_on_bg_thread = true;") != 1 or memory.count("import_on_bg_thread") != 3:
|
||||
raise SystemExit("vk_memory.cpp: import_on_bg_thread is set or read in a place this test does not know")
|
||||
in_order(memory, ["thread_local bool import_on_bg_thread = false;"], "vk_memory.cpp")
|
||||
bg = block(memory, "void bg_main() {")
|
||||
in_order(bg, ["import_on_bg_thread = true;", "for (;;) {", "import_pool(r.first, r.second, p);"], "vk_memory.cpp bg_main")
|
||||
# (the report: the read's time named, and not counted as the commit's; the large imports on their own count of lines)
|
||||
in_order(pool, ["double touch_ms = 0;", "const double& touch;",
|
||||
"if (total < 2.0 || (mb >= import_touch::kLargeMb ? logged_large++ >= 48 : logged++ >= 12)) return;",
|
||||
"pages read first %.1f", "ms(a, b) - touch, touch,",
|
||||
"} report{t0, t1, t2, t3, t4, touch_ms, bytes >> 20};"], "vk_memory.cpp import_pool's report")
|
||||
row = next((l for l in dev.splitlines() if l.startswith("| `RX_VK_IMPORT_TOUCH=0` |")), "")
|
||||
if "Windows" not in row or "background thread" not in row:
|
||||
raise SystemExit("docs/development.md: RX_VK_IMPORT_TOUCH's row is missing, or does not say where the read is made")
|
||||
|
||||
|
||||
def build(cxx, d, name, src, include, extra=()):
|
||||
cpp, exe = d / (name + ".cpp"), d / (name + ".exe")
|
||||
cpp.write_text(src, encoding="utf-8")
|
||||
r = subprocess.run([cxx, "-std=c++20", "-O1", "-Wall", "-Wextra", "-Werror", "-Wno-unused-function", *extra, "-I" + str(include), str(cpp),
|
||||
"-o", str(exe)], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
|
||||
if r.returncode:
|
||||
return None, r.stdout
|
||||
return exe, ""
|
||||
|
||||
|
||||
def run(exe):
|
||||
return subprocess.run([str(exe)], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, timeout=60)
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--cxx", default=os.environ.get("CXX", "g++"))
|
||||
a = ap.parse_args()
|
||||
memory = (VK / "vk_memory.cpp").read_text(encoding="utf-8")
|
||||
header = (VK / "import_touch.h").read_text(encoding="utf-8")
|
||||
check_source(memory, header, (ROOT / "docs" / "development.md").read_text(encoding="utf-8"))
|
||||
print("PASS sources: import_pool reads the pages on the background thread, where the range was committed whole, after the "
|
||||
"commit and before the allocate, through a handler that leaves a fault behind; the report names the read's time; the "
|
||||
"switch's row")
|
||||
with tempfile.TemporaryDirectory(prefix="import-touch-") as tmp:
|
||||
d = Path(tmp)
|
||||
exe, out = build(a.cxx, d, "header", HEADER_TEST, VK)
|
||||
if not exe:
|
||||
raise SystemExit("header: the build failed:\n" + out)
|
||||
r = run(exe)
|
||||
if r.returncode:
|
||||
raise SystemExit("the header test failed:\n" + r.stdout)
|
||||
print(r.stdout.strip())
|
||||
for i, (what, old, new) in enumerate(MUTATIONS):
|
||||
if header.count(old) != 1:
|
||||
raise SystemExit("mutation %r: its text is not once in import_touch.h (update the test with the header)" % what)
|
||||
inc = d / ("mutant%d" % i)
|
||||
inc.mkdir()
|
||||
(inc / "import_touch.h").write_text(header.replace(old, new), encoding="utf-8")
|
||||
exe, out = build(a.cxx, d, "mutant%d" % i, HEADER_TEST, inc)
|
||||
if not exe:
|
||||
raise SystemExit("mutation %r: the mutant does not build (a mutant must fail the test, not the compiler):\n%s" % (what, out))
|
||||
if run(exe).returncode == 0:
|
||||
raise SystemExit("mutation %r: the header test still passed without it" % what)
|
||||
print("PASS mutations: %d rules of import_touch.h, each taken out, fail the header's test" % len(MUTATIONS))
|
||||
if sys.platform != "win32":
|
||||
print("SKIP run: guarded_touch's handler is Windows' (the read is not made elsewhere)")
|
||||
return
|
||||
at = memory.index(TOUCH_PTR)
|
||||
guarded = memory[at:memory.index(TOUCH_SIG)] + block(memory, TOUCH_SIG)
|
||||
guarded = guarded[:guarded.rindex("}")] + "}"
|
||||
src = RUNTIME_TEST.replace("@GUARDED@", guarded)
|
||||
ms = ["-fms-extensions"] # (__try, as the game's build has it)
|
||||
exe, out = build(a.cxx, d, "run", src, VK, ms)
|
||||
if not exe:
|
||||
raise SystemExit("the Windows run: the build failed:\n" + out)
|
||||
r = run(exe)
|
||||
if r.returncode:
|
||||
raise SystemExit("the Windows run failed:\n" + r.stdout)
|
||||
print(r.stdout.strip())
|
||||
for i, (what, old, new) in enumerate(RUNTIME_MUTATIONS):
|
||||
if header.count(old) != 1:
|
||||
raise SystemExit("mutation %r: its text is not once in import_touch.h (update the test with the header)" % what)
|
||||
inc = d / ("runmutant%d" % i)
|
||||
inc.mkdir()
|
||||
(inc / "import_touch.h").write_text(header.replace(old, new), encoding="utf-8")
|
||||
exe, out = build(a.cxx, d, "runmutant%d" % i, src.replace("(*volatile touch_read)(const volatile uint8_t*, size_t)",
|
||||
"(*volatile touch_read)(const uint8_t*, size_t)") if "volatile" in what else src, inc, ms)
|
||||
if not exe:
|
||||
raise SystemExit("mutation %r: the mutant does not build:\n%s" % (what, out))
|
||||
if run(exe).returncode == 0:
|
||||
raise SystemExit("mutation %r: the Windows run still passed without it" % what)
|
||||
print("PASS mutations: %d more, on the read itself, fail the Windows run" % len(RUNTIME_MUTATIONS))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -49,7 +49,7 @@ int failures=0,imports=0,retires=0,bg_starts=0;
|
||||
int64_t st_bg_waits=0,st_prefetch_used=0,st_prefetch_sent=0,st_prefetch_dropped=0;
|
||||
thread_local const char* tl_sync_why=nullptr; // (Triforce: why a binding's import ran on its own thread, for the log line)
|
||||
struct { bool external_memory_host=true; } dev;
|
||||
std::mutex bg_mu;std::condition_variable bg_done_cv,bg_cv;std::vector<uint64_t> bg_inflight;
|
||||
std::mutex bg_mu;std::condition_variable bg_done_cv,bg_cv;std::vector<uint64_t> bg_inflight;std::atomic<int> bg_waiters{0};
|
||||
std::deque<std::pair<uint64_t,uint64_t>> bg_queue;
|
||||
void bg_start() { bg_starts++; } // Recording spy: no thread or GPU import is started.
|
||||
void logf(const char*,...){} void bg_drain(){}
|
||||
|
||||
108
tests/test_launcher_color.py
Normal file
108
tests/test_launcher_color.py
Normal file
@@ -0,0 +1,108 @@
|
||||
"""The launcher's Color scheme (Settings > Launcher): the page and the launcher agree on the message, the default and
|
||||
the image, read from the source (no launcher is built or started).
|
||||
|
||||
The page (launcher/ui/app.js) draws any color in place of Triforce gold and sends {t:'cmd', c:'color', hex:'#rrggbb'};
|
||||
the launcher (launcher/App, launcher/Logic) keeps it with its other settings (Settings.Color, LauncherColor) and sends
|
||||
it back as state.color at start and with the Settings list. The parsing and the keeping are tested in
|
||||
launcher/LogicTests (dotnet run --project launcher/LogicTests color); this checks what joins the two:
|
||||
|
||||
- the page sends 'color' with hex, takes state.color, and keeps a choice not sent yet over the launcher's older one;
|
||||
- the page's gold (GOLD, the first preset) is the launcher's default (LauncherColor.Default);
|
||||
- the launcher takes 'color' as it arrives and puts that choice (else the kept color) in the start state and in the
|
||||
list the page asks for, so a --snapshot run or a list handled first does not set the page back;
|
||||
- img/crest-gold.png (the crest's metal, the mask the tint uses) is a PNG and rides in the exe with the rest of ui/;
|
||||
- every word the page shows spells "color" (US): the page's own words (app.js, demo.js, index.html) and every string the
|
||||
launcher's C# has (launcher/App, Logic, Core), the game options' help that the Settings rows show among them.
|
||||
|
||||
python -I -B tests/test_launcher_color.py
|
||||
"""
|
||||
from pathlib import Path
|
||||
import re
|
||||
import unittest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
LAUNCHER = ROOT / "launcher"
|
||||
UI = LAUNCHER / "ui"
|
||||
|
||||
|
||||
def read(path):
|
||||
return path.read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def without_comments(js):
|
||||
"""The script's code with its /* */ and // comments taken out (a // inside a string, as in a URL, takes the rest of
|
||||
its line with it: fine for looking for words)."""
|
||||
js = re.sub(r"/\*.*?\*/", "", js, flags=re.S)
|
||||
return re.sub(r"(^|[^:\\])//[^\n]*", r"\1", js)
|
||||
|
||||
|
||||
class LauncherColorTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.app = read(UI / "app.js")
|
||||
self.color_cs = read(LAUNCHER / "Logic" / "LauncherColor.cs")
|
||||
self.core = read(LAUNCHER / "App" / "Backend.Core.cs")
|
||||
self.settings = read(LAUNCHER / "App" / "Backend.Settings.cs")
|
||||
|
||||
def test_same_default(self):
|
||||
page = re.search(r"const GOLD = '(#[0-9a-f]{6})';", self.app)
|
||||
launcher = re.search(r'public const string Default = "(#[0-9a-f]{6})";', self.color_cs)
|
||||
self.assertTrue(page and launcher)
|
||||
self.assertEqual(page.group(1), launcher.group(1))
|
||||
self.assertEqual(page.group(1), "#e0b23e")
|
||||
self.assertIn("const PRESETS = [[GOLD, 'Triforce gold']", self.app)
|
||||
|
||||
def test_page_message(self):
|
||||
self.assertIn("cmd('color', { hex: CS.hex })", self.app)
|
||||
self.assertIn("if (typeof m.color === 'string') setColor(m.color, 'host');", self.app)
|
||||
# (the launcher's kept color is older than a choice still waiting for its 400 ms)
|
||||
self.assertIn("if (from === 'host' && colorSave) return;", self.app)
|
||||
self.assertIn("colorSave = setTimeout(() => { colorSave = 0;", self.app)
|
||||
|
||||
def test_launcher_keeps_and_sends(self):
|
||||
# (the color is taken as the message arrives, before its handler goes to a worker, and what is sent back is that
|
||||
# choice: a --snapshot run writes nothing, and a 'settings.list' may run before the 'color' just ahead of it)
|
||||
backend = read(LAUNCHER / "App" / "Backend.cs")
|
||||
cmd = backend.split('case "cmd":', 1)[1].split("break;", 1)[0]
|
||||
self.assertLess(cmd.index('if (c == "color") ColorArrived(m);'), cmd.index("Task.Run("))
|
||||
self.assertIn("colorChoice.Take(m)", self.core)
|
||||
self.assertIn('On("color", _ => colorChoice.Keep());', self.core)
|
||||
self.assertIn("LauncherColor.FromCommand(message)", self.color_cs)
|
||||
self.assertIn("settings.Color = hex;", self.color_cs)
|
||||
on_ready = self.core.split("void OnReady()", 1)[1].split("\n }\n", 1)[0]
|
||||
self.assertIn('["color"] = colorChoice.Current', on_ready)
|
||||
self.assertIn('On("settings.list", _ => SendSettings(color: true));', self.settings)
|
||||
self.assertIn('if (color) o["color"] = colorChoice.Current;', self.settings)
|
||||
self.assertNotIn('["color"] = ctx.Settings.Color', self.settings + self.core)
|
||||
self.assertNotIn('["color"] = s.Color', self.core)
|
||||
names = read(LAUNCHER / "Logic" / "Platform" / "Settings.cs")
|
||||
self.assertIn('public const string Color = "Color";', names)
|
||||
|
||||
def test_crest_mask_embedded(self):
|
||||
png = (UI / "img" / "crest-gold.png").read_bytes()
|
||||
self.assertEqual(png[:8], b"\x89PNG\r\n\x1a\n")
|
||||
self.assertLess(len(png), 64 * 1024)
|
||||
self.assertIn("img/crest-gold.png", read(UI / "app.css"))
|
||||
csproj = read(LAUNCHER / "App" / "Triforce.Launcher.csproj")
|
||||
self.assertIn('<EmbeddedResource Include="..\\ui\\**\\*" LogicalName="ui/%(RecursiveDir)%(Filename)%(Extension)" />', csproj)
|
||||
|
||||
def test_us_spelling(self):
|
||||
for name in ("app.js", "demo.js", "index.html"):
|
||||
text = read(UI / name)
|
||||
if name.endswith(".js"):
|
||||
text = without_comments(text)
|
||||
else:
|
||||
text = re.sub(r"<!--.*?-->", "", text, flags=re.S)
|
||||
self.assertEqual(re.findall(r"(?i)colour", text), [], name)
|
||||
# (what the launcher sends the page: every string in its C#, the game options' help among them, which the
|
||||
# Settings page shows as each row's tooltip; comments are not shown and keep their own spelling)
|
||||
literal = re.compile(r'"(?:[^"\\\n]|\\.)*"')
|
||||
for part in ("App", "Logic", "Core"):
|
||||
for path in sorted((LAUNCHER / part).rglob("*.cs")):
|
||||
if {"bin", "obj"} & set(path.relative_to(LAUNCHER).parts):
|
||||
continue
|
||||
found = [s for s in literal.findall(read(path)) if re.search(r"(?i)colour", s)]
|
||||
self.assertEqual(found, [], path.relative_to(ROOT).as_posix())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
114
tests/test_launcher_music.py
Normal file
114
tests/test_launcher_music.py
Normal file
@@ -0,0 +1,114 @@
|
||||
"""The launcher's music loops as the game's does and is not cut off: the page (launcher/ui/app.js) and the launcher
|
||||
(launcher/Core/GameFiles) agree on the loop, read from the source and run in node (no launcher is built or started, no
|
||||
game file is read, and no sound is made).
|
||||
|
||||
The game's music plays an intro once and then loops from a sample after it to its end (Saria's Song, the Fairy
|
||||
Fountain and the Temple of Time; the BWAV header gives the loop). The page played the WAV in an <audio> element with loop on, which starts the whole file again, intro and
|
||||
all, after a pause, and the end does not join the start (a step in the wave, a click). Now the launcher keeps the loop
|
||||
in the WAV as a smpl chunk (Bwav.ToWav; its reading and writing are tested in launcher/LogicTests: dotnet run --project
|
||||
launcher/LogicTests media) and the page plays music through Web Audio, looping a decoded buffer between those points.
|
||||
|
||||
This checks what joins the two, and runs the page's music code (from "const TRACKS" to the end of audioTick) in node
|
||||
with stand-ins for Web Audio, fetch and <audio> (tests/launcher_music_test.js):
|
||||
|
||||
- the page reads the loop where the launcher writes it (a smpl chunk's first loop, its last sample counted in), and a
|
||||
file without one, an older launcher's, loops whole;
|
||||
- a track is read once, loops between its points at the game's rate, fades in once it is read, follows the volume and
|
||||
mute, fades out whole before it stops, and lets go of its samples; a track faded out before it is read never starts;
|
||||
- the item fanfare plays once at its full level from its first note, and what plays after it is asked for when it ends;
|
||||
- a context the browser holds back resumes on the first click or key; without Web Audio, or for a file it cannot
|
||||
decode, the <audio> element plays as before;
|
||||
- the music each screen plays and its fades are as before, and the WAV cache is made again once for the loop (the art's
|
||||
is not).
|
||||
|
||||
python -I -B tests/test_launcher_music.py [--node node]
|
||||
"""
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
RUN_ALL_ARGS = ["--node", "{node}"]
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
LAUNCHER = ROOT / "launcher"
|
||||
|
||||
|
||||
def read(path):
|
||||
return path.read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def need(text, needle, why):
|
||||
if needle not in text:
|
||||
raise SystemExit(why + "\n (looked for: " + needle + ")")
|
||||
|
||||
|
||||
def check_source(app, bwav, media):
|
||||
# (the screens' music and fades as before: the page plays the same tracks at the same places)
|
||||
need(app, "const MUSIC = { welcome: null, reveal: 'saria', work: 'temple', done: 'itemget', home: 'fairy', saves: 'fairy', "
|
||||
"mods: 'fairy', settings: 'fairy', bench: 'fairy', brun: null, playing: null };",
|
||||
"launcher/ui/app.js: the music a screen plays changed")
|
||||
need(app, "if (name === 'done') music('itemget', false, .3);", "launcher/ui/app.js: the fanfare on the done screen changed")
|
||||
need(app, "music(m, true, name === 'playing' || name === 'brun' ? 2.2 : 1.4);", "launcher/ui/app.js: the fades between screens changed")
|
||||
need(app, "function music(name, loop = true, fade = 1.4) {", "launcher/ui/app.js: music() takes other arguments")
|
||||
# (Web Audio first, looping between the loop points; the <audio> element only as the fallback)
|
||||
for needle in ("src.loop = true; src.loopStart = t.start; src.loopEnd = t.end;", "actx.decodeAudioData(ab, ok, no)",
|
||||
"new AC({ sampleRate: 48000 })", "if (audioCtx()) track(name).then(t => { if (!m.dead) startBuffer(m, t); }, () => { if (!m.dead) startElement(m); });",
|
||||
"else startElement(m);", "addEventListener('pointerdown', unlock, true); addEventListener('keydown', unlock, true);"):
|
||||
need(app, needle, "launcher/ui/app.js: the music no longer plays through Web Audio with its loop, or has no fallback")
|
||||
sound = app[app.index("const TRACKS = "):app.index("const SFX_IDS")]
|
||||
if sound.count("new Audio(") != 1 or "el.loop = m.loop;" not in sound[sound.index("function startElement("):]:
|
||||
raise SystemExit("launcher/ui/app.js: an <audio> element plays music outside startElement (the fallback)")
|
||||
# (where the page reads the loop is where the launcher writes it: a smpl chunk's body starts 8 bytes after the chunk,
|
||||
# its first loop's start 44 bytes into the body and its last sample 48)
|
||||
need(app, "loop = { start: d.getUint32(body + 44, true), end: d.getUint32(body + 48, true) + 1 };",
|
||||
"launcher/ui/app.js: the smpl loop is read elsewhere")
|
||||
to_wav = bwav[bwav.index("public static byte[] ToWav(Pcm pcm)"):bwav.index("static (int Start, int End)? SmplLoop(")]
|
||||
for needle in ('Tag(at, "smpl"); Put(at + 4, 36 + 24, 4);', "Put(at + 36, 1, 4);", "Put(at + 52, loop.Start, 4); Put(at + 56, loop.End - 1, 4);",
|
||||
"var at = 44 + data;", "Put(4, 36 + data + smpl, 4);"):
|
||||
need(to_wav, needle, "launcher/Core/GameFiles/Bwav.cs ToWav: the smpl chunk is written otherwise than the page reads it")
|
||||
need(bwav, "Loop = LoopOf(b, 0x10, frames)", "launcher/Core/GameFiles/Bwav.cs: Decode no longer reads the game's loop")
|
||||
need(bwav, "long end = U32(b, info + 0x3C), start = U32(b, info + 0x40);", "launcher/Core/GameFiles/Bwav.cs: the loop is read elsewhere in the header")
|
||||
# (the sounds' cache is made again once, with the loop; the art's files keep their names)
|
||||
wav = media[media.index("public string WavFile(string id)"):media.index("public IReadOnlyList<BntxTexture> Textures(")]
|
||||
need(wav, "}, SoundVersion);", "launcher/Core/GameFiles/GameMedia.cs: a WAV made before the loop was kept would be used")
|
||||
png = media[media.index("public string PngFile(string archive, string textureName)"):media.index("public string PngFile(string textureName)")]
|
||||
if "SoundVersion" in png:
|
||||
raise SystemExit("launcher/Core/GameFiles/GameMedia.cs: the art is decoded again for a change to the sounds")
|
||||
if not re.search(r'const string SoundVersion = CacheVersion \+ "\+loop-\d+";', media):
|
||||
raise SystemExit("launcher/Core/GameFiles/GameMedia.cs: SoundVersion is not CacheVersion and the loop's version")
|
||||
|
||||
|
||||
def run_node(node, app):
|
||||
sound = app[app.index("const TRACKS = "):app.index("const SFX_IDS")]
|
||||
harness = read(ROOT / "tests" / "launcher_music_test.js")
|
||||
if harness.count("/*@@APP_SOUND@@*/") != 1:
|
||||
raise SystemExit("tests/launcher_music_test.js: no place for the page's code")
|
||||
with tempfile.TemporaryDirectory(prefix="launcher-music-") as folder:
|
||||
script = Path(folder) / "launcher_music_test.js"
|
||||
script.write_text(harness.replace("/*@@APP_SOUND@@*/", sound), encoding="utf-8")
|
||||
r = subprocess.run([node, str(script)], capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=120)
|
||||
sys.stdout.write(r.stdout)
|
||||
if r.returncode != 0:
|
||||
raise SystemExit("the page's music in node failed:\n" + r.stdout + r.stderr)
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description=__doc__.split("\n", 1)[0])
|
||||
p.add_argument("--node", default="node")
|
||||
a = p.parse_args()
|
||||
node = shutil.which(a.node)
|
||||
if not node:
|
||||
p.error("node is needed to run the page's music code")
|
||||
app = read(LAUNCHER / "ui" / "app.js")
|
||||
check_source(app, read(LAUNCHER / "Core" / "GameFiles" / "Bwav.cs"), read(LAUNCHER / "Core" / "GameFiles" / "GameMedia.cs"))
|
||||
subprocess.run([node, "--check", str(LAUNCHER / "ui" / "app.js")], check=True)
|
||||
run_node(node, app)
|
||||
print("launcher music: source checks passed")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -171,7 +171,7 @@ def main():
|
||||
check(row and row.group(1).rstrip().endswith("hn_lazy_write_back, true, true"),
|
||||
"no Lazy write-back row on the Debug tab that applies after a restart and leaves the preset alone")
|
||||
if row:
|
||||
check(menu.index('"Developer", nullptr') < row.start() < menu.index('{TAB_SYSTEM, "Restart"'),
|
||||
check(menu.index('"Developer", nullptr') < row.start() < menu.index('constexpr int kRowsEnd'), # ((Triforce, 11-19) the table's end)
|
||||
"the Lazy write-back row is not under the Debug tab's Developer heading")
|
||||
check("int lazy_write_back = 1;" in opts, "the Lazy write-back row is not on by default (options_version 5)")
|
||||
hint = re.search(r"MENU_HINTS\(hn_lazy_write_back, 0,(.*?)\)\n", menu, re.S)
|
||||
|
||||
257
tests/test_lib_check.py
Normal file
257
tests/test_lib_check.py
Normal file
@@ -0,0 +1,257 @@
|
||||
"""Whether the stage libraries the preparation made are still in the pipeline cache, at a start whose record says they were made
|
||||
(gpu/vk/lib_check.h; vk_draw.cpp lib_check_sample, lib_check_cold, lib_check_made, prepare_run; after NX2navi e10ef60; no game/GPU).
|
||||
|
||||
The header is compiled and run as it is:
|
||||
- RX_VK_LIB_CHECK: on unless 0;
|
||||
- a variant asked of the caches only is cold by their answer alone (a slow first lookup they answered is not cold); one made
|
||||
without asking is cold by its time against its own second making (the warm reference), never by a fixed time;
|
||||
- a sample is cold when more than half of the variants that count are, says nothing under half a sample, and a library the
|
||||
driver refused does not count;
|
||||
- the places sampled are spread over the whole program cache, distinct, and move with the start;
|
||||
- the record of the starts that found them cold again: written whole, read back, another stamp's or a broken one is no record;
|
||||
- starts in a row against a cache that loses the libraries every time: made again once, then left to the draws; a start that
|
||||
finds them warm begins the count anew; another stamp begins it anew; a part left out, or one whose cache was not saved,
|
||||
stops the same way.
|
||||
Then the source: the sample makes the very libraries warm_libraries makes (same state, targets, topology, the same variants
|
||||
left out, the shading rate's libraries of a native mesh program in both), asks with the flag only where the device can, the
|
||||
check runs only before the game from prepare_run, at a start recorded as made, and makes the part again through warm_begin
|
||||
and warm_libraries, recorded on every way out but a stopped one; a cache over its bound is not made again.
|
||||
python -I -B tests/test_lib_check.py --cxx clang++
|
||||
"""
|
||||
import argparse
|
||||
import subprocess
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
RUN_ALL_ARGS = ["--cxx", "{cxx}"]
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
FIXTURE = r"""
|
||||
#include <cstdio>
|
||||
#include <set>
|
||||
#include "lib_check.h"
|
||||
#define CHECK(x) do { if (!(x)) { std::printf("line %d: %s\n", __LINE__, #x); return 1; } } while (0)
|
||||
using namespace lib_check;
|
||||
static Probe asked(bool cold_answer, double first = 0.4, double again = 0.4) {
|
||||
Probe p;
|
||||
p.asked = true, p.answered_cold = cold_answer, p.made = !cold_answer, p.first_ms = first, p.again_ms = cold_answer ? 0 : again;
|
||||
return p;
|
||||
}
|
||||
static Probe timed(double first, double again) {
|
||||
Probe p;
|
||||
p.made = true, p.first_ms = first, p.again_ms = again;
|
||||
return p;
|
||||
}
|
||||
static std::vector<Probe> sample(int cold, int warm, int refused = 0) {
|
||||
std::vector<Probe> v;
|
||||
for (int i = 0; i < cold; i++) v.push_back(asked(true));
|
||||
for (int i = 0; i < warm; i++) v.push_back(asked(false));
|
||||
for (int i = 0; i < refused; i++) v.push_back(Probe{}); // (not made, not answered cold: refused by the driver)
|
||||
return v;
|
||||
}
|
||||
// A start as prepare_run makes it: the sample's verdict, the record, and the part made again (made: it was begun and finished,
|
||||
// left: warm_begin left it out). Returns what the start did
|
||||
static Do start(const std::string& rec, uint64_t stamp, Verdict v, bool left = false) {
|
||||
int next = -1;
|
||||
const Do d = decide(v, state_read(rec), stamp, &next);
|
||||
if (v == Verdict::Warm && state_read(rec).found) remove(rec.c_str());
|
||||
if (d == Do::Again && !state_write(rec, stamp, left ? kStrikes : next)) return Do::Nothing;
|
||||
return d;
|
||||
}
|
||||
|
||||
int main(int, char** argv) {
|
||||
const std::string dir = argv[1];
|
||||
// ---- the switch
|
||||
CHECK(on(nullptr) && on("") && on("1") && !on("0"));
|
||||
// ---- a variant
|
||||
CHECK(cold(asked(true)) && !cold(asked(false)));
|
||||
CHECK(!cold(asked(false, 40, 0.3))); // (asked and answered: made without a compile, whatever its first lookup took)
|
||||
CHECK(cold(timed(120, 0.6)) && cold(timed(30, 2))); // (compiled, against the warm second making)
|
||||
CHECK(!cold(timed(0.7, 0.6)) && !cold(timed(4, 0.4)) && !cold(timed(2.5, 0.1))); // (lookups: a few ms say nothing)
|
||||
CHECK(!cold(timed(9, 2)) && cold(timed(12, 2))); // (relative: kRatio times the reference and kSlackMs more)
|
||||
CHECK(!cold(timed(300, 80)) && cold(timed(400, 80))); // (a driver slow at lookups too: still by its own reference)
|
||||
CHECK(!counts(Probe{}) && counts(asked(true)) && counts(timed(1, 1)));
|
||||
// ---- a sample
|
||||
CHECK(verdict(tally(sample(0, 12))) == Verdict::Warm);
|
||||
CHECK(verdict(tally(sample(12, 0))) == Verdict::Cold);
|
||||
CHECK(verdict(tally(sample(7, 5))) == Verdict::Cold);
|
||||
CHECK(verdict(tally(sample(6, 6))) == Verdict::Warm); // (more than half: the median)
|
||||
CHECK(verdict(tally(sample(1, 5, 6))) == Verdict::Warm && tally(sample(1, 5, 6)).got == 6); // (refused: not counted)
|
||||
CHECK(verdict(tally(sample(4, 1, 7))) == Verdict::Unknown); // (under half a sample says nothing)
|
||||
CHECK(verdict(tally({})) == Verdict::Unknown);
|
||||
{
|
||||
const Tally t = tally({timed(100, 1), timed(1, 1), timed(200, 2), asked(true, 0.01)});
|
||||
CHECK(t.got == 4 && t.cold == 3 && t.answered == 1);
|
||||
CHECK(t.first_median == 100 && t.again_median == 1); // (the median: of all first makings, of the second ones made)
|
||||
}
|
||||
// ---- the places sampled
|
||||
{
|
||||
CHECK(spots(0, 24, 7).empty() && spots(10, 0, 7).empty());
|
||||
CHECK((spots(5, 24, 99) == std::vector<size_t>{0, 1, 2, 3, 4})); // (fewer programs than places: all of them)
|
||||
const std::vector<size_t> a = spots(46600, kLook, 0), b = spots(46600, kLook, 1234567);
|
||||
CHECK((int)a.size() == kLook && (int)b.size() == kLook && a != b);
|
||||
CHECK(a.front() == 0 && b.front() == 1234567 % (46600 / kLook) && b.back() < 46600);
|
||||
CHECK(a.back() >= 46600 - 2 * (46600 / kLook)); // (over the whole cache, not its first part)
|
||||
CHECK(std::set<size_t>(b.begin(), b.end()).size() == b.size());
|
||||
}
|
||||
// ---- the record
|
||||
const uint64_t stamp = 0x0123456789ABCDEFull;
|
||||
{
|
||||
const std::string rec = dir + "/a.check";
|
||||
CHECK(!state_read(rec).found);
|
||||
CHECK(state_write(rec, stamp, 1));
|
||||
State s = state_read(rec);
|
||||
CHECK(s.found && s.stamp == stamp && s.strikes == 1);
|
||||
CHECK(state_write(rec, stamp + 1, 0) && state_read(rec).stamp == stamp + 1 && state_read(rec).strikes == 0); // (replaced)
|
||||
FILE* f = fopen(rec.c_str(), "wb");
|
||||
CHECK(f && fputs("lib check 12 x\n", f) >= 0 && fclose(f) == 0);
|
||||
CHECK(!state_read(rec).found); // (broken: no record)
|
||||
CHECK(!state_write(dir + "/no-such-folder/a.check", stamp, 0));
|
||||
}
|
||||
// ---- what a start does
|
||||
{
|
||||
int next = -1;
|
||||
CHECK(decide(Verdict::Warm, State{}, stamp, &next) == Do::Nothing && next == -1);
|
||||
CHECK(decide(Verdict::Unknown, State{true, stamp, 0}, stamp, &next) == Do::Nothing);
|
||||
CHECK(decide(Verdict::Cold, State{}, stamp, &next) == Do::Again && next == 0);
|
||||
CHECK(decide(Verdict::Cold, State{true, stamp, kStrikes}, stamp, &next) == Do::Stop);
|
||||
CHECK(decide(Verdict::Cold, State{true, stamp, kStrikes + 3}, stamp, &next) == Do::Stop);
|
||||
CHECK(decide(Verdict::Cold, State{true, stamp + 1, 9}, stamp, &next) == Do::Again && next == 0); // (another driver's)
|
||||
CHECK(kStrikes == 0); // (each try holds a start for minutes: made again once, not again right after)
|
||||
}
|
||||
{
|
||||
// (a cache that loses the libraries at every start: made again once, then left to the draws, for good)
|
||||
const std::string rec = dir + "/b.check";
|
||||
CHECK(start(rec, stamp, Verdict::Cold) == Do::Again && state_read(rec).found);
|
||||
CHECK(start(rec, stamp, Verdict::Cold) == Do::Stop);
|
||||
CHECK(start(rec, stamp, Verdict::Unknown) == Do::Nothing && state_read(rec).found); // (nothing said: the record stays)
|
||||
CHECK(start(rec, stamp, Verdict::Cold) == Do::Stop);
|
||||
// (a driver update: a stamp of its own, the count begins anew)
|
||||
CHECK(start(rec, stamp + 1, Verdict::Cold) == Do::Again);
|
||||
// (kept this time: the record goes, and a later loss is made again)
|
||||
CHECK(start(rec, stamp + 1, Verdict::Warm) == Do::Nothing && !state_read(rec).found);
|
||||
CHECK(start(rec, stamp + 1, Verdict::Cold) == Do::Again && state_read(rec).strikes == 0);
|
||||
// (the usual start: warm, no record, nothing written)
|
||||
const std::string none = dir + "/c.check";
|
||||
for (int i = 0; i < 3; i++) CHECK(start(none, stamp, Verdict::Warm) == Do::Nothing && !state_read(none).found);
|
||||
// (left out by warm_begin, or made into a cache it could not write: no second try)
|
||||
const std::string left = dir + "/d.check";
|
||||
CHECK(start(left, stamp, Verdict::Cold, true) == Do::Again && start(left, stamp, Verdict::Cold) == Do::Stop);
|
||||
// (a cache whose save fails every time: made again once, then left to the draws, not held at every start)
|
||||
const std::string unsaved = dir + "/e.check";
|
||||
CHECK(start(unsaved, stamp, Verdict::Cold, true) == Do::Again);
|
||||
for (int i = 0; i < 3; i++) CHECK(start(unsaved, stamp, Verdict::Cold) == Do::Stop);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def between(text, start, end):
|
||||
a = text.index(start)
|
||||
return text[a:text.index(end, a)]
|
||||
|
||||
|
||||
def check_source():
|
||||
draw = (ROOT / "gpu/vk/vk_draw.cpp").read_text(encoding="utf-8")
|
||||
sample = between(draw, "lib_check::Tally lib_check_sample(", "\n}\n")
|
||||
warm = between(draw, "bool warm_libraries(", "\n}\n")
|
||||
# ---- the sample makes the very libraries the driver's part made
|
||||
lib = "build_graphics(p, *blank, at, VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, part"
|
||||
for text, who in ((sample, "lib_check_sample"), (warm, "warm_libraries")):
|
||||
for need in ("blank->nvattr = 16;", "Targets at{};", lib, "for (int part = 1; part <= 2; part++)"):
|
||||
if need not in text:
|
||||
raise SystemExit(who + ": " + need + " is missing (the sample would ask for other libraries than the part made)")
|
||||
# ((Triforce) and a native mesh program's shading rate libraries (pipeline_rate, keyed apart in gpl_keys) in both: the
|
||||
# warm made none of them once, and the check could not see it)
|
||||
for text, who in ((sample, "lib_check_sample"), (warm, "warm_libraries")):
|
||||
steps = ("for (int rate = 0; rate < 2", "if (rate) {", "at = rate_targets();", "if (!pipeline_rate(p, at)) break;", lib)
|
||||
if any(s not in text for s in steps):
|
||||
raise SystemExit(who + ": the shading rate's libraries of a native mesh program are not made with the others")
|
||||
at = [text.index(s) for s in steps]
|
||||
if at != sorted(at):
|
||||
raise SystemExit(who + ": the rate's targets are not set before its libraries are made (the loop's second round)")
|
||||
targets = between(draw, "Targets rate_targets() {", "\n}\n")
|
||||
if "t.depth_format = VK_FORMAT_D32_SFLOAT;" not in targets or "t.n" in targets:
|
||||
raise SystemExit("rate_targets: wanted no colour target and a depth format, so that pipeline_rate holds")
|
||||
if "p.failed || p.compute || p.fallback || p.stages.empty()" not in warm or \
|
||||
"if (taken || p.failed || p.compute || p.fallback || p.stages.empty() || gpl_skipped(p)) return;" not in sample:
|
||||
raise SystemExit("lib_check_sample samples other variants than warm_libraries makes libraries of")
|
||||
if lib + ", ask ? &cold : nullptr);" not in sample or "const bool ask = gpl_ask_only();" not in sample or \
|
||||
"pr.asked = ask, pr.made = true;" not in sample:
|
||||
raise SystemExit("lib_check_sample does not ask the caches only where the device can, as a draw's link does")
|
||||
for need in ("program_cache_keys(&loaded)", "lib_check::spots(keys.size(), lib_check::kLook, seed)",
|
||||
"program_cache_borrow(keys[i],", "vkDestroyPipeline(dev.device, lib, nullptr);", "prepare_stopped()",
|
||||
"return lib_check::tally(probes);"):
|
||||
if need not in sample:
|
||||
raise SystemExit("lib_check_sample: " + need + " is missing")
|
||||
if "program_cache_each(" in sample or "SetThreadPriority" in sample:
|
||||
raise SystemExit("lib_check_sample reads every record or runs on threads of its own")
|
||||
# ---- the check
|
||||
check = between(draw, "bool lib_check_cold(", "\n}\n")
|
||||
for need in ('lib_check::on(getenv("RX_VK_LIB_CHECK"))', "gpl_libs_cached()", "pcache_init();",
|
||||
"!pcache_bound::within((uint64_t)size, pcache_bound_bytes)) return false;",
|
||||
"lib_check::decide(v, had, warmed, &lib_check_next)", "if (had.found) remove(state.c_str());",
|
||||
"return d == lib_check::Do::Again;", 'prepared + ".check"'):
|
||||
if need not in check:
|
||||
raise SystemExit("lib_check_cold: " + need + " is missing")
|
||||
if check.index("!pcache_bound::within(") > check.index("lib_check_sample(&ms)"):
|
||||
raise SystemExit("lib_check_cold samples a cache over its bound, which a making again could not write")
|
||||
made = between(draw, "void lib_check_made(", "\n}\n")
|
||||
if "!made || warm_unsaved ? lib_check::kStrikes : lib_check_next" not in made:
|
||||
raise SystemExit("lib_check_made: a part left out or made into a cache it could not write is tried again")
|
||||
over = warm.index("!pcache_bound::within(held, pcache_bound_bytes)) {")
|
||||
if warm.index("warm_unsaved = true;", over) > warm.index("return true;", over):
|
||||
raise SystemExit("warm_libraries does not say that its cache over the bound was not written")
|
||||
# ---- before the game only, from prepare_run, at a start recorded as made
|
||||
if draw.count("lib_check_cold(") != 2 or draw.count("lib_check_made(") != 3 or draw.count("lib_check_sample(") != 2:
|
||||
raise SystemExit("the check is called past prepare_run")
|
||||
prep = between(draw, "bool prepare_run(", "\n}\n")
|
||||
for need in ("const bool cold = !background && libraries && prepared_for.warmed == warmed && lib_check_cold(path, warmed);",
|
||||
"if (!cold && (prepared_for.warmed == warmed || background)) return false;",
|
||||
"const bool begun = warm_begin(warming, warmed);", "if (cold) lib_check_made(path, warmed, begun);"):
|
||||
if need not in prep:
|
||||
raise SystemExit("prepare_run: " + need + " is missing")
|
||||
alone = prep[:prep.index("seed_open();\n if (!programs)")]
|
||||
a = alone.index("const bool cold = ")
|
||||
b = alone.index("if (!warm_libraries(progress)) {", a)
|
||||
c = alone.index("if (cold) lib_check_made(path, warmed, begun);", b)
|
||||
if not (alone.index("(prepared_for.warmed == warmed || background)) return false;", a) < b < c < alone.index("warm_end(warming);", c)):
|
||||
raise SystemExit("prepare_run: the part made again is not the warm_begin / warm_libraries path, or recorded before it ends")
|
||||
if alone.index("return false;", b) > c:
|
||||
raise SystemExit("prepare_run records the part made again when its pass was stopped")
|
||||
# ((Triforce) every way out after the making again records it, but for a stopped pass: one whose cache could not be saved
|
||||
# too, or every start would make the part again for minutes, for good. But for warm_reset: a cache over the bound only by
|
||||
# what an older file held, made again once into a new file, which is not read from that file: once at most; and for a
|
||||
# carried cache past what it may hold, built again into a fresh cache: pcache_carry.h)
|
||||
unsaved = "if (cold && !prepare_stopped() && !warm_reset && !pcache_carry_over.load()) lib_check_made(path, warmed, false);"
|
||||
if unsaved not in alone or not b < alone.index(unsaved) < alone.index("return false;", b):
|
||||
raise SystemExit("prepare_run: a making again whose cache was not saved is not recorded before it returns")
|
||||
# ---- documented
|
||||
if "| `RX_VK_LIB_CHECK=0` |" not in (ROOT / "docs/development.md").read_text(encoding="utf-8"):
|
||||
raise SystemExit("RX_VK_LIB_CHECK is not in docs/development.md's switches")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--cxx", default="g++")
|
||||
args = parser.parse_args()
|
||||
check_source()
|
||||
with tempfile.TemporaryDirectory(prefix="lib-check-") as tmp:
|
||||
tmp = Path(tmp)
|
||||
(tmp / "t.cpp").write_text(FIXTURE, encoding="utf-8")
|
||||
exe = tmp / "lib-check"
|
||||
subprocess.run([args.cxx, "-std=c++20", "-O1", "-Wall", "-Wextra", "-Werror", "-I" + str(ROOT / "gpu/vk"),
|
||||
str(tmp / "t.cpp"), "-o", str(exe)], check=True)
|
||||
data = tmp / "data"
|
||||
data.mkdir()
|
||||
r = subprocess.run([str(exe), str(data)], capture_output=True, text=True, timeout=120)
|
||||
if r.returncode:
|
||||
raise SystemExit(f"lib_check.h: {r.stdout.strip() or r.returncode}")
|
||||
print("PASS: a start recorded as prepared samples the driver's part as it was made, makes it again before the game when the "
|
||||
"cache lost it, and stops after a making again that did not stay")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -21,7 +21,7 @@ SOURCE = ROOT / "nx2/make_game.py"
|
||||
|
||||
def production():
|
||||
tree = ast.parse(SOURCE.read_text(encoding="utf-8"), filename=str(SOURCE))
|
||||
helpers = {"say", "fail", "gen_print", "write_lift_key", "lifted_before"}
|
||||
helpers = {"say", "fail", "gen_print", "write_lift_key", "lifted_before", "key_after_lift"}
|
||||
definitions = [node for node in tree.body if isinstance(node, ast.FunctionDef) and node.name in helpers]
|
||||
assert {node.name for node in definitions} == helpers
|
||||
key = next(node for node in tree.body if isinstance(node, ast.Assign) and
|
||||
@@ -48,8 +48,10 @@ class LiftCleanupErrorTests(unittest.TestCase):
|
||||
self.key = self.gen / ".lift_key"
|
||||
self.events = []
|
||||
self.namespace, self.branch = production()
|
||||
self.namespace.update(work=str(self.work), exefs=str(self.root / "exefs"), env={}, key="b" * 40, PY=["authored-python"])
|
||||
self.namespace.update(work=str(self.work), exefs=str(self.root / "exefs"), env={}, key="b" * 40, PY=["authored-python"],
|
||||
lift_key=self.lift_key, chunks_copied=False)
|
||||
self.actual_write = self.namespace["write_lift_key"]
|
||||
self.tools = b"" # (what the stand-in key reads of the tools: changed by a test, as an update during the lift)
|
||||
|
||||
def write_key(work, key):
|
||||
self.events.append("key")
|
||||
@@ -83,6 +85,14 @@ class LiftCleanupErrorTests(unittest.TestCase):
|
||||
self.namespace.update(run=run, write_lift_key=write_key, EarlyCompile=Early, a=mock.Mock(jobs=None),
|
||||
atexit=mock.Mock())
|
||||
|
||||
def lift_key(self, exefs, work, env, chunks=True):
|
||||
"""make_game.lift_key's stand-in: "b" * 40 for these inputs while there is no <work>/image/chunks.txt (the key the
|
||||
tests begin with), another key with the chunk boundaries in it or other tools"""
|
||||
self.assertEqual((exefs, work), (str(self.root / "exefs"), str(self.work)))
|
||||
boundaries = self.work / "image/chunks.txt"
|
||||
seen = self.tools + (boundaries.read_bytes() if chunks and boundaries.exists() else b"")
|
||||
return hashlib.sha1(seen).hexdigest() if seen else "b" * 40
|
||||
|
||||
def seed(self, same_key=False):
|
||||
self.gen.mkdir(parents=True)
|
||||
self.image.mkdir(parents=True)
|
||||
@@ -189,6 +199,45 @@ class LiftCleanupErrorTests(unittest.TestCase):
|
||||
self.assertEqual(self.events, ["early", "lift", "early done", "key"])
|
||||
self.assertTrue(self.namespace["lifted_before"](str(self.work), "b" * 40))
|
||||
|
||||
def lift_writing_chunks(self, tools=b""):
|
||||
"""The lift as nx2/chunks.py save does it into a work folder without chunks.txt: the boundaries the sizes gave"""
|
||||
child = self.namespace["run"]
|
||||
|
||||
def run(command, environment):
|
||||
child(command, environment)
|
||||
(self.work / "image").mkdir(parents=True, exist_ok=True)
|
||||
(self.work / "image/chunks.txt").write_text("# first guest address\n80001000\n", encoding="utf-8")
|
||||
self.tools = tools
|
||||
|
||||
self.namespace["run"] = run
|
||||
|
||||
def test_chunks_the_lift_wrote_are_in_the_kept_key(self):
|
||||
# (the build after a first lift into a fresh work folder: its key has the boundaries that lift wrote, and it skips)
|
||||
self.lift_writing_chunks()
|
||||
self.exercise()
|
||||
self.assertEqual(self.events, ["early", "lift", "early done", "key"])
|
||||
next_build = self.lift_key(str(self.root / "exefs"), str(self.work), {})
|
||||
self.assertNotEqual(next_build, "b" * 40)
|
||||
self.assertTrue(self.namespace["lifted_before"](str(self.work), next_build))
|
||||
self.events.clear()
|
||||
self.namespace["key"] = next_build
|
||||
self.exercise()
|
||||
self.assertEqual(self.events, [], "the same game and tools were translated again")
|
||||
|
||||
def test_chunks_copied_from_the_source_keep_the_key_from_before(self):
|
||||
# (an input, copied in at every build before its key is taken: that key is the one the next build takes)
|
||||
self.namespace["chunks_copied"] = True
|
||||
self.lift_writing_chunks()
|
||||
self.exercise()
|
||||
self.assertTrue(self.namespace["lifted_before"](str(self.work), "b" * 40))
|
||||
|
||||
def test_tools_changed_during_the_lift_keep_the_key_from_before(self):
|
||||
# (an update of the tools while the lift ran: its C is the older tools', so the next build must lift again)
|
||||
self.lift_writing_chunks(tools=b"tools updated meanwhile")
|
||||
self.exercise()
|
||||
self.assertTrue(self.namespace["lifted_before"](str(self.work), "b" * 40))
|
||||
self.assertFalse(self.namespace["lifted_before"](str(self.work), self.lift_key(str(self.root / "exefs"), str(self.work), {})))
|
||||
|
||||
def test_failed_lift_leaves_no_fresh_key(self):
|
||||
self.seed()
|
||||
|
||||
|
||||
@@ -80,6 +80,17 @@ class NgxRuntimeTests(unittest.TestCase):
|
||||
self.assertTrue(make_game.fsr_wanted(update, out))
|
||||
self.assertFalse(make_game.fsr_wanted(SimpleNamespace(fsr=False, no_fsr=True, update=out), out))
|
||||
self.assertFalse(make_game.fsr_wanted(plain, out)) # (a new build without --fsr: the mark is for --update only)
|
||||
# ((Triforce) 11-20) HOOKSHOT_FSR=1 in the environment asks for it as --fsr does; --no-fsr still wins
|
||||
saved = os.environ.get("HOOKSHOT_FSR")
|
||||
try:
|
||||
os.environ["HOOKSHOT_FSR"] = "1"
|
||||
self.assertTrue(make_game.fsr_wanted(plain, out))
|
||||
self.assertFalse(make_game.fsr_wanted(SimpleNamespace(fsr=False, no_fsr=True, update=None), out))
|
||||
finally:
|
||||
if saved is None:
|
||||
os.environ.pop("HOOKSHOT_FSR", None)
|
||||
else:
|
||||
os.environ["HOOKSHOT_FSR"] = saved
|
||||
|
||||
def test_linux_runtime(self):
|
||||
self.sdk_files("linux")
|
||||
|
||||
131
tests/test_mem_limit.py
Normal file
131
tests/test_mem_limit.py
Normal file
@@ -0,0 +1,131 @@
|
||||
"""The game's memory held to what it is told it has (host/hos_mem.c, host/hos_svc.c, HOS_MEM_LIMIT; no game).
|
||||
|
||||
1. The rule (hos_mem_fits, cut out of the host's file and compiled alone): with no limit everything fits; with one, a range
|
||||
fits while the count with its new pages is within the limit, and not past it.
|
||||
2. The sources: the count is kept where the game's pages and physical maps are noted and where they go; only the pages of a
|
||||
range the game does not hold yet count; AllocateMemoryPages and MapPhysicalMemory ask before they commit, and answer a
|
||||
refusal with the results the console gives; UsedMemorySize is the count only with the limit on, and never more than the
|
||||
total; unset, the limit is none.
|
||||
|
||||
python -I -B tests/test_mem_limit.py [--cc gcc]
|
||||
"""
|
||||
import argparse
|
||||
import subprocess
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
RUN_ALL_ARGS = ["--cc", "gcc"]
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
HOST = ROOT / "host"
|
||||
|
||||
|
||||
def block(text, marker):
|
||||
start = text.index(marker)
|
||||
end = text.index("{", start) + 1
|
||||
depth = 1
|
||||
while depth:
|
||||
depth += (text[end] == "{") - (text[end] == "}")
|
||||
end += 1
|
||||
return text[start:end]
|
||||
|
||||
|
||||
def in_order(text, parts, where):
|
||||
at = 0
|
||||
for part in parts:
|
||||
found = text.find(part, at)
|
||||
if found < 0:
|
||||
raise SystemExit("%s: %r is missing, or not after the part before it (update the test with the code)" % (where, part))
|
||||
at = found + len(part)
|
||||
|
||||
|
||||
RULE_TEST = r'''
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#define CHECK(x) do { if (!(x)) { fprintf(stderr, "FAIL:%d %s\n", __LINE__, #x); exit(1); } } while (0)
|
||||
RULE
|
||||
int main(void) {
|
||||
const uint64_t MB = 1ull << 20;
|
||||
/* (no limit: as before, whatever is held) */
|
||||
CHECK(hos_mem_fits(0, 0, 0) && hos_mem_fits(20000 * MB, 4096, 0));
|
||||
/* (a limit: within it, up to it, not past it) */
|
||||
CHECK(hos_mem_fits(9000 * MB, 100 * MB, 9809 * MB) && hos_mem_fits(9709 * MB, 100 * MB, 9809 * MB));
|
||||
CHECK(!hos_mem_fits(9709 * MB, 100 * MB + 4096, 9809 * MB) && !hos_mem_fits(9809 * MB, 4096, 9809 * MB));
|
||||
/* (pages the game holds already cost nothing: a range of them fits at the limit, and past it) */
|
||||
CHECK(hos_mem_fits(9809 * MB, 0, 9809 * MB) && hos_mem_fits(11000 * MB, 0, 9809 * MB));
|
||||
puts("PASS rule: no limit unless set; within the limit and up to it, not past it; held pages cost nothing");
|
||||
return 0;
|
||||
}
|
||||
'''
|
||||
|
||||
MUTATIONS = [
|
||||
("no limit unless set", "return !limit || !fresh || used + fresh <= limit;", "return !fresh || used + fresh <= limit;"),
|
||||
("held pages cost nothing", "return !limit || !fresh || used + fresh <= limit;", "return !limit || used + fresh <= limit;"),
|
||||
("not past the limit", "return !limit || !fresh || used + fresh <= limit;", "return !limit || !fresh || used <= limit;"),
|
||||
("up to the limit", "return !limit || !fresh || used + fresh <= limit;", "return !limit || !fresh || used + fresh < limit;"),
|
||||
]
|
||||
|
||||
|
||||
def check_source(mem, svc):
|
||||
note = block(mem, "void hos_mem_note(int what, uint64_t addr, uint64_t size) {")
|
||||
if note.count("__atomic_add_fetch(&census_game_bytes, (int64_t)gc_change(&census, GC_GAME, lo, hi, 1)") != 1:
|
||||
raise SystemExit("hos_mem.c hos_mem_note: the game's pages and maps are not counted where they are noted")
|
||||
if note.count("__atomic_sub_fetch(&census_game_bytes, (int64_t)gc_change(&census, GC_GAME, lo, hi, 0)") != 3:
|
||||
raise SystemExit("hos_mem.c hos_mem_note: the count does not fall at each of the three places the game's pages go")
|
||||
if "gc_change(&census, GC_GAME" in note.replace("(int64_t)gc_change(&census, GC_GAME", ""):
|
||||
raise SystemExit("hos_mem.c hos_mem_note: the game's pages change somewhere without the count")
|
||||
limit = block(mem, "int64_t hos_mem_limit(void) {")
|
||||
in_order(limit, ['getenv("HOS_MEM_LIMIT")', "n <= 0 || !hos_mem_census_on() ? 0 : n == 1 ? (int64_t)hos_total_memory : (int64_t)n << 20;"],
|
||||
"hos_mem.c hos_mem_limit")
|
||||
room = block(mem, "int hos_mem_room(uint64_t addr, uint64_t size) {")
|
||||
in_order(room, ["if (!limit || !size || addr + size < addr || addr + size > GC_SPACE) return 1;",
|
||||
"const uint64_t held = gc_count(&census, GC_GAME, addr, addr + size);",
|
||||
"const uint64_t fresh = size > held ? size - held : 0, used = hos_mem_used();",
|
||||
"if (hos_mem_fits(used, fresh, (uint64_t)limit)) return 1;", "return 0;"], "hos_mem.c hos_mem_room")
|
||||
pages = block(mem, "HLE(_ZN2nn2os19AllocateMemoryPagesEmm) {")
|
||||
in_order(pages, ["if (!hos_guest_range(a, n)) {", "if (!hos_mem_room(a, n)) {", "RET(0x1A01);", "hos_commit(a, n);",
|
||||
"hos_mem_note(HOS_MEM_PAGES, a, n);"], "hos_mem.c AllocateMemoryPages")
|
||||
in_order(svc, ["static uint64_t hos_mem_used_told(void) {", "if (!hos_mem_limit()) return hos_program_size + hos_heap_size;",
|
||||
"return used < hos_total_memory ? used : hos_total_memory;", "case 7: return hos_mem_used_told();",
|
||||
"case 22: return hos_mem_used_told();", "case 0x2C: { /* MapPhysicalMemory(address, size) */",
|
||||
"if (!hos_mem_room(c->x[0], c->x[1])) {", "c->x[0] = 0x10801;", "const int committed = hos_commit(c->x[0], c->x[1]);"],
|
||||
"hos_svc.c")
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument("--cc", default="gcc")
|
||||
a = p.parse_args()
|
||||
mem = (HOST / "hos_mem.c").read_text(encoding="utf-8")
|
||||
check_source(mem, (HOST / "hos_svc.c").read_text(encoding="utf-8"))
|
||||
print("PASS sources: the count kept with the census's notes, a range asked before its commit, the console's refusals, "
|
||||
"UsedMemorySize the count only with the limit on")
|
||||
rule = block(mem, "int hos_mem_fits(uint64_t used, uint64_t fresh, uint64_t limit) {")
|
||||
with tempfile.TemporaryDirectory(prefix="mem-limit-") as tmp:
|
||||
d = Path(tmp)
|
||||
|
||||
def run(name, text):
|
||||
c, exe = d / (name + ".c"), d / (name + ".exe")
|
||||
c.write_text(RULE_TEST.replace("RULE", text), encoding="utf-8")
|
||||
r = subprocess.run([a.cc, "-std=gnu11", "-O1", "-Wall", "-Wextra", "-Werror", str(c), "-o", str(exe)],
|
||||
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
|
||||
if r.returncode:
|
||||
return None, r.stdout
|
||||
r = subprocess.run([str(exe)], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, timeout=60)
|
||||
return r.returncode == 0, r.stdout
|
||||
ok, out = run("rule", rule)
|
||||
if not ok:
|
||||
raise SystemExit("the rule's test failed:\n" + out)
|
||||
print(out.strip())
|
||||
for i, (what, old, new) in enumerate(MUTATIONS):
|
||||
if rule.count(old) != 1:
|
||||
raise SystemExit("mutation %r: its text is not once in the rule (update the test with the host's file)" % what)
|
||||
ok, out = run("mutant%d" % i, rule.replace(old, new))
|
||||
if ok:
|
||||
raise SystemExit("mutation %r: the rule's test still passed without it" % what)
|
||||
print("PASS mutations: %d parts of the rule, each taken out, fail its test" % len(MUTATIONS))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
282
tests/test_memory_trial.py
Normal file
282
tests/test_memory_trial.py
Normal file
@@ -0,0 +1,282 @@
|
||||
"""The trial of the newer memory handling on a card that is not NVIDIA's (gpu/vk/vk_memory.cpp memory_trial_on,
|
||||
memory_trial_used, memory_trial_tick, memory_trial_device_lost; triforce_memtrial.txt; no game/GPU).
|
||||
|
||||
A lab run with RX_VK_MIRROR_PIECES=0 and RX_VK_COMPACT=0 passed the trial on an AMD card whose session with the handling
|
||||
on had blue-screened the PC that morning: memory_trial_tick said "ok" 300 s after the start whatever those switches said,
|
||||
so the trial passed with neither part ever on, and the next run without them had both on, untested. A session counts
|
||||
for the trial now only when the handling runs in it, and passes once all of it has run for the trial's time.
|
||||
|
||||
The trial's code is cut from vk_memory.cpp into a fixture (stand-ins for the device, the log and the executable's path)
|
||||
and run once a session, on a file of its own:
|
||||
- with a switch that keeps a part off (RX_VK_MIRROR_PIECES=0, RX_VK_MIRROR=0, RX_VK_COMPACT=0, RX_VK_NO_IMAGE_POOL) the
|
||||
file stays as it was, byte for byte, through the trial's time, a device lost and an orderly end, and the log says which
|
||||
switch; a pass of earlier sessions' "trying" is not turned into a failure there either;
|
||||
- a session in which nothing of the handling ran says nothing: the file stays as it was;
|
||||
- one part alone in use (the compaction, on a card that has mirrors in pieces) begins the trial (trying) but does not pass
|
||||
it, and an orderly end then says new;
|
||||
- both parts in use pass it ("ok"), and on a card without sparse residency buffers the compaction alone does, as before;
|
||||
- a device lost with it on turns it off, as before, and the same after a trial that passed starts one more;
|
||||
- a session with a switch keeping a part off has the other parts off too (memory_trial_on says no): nothing would turn
|
||||
them off if they lost the GPU there;
|
||||
- the file says v=2 now; a v=1 ok came from a build that passed the trial with the handling switched off, so the trial
|
||||
runs again; a v=1 trying is one bad session, and a v=1 off stays off;
|
||||
- a part the driver could not make (a mirror's sparse buffer refused, the textures' pool not made) is not waited for, or
|
||||
the trial could never pass there;
|
||||
- RX_VK_MIRROR=0 or RX_VK_MIRROR_PIECES=0 on an integrated GPU (mirrors off by default) changes nothing for the trial;
|
||||
- the log says why a session gave no verdict: the part it waits for, an end before the trial was over, nothing ran.
|
||||
Then the source: the first piece of a mirror bound and a texture made in the compacted pool say so (memory_trial_used),
|
||||
a refused sparse buffer or textures' pool says so (memory_trial_refused), and memory_trial_tick passes only once all of
|
||||
it is in use.
|
||||
|
||||
python -I -B tests/test_memory_trial.py [--cxx g++]
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
RUN_ALL_ARGS = ["--cxx", "{cxx}"]
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def block(text, marker):
|
||||
if text.count(marker) != 1:
|
||||
raise SystemExit("marker not found once: " + marker)
|
||||
start = text.index(marker)
|
||||
end = text.index("{", start) + 1
|
||||
depth = 1
|
||||
while depth:
|
||||
depth += (text[end] == "{") - (text[end] == "}")
|
||||
end += 1
|
||||
return text[start:end]
|
||||
|
||||
|
||||
def need(where, text, needles):
|
||||
for needle in needles:
|
||||
if needle not in text:
|
||||
raise SystemExit("FAIL: " + where + " no longer has: " + needle)
|
||||
|
||||
|
||||
FIXTURE = r"""
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cstdarg>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#ifdef _WIN32
|
||||
#include <windows.h>
|
||||
#else
|
||||
typedef unsigned long DWORD;
|
||||
typedef long LONG;
|
||||
#define WINAPI
|
||||
#define MAX_PATH 260
|
||||
#define EXCEPTION_CONTINUE_SEARCH 0
|
||||
struct EXCEPTION_POINTERS {};
|
||||
typedef LONG (*LPTOP_LEVEL_EXCEPTION_FILTER)(EXCEPTION_POINTERS*);
|
||||
LPTOP_LEVEL_EXCEPTION_FILTER SetUnhandledExceptionFilter(LPTOP_LEVEL_EXCEPTION_FILTER) { return nullptr; }
|
||||
#endif
|
||||
namespace mkwvk {
|
||||
struct {
|
||||
struct { uint32_t vendorID = 0x1002, deviceID = 0x744c, driverVersion = 0x8001a0; } props;
|
||||
bool sparse_buffers = true;
|
||||
struct { bool sparseResidencyBuffer = true; } features;
|
||||
} dev;
|
||||
void logf(const char* fmt, ...) {
|
||||
va_list ap;
|
||||
va_start(ap, fmt);
|
||||
std::vprintf(fmt, ap);
|
||||
va_end(ap);
|
||||
std::printf("\n");
|
||||
}
|
||||
DWORD game_module_path(char* buf, DWORD size) {
|
||||
const char* p = std::getenv("TRIAL_FIXTURE_EXE");
|
||||
std::snprintf(buf, size, "%s", p ? p : "game.exe");
|
||||
return (DWORD)std::strlen(buf);
|
||||
}
|
||||
@@ENUM@@
|
||||
bool memory_trial_on();
|
||||
void memory_trial_used(MemoryTrialPart part);
|
||||
void memory_trial_refused(MemoryTrialPart part);
|
||||
@@TRIAL@@
|
||||
namespace { // (as vk_memory.cpp's: RX_VK_MIRROR decides, else on a discrete GPU; TRIAL_FIXTURE_IGPU plays an integrated one)
|
||||
bool mirror_by_default() { return std::getenv("TRIAL_FIXTURE_IGPU") == nullptr; }
|
||||
bool mirror_on() { return std::getenv("RX_VK_MIRROR") ? std::atoi(std::getenv("RX_VK_MIRROR")) != 0 : mirror_by_default(); }
|
||||
}
|
||||
} // namespace mkwvk
|
||||
int main(int argc, char** argv) {
|
||||
using namespace mkwvk;
|
||||
if (argc > 2 && argv[2][0] == '0') dev.sparse_buffers = false;
|
||||
for (const char* a = argc > 1 ? argv[1] : ""; *a; a++) switch (*a) {
|
||||
case 'o': std::printf("on: %d\n", (int)memory_trial_on()); break;
|
||||
case 'p': memory_trial_used(MEMTRIAL_PIECES); break;
|
||||
case 'c': memory_trial_used(MEMTRIAL_COMPACT); break;
|
||||
case 'r': memory_trial_refused(MEMTRIAL_PIECES); break;
|
||||
case 'R': memory_trial_refused(MEMTRIAL_COMPACT); break;
|
||||
case 't': memory_trial_tick(); break;
|
||||
case 'l': memory_trial_device_lost(); break;
|
||||
case 'e': memory_trial_orderly_end(); break;
|
||||
}
|
||||
std::fflush(stdout);
|
||||
std::_Exit(0); // (as a session killed: the exit handler's own word is 'e')
|
||||
}
|
||||
"""
|
||||
|
||||
HEAD = "v=2 vendor=1002 device=744c driver=8001a0 state=%s fails=%d\n"
|
||||
HEAD_V1 = "v=1 vendor=1002 device=744c driver=8001a0 state=%s fails=%d\n" # (the builds before 11-17)
|
||||
|
||||
|
||||
def trial_file(state, fails, head=HEAD):
|
||||
return head % (state, fails) + "# set by the test\n"
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--cxx", default="g++")
|
||||
args = parser.parse_args()
|
||||
mem = (ROOT / "gpu/vk/vk_memory.cpp").read_text(encoding="utf-8")
|
||||
vma = (ROOT / "gpu/vk/vk_vma.cpp").read_text(encoding="utf-8")
|
||||
internal = (ROOT / "gpu/vk/vk_internal.h").read_text(encoding="utf-8")
|
||||
|
||||
# ---- the source: where the parts say they ran, and the pass waits for them
|
||||
tick = block(mem, "void memory_trial_tick() {")
|
||||
need("vk_memory.cpp: memory_trial_tick()", tick, ["in_use.load(std::memory_order_acquire)", 'write(OK, 0, "played with it on: kept");'])
|
||||
on = block(mem, "bool memory_trial_on() {")
|
||||
need("vk_memory.cpp: memory_trial_on()", on, ["held_off = switches_off();", "if (was != OFF && held_off.empty()) write(OFF,",
|
||||
"does not count for the trial", "candidate = true;", "(v == kVersion || v == 1)",
|
||||
"if (v == 1 && was == OK) {"])
|
||||
if "write(TRYING" in on or "SetUnhandledExceptionFilter" in on:
|
||||
raise SystemExit("FAIL: memory_trial_on begins the trial before any of the handling has run")
|
||||
if on.index("if (!held_off.empty())") > on.index("candidate = true;"):
|
||||
raise SystemExit("FAIL: memory_trial_on makes a session with a part switched off count for the trial")
|
||||
held = block(on, "if (!held_off.empty()) {")
|
||||
if "return false;" not in held:
|
||||
raise SystemExit("FAIL: memory_trial_on turns on, with no trial to guard them, the parts no switch names")
|
||||
if "constexpr int kVersion = 2;" not in mem:
|
||||
raise SystemExit("FAIL: vk_memory.cpp's triforce_memtrial.txt is not v=2: a v=1 file's ok cannot be told from a pass given switched off")
|
||||
used = block(mem, "void memory_trial_used(MemoryTrialPart part) {")
|
||||
need("vk_memory.cpp: memory_trial_used()", used, ["if (!candidate || state != TRYING) return;", 'write(TRYING, fails, "a session has it on");',
|
||||
"all_in_use();"])
|
||||
need("vk_memory.cpp: all_in_use()", block(mem, "void all_in_use() {"),
|
||||
["if (needed(p) && !used[p].load()) return;", "in_use.store(true, std::memory_order_release);"])
|
||||
need("vk_memory.cpp: needed()", block(mem, "bool needed(int part) {"), ["if (refused[part].load()) return false;"])
|
||||
need("vk_memory.cpp: memory_trial_refused()", block(mem, "void memory_trial_refused(MemoryTrialPart part) {"),
|
||||
["if (active.load()) all_in_use();"])
|
||||
need("vk_memory.cpp: switches_off()", block(mem, "std::string switches_off() {"),
|
||||
['if (pieces_can() && mirror_on()) add("RX_VK_MIRROR_PIECES")', 'if (pieces_can() && mirror_by_default()) add("RX_VK_MIRROR")',
|
||||
'add("RX_VK_COMPACT")', 'getenv("RX_VK_NO_IMAGE_POOL")'])
|
||||
need("vk_memory.cpp: mirror_on()", block(mem, "bool mirror_on() {\n static"), ["atoi(e) != 0 : mirror_by_default();"])
|
||||
need("vk_memory.cpp: mirror_pieces_make()", block(mem, "bool mirror_pieces_make(Pool& p,"),
|
||||
["st_piece_binds++;", "memory_trial_used(MEMTRIAL_PIECES);"])
|
||||
make = block(mem, "if (mirror_pieces_on() && n <= (1ull << 30) && !tight && n >= 4 * piece_cfg) {")
|
||||
need("vk_memory.cpp: mirror_make()'s pieces", make, ["if (!in_pieces) memory_trial_refused(MEMTRIAL_PIECES);"])
|
||||
need("vk_vma.cpp: textures_pool()", block(vma, "VmaPool textures_pool() {"),
|
||||
["memory_trial_refused(MEMTRIAL_COMPACT);", "if (!texture_pool) memory_trial_refused(MEMTRIAL_COMPACT);"])
|
||||
# (v0.5.1: the work is create_image_inner_, create_image_inner names the image for RX_VK_RT_MAP around it)
|
||||
need("vk_vma.cpp: create_image_inner_()", block(vma, "bool create_image_inner_(const VkImageCreateInfo& ci, VkImage& image, VmaAllocation& allocation, bool dedicated, bool target, bool textures) {"),
|
||||
["if (pool == texture_pool) memory_trial_used(MEMTRIAL_COMPACT);", "== VK_SUCCESS) return made();"])
|
||||
enum = [line for line in internal.splitlines() if line.startswith("enum MemoryTrialPart")]
|
||||
if len(enum) != 1:
|
||||
raise SystemExit("FAIL: vk_internal.h has no enum MemoryTrialPart line")
|
||||
|
||||
# ---- the trial's code, run
|
||||
start = mem.index("namespace { bool mirror_on(); bool mirror_by_default(); }")
|
||||
lost = mem.index("void memory_trial_device_lost() {")
|
||||
trial = mem[start:lost] + block(mem, "void memory_trial_device_lost() {")
|
||||
with tempfile.TemporaryDirectory(prefix="memtrial-") as tmp:
|
||||
src, exe = Path(tmp) / "fixture.cpp", Path(tmp) / "fixture.exe"
|
||||
src.write_text(FIXTURE.replace("@@ENUM@@", enum[0]).replace("@@TRIAL@@", trial), encoding="utf-8")
|
||||
command = [args.cxx, "-std=c++20", "-O1", str(src), "-o", str(exe)] + ([] if os.name == "nt" else ["-pthread"])
|
||||
r = subprocess.run(command, capture_output=True, text=True, timeout=120)
|
||||
if r.returncode:
|
||||
print(r.stdout + r.stderr)
|
||||
raise SystemExit("the fixture did not build")
|
||||
file = Path(tmp) / "triforce_memtrial.txt"
|
||||
base_env = {k: v for k, v in os.environ.items() if not k.startswith("RX_VK_") and not k.startswith("TRIAL_FIXTURE_")}
|
||||
base_env.update(TRIAL_FIXTURE_EXE=str(Path(tmp) / "game.exe"), RX_VK_TEST_TRIAL_S="0")
|
||||
failures = []
|
||||
|
||||
def session(name, before, steps, env=(), sparse=True, after=None, log=()):
|
||||
if before is None:
|
||||
file.unlink(missing_ok=True)
|
||||
else:
|
||||
file.write_text(before, encoding="utf-8", newline="\n")
|
||||
e = dict(base_env)
|
||||
e.update(env)
|
||||
r = subprocess.run([str(exe), steps, "1" if sparse else "0"], capture_output=True, text=True, timeout=30, env=e)
|
||||
got = file.read_text(encoding="utf-8") if file.exists() else None
|
||||
# (after: None for the file as it was, byte for byte; else the state and fails it must say)
|
||||
want = before if after is None else HEAD % after
|
||||
ok = r.returncode == 0 and (got == before if after is None else got is not None and got.startswith(want))
|
||||
ok = ok and all(s in r.stdout for s in log)
|
||||
print(("pass " if ok else "FAIL ") + name)
|
||||
if not ok:
|
||||
failures.append(name)
|
||||
print(" log:\n " + r.stdout.strip().replace("\n", "\n ") + "\n file: " + repr(got) + "\n wanted: " + repr(want))
|
||||
|
||||
trying = trial_file("trying", 0) # (the session that blue-screened the PC: it left no word)
|
||||
# (the lab's pins: the file stays as it was through the trial's time, a device lost and an orderly end)
|
||||
for pins in ({"RX_VK_MIRROR_PIECES": "0", "RX_VK_COMPACT": "0"}, {"RX_VK_COMPACT": "0"}, {"RX_VK_MIRROR_PIECES": "0"},
|
||||
{"RX_VK_MIRROR": "0"}, {"RX_VK_NO_IMAGE_POOL": "1"}):
|
||||
label = ", ".join("%s=%s" % kv for kv in pins.items())
|
||||
session("pinned (%s): no verdict, the rest off too" % label, trying, "otttte", pins,
|
||||
log=["does not count for the trial", label.split(",")[0].replace("=1", ""), "on: 0"])
|
||||
session("pinned (%s), parts it lets on used: no verdict" % label, trying, "opcttt", pins)
|
||||
session("pinned (%s), device lost: no verdict" % label, trying, "optl", pins)
|
||||
session("pinned (%s), after a pass, device lost: no verdict" % label, trial_file("ok", 0), "opcl", pins)
|
||||
session("pinned, one earlier failure and no word: not turned off here", trial_file("trying", 1), "otl",
|
||||
{"RX_VK_MIRROR_PIECES": "0", "RX_VK_COMPACT": "0"})
|
||||
# (no pieces on this card: RX_VK_MIRROR_PIECES=0 keeps nothing off, and the compaction alone passes)
|
||||
session("no sparse buffers, RX_VK_MIRROR_PIECES=0: compaction alone passes", trying, "octt", {"RX_VK_MIRROR_PIECES": "0"}, False, ("ok", 0))
|
||||
# (the players' sessions, no switches)
|
||||
session("nothing of it ran: no verdict", trying, "ottte", log=["nothing of it ran in this session: no verdict"])
|
||||
session("nothing of it ran, ended with no word: no verdict", trial_file("new", 0), "ott")
|
||||
session("compaction alone in use on a card with pieces: trying, not passed", trying, "octtt", after=("trying", 1),
|
||||
log=["waits for mirrors in pieces, which has not run"])
|
||||
session("compaction alone in use, orderly end: new", trying, "octte", after=("new", 1),
|
||||
log=["ended before the trial was over: no verdict"])
|
||||
# (a part the driver could not make is not waited for)
|
||||
session("sparse buffer refused: compaction alone passes", None, "ocrt", after=("ok", 0), log=["goes on without mirrors in pieces"])
|
||||
session("sparse buffer refused before any use: compaction alone passes", None, "orct", after=("ok", 0))
|
||||
session("textures' pool not made: pieces alone pass", None, "oRpt", after=("ok", 0))
|
||||
session("sparse buffer refused, nothing else ran: no verdict", trying, "ortte")
|
||||
# (an integrated GPU: mirrors off by default, so the switches that keep them off change nothing)
|
||||
igpu = {"TRIAL_FIXTURE_IGPU": "1"}
|
||||
session("integrated GPU, RX_VK_MIRROR=0: compaction alone passes", None, "oct", dict(igpu, RX_VK_MIRROR="0"), after=("ok", 0))
|
||||
session("integrated GPU, RX_VK_MIRROR_PIECES=0: compaction alone passes", None, "oct", dict(igpu, RX_VK_MIRROR_PIECES="0"), after=("ok", 0))
|
||||
session("integrated GPU, RX_VK_MIRROR=1 and RX_VK_MIRROR_PIECES=0: no verdict", trying, "opctl",
|
||||
dict(igpu, RX_VK_MIRROR="1", RX_VK_MIRROR_PIECES="0"), log=["RX_VK_MIRROR_PIECES=0 keeps a part of it off"])
|
||||
session("discrete GPU, RX_VK_MIRROR=0: no verdict", trying, "octl", {"RX_VK_MIRROR": "0"}, log=["RX_VK_MIRROR=0 keeps"])
|
||||
# (a v=1 file, from the builds before 11-17: its ok may have been given with the handling switched off)
|
||||
old_ok = trial_file("ok", 0, HEAD_V1)
|
||||
session("v=1 ok: on trial again, and passes when it runs", old_ok, "opct", after=("ok", 0), log=["passed under an older build"])
|
||||
session("v=1 ok: on trial again, killed before the trial's time: trying", old_ok, "opc", {"RX_VK_TEST_TRIAL_S": "3600"}, after=("trying", 0))
|
||||
session("v=1 ok, pinned: off, file as it was", old_ok, "opctl", {"RX_VK_MIRROR_PIECES": "0", "RX_VK_COMPACT": "0"}, log=["on: 0"])
|
||||
session("v=1 ok, nothing of it ran: file as it was", old_ok, "ottte")
|
||||
session("v=1 trying: one bad session", trial_file("trying", 0, HEAD_V1), "octt", after=("trying", 1))
|
||||
session("v=1 trying, one earlier failure: off", trial_file("trying", 1, HEAD_V1), "o", after=("off", 2), log=["on: 0"])
|
||||
session("v=1 off: stays off", trial_file("off", 2, HEAD_V1), "opctl", log=["on: 0", "is off on this card"])
|
||||
session("both in use: passed", trying, "octpt", after=("ok", 0), log=["passed its trial"])
|
||||
session("both in use, first session: passed", None, "opct", after=("ok", 0))
|
||||
session("no sparse buffers: compaction alone passes", None, "oct", sparse=False, after=("ok", 0))
|
||||
session("mirrors off (integrated GPU): compaction alone passes", None, "oct", {"TRIAL_FIXTURE_IGPU": "1"}, after=("ok", 0))
|
||||
session("both in use, ended before the trial's time: new", None, "opce", {"RX_VK_TEST_TRIAL_S": "3600"}, after=("new", 0))
|
||||
session("both in use, killed before the trial's time: trying", None, "opct", {"RX_VK_TEST_TRIAL_S": "3600"}, after=("trying", 0))
|
||||
session("device lost with it on: off", trying, "opcl", after=("off", 2))
|
||||
session("device lost after a pass: tried once more", trial_file("ok", 0), "opcl", after=("new", 1))
|
||||
session("two sessions without a word: off", trial_file("trying", 1), "o", after=("off", 2))
|
||||
session("a pass on another card does not carry over", "v=2 vendor=1002 device=7480 driver=8001a0 state=ok fails=0\n", "opct", after=("ok", 0),
|
||||
log=["is on trial on this card"])
|
||||
session("NVIDIA: on, no file", None, "opctl", {"RX_VK_TEST_VENDOR": "10de"}, log=["on: 1"])
|
||||
if failures:
|
||||
raise SystemExit("FAIL: %d session(s): %s" % (len(failures), "; ".join(failures)))
|
||||
print("PASS: a session counts for the memory trial only when the handling runs in it; switches that keep it off leave the file as it was")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
309
tests/test_menu_bound_keys.py
Normal file
309
tests/test_menu_bound_keys.py
Normal file
@@ -0,0 +1,309 @@
|
||||
"""The options' tabs and Back answer to the keys the player bound to the Switch's L, R and B, and the guides name them
|
||||
(gpu/vk/vk_menu.cpp, gpu/vk/vk_ui.h, host/nn_hid.c; no game).
|
||||
|
||||
The lab's playtest showed the hints at odds: the tab strip's ends named the keys bound to L and R (Q and R), the guides
|
||||
said "Category Q E" and "Back Esc", and the game's own tab said "Back Shift" (key_b=16). Our tabs took neither R nor
|
||||
Shift. Now the guides and the strip name the same keys, taken from the bindings as the game's guides are, and the menu
|
||||
takes them beside its own Q, E, Tab and Esc.
|
||||
|
||||
The key handling is compiled from menu_tick as it is (the block between its markers) with stand-ins for Windows and the
|
||||
host, and run: a bound R steps a tab once per press; a bound Shift is Back as it is let go, and not when Tab was pressed
|
||||
with it (Shift+Tab still steps back a tab), nor while a binding waits for its key, nor when it went down with the menu
|
||||
closed, nor when the window lost the front while it was held, nor when another key, a mouse button or a
|
||||
pad press went with it; a bound R tapped between two ticks counts from the host's queue, once; a bound key the menu has its own use for (an arrow) keeps that use; a mouse button bound to B is no key of the
|
||||
menu's; the gamepad input L is bound to steps a tab unless it is one the menu uses (A's). The keys bound to L and R as the
|
||||
game has them (for its own tab, which opens ours) are read every tick. While the Mods screen's search takes text
|
||||
(menu_mods_typing) the bound keys type there: a bound R is no category and Shift no Back, and nothing of theirs is kept
|
||||
for after; the guides then name the menu's own Q, E and Esc. The rest is read in the source: the labels, the
|
||||
glyphs, the strip, and the host's Back tapped for a let-go modifier.
|
||||
|
||||
python -I -B tests/test_menu_bound_keys.py [--cxx g++]
|
||||
"""
|
||||
import argparse
|
||||
import subprocess
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
RUN_ALL_ARGS = ["--cxx", "{cxx}"]
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def check(ok, why):
|
||||
if not ok:
|
||||
raise SystemExit("FAIL: " + why)
|
||||
|
||||
|
||||
def function(text, head):
|
||||
start = text.index(head)
|
||||
end = text.index("{", start) + 1
|
||||
depth = 1
|
||||
while depth:
|
||||
depth += (text[end] == "{") - (text[end] == "}")
|
||||
end += 1
|
||||
return text[start:end]
|
||||
|
||||
|
||||
def enum_block(text, head):
|
||||
start = text.index(head)
|
||||
return text[start:text.index("};", start) + 2]
|
||||
|
||||
|
||||
FIXTURE = r'''#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#define CHECK(x) do { if (!(x)) { std::fprintf(stderr, "FAIL:%d %s\n", __LINE__, #x); std::exit(1); } } while (0)
|
||||
@ENUMS@
|
||||
enum {
|
||||
VK_INSERT = 0x2d, VK_UP = 0x26, VK_DOWN = 0x28, VK_LEFT = 0x25, VK_RIGHT = 0x27, VK_ESCAPE = 0x1b, VK_F1 = 0x70,
|
||||
VK_RETURN = 0x0d, VK_DELETE = 0x2e, VK_BACK = 8, VK_TAB = 9, VK_PRIOR = 0x21, VK_NEXT = 0x22, VK_HOME = 0x24,
|
||||
VK_END = 0x23, VK_F8 = 0x77, VK_SHIFT = 0x10, VK_CONTROL = 0x11, VK_MENU = 0x12, VK_RBUTTON = 2, VK_LBUTTON = 1,
|
||||
VK_LSHIFT = 0xa0, VK_RSHIFT = 0xa1, VK_LCONTROL = 0xa2, VK_RCONTROL = 0xa3, VK_LMENU = 0xa4, VK_RMENU = 0xa5, VK_LWIN = 0x5b
|
||||
};
|
||||
static bool key_down[256];
|
||||
static short GetAsyncKeyState(int k) { return key_down[k & 255] ? (short)0x8000 : 0; }
|
||||
static int bind_key[HOS_KEY_N][2], bind_pad[HOS_SW_N];
|
||||
static int binding(int set, int button, int slot) { return set == HOS_BIND_PAD ? (slot ? -1 : bind_pad[button]) : bind_key[button][slot]; }
|
||||
static bool queue[256]; // (the host's queue of presses, host/rx_backend.c: a key's press until it is taken)
|
||||
static int take_key_press(int k) { const bool q = queue[k & 255]; queue[k & 255] = false; return q; }
|
||||
static struct { int (*binding)(int, int, int); int (*take_key_press)(int); } host_stub{binding, take_key_press}, *host = &host_stub;
|
||||
static struct { bool v; bool load() const { return v; } } open_now{true};
|
||||
static int listening;
|
||||
static bool pad_last;
|
||||
static bool focused = true;
|
||||
static int pad_confirm = HOS_PAD_EAST, pad_back = HOS_PAD_SOUTH;
|
||||
static bool typing_now; // (the Mods screen's search taking text)
|
||||
static bool menu_mods_typing() { return typing_now; }
|
||||
@HELPERS@
|
||||
struct Out { bool left, right, back, game_l, game_r; };
|
||||
static uint32_t pad_press;
|
||||
static Out tick() {
|
||||
enum { K_N = 17 };
|
||||
static bool held[K_N];
|
||||
static const int keys[K_N] = {VK_INSERT, VK_UP, VK_DOWN, VK_LEFT, VK_RIGHT, VK_ESCAPE, VK_F1, VK_RETURN, VK_DELETE, VK_BACK,
|
||||
'Q', 'E', VK_TAB, VK_PRIOR, VK_NEXT, VK_HOME, VK_END};
|
||||
bool press[K_N] = {};
|
||||
for (int i = 0; i < K_N; i++) {
|
||||
const bool down = key_down[keys[i]];
|
||||
press[i] = down && !held[i];
|
||||
held[i] = down;
|
||||
}
|
||||
const bool mine = focused;
|
||||
bool tab_left = false, tab_right = false;
|
||||
int gk_vk[20] = {}, gk_n = 0; // ((11-19) the game's keys menu_tick reads before (none here): their queued presses shared
|
||||
bool gk_q[20] = {}; // with these keys' read)
|
||||
auto pad = [&](int p) { return listening != 1 && (pad_press >> p & 1) != 0; };
|
||||
@TRACKER@
|
||||
pad_press = 0;
|
||||
return {tab_left, tab_right, press[5], game_lr[0], game_lr[1]};
|
||||
}
|
||||
int main() {
|
||||
bind_key[HOS_SW_L][0] = 'Q', bind_key[HOS_SW_R][0] = 'R', bind_key[HOS_SW_B][0] = VK_SHIFT; // (the defaults)
|
||||
bind_pad[HOS_SW_L] = HOS_PAD_LSHOULDER, bind_pad[HOS_SW_R] = HOS_PAD_RSHOULDER;
|
||||
// R: the next tab, once a press
|
||||
key_down['R'] = true;
|
||||
pad_last = true;
|
||||
Out o = tick();
|
||||
CHECK(o.right && !o.left && !o.back && o.game_r && !pad_last); // (and the prompts show the keys)
|
||||
o = tick();
|
||||
CHECK(!o.right && !o.game_r); // (held: no second press)
|
||||
key_down['R'] = false;
|
||||
CHECK(!tick().right);
|
||||
// Shift: Back as it is let go
|
||||
key_down[VK_SHIFT] = true;
|
||||
CHECK(!tick().back);
|
||||
CHECK(!tick().back);
|
||||
key_down[VK_SHIFT] = false;
|
||||
o = tick();
|
||||
CHECK(o.back && !o.left && !o.right);
|
||||
CHECK(!tick().back);
|
||||
// Shift+Tab: no Back (the menu's own keys step back a tab)
|
||||
key_down[VK_SHIFT] = true;
|
||||
tick();
|
||||
key_down[VK_TAB] = true;
|
||||
tick();
|
||||
key_down[VK_TAB] = false, key_down[VK_SHIFT] = false;
|
||||
CHECK(!tick().back);
|
||||
// a binding waiting for its key: Shift is the key, not Back
|
||||
listening = 2;
|
||||
key_down[VK_SHIFT] = true;
|
||||
tick();
|
||||
listening = 0;
|
||||
key_down[VK_SHIFT] = false;
|
||||
CHECK(!tick().back);
|
||||
// pressed in play, let go with the menu open: no Back
|
||||
open_now.v = false;
|
||||
key_down[VK_SHIFT] = true;
|
||||
tick();
|
||||
open_now.v = true;
|
||||
key_down[VK_SHIFT] = false;
|
||||
CHECK(!tick().back);
|
||||
// Shift held as the window loses the front (Win+Shift+S, Shift+Alt+Tab): no Back, then or as it comes back
|
||||
key_down[VK_SHIFT] = true;
|
||||
tick();
|
||||
focused = false;
|
||||
CHECK(!tick().back);
|
||||
key_down[VK_SHIFT] = false;
|
||||
CHECK(!tick().back);
|
||||
focused = true;
|
||||
CHECK(!tick().back);
|
||||
// Shift with another key, a mouse button or a pad press: no Back as Shift is let go (Shift+R steps a tab only)
|
||||
static const int withs[] = {'R', 'A', VK_LBUTTON, VK_LWIN, -1};
|
||||
for (int with : withs) {
|
||||
key_down[VK_SHIFT] = key_down[VK_LSHIFT] = true;
|
||||
tick();
|
||||
if (with < 0) pad_press = 1u << HOS_PAD_NORTH;
|
||||
else key_down[with] = true;
|
||||
o = tick();
|
||||
CHECK(o.right == (with == 'R') && !o.back);
|
||||
if (with >= 0) key_down[with] = false;
|
||||
tick();
|
||||
key_down[VK_SHIFT] = key_down[VK_LSHIFT] = false;
|
||||
o = tick();
|
||||
CHECK(!o.back && !o.right);
|
||||
}
|
||||
// Shift alone, its left key read as well: still Back
|
||||
key_down[VK_SHIFT] = key_down[VK_LSHIFT] = true;
|
||||
tick();
|
||||
key_down[VK_SHIFT] = key_down[VK_LSHIFT] = false;
|
||||
CHECK(tick().back);
|
||||
// R tapped between two ticks: the host's queue has it, one tab
|
||||
queue['R'] = true;
|
||||
o = tick();
|
||||
CHECK(o.right && !queue['R']);
|
||||
CHECK(!tick().right);
|
||||
// Shift held and R tapped between two ticks: one tab, and no Back as Shift is let go
|
||||
key_down[VK_SHIFT] = true;
|
||||
tick();
|
||||
queue['R'] = true;
|
||||
o = tick();
|
||||
CHECK(o.right && !o.back);
|
||||
key_down[VK_SHIFT] = false;
|
||||
CHECK(!tick().back);
|
||||
// R down at a tick and its queued press taken at the next: one tab, not two
|
||||
key_down['R'] = true;
|
||||
CHECK(tick().right);
|
||||
queue['R'] = true;
|
||||
CHECK(!tick().right);
|
||||
key_down['R'] = false;
|
||||
CHECK(!tick().right);
|
||||
// a queued press from another window is not ours (and is taken, so it does not come later)
|
||||
focused = false, queue['R'] = true;
|
||||
CHECK(!tick().right);
|
||||
focused = true;
|
||||
CHECK(!tick().right);
|
||||
// the menu closed: our tabs take nothing, the game's tab sees its keys
|
||||
open_now.v = false;
|
||||
key_down['R'] = true;
|
||||
o = tick();
|
||||
CHECK(!o.right && o.game_r);
|
||||
key_down['R'] = false;
|
||||
tick();
|
||||
open_now.v = true;
|
||||
// a key the menu has its own use for keeps it; a mouse button is not one of the menu's keys
|
||||
bind_key[HOS_SW_R][0] = VK_RIGHT, bind_key[HOS_SW_B][0] = VK_RBUTTON;
|
||||
key_down[VK_RIGHT] = true;
|
||||
CHECK(!tick().right);
|
||||
key_down[VK_RIGHT] = false;
|
||||
tick();
|
||||
CHECK(menu_bound_key(HOS_SW_R, 0) == 0 && menu_bound_key(HOS_SW_B, 0) == 0 && menu_bound_key(HOS_SW_L, 0) == 0);
|
||||
bind_key[HOS_SW_R][1] = 'T';
|
||||
CHECK(menu_bound_key(HOS_SW_R, 1) == 'T' && menu_modifier_key(VK_SHIFT) && !menu_modifier_key('T'));
|
||||
// the gamepad: L bound to the left face button steps a tab; bound to A's button it stays A
|
||||
bind_pad[HOS_SW_L] = HOS_PAD_WEST;
|
||||
pad_press = 1u << HOS_PAD_WEST;
|
||||
CHECK(tick().left);
|
||||
bind_pad[HOS_SW_L] = pad_confirm;
|
||||
pad_press = 1u << pad_confirm;
|
||||
CHECK(!tick().left);
|
||||
// the Mods screen's search taking text: a bound R is a letter, not the next category; Shift let go alone no Back
|
||||
bind_key[HOS_SW_R][0] = 'R', bind_key[HOS_SW_R][1] = 0, bind_key[HOS_SW_B][0] = VK_SHIFT;
|
||||
bind_pad[HOS_SW_L] = HOS_PAD_WEST;
|
||||
typing_now = true;
|
||||
key_down['R'] = true;
|
||||
o = tick();
|
||||
CHECK(!o.right && !o.left && !o.back);
|
||||
key_down['R'] = false;
|
||||
queue['R'] = true;
|
||||
CHECK(!tick().right && !queue['R']); // (taken, so it does not come once the search stops taking text)
|
||||
key_down[VK_SHIFT] = true;
|
||||
tick();
|
||||
key_down[VK_SHIFT] = false;
|
||||
CHECK(!tick().back);
|
||||
pad_press = 1u << HOS_PAD_WEST; // (the gamepad input bound to L is no letter: still the categories)
|
||||
CHECK(tick().left);
|
||||
typing_now = false;
|
||||
o = tick();
|
||||
CHECK(!o.right && !o.back); // (nothing kept from the typing)
|
||||
key_down['R'] = true;
|
||||
CHECK(tick().right);
|
||||
key_down['R'] = false;
|
||||
tick();
|
||||
std::puts("ok");
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument("--cxx", default="g++")
|
||||
a = p.parse_args()
|
||||
menu = (ROOT / "gpu/vk/vk_menu.cpp").read_text(encoding="utf-8")
|
||||
ui = (ROOT / "gpu/vk/vk_ui.h").read_text(encoding="utf-8")
|
||||
api = (ROOT / "gpu/vk/vk_api.h").read_text(encoding="utf-8")
|
||||
hid = (ROOT / "host/nn_hid.c").read_text(encoding="utf-8")
|
||||
tick = function(menu, "void menu_tick() {")
|
||||
|
||||
# the guides' keys and the strip's: the bindings', else the menu's own
|
||||
glyph = function(ui, "inline float glyph(")
|
||||
check("key(x, c.key_tab_l)" in glyph and "key(x + w + gap, c.key_tab_r)" in glyph and "return key(x, c.key_back);" in glyph,
|
||||
"the guides do not name the keys the tabs and Back take")
|
||||
check('key(x, "Q")' not in glyph and 'key(x, "Esc")' not in glyph, "the guides still name Q, E and Esc whatever is bound")
|
||||
ctx = function(menu, "ui::Ctx ui_ctx(")
|
||||
check("{HOS_SW_L, HOS_SW_R, HOS_SW_B}" in ctx and "menu_bound_key(buttons[b], 0)" in ctx and '{"Q", "E", "Esc"}' in ctx
|
||||
and "c.key_tab_l = names[0], c.key_tab_r = names[1], c.key_back = names[2];" in ctx,
|
||||
"ui_ctx does not take the labels from the bindings the menu takes")
|
||||
check("const bool typing = menu_mods_typing();" in ctx and "int vk = typing ? 0 : menu_bound_key(buttons[b], 0);" in ctx,
|
||||
"the guides name the bound keys while the Mods search takes them as text")
|
||||
check("bool menu_mods_typing() { return open_now.load() && page == kModsPage && mods_text_wanted.load(" in menu,
|
||||
"menu_mods_typing is not the Mods screen's search taking text")
|
||||
tabs = function(menu, "void draw_tabs(")
|
||||
check("(i ? c.key_tab_r : c.key_tab_l)" in tabs and "!c.pad && sel < 0 && can_bind()" in tabs,
|
||||
"the strip's ends do not name the keys our tabs take (the game's own tab: its bindings)")
|
||||
controls = function(menu, "void draw_controls(")
|
||||
check('{ui::kKey, "Cancel", "Esc"}' in controls, "a binding's wait names B's key, which it would bind, for cancel")
|
||||
|
||||
# the host: a Back from a let-go modifier taps the game's Back too
|
||||
check("hos_binding(HOS_BIND_KEY, HOS_SW_B, k)" in hid and "now - b_key_ns < 300000000LL" in hid,
|
||||
"host/nn_hid.c does not tap the game's Back for our tabs left with B's key")
|
||||
# the game's own tab opens ours with the keys read every tick
|
||||
check("if (game_lr[side]) go[side] = true, pad_last = false;" in tick and "static bool key_held" not in tick,
|
||||
"the game's tab does not take its keys from the tick's reading")
|
||||
|
||||
begin = tick.index(" bool bound_go[3] = {}, game_lr[2] = {};")
|
||||
end_mark = "if (p >= 0 && p < HOS_PAD_N && !own && pad(p)) (side ? tab_right : tab_left) = true;\n }\n }\n"
|
||||
end = tick.index(end_mark, begin) + len(end_mark)
|
||||
tracker = tick[begin:end]
|
||||
check("if (!menu_mods_typing()) tab_left |= bound_go[0], tab_right |= bound_go[1], press[5] |= bound_go[2];" in tracker,
|
||||
"the bound keys are not the tabs and Back")
|
||||
# a click or the wheel with a modifier held (read after this block, with the mouse): it is no press of its own
|
||||
wheel = tick.index("if (ptr.pressed || ptr.wheel)")
|
||||
check(wheel > end and "for (auto& armed : bound_armed) armed[0] = armed[1] = false;" in tick[wheel:wheel + 200],
|
||||
"a click or the wheel does not keep a held modifier from counting as its press")
|
||||
helpers = "\n".join(function(menu, head) for head in ("bool menu_own_key(", "bool menu_modifier_key(",
|
||||
"bool menu_same_modifier(", "int menu_bound_key("))
|
||||
enums = "\n".join(enum_block(api, head) for head in ("enum { HOS_SW_A", "enum { HOS_PAD_SOUTH", "enum { HOS_BIND_PAD",
|
||||
"enum { HOS_KEY_MOVE_UP"))
|
||||
fixture = FIXTURE.replace("@ENUMS@", enums).replace("@HELPERS@", helpers).replace("@TRACKER@", tracker)
|
||||
with tempfile.TemporaryDirectory(prefix="menu-bound-keys-") as tmp:
|
||||
cpp, exe = Path(tmp) / "fixture.cpp", Path(tmp) / "fixture.exe"
|
||||
cpp.write_text(fixture, encoding="utf-8")
|
||||
subprocess.run([a.cxx, "-std=c++20", "-Wall", "-Wextra", "-Werror", "-Wno-unused-variable", str(cpp), "-o", str(exe)], check=True)
|
||||
run = subprocess.run([str(exe)], capture_output=True, text=True)
|
||||
if run.returncode or run.stdout.strip() != "ok":
|
||||
raise SystemExit("FAIL: the bound keys in the menu (exit %d)\n%s%s" % (run.returncode, run.stdout, run.stderr))
|
||||
print("PASS: the tabs and Back take the keys bound to L, R and B, and the guides and the strip name them")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -51,10 +51,11 @@ def sources():
|
||||
down = down[:down.index("return 0;")]
|
||||
if "if (menu_open)" not in down or "else if (renderer && !mouse_captured) mouse_capture(w, 1);" not in down:
|
||||
raise SystemExit("display.c: a click with the menu open captures the mouse")
|
||||
# ((Triforce) a toggle's halves: split where halves_cell draws them meeting, on both pages that draw them; a half picks)
|
||||
# ((Triforce) a toggle's halves: split where halves_cell draws them meeting, on the tabs' rows (the Debug tab's among
|
||||
# them since 11-17: one loop draws every tab); a half picks)
|
||||
if "float halves_meet(ImVec2 a, ImVec2 b)" not in menu or "const float xm = halves_meet(a, b);" not in menu:
|
||||
raise SystemExit("the menu's toggles are not split for the mouse where they are drawn to meet")
|
||||
if len(re.findall(r"hits\.add\([^;]*menu_hit::kRow[^;]*, vm\);", menu)) != 2:
|
||||
if len(re.findall(r"hits\.add\([^;]*menu_hit::kRow[^;]*, vm\);", menu)) != 1:
|
||||
raise SystemExit("a page of rows records its toggles without where their halves meet")
|
||||
if "if (*d.value != (hit.side < 0 ? d.hi : d.lo)) press[4] = true;" not in menu:
|
||||
raise SystemExit("a click on a toggle's half does not pick that value")
|
||||
@@ -65,7 +66,7 @@ def sources():
|
||||
raise SystemExit("draw_game_tab does not record the tabs it draws over the game's header")
|
||||
embed = menu[menu.index("if (in_game_options && !open_now.load()) {"):]
|
||||
embed = embed[:embed.index("tab_left = tab_right = false;")]
|
||||
for need in ("host->pointer(&gp)", "hits.at((float)(ix - (int)game_tab_ox), (float)iy)", "if (!game_tab_read) gp.pressed = 0",
|
||||
for need in ("host->pointer(&gp)", "hits.at(game_tab_map.back_x((float)ix), game_tab_map.back_y((float)iy))", "if (!game_tab_read) gp.pressed = 0",
|
||||
"clicked_tab = hover_tab", "cur_tab = clicked_tab >= 0 ? clicked_tab"):
|
||||
if need not in embed:
|
||||
raise SystemExit("the game's own tab does not take the mouse on our tabs: " + need)
|
||||
|
||||
@@ -147,7 +147,7 @@ def main():
|
||||
need(tick, r'"PADS", "PADE", "PADW", "PADN".*?press\[5\] \|= p == pad_back, press\[7\] \|= p == pad_confirm',
|
||||
"RX_VK_MENU_SCRIPT's pad presses do not go through the same mapping")
|
||||
# (the page links on the tabs: confirm opens them)
|
||||
need(tick, r"else if \(r\.cheat >= 0\) cheat_press\(r\.cheat, press, changed\)", "the debug tools' rows do not act on the Debug tab")
|
||||
need(tick, r"if \(r\.cheat >= 0\) cheat_press\(r\.cheat, press, changed\)", "the debug tools' rows do not act on the Debug tab")
|
||||
need(tick, r"press\[7\] && is_motion_row\(r\)\) cur_tab = TAB_MOTION", "Motion does not open on confirm")
|
||||
need(tick, r"press\[7\] && !r\.value && can_bind\(\)\) page = 1", "Controls does not open on confirm")
|
||||
need(tick, r"press\[5\] && cur_tab == TAB_MOTION\) cur_tab = TAB_CONTROLS", "back does not leave the Motion page")
|
||||
|
||||
@@ -78,8 +78,11 @@ def function(source, start):
|
||||
|
||||
def sources():
|
||||
menu = (ROOT / "gpu" / "vk" / "vk_menu.cpp").read_text(encoding="utf-8")
|
||||
for row in ('"GPU device", &opts.gpu_device', '"Output resolution", &opts.output_res', '"Handheld profile", &opts.handheld',
|
||||
'"Ultrawide", &opts.ultrawide', '"Robust buffers", &opts.robust'):
|
||||
# ((Triforce, options_version 7) the handheld profile is an Output resolution; the merged rows take a restart for what of
|
||||
# them is read at the start: restart_value_of)
|
||||
for row in ('"GPU device", &opts.gpu_device', '"Output resolution", &opts.output_res', '"Aspect ratio", &opts.ultrawide',
|
||||
'"Robust buffers", &opts.robust', '"HDR", &merged.hdr', '"Frame generation", &merged.framegen',
|
||||
'"Frame pacing", &merged.pacing'):
|
||||
at = menu.find(row)
|
||||
if at < 0:
|
||||
raise SystemExit("vk_menu.cpp: a row that takes a restart is missing: " + row)
|
||||
|
||||
@@ -26,7 +26,7 @@ def main():
|
||||
raise SystemExit("FAIL: %d rows take a restart (%s), menu_restart.h kMax is %d" % (len(restart), ", ".join(restart), kmax))
|
||||
if re.search(r"restart_state\.start\[restart_slot_of\(", menu):
|
||||
raise SystemExit("FAIL: vk_menu.cpp indexes restart_state.start with a slot that can be -1: use restart_changed")
|
||||
if "slot >= 0 && *r.value != restart_state.start[slot]" not in menu:
|
||||
if "slot >= 0 && restart_value_of(r) != restart_state.start[slot]" not in menu:
|
||||
raise SystemExit("FAIL: restart_changed does not skip a row with no slot")
|
||||
print("PASS: %d rows take a restart, %d slots" % (len(restart), kmax))
|
||||
|
||||
|
||||
@@ -151,12 +151,18 @@ int main() {
|
||||
CHECK(sound_of(on_page(rows(2, 0), 5), closed(), In().confirm_()) == kDecide);
|
||||
std::puts("sound_of: NX2navi's mapping, the game's own Options screen, the pages and modes");
|
||||
|
||||
/* the queue: one of the seven, in order; 16 wait, a 17th is dropped; a stale one is not played */
|
||||
/* the queue: one of the sounds (1 to kLast), in order; 16 wait, a 17th is dropped; a stale one is not played */
|
||||
Queue q;
|
||||
CHECK(!q.put(kNone, 0) && !q.put(-1, 0) && !q.put(kTabRight + 1, 0) && q.take(0) == kNone);
|
||||
for (int i = 0; i < kQueue; i++) CHECK(q.put(1 + i % 7, 1000));
|
||||
CHECK(!q.put(kNone, 0) && !q.put(-1, 0) && !q.put(kLast + 1, 0) && q.take(0) == kNone);
|
||||
for (int i = 0; i < kQueue; i++) CHECK(q.put(1 + i % kLast, 1000));
|
||||
CHECK(!q.put(kOpen, 1000));
|
||||
for (int i = 0; i < kQueue; i++) CHECK(q.take(2000) == 1 + i % 7);
|
||||
for (int i = 0; i < kQueue; i++) CHECK(q.take(2000) == 1 + i % kLast);
|
||||
CHECK(q.take(2000) == kNone);
|
||||
/* ((Triforce) 11-19) the Mods entry's and screen's own: the system menu's cursor and decide, and the fanfare, are queued
|
||||
and taken as the others are (they were dropped: the entry under the title's list made no sound) */
|
||||
CHECK(kFanfare == kTabRight + 1 && kSysCursor == kFanfare + 1 && kSysDecide == kSysCursor + 1 && kLast == kSysDecide);
|
||||
CHECK(q.put(kSysCursor, 1000) && q.put(kSysDecide, 1000) && q.put(kFanfare, 1000));
|
||||
CHECK(q.take(1000) == kSysCursor && q.take(1000) == kSysDecide && q.take(1000) == kFanfare);
|
||||
CHECK(q.take(2000) == kNone);
|
||||
CHECK(q.put(kCursor, 0) && q.put(kDecide, kStaleNs) && q.put(kCancel, kStaleNs + 10));
|
||||
CHECK(q.take(kStaleNs + 1) == kDecide); /* (the cursor a quarter second and more ago: dropped) */
|
||||
@@ -259,6 +265,13 @@ def main():
|
||||
"if (id == HOS_OPT_MENU_SOUND_VOLUME) return std::clamp(opts.menu_sounds, 0, 100);" in replay,
|
||||
"the renderer does not answer the host's two options: the sounds asked for, the Menu sounds row")
|
||||
check("static_assert(menu_sound::kOpen == HOS_MENU_SOUND_OPEN" in menu, "vk_menu.cpp does not hold the sounds against vk_api.h's")
|
||||
# ((Triforce) 11-19: the Mods entry's sounds, the system menu's, are the queue's too, and held against vk_api.h's)
|
||||
check("menu_sound::kSysCursor == HOS_MENU_SOUND_SYS_CURSOR" in menu and "menu_sound::kSysDecide == HOS_MENU_SOUND_SYS_DECIDE" in menu
|
||||
and "menu_sound::kFanfare == HOS_MENU_SOUND_FANFARE" in menu and "menu_sound::kLast + 1 == HOS_MENU_SOUND_N" in menu,
|
||||
"vk_menu.cpp does not hold the Mods entry's sounds (the fanfare, the system menu's cursor and decide) against vk_api.h's")
|
||||
events = (vk / "menu_sound_events.h").read_text(encoding="utf-8")
|
||||
check("if (sound <= kNone || sound > kLast) return false;" in events,
|
||||
"the sounds' queue does not take every sound up to kLast (the Mods entry's are dropped)")
|
||||
|
||||
# (the row: under Master volume on the Audio tab, its default, its line in the readme and the options file's table)
|
||||
row = re.search(r'\{TAB_AUDIO, "Menu sounds", &opts\.menu_sounds, 0, 100, 5, tx_menu_sounds,\s*"[^{}]*?", nullptr, false, true\},',
|
||||
@@ -279,7 +292,7 @@ def main():
|
||||
.replace("@TEXT@", block(menu, "const char* tx_percent(int v) {") + "\n" +
|
||||
re.search(r"const char\* tx_menu_sounds\(int v\) \{[^\n]*\}", menu).group(0)) \
|
||||
.replace("@ROW@", row.group(0)) \
|
||||
.replace("@INI@", block(menu, "bool ini_row(") + "\n" + block(menu, "const char* ini_key(")) \
|
||||
.replace("@INI@", "bool is_merged(const int*) { return false; } /* ((Triforce, options_version 7) no merged row here */\n" + block(menu, "bool ini_row(") + "\n" + block(menu, "const char* ini_key(")) \
|
||||
.replace("@LOOP@", loop)
|
||||
with tempfile.TemporaryDirectory(prefix="menu-sound-events-") as tmp:
|
||||
run(a.cxx, EVENTS.replace("@ROOT@", ROOT.as_posix()), "events.cpp", tmp, [] if os.name == "nt" else ["-pthread"])
|
||||
|
||||
164
tests/test_menu_vanilla_look.py
Normal file
164
tests/test_menu_vanilla_look.py
Normal file
@@ -0,0 +1,164 @@
|
||||
"""The options menu drawn as the game's own Options screen looks (gpu/vk/vk_game_tex.h, vk_ui.h, vk_menu.cpp; no game).
|
||||
|
||||
The colours are the game's layouts' own (UI/Layout2Archive/Common.*.blarc: each pane's material has a white and a black
|
||||
colour, linear, and its texture picks between them), written into vk_game_tex.h and vk_ui.h as numbers. This compiles
|
||||
vk_game_tex.h's makers with made-up textures and checks what they give against the game's Options screen as measured:
|
||||
|
||||
- the chosen value's orange plate is 212,145,37 where its texture is white (measured 211,144,37), darker where the
|
||||
texture is grey, as the game's: not the texture times one colour, which made its middle 168,115,29;
|
||||
- the value's dark panel, the chosen tab's plate and a mask (white) take their white colour where the texture is white
|
||||
and their black colour where it is black, the texture's alpha kept;
|
||||
- a row's plate is darker at its rim (98,74,37 measured) than in its middle (111,84,44), where the grain texture is
|
||||
white and dark: the browns ran the other way before;
|
||||
- the standalone background's shade is shrunk without changing its mean.
|
||||
|
||||
And reads the source for what only the game shows: inside the game's own Options screen nothing dims the game's own
|
||||
background and only the opaque middle of the column is drawn over the game's identical one (its soft edges stay single);
|
||||
over play the System screens' shade and noise, or the flat dim without them; the two textures that needs are optional,
|
||||
so a romfs without them keeps the rest of the game's look; the plates, the tab and the separator use the layouts'
|
||||
colours.
|
||||
|
||||
python -I -B tests/test_menu_vanilla_look.py [--cxx clang++]
|
||||
"""
|
||||
import argparse
|
||||
import re
|
||||
import subprocess
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
VK = ROOT / "gpu" / "vk"
|
||||
RUN_ALL_ARGS = ["--cxx", "{cxx}"]
|
||||
|
||||
|
||||
def check(ok, why):
|
||||
if not ok:
|
||||
raise SystemExit("FAIL: " + why)
|
||||
|
||||
|
||||
def function(text, head):
|
||||
start = text.index(head)
|
||||
end = text.index("{", start) + 1
|
||||
depth = 1
|
||||
while depth:
|
||||
depth += (text[end] == "{") - (text[end] == "}")
|
||||
end += 1
|
||||
return text[start:end]
|
||||
|
||||
|
||||
PROGRAM = r"""
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include "vk_game_tex.h"
|
||||
using namespace mkwvk::game_tex;
|
||||
static int fails = 0;
|
||||
static void near(const unsigned char* px, int r, int g, int b, int a, int tol, const char* what) {
|
||||
if (std::abs(px[0] - r) > tol || std::abs(px[1] - g) > tol || std::abs(px[2] - b) > tol || px[3] != a) {
|
||||
std::printf("FAIL: %s: %d,%d,%d,%d, not %d,%d,%d,%d\n", what, px[0], px[1], px[2], px[3], r, g, b, a);
|
||||
fails++;
|
||||
}
|
||||
}
|
||||
static Image grey(std::initializer_list<int> values, bool srgb, int alpha = 255) {
|
||||
Image im;
|
||||
im.w = (uint32_t)values.size(), im.h = 1, im.srgb = srgb;
|
||||
for (int v : values) im.rgba.insert(im.rgba.end(), {(unsigned char)v, (unsigned char)v, (unsigned char)v, (unsigned char)alpha});
|
||||
return im;
|
||||
}
|
||||
int main() {
|
||||
// the chosen value's plate (W_CheckL_00): white texel the white colour, the measured orange; grey darker, as the game's
|
||||
const Image el = grey({255, 203, 0}, true);
|
||||
const Image on = make_tinted(el, kValueOnBlack, kValueOnWhite);
|
||||
near(&on.rgba[0], 211, 144, 37, 255, 1, "the orange plate where its texture is white");
|
||||
near(&on.rgba[4], 191, 126, 31, 255, 2, "the orange plate where its texture is 203 (its middle)");
|
||||
near(&on.rgba[8], 153, 89, 19, 255, 1, "the orange plate where its texture is black");
|
||||
// the value's dark panel (W_Base_01) and the tab (P_PlusMenuBg_00)
|
||||
const Image panel = make_tinted(el, kValueBlack, kValueWhite);
|
||||
near(&panel.rgba[0], 15, 14, 11, 255, 1, "the value's panel where its texture is white");
|
||||
near(&panel.rgba[8], 51, 45, 27, 255, 1, "the value's panel where its texture is black");
|
||||
const Image tab = make_tinted(grey({255, 0}, true, 128), kTabBlack, kTabWhite);
|
||||
near(&tab.rgba[0], 146, 113, 66, 128, 1, "the tab's plate where its texture is white (its alpha kept)");
|
||||
near(&tab.rgba[4], 50, 13, 0, 128, 1, "the tab's plate where its texture is black");
|
||||
// a mask (BC4: white, its strength in alpha) is its white colour
|
||||
Image mask = grey({255}, false, 77);
|
||||
near(&make_tinted(mask, kValueOnBlack, kValueOnWhite).rgba[0], 212, 145, 37, 77, 1, "a mask tinted");
|
||||
// a row's plate: the grain white at the rim, dark in the middle; the line over it where its mask is
|
||||
Image shape = grey({255, 255, 255}, true), grain = grey({250, 80, 0}, true), line = grey({255, 255, 255}, false, 0);
|
||||
line.rgba[2 * 4 + 3] = 255;
|
||||
const Image plate = make_plate(shape, grain, &line, kPlateBlack, kPlateWhite, kPlateLine);
|
||||
near(&plate.rgba[0], 98, 74, 37, 255, 2, "a row's plate at its rim (the grain white)");
|
||||
near(&plate.rgba[4], 111, 84, 44, 255, 2, "a row's plate in its middle (the grain dark)");
|
||||
near(&plate.rgba[8], 124, 104, 62, 255, 1, "a row's plate under its line");
|
||||
if (plate.rgba[0] >= plate.rgba[4]) std::printf("FAIL: the plate's rim is not darker than its middle\n"), fails++;
|
||||
// the shade shrunk: each texel its block's mean
|
||||
Image big;
|
||||
big.w = 8, big.h = 4, big.mask = true;
|
||||
big.rgba.assign(8 * 4 * 4, 255);
|
||||
for (int i = 0; i < 32; i++) big.rgba[i * 4 + 3] = (unsigned char)((i % 8) < 4 ? 0 : 200);
|
||||
const Image small = shrink_mask(big, 4);
|
||||
if (small.w != 2 || small.h != 1 || small.rgba[3] != 0 || small.rgba[7] != 200 || !small.mask)
|
||||
std::printf("FAIL: shrink_mask: %ux%u %d %d\n", small.w, small.h, small.rgba[3], small.rgba[7]), fails++;
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--cxx", default="clang++")
|
||||
args = parser.parse_args()
|
||||
tex = (VK / "vk_game_tex.h").read_text(encoding="utf-8")
|
||||
ui = (VK / "vk_ui.h").read_text(encoding="utf-8")
|
||||
menu = (VK / "vk_menu.cpp").read_text(encoding="utf-8")
|
||||
|
||||
# the background: inside the game's Options screen, its own; over play, the System screens' shade and noise
|
||||
# (v0.5.1: draw_menu takes perf_under, and over the Mods entry (row) dims nothing)
|
||||
draw = function(menu, "void draw_menu(ui::Ctx& c, bool perf_under) {")
|
||||
check("if (!embed_open && !row && !ui::system_bg(c)) c.d->AddRectFilled(" in draw,
|
||||
"draw_menu dims the game's own Options screen, or not the System screens' way over play")
|
||||
check(draw.count("AddRectFilled(ImVec2(0, 0), ImVec2(c.w, c.h)") == 1, "draw_menu dims the window more than once")
|
||||
check("ui::column_bg(k, cx0, cx1, k.over_game);" in draw and "k.over_game = embed_open;" in draw,
|
||||
"over the game's Options screen the column is not only its opaque middle")
|
||||
column = function(ui, "inline void column_bg(")
|
||||
check("60.0f / 1440" in column and "1380.0f / 1440" in column and "PushClipRect(clip0, clip1, true)" in column,
|
||||
"column_bg's inner part is not the texture's opaque middle")
|
||||
check("at(c, 0, 1240 + 2500)" in column and "at(c, 0, 1240 - 2500)" in column and "lu(c, 20)" in column,
|
||||
"column_bg is not P_OptionBg_00's place (2240 x 5000 units, 1240 up, seen through S_Scissor_00)")
|
||||
bg = function(ui, "inline bool system_bg(")
|
||||
check('art("SystemBgSh_00")' in bg and 'art("DecoNoise_00")' in bg and "return false;" in bg, "system_bg does not fall back")
|
||||
check("kNoiseAlpha = 102, kShadeAlpha = 179;" in ui, "the shade and the noise are not the layout's 0.7 and 0.4")
|
||||
check("kBgNoise = rgba(28, 13, 13)" in ui and "kSeparator = rgba(75, 57, 34)" in ui and "kInk = rgba(255, 254, 228)" in ui,
|
||||
"vk_ui.h's colours are not the layouts' own")
|
||||
# (v0.5.1: the colour is a parameter, the performance overlay asks for its own; kSeparator is its default)
|
||||
check("ImU32 col = kSeparator, ImU32 line_col = 0) {" in ui, "the separator is not the layout's colour")
|
||||
|
||||
# the skin: the two background textures optional; the baked plates made and used
|
||||
skin = function(tex, "inline bool make_skin(")
|
||||
names = re.search(r"names\[\] = \{(.*?)\};", skin, re.S).group(1)
|
||||
optional = re.search(r"optional\[\] = \{(.*?)\};", skin, re.S).group(1)
|
||||
check("SystemBgSh_00" not in names and "DecoNoise_00" not in names, "a background texture is a required one")
|
||||
check('"SystemBgSh_00", "DecoNoise_00"' in optional, "the background textures are not the optional ones")
|
||||
loop = skin[skin.index("for (const char* n : optional)"):]
|
||||
loop = loop[:loop.index("\n }\n") + 6]
|
||||
check("continue;" in loop and "return false" not in loop, "a missing optional texture throws the skin away")
|
||||
for made in ('"value_plate", make_tinted(*element, kValueBlack, kValueWhite)',
|
||||
'"value_plate_on", make_tinted(*element, kValueOnBlack, kValueOnWhite)',
|
||||
'"tab_select", make_tinted(*tab, kTabBlack, kTabWhite)',
|
||||
'"plate_row", make_plate(*shape, *grain, skin.get("BtnThinBase_04"), kPlateBlack, kPlateWhite, kPlateLine)'):
|
||||
check(made in skin, "make_skin does not make " + made.split(",")[0])
|
||||
plate = function(ui, "inline void value_plate(")
|
||||
check('art(on ? "value_plate_on" : "value_plate")' in plate and "alpha(IM_COL32_WHITE, k)" in plate,
|
||||
"value_plate does not draw the baked plates untinted")
|
||||
check('ui::art("tab_select")) ui::image(c, t, a, b);' in function(menu, "void draw_tabs("), "the chosen tab is not the baked plate")
|
||||
|
||||
with tempfile.TemporaryDirectory(prefix="vanilla-look-") as tmp:
|
||||
src, exe = Path(tmp) / "look.cpp", Path(tmp) / "look.exe"
|
||||
src.write_text(PROGRAM, encoding="utf-8")
|
||||
inc = [VK, ROOT / "gpu" / "third_party" / "suyu", VK / "compat", ROOT / "gpu" / "compat"]
|
||||
subprocess.run([args.cxx, "-std=c++20", "-O1", "-w", *("-I" + str(p) for p in inc), str(src), "-o", str(exe)], check=True)
|
||||
r = subprocess.run([str(exe)], capture_output=True, text=True)
|
||||
check(r.returncode == 0, "the colours as made:\n" + r.stdout)
|
||||
print("PASS: the menu's plates, tab, separator and background in the game's layouts' colours")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
438
tests/test_merged_rows.py
Normal file
438
tests/test_merged_rows.py
Normal file
@@ -0,0 +1,438 @@
|
||||
"""The Insert menu's options_version 7 (Triforce): the rows grouped, the rows that chose one thing twice merged into one
|
||||
(gpu/vk/merged_rows.h), the rows whose job is done otherwise gone. An options file from before must play the same.
|
||||
|
||||
Checked without a game or a GPU:
|
||||
- merged_rows.h's views and their writes back, over every saved value they stand for: HDR (hdr, renodx_hdr), Frame
|
||||
generation (frame_generation, dlss_frame_generation), Frame pacing (frame_pacing, steady_frame_rate), Low latency
|
||||
(nvidia_reflex or amd_anti-lag_2 by the card's maker), and its migration (handheld_profile, stick_dead_zone);
|
||||
- the menu's own row table, ini_key, ini_row and menu_init's reading of the file, compiled with stand-ins and fed a copy of
|
||||
an owner's options file of version 6 (an RX 7900 XT: HDR Native with RenoDX, AMD FSR 4 at Performance, Upscale before
|
||||
bloom, 21:9, Frame pacing on): every value lands where it did, the merged rows show what ran (Native + RenoDX, Frame
|
||||
pacing Even, Low latency Off), no line of the file is lost unless merged_rows.h drops it, no two rows save one key, the
|
||||
readers before the menu still find their keys, and the file the menu then writes reads back to the same values.
|
||||
|
||||
python -I -B tests/test_merged_rows.py [--cxx g++]
|
||||
"""
|
||||
import argparse
|
||||
import re
|
||||
import subprocess
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
RUN_ALL_ARGS = ["--cxx", "g++"]
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
VK = ROOT / "gpu" / "vk"
|
||||
|
||||
# (a copy of an owner's triforce_options.ini as version 6 wrote it, without the controls' pad_ and key_ lines)
|
||||
OWNER = """fullscreen=1
|
||||
output_res=1
|
||||
ultrawide=2
|
||||
ultrawide_hud=0
|
||||
ultrawide_menus=1
|
||||
hdr=2
|
||||
hdr_paper_white=200
|
||||
hdr_peak_brightness=1000
|
||||
renodx_hdr=1
|
||||
renodx_tonemapper=1
|
||||
renodx_gamma_correction=0
|
||||
renodx_midgray=1
|
||||
renodx_match_tone_slope=1
|
||||
renodx_tone_slope=50
|
||||
renodx_hue_clip=50
|
||||
renodx_ui_brightness=200
|
||||
renodx_color_space=2
|
||||
renodx_exposure=100
|
||||
renodx_highlights=50
|
||||
renodx_shadows=50
|
||||
renodx_contrast=50
|
||||
renodx_saturation=50
|
||||
renodx_highlight_saturation=50
|
||||
renodx_blowout=0
|
||||
renodx_flare=0
|
||||
renodx_hue_correction=100
|
||||
renodx_color_grading=100
|
||||
renodx_bloom=50
|
||||
frame_rate_cap=5
|
||||
steady_frame_rate=0
|
||||
reflex_frame_limit=0
|
||||
vsync=0
|
||||
fps_counter=2
|
||||
gpu_device=0
|
||||
quality_preset=0
|
||||
dlss=4
|
||||
dlss_model=0
|
||||
upscale_before_bloom=1
|
||||
resolution=4
|
||||
anti-aliasing=0
|
||||
upscaling=0
|
||||
sharpness=0
|
||||
texture_filtering=0
|
||||
texture_detail=0
|
||||
frame_generation=0
|
||||
dlss_frame_generation=0
|
||||
frame_pacing=1
|
||||
nvidia_reflex=2
|
||||
amd_anti-lag_2=0
|
||||
handheld_profile=0
|
||||
robust_buffers=0
|
||||
game_speed=1
|
||||
text_speed=0
|
||||
master_volume=100
|
||||
menu_sounds=80
|
||||
audio_output=0
|
||||
microphone=1
|
||||
discord_status=1
|
||||
controller_in_background=0
|
||||
mouse_camera=0
|
||||
mouse_sensitivity=100
|
||||
invert_mouse_vertical=0
|
||||
camera_speed=100
|
||||
invert_camera_x=0
|
||||
invert_camera_y=0
|
||||
sprint_button=0
|
||||
sprint_mode=0
|
||||
stick_dead_zone=0
|
||||
left_stick_dead_zone=-1
|
||||
right_stick_dead_zone=-1
|
||||
rumble_strength=100
|
||||
vibration_curve=100
|
||||
trigger_vibration=0
|
||||
walk_key=0
|
||||
walk_scale=51
|
||||
motion_controls=1
|
||||
motion_sensitivity_x=100
|
||||
motion_sensitivity_y=100
|
||||
invert_motion_x=0
|
||||
invert_motion_y=0
|
||||
motion_deadzone=1
|
||||
layout_preset=0
|
||||
button_prompts=0
|
||||
menu_shortcut=0
|
||||
debug_tools=0
|
||||
descriptor_reuse=1
|
||||
fast_pipeline_link=1
|
||||
sampler_cache=1
|
||||
lazy_write-back=1
|
||||
replay_helper_threads=8
|
||||
tail_early=1
|
||||
opaque_textures_as_bc1=1
|
||||
options_version=6
|
||||
"""
|
||||
|
||||
# (the keys read before the menu, by the code that needs them: host/*.c hos_ini_option and line reads, vk_dlssg.cpp,
|
||||
# vk_main.cpp, vk_draw.cpp menu_env_on, vk_memory.cpp, vk_replay.cpp, vk_texture.cpp)
|
||||
READ_BEFORE = ["output_res", "frame_rate_cap", "hdr", "renodx_hdr", "steady_frame_rate", "ultrawide", "ultrawide_hud", "sprint_button",
|
||||
"sprint_mode", "master_volume", "camera_speed", "audio_output", "button_prompts", "dlss_frame_generation",
|
||||
"robust_buffers", "descriptor_reuse", "sampler_cache", "fast_pipeline_link", "lazy_write-back", "tail_early"]
|
||||
|
||||
MERGED = r"""
|
||||
#include <cstdio>
|
||||
#include <initializer_list>
|
||||
#include "@VK@/merged_rows.h"
|
||||
#define CHECK(x) do { if (!(x)) { std::fprintf(stderr, "FAIL:%d %s\n", __LINE__, #x); return 1; } } while (0)
|
||||
namespace mr = mkwvk::merged_rows;
|
||||
int main() {
|
||||
/* HDR: every saved pair has its view, and the view written back is the same pair where RenoDX runs */
|
||||
for (int hdr = 0; hdr <= 2; hdr++)
|
||||
for (int renodx = 0; renodx <= 1; renodx++) {
|
||||
const int row = mr::hdr_row(hdr, renodx);
|
||||
CHECK(row == (hdr == 2 && renodx ? mr::HDR_RENODX : hdr));
|
||||
int h = -1, r = -1;
|
||||
mr::hdr_set(row, h, r);
|
||||
CHECK(h == hdr && (r == renodx || hdr != 2)); /* (RenoDX off with Off and Expanded: it ran only with Native) */
|
||||
}
|
||||
for (int row = 0; row <= 3; row++) {
|
||||
int h = 0, r = 0;
|
||||
mr::hdr_set(row, h, r);
|
||||
CHECK(mr::hdr_row(h, r) == row);
|
||||
}
|
||||
/* Frame generation: the renderer's own and AMD FSR 4's, then NVIDIA DLSS 2x to 4x; one sets the other off */
|
||||
for (int fg = 0; fg <= 9; fg++)
|
||||
for (int dlssg = 0; dlssg <= 3; dlssg++)
|
||||
CHECK(mr::framegen_row(fg, dlssg) == (dlssg ? mr::FG_DLSS + dlssg - 1 : fg));
|
||||
for (int row = 0; row <= mr::FG_DLSS_LAST; row++) {
|
||||
int fg = 5, dlssg = 2;
|
||||
mr::framegen_set(row, fg, dlssg);
|
||||
CHECK(mr::framegen_row(fg, dlssg) == row && (row < mr::FG_DLSS ? dlssg == 0 && fg == row : fg == 0 && dlssg == row - 9));
|
||||
}
|
||||
int list[16];
|
||||
CHECK(mr::framegen_choices(list, false, false) == 9 && list[8] == 8);
|
||||
CHECK(mr::framegen_choices(list, true, false) == 10 && list[9] == 9);
|
||||
CHECK(mr::framegen_choices(list, true, true) == 13 && list[10] == mr::FG_DLSS && list[12] == mr::FG_DLSS_LAST);
|
||||
CHECK(mr::framegen_choices(list, false, true) == 12 && list[9] == mr::FG_DLSS);
|
||||
/* Frame pacing: Off, Even, Steady (any rate), Steady (refresh steps) */
|
||||
for (int pace = 0; pace <= 1; pace++)
|
||||
for (int steady = 0; steady <= 2; steady++)
|
||||
CHECK(mr::pacing_row(pace, steady) == (steady ? 1 + steady : pace));
|
||||
for (int row = 0; row <= 3; row++) {
|
||||
int pace = -1, steady = -1;
|
||||
mr::pacing_set(row, pace, steady);
|
||||
CHECK(mr::pacing_row(pace, steady) == row && pace == (row != 0) && steady == (row >= 2 ? row - 1 : 0));
|
||||
}
|
||||
/* Low latency: Reflex's three on an NVIDIA card, Anti-Lag 2's two on an AMD one, the other vendor's value left alone */
|
||||
for (int v = 0; v <= 2; v++) {
|
||||
int reflex = 1, antilag = 1;
|
||||
mr::latency_set(v, mr::LATENCY_NVIDIA, reflex, antilag);
|
||||
CHECK(reflex == v && antilag == 1 && mr::latency_row(mr::LATENCY_NVIDIA, reflex, antilag) == v);
|
||||
reflex = 2, antilag = 0;
|
||||
mr::latency_set(v, mr::LATENCY_AMD, reflex, antilag);
|
||||
CHECK(reflex == 2 && antilag == (v > 0) && mr::latency_row(mr::LATENCY_AMD, reflex, antilag) == (v > 0));
|
||||
}
|
||||
CHECK(mr::latency_hi(mr::LATENCY_NVIDIA) == 2 && mr::latency_hi(mr::LATENCY_AMD) == 1 && mr::latency_hi(mr::LATENCY_NONE) == 0);
|
||||
CHECK(mr::latency_row(mr::LATENCY_NONE, 2, 1) == 0);
|
||||
/* step_in: wraps, and a value that is not a choice steps to its neighbours */
|
||||
const int some[] = {0, 1, 2, 10, 11};
|
||||
CHECK(mr::step_in(some, 5, 0, 1) == 1 && mr::step_in(some, 5, 11, 1) == 0 && mr::step_in(some, 5, 0, -1) == 11);
|
||||
CHECK(mr::step_in(some, 5, 9, 1) == 10 && mr::step_in(some, 5, 9, -1) == 2 && mr::step_in(some, 5, 12, 1) == 0);
|
||||
/* the migration: the handheld profile, the shared dead zone; nothing for a file of version 8 (v0.5.1's 7 still had the
|
||||
rows: it is moved too) */
|
||||
for (int version : {0, 5, 6, 7, 8}) {
|
||||
mr::Before7 old;
|
||||
old.handheld = 1, old.stick_shared = 3;
|
||||
int out = 1, l = -1, r = 20;
|
||||
mr::migrate(version, old, out, l, r);
|
||||
CHECK(version >= 8 ? out == 1 && l == -1 : out == mr::kHandheldOutput && l == 15);
|
||||
CHECK(r == 20);
|
||||
old = mr::Before7{};
|
||||
out = 2, l = -1, r = -1;
|
||||
mr::migrate(version, old, out, l, r);
|
||||
CHECK(out == 2 && l == -1 && r == -1);
|
||||
}
|
||||
std::puts("merged rows: views, writes back, choices and the migration: all checks passed");
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
LOAD = r"""
|
||||
#define NOMINMAX
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <set>
|
||||
#include <string>
|
||||
#ifdef _WIN32
|
||||
#include <windows.h>
|
||||
#endif
|
||||
#include "@VK@/vk_api.h"
|
||||
#include "@VK@/upscaler_rows.h"
|
||||
#include "@VK@/aa_rows.h"
|
||||
#include "@VK@/framegen_rows.h"
|
||||
#include "@VK@/merged_rows.h"
|
||||
#include "@VK@/ultrawide_rows.h"
|
||||
#include "@VK@/replay_threads.h"
|
||||
#include "@VK@/ini_merge.h"
|
||||
#define CHECK(x) do { if (!(x)) { std::fprintf(stderr, "FAIL:%d %s\n", __LINE__, #x); return 1; } } while (0)
|
||||
namespace mkwvk {
|
||||
@OPTIONS@
|
||||
Options opts;
|
||||
namespace ur = upscaler_rows;
|
||||
namespace mr7 = merged_rows;
|
||||
@TABS@
|
||||
@ROW@
|
||||
@OUT@
|
||||
@STUBS@
|
||||
constexpr int kMaxMics = 16;
|
||||
constexpr char kModCheatHelp[] = "";
|
||||
struct { char names[96][8]; } mod_cheats;
|
||||
@MOD_ROWS@
|
||||
@MERGED@
|
||||
@TABLE@
|
||||
constexpr int kRows = sizeof rows / sizeof rows[0];
|
||||
@INI_KEY@
|
||||
@INI_ROW@
|
||||
/* (stand-ins for what menu_init's reading touches besides the rows) */
|
||||
std::string path;
|
||||
std::string ini_path() { return path; }
|
||||
ini_merge::Map ini_base;
|
||||
std::string mic_want;
|
||||
std::string mic_key(const char* name) { return name; }
|
||||
void refresh_mics() {}
|
||||
void mic_tell_host() {}
|
||||
int rumble_step(int v) { return (std::min(std::max(v, 0), 300) + 12) / 25 * 25; }
|
||||
int hdr_at_start, renodx_at_start, upscale_pre_at_start, tex_detail_at_start, tex_bc1_at_start, replay_threads_at_start;
|
||||
bool has_options = false;
|
||||
void load() {
|
||||
@LOAD@
|
||||
}
|
||||
/* (the card's maker for Low latency: an AMD card, as the owner's) */
|
||||
mr7::Vendor latency_vendor() { return mr7::LATENCY_AMD; }
|
||||
@SYNC@
|
||||
@RESTART@
|
||||
} // namespace mkwvk
|
||||
using namespace mkwvk;
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
if (argc < 3) return 2;
|
||||
path = argv[1];
|
||||
load();
|
||||
merged_sync();
|
||||
/* what ran before runs: HDR Native with RenoDX, AMD FSR 4 at its Performance mode (resolution 4, 50%), Upscale before
|
||||
bloom, 21:9 with the menus' sides blurred, a cap of 240, VSync off, the FPS counter Full, the frames paced evenly, no
|
||||
frame generation; AMD Anti-Lag 2 off */
|
||||
CHECK(opts.hdr == 2 && opts.renodx == 1 && merged.hdr == mr7::HDR_RENODX);
|
||||
CHECK(opts.dlss == ur::FSR4 && ur::engine(opts.dlss) == ur::FSR4 && !ur::full_scale(opts.dlss));
|
||||
CHECK(opts.resolution == 4 && ur::percent(opts.resolution) == 50 && !std::strcmp(ur::dlss_mode_name(opts.resolution), "Performance"));
|
||||
CHECK(opts.upscale_pre == 1 && opts.ultrawide == 2 && opts.wide_hud == 0 && opts.wide_menus == 1 && opts.fullscreen == 1);
|
||||
CHECK(opts.fps_cap == 5 && opts.vsync == 0 && opts.show_fps == 2 && opts.output_res == 1);
|
||||
CHECK(opts.pace == 1 && opts.steady_fps == 0 && merged.pacing == mr7::PACE_EVEN);
|
||||
CHECK(opts.framegen == 0 && opts.dlssg == 0 && merged.framegen == 0);
|
||||
CHECK(opts.antilag == 0 && opts.reflex == 2 && merged.latency == 0);
|
||||
CHECK(opts.hdr_white == 200 && opts.hdr_peak == 1000 && opts.rdx_tonemap == 1 && opts.rdx_midgray == 1 && opts.rdx_space == 2 &&
|
||||
opts.rdx_ui_white == 200 && opts.rdx_hue == 100 && opts.rdx_grade == 100 && opts.rdx_match_slope == 1);
|
||||
CHECK(opts.lstick_dead_zone == -1 && opts.rstick_dead_zone == -1 && opts.stick_dead_zone == 0);
|
||||
CHECK(opts.realtime == 1 && opts.replay_threads == 8 && opts.tail_early == 1 && opts.tex_bc1 == 1 && opts.walk_scale == 51);
|
||||
/* (the Reflex frame limit: off, its old default and the file's 0, until it has been played: vk_menu.h reflex_limit) */
|
||||
CHECK(opts.upscale == 0 && opts.reflex_limit == 0 && opts.vram_mb == 0 && opts.mirror_mb == 0);
|
||||
CHECK(hdr_at_start == 2 && renodx_at_start == 1 && upscale_pre_at_start == 1);
|
||||
/* no two rows save one key, and the merged rows save none of their own */
|
||||
std::set<std::string> keys;
|
||||
for (const Row& r : rows) {
|
||||
if (!ini_row(r)) continue;
|
||||
CHECK(keys.insert(ini_key(r)).second);
|
||||
CHECK(!is_merged(r.value));
|
||||
}
|
||||
/* each line the file had is read by a row or dropped by merged_rows.h, its job done otherwise */
|
||||
FILE* f = std::fopen(argv[1], "r");
|
||||
char line[128];
|
||||
int lines = 0;
|
||||
while (f && std::fgets(line, sizeof line, f)) {
|
||||
char* eq = std::strchr(line, '=');
|
||||
if (!eq) continue;
|
||||
*eq = 0;
|
||||
bool dropped = false;
|
||||
for (const char* d : mr7::kDropped) dropped |= !std::strcmp(line, d);
|
||||
CHECK(keys.count(line) || dropped || !std::strcmp(line, "options_version"));
|
||||
lines++;
|
||||
}
|
||||
if (f) std::fclose(f);
|
||||
CHECK(lines > 90);
|
||||
/* the readers before the menu find their keys in the file the menu writes */
|
||||
for (int i = 3; i < argc; i++) CHECK(keys.count(argv[i]));
|
||||
/* the file the menu then writes (every saved row by its key, options_version 7) reads back to the same values */
|
||||
const Options before = opts;
|
||||
const Merged shown = merged;
|
||||
{
|
||||
FILE* w = std::fopen(argv[2], "w");
|
||||
for (const Row& r : rows)
|
||||
if (ini_row(r)) std::fprintf(w, "%s=%d\n", ini_key(r), *r.value);
|
||||
std::fprintf(w, "options_version=%d\n", mr7::kVersion);
|
||||
std::fclose(w);
|
||||
}
|
||||
opts = Options{};
|
||||
path = argv[2];
|
||||
load();
|
||||
merged_sync();
|
||||
CHECK(!std::memcmp(&before, &opts, sizeof opts));
|
||||
CHECK(shown.hdr == merged.hdr && shown.framegen == merged.framegen && shown.pacing == merged.pacing && shown.latency == merged.latency);
|
||||
/* an older file with the rows that went: the handheld profile as the Output resolution's, the shared dead zone each
|
||||
stick's own, the other lines without effect */
|
||||
{
|
||||
FILE* w = std::fopen(argv[2], "w");
|
||||
std::fprintf(w, "output_res=2\nhandheld_profile=1\nstick_dead_zone=2\nright_stick_dead_zone=30\nquality_preset=3\nupscaling=2\n"
|
||||
"reflex_frame_limit=0\noptions_version=6\n");
|
||||
std::fclose(w);
|
||||
}
|
||||
opts = Options{};
|
||||
load();
|
||||
CHECK(opts.output_res == mr7::kHandheldOutput && opts.lstick_dead_zone == 10 && opts.rstick_dead_zone == 30);
|
||||
CHECK(opts.upscale == 0 && opts.reflex_limit == 0 && opts.vram_mb == 0);
|
||||
/* the HDR row takes a restart for Native + RenoDX alone (the scene's RGBA16F target and RenoDX's shaders are chosen at
|
||||
the start); Off, Expanded and Native change at once, as the HDR row did */
|
||||
const Row* hdr = nullptr;
|
||||
for (const Row& r : rows)
|
||||
if (r.value == &merged.hdr) hdr = &r;
|
||||
CHECK(hdr && hdr->restart);
|
||||
for (int row = 0; row <= 3; row++) {
|
||||
mr7::hdr_set(row, opts.hdr, opts.renodx);
|
||||
merged_sync();
|
||||
CHECK(merged.hdr == row && restart_value_of(*hdr) == (row == mr7::HDR_RENODX ? 1 : 0));
|
||||
}
|
||||
opts.hdr = 2, opts.renodx = 1; /* (RenoDX chosen with HDR Off or Expanded runs nothing: no restart for it) */
|
||||
merged_sync();
|
||||
CHECK(restart_value_of(*hdr) == 1);
|
||||
opts.hdr = 1;
|
||||
CHECK(restart_value_of(*hdr) == 0);
|
||||
std::puts("merged rows: an owner's file of version 6 plays the same, and what is written reads back the same");
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def check(cond, what):
|
||||
if not cond:
|
||||
raise SystemExit("FAIL: " + what)
|
||||
|
||||
|
||||
def block(text, at):
|
||||
start = text.index("{", at)
|
||||
depth = 0
|
||||
for i in range(start, len(text)):
|
||||
depth += text[i] == "{"
|
||||
depth -= text[i] == "}"
|
||||
if depth == 0:
|
||||
return text[at:i + 1]
|
||||
raise SystemExit("FAIL: no end for the block at %d" % at)
|
||||
|
||||
|
||||
def definition(text, head):
|
||||
found = re.search(re.escape(head) + r"\([^;{]*\)\s*\{", text)
|
||||
check(found, "no definition of " + head)
|
||||
return block(text, found.start())
|
||||
|
||||
|
||||
def load_fixture():
|
||||
menu = (VK / "vk_menu.cpp").read_text(encoding="utf-8")
|
||||
header = (VK / "vk_menu.h").read_text(encoding="utf-8")
|
||||
table = menu[menu.index("Row rows[] = {"):]
|
||||
table = table[:table.index("\n};\n") + 4]
|
||||
# (the rows' words and lines: stand-ins, this is about what is saved)
|
||||
names = sorted(set(re.findall(r"\b((?:tx|hn)_[a-z0-9_]+)\b", table)))
|
||||
stubs = "\n".join("const char* %s(int%s) { return nullptr; }" % (n, ", int" if n.startswith("hn_") else "") for n in names)
|
||||
mod_rows = menu[menu.index("#define MOD_CHEAT_ROW(i)"):menu.index("static_assert(mod_cheat_rows::kSlots")]
|
||||
merged = menu[menu.index("struct Merged {"):menu.index("Row rows[] = {")]
|
||||
out = menu[menu.index("struct Out {"):menu.index("int step_output_choice(int id, int dir) {")]
|
||||
init = definition(menu, "void menu_init")
|
||||
reading = block(init, init.index('if (FILE* f = fopen(ini_path().c_str(), "r")) {'))
|
||||
check("merged_rows::migrate(version, before7, opts.output_res, opts.lstick_dead_zone, opts.rstick_dead_zone);" in reading,
|
||||
"menu_init's reading of the file does not migrate an older one")
|
||||
sync = definition(menu, "void merged_sync")
|
||||
fixture = LOAD
|
||||
for mark, text in (("@OPTIONS@", re.search(r"struct Options \{.*?\n\};", header, re.S).group(0)),
|
||||
("@TABS@", re.search(r"enum MenuTab \{.*?\};", menu, re.S).group(0)),
|
||||
("@ROW@", re.search(r"struct Row \{.*?\n\};", menu, re.S).group(0)),
|
||||
("@OUT@", out), ("@STUBS@", stubs), ("@MOD_ROWS@", mod_rows), ("@MERGED@", merged), ("@TABLE@", table),
|
||||
("@INI_KEY@", definition(menu, "const char* ini_key")), ("@INI_ROW@", definition(menu, "bool ini_row")),
|
||||
("@LOAD@", reading), ("@SYNC@", sync), ("@RESTART@", definition(menu, "int restart_value_of"))):
|
||||
fixture = fixture.replace(mark, text)
|
||||
return fixture.replace("@VK@", VK.as_posix())
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--cxx", default="g++")
|
||||
args = parser.parse_args()
|
||||
menu = (VK / "vk_menu.cpp").read_text(encoding="utf-8")
|
||||
check('out += "options_version=8\\n";' in definition(menu, "void save"), "save does not write options_version=8")
|
||||
check("for (const char* dropped : merged_rows::kDropped) mine |= key == dropped;" in definition(menu, "void save"),
|
||||
"save writes back the lines of the rows that went")
|
||||
with tempfile.TemporaryDirectory(prefix="merged-rows-") as tmp:
|
||||
tmp = Path(tmp)
|
||||
src, exe = tmp / "merged.cpp", tmp / "merged.exe"
|
||||
src.write_text(MERGED.replace("@VK@", VK.as_posix()), encoding="utf-8")
|
||||
subprocess.run([args.cxx, "-std=c++20", "-Wall", "-Wextra", "-Werror", str(src), "-o", str(exe)], check=True)
|
||||
subprocess.run([str(exe)], check=True)
|
||||
src, exe = tmp / "load.cpp", tmp / "load.exe"
|
||||
src.write_text(load_fixture(), encoding="utf-8")
|
||||
subprocess.run([args.cxx, "-std=c++20", "-Wall", "-Wextra", "-Wno-unused-function", "-Wno-unused-variable",
|
||||
"-Wno-unused-parameter", "-I", str(ROOT / "gpu" / "render"), str(src), "-o", str(exe)], check=True)
|
||||
owner = tmp / "triforce_options.ini"
|
||||
owner.write_text(OWNER, encoding="ascii")
|
||||
subprocess.run([str(exe), str(owner), str(tmp / "written.ini")] + READ_BEFORE, check=True)
|
||||
print("PASS: options_version 7: the merged rows, the migration, and an owner's file of version 6 as it played")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -170,11 +170,14 @@ def check_sources(menu, header, api, replay, readme):
|
||||
check("#define MOD_CHEAT_ROW(i) {TAB_SYSTEM, mod_cheats.names[i], nullptr, 0, 0, 0, nullptr, kModCheatHelp, nullptr, false, true}," in menu,
|
||||
"a cheat's row is not a row of the System tab without a value of the options file")
|
||||
at = table.index('{TAB_SYSTEM, "Bug capture (F8)", nullptr,')
|
||||
heading = table.index('{TAB_SYSTEM, "Mod cheats", nullptr, 0, 0, 0, nullptr, nullptr, nullptr, false, true, -1, true},')
|
||||
check(at < heading < table.index("MOD_CHEAT_ROWS8(0)") < table.index("// Controls ("), "the cheats' rows do not stand after Bug capture (F8) on the System tab")
|
||||
# ((Triforce, options_version 7) the heading is a group's: MENU_HEADING, hidden while its group's rows are)
|
||||
check("#define MENU_HEADING(tab, title) {tab, title, nullptr, 0, 0, 0, nullptr, nullptr, nullptr, false, true, -1, true}" in menu,
|
||||
"a group's heading is not a row without a value that the selection steps over")
|
||||
heading = table.index('MENU_HEADING(TAB_SYSTEM, "Mod cheats"),')
|
||||
check(at < heading < table.index("MOD_CHEAT_ROWS8(0)") < table.index("// ---- Controls ("), "the cheats' rows do not stand after Bug capture (F8) on the System tab")
|
||||
check('constexpr char kModCheatHeading[] = "Mod cheats";' in menu, "the heading's name in the table is not the one row_shown tells it by")
|
||||
check(re.search(r"static_assert\(mod_cheat_rows::kSlots == %d," % slots, menu), "nothing holds the table to the list's slots")
|
||||
check('bool ini_row(const Row& r) { return r.value && r.value != &opts.language; }' in menu, "a row without a value may be a row of the options file now")
|
||||
check('bool ini_row(const Row& r) { return r.value && r.value != &opts.language && !is_merged(r.value); }' in menu, "a row without a value may be a row of the options file now")
|
||||
# shown only once named
|
||||
shown = block(menu, "bool row_shown(int i) {")
|
||||
check("(!rows[i].heading || strcmp(rows[i].name, kModCheatHeading) || mod_cheats.shown() > 0)" in shown
|
||||
|
||||
420
tests/test_mods_entry_input.py
Normal file
420
tests/test_mods_entry_input.py
Normal file
@@ -0,0 +1,420 @@
|
||||
"""The controller, the keys and a test's script on the Mods entry under the game's lists (host/nn_hid.c mods_input,
|
||||
host/oot_menu.c hos_oot_mods_down, gpu/vk/vk_menu.cpp mods_list_age and menu_tick; no game).
|
||||
|
||||
(Triforce, 11-19) The lab's check of port052:
|
||||
- "pause menu System list, a normal DOWN from Title Screen skips Mods to Quit ... the log says 'the Mods entry has the cursor'
|
||||
but the white cursor only appears on Quit. A 16 ms DOWN lands on Mods." The host takes the Down at the last button for
|
||||
Mods (the enter word) and, once Mods has the cursor, passes a script's presses on to the menu; a press was new against
|
||||
the buttons before, which were taken as none while the game had the cursor, so the Down that came onto Mods, still held,
|
||||
was a press of the entry's: on to Quit. It has to work for a controller's press (100 to 300 ms, the D-pad and the stick),
|
||||
the keys, the live input file, and a Down held, which repeats at the menu's rate as a pad's.
|
||||
- "One DOWN from Options on the title did nothing and logged nothing": the game's frames came 80 to 235 ms apart (its window
|
||||
behind another one), and the host's 80 ms and the renderer's 150 ms took the list for gone: the Down went to the game,
|
||||
or the enter word was dropped, without a line.
|
||||
|
||||
This compiles the real code, extracted from the sources, against fakes:
|
||||
- ((a review of beb9b9e) a Down held from higher up the list goes on onto Mods once the game's cursor is on the last
|
||||
button: one word 5 a step (83 ms, 33 past 1.5 s) after it came there and past the first 0.35 s held; a 300 ms press
|
||||
from the button above, or one let go before the step, stays on the last button.)
|
||||
- ((a review of 63a5020) the keys read by their state and the host's queue as one press, menu_keys::key_press: a tap
|
||||
between two ticks counts, the queued press of one counted on the state at the tick before does not count again, on the
|
||||
Mods screen A opened either.)
|
||||
- mods_input (nn_hid.c) with the renderer as a fake that takes the enter word at its next tick: a Down held 150 ms or
|
||||
300 ms from Title Screen, the D-pad's or the stick's, is no press of the entry's at the first read with Mods chosen, and is
|
||||
told as held at each read (the menu repeats it); a 16 ms Down the same; a second Down on Mods is one press; A held as
|
||||
the mouse takes Mods is no press; the presses after Mods let the cursor go are the game's again when let go and pressed.
|
||||
- hos_oot_mods_down (oot_menu.c): the list's last frame is the game's last one (one present since at most) however long
|
||||
ago, and within 80 ms as before; three presents and 200 ms after it the list is gone.
|
||||
- mods_list_age (vk_menu.cpp): 0 while the list was told of at the game's last two frames, its age after.
|
||||
|
||||
And reads the source for what only the game shows: the menu repeats the held directions the host tells of while Mods or
|
||||
its screen has the cursor, as a pad's (0.35 s, then 12 and 30 a second); the keys bound to the game's D-pad, movement and A
|
||||
act on Mods, Quit and its dialog (and a key's Up that leaves them is not the game's too, mods_input); the enter word not
|
||||
taken says so in the log.
|
||||
|
||||
python -I -B tests/test_mods_entry_input.py [--cxx clang++]
|
||||
"""
|
||||
import argparse
|
||||
import re
|
||||
import subprocess
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
VK = ROOT / "gpu" / "vk"
|
||||
RUN_ALL_ARGS = ["--cxx", "{cxx}"]
|
||||
|
||||
|
||||
def check(ok, why):
|
||||
if not ok:
|
||||
raise SystemExit("FAIL: " + why)
|
||||
|
||||
|
||||
def block(text, head):
|
||||
start = text.index(head)
|
||||
end = text.index("{", start) + 1
|
||||
depth = 1
|
||||
while depth:
|
||||
depth += (text[end] == "{") - (text[end] == "}")
|
||||
end += 1
|
||||
return text[start:end]
|
||||
|
||||
|
||||
HID_FIXTURE = r"""
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include "vk_api.h"
|
||||
static int fails;
|
||||
#define CHECK(x) do { if (!(x)) { printf("FAIL:%d %s\n", __LINE__, #x); fails++; } } while (0)
|
||||
/* the host's options, as the renderer answers them: 1 the menu open, HOS_OPT_MODS_SELECTED Mods has the cursor */
|
||||
static int menu_open, selected, entered, presses, held_dirs, reports;
|
||||
int rx_option(int id, int otherwise) {
|
||||
if (id == 1) return menu_open;
|
||||
if (id == HOS_OPT_MODS_SELECTED) return selected;
|
||||
return otherwise;
|
||||
}
|
||||
void rx_option_set(int id, int value) {
|
||||
if (id == HOS_OPT_MODS_ENTER) entered = value;
|
||||
if (id == HOS_OPT_MODS_PRESS) {
|
||||
presses |= value & 0xff;
|
||||
if (value & HOS_MODS_REPORT) reports++, held_dirs = value >> HOS_MODS_HELD_SHIFT & HOS_MODS_PRESS_DIRS;
|
||||
}
|
||||
}
|
||||
/* the game's cursor on its list's last button (Title Screen) */
|
||||
static int on_last = 1;
|
||||
static int64_t now_ns = 1000000000LL; /* (a read each 16 ms: read_once) */
|
||||
int64_t hos_now_ns(void) { return now_ns; }
|
||||
int hos_oot_mods_down(void) { return on_last; }
|
||||
%(enum)s;
|
||||
%(func)s
|
||||
/* one read: the buttons and stick the devices and the script give; what the game is given */
|
||||
static uint64_t game;
|
||||
static int32_t game_stick[4];
|
||||
static void read_once(uint64_t buttons, int32_t ly) {
|
||||
int32_t stick[4] = {0, ly, 0, 0};
|
||||
now_ns += 16000000;
|
||||
mods_input(&buttons, stick);
|
||||
game = buttons, memcpy(game_stick, stick, sizeof stick);
|
||||
}
|
||||
/* the renderer's tick between two reads: the enter word taken (Mods chosen, the menu open), its presses read */
|
||||
static int last_word;
|
||||
static void tick(void) {
|
||||
if (entered == 1 || entered == 5) selected = 1, menu_open = 1, on_last = 0;
|
||||
if (entered) last_word = entered;
|
||||
entered = 0;
|
||||
}
|
||||
static void reset(void) {
|
||||
menu_open = selected = entered = presses = held_dirs = reports = last_word = 0, on_last = 1;
|
||||
for (int i = 0; i < 8; i++) read_once(0, 0), tick(); /* (nothing held: the statics as after a while of play) */
|
||||
presses = reports = 0;
|
||||
}
|
||||
/* a Down held ms long from Title Screen, a read every 16 ms (the D-pad's, or the stick's when stick) */
|
||||
static void down_from_title(int ms, int stick) {
|
||||
reset();
|
||||
for (int t = 0; t <= ms + 64; t += 16) {
|
||||
const int held = t < ms;
|
||||
read_once(held && !stick ? 1ULL << B_DOWN : 0, held && stick ? -30000 : 0);
|
||||
if (t == 0) CHECK(entered == 1 && !(game >> B_DOWN & 1) && game_stick[1] == 0); /* (the game never sees it) */
|
||||
if (held && t > 0 && selected) CHECK(held_dirs == HOS_MODS_PRESS_DOWN); /* (told as held: the menu repeats it) */
|
||||
if (!held && selected) CHECK(held_dirs == 0);
|
||||
tick();
|
||||
}
|
||||
CHECK(selected && reports > 0);
|
||||
CHECK(!(presses & HOS_MODS_PRESS_DOWN)); /* (the Down onto Mods is not the entry's own: no Quit) */
|
||||
}
|
||||
/* ((Triforce, 11-19) a review of beb9b9e) a Down held from higher up the list (New Game, Save): the game's own repeat takes
|
||||
its cursor onto the last button after above_ms, and the Down goes on onto Mods as a repeat: once held past the menu's
|
||||
first delay (350 ms) and a step (83 ms) on the last button, one word, 5; none while held for less. Before, the cursor
|
||||
stayed on the last button as long as the Down was held */
|
||||
static void down_held_from_above(int above_ms, int ms, int stick, int want_ms) {
|
||||
reset();
|
||||
on_last = 0;
|
||||
int words = 0, at = -1;
|
||||
for (int t = 0; t <= ms + 64; t += 16) {
|
||||
const int held = t < ms;
|
||||
if (t >= above_ms && !selected) on_last = 1; /* (the game's repeat, or its move from the button above) */
|
||||
read_once(held && !stick ? 1ULL << B_DOWN : 0, held && stick ? -30000 : 0);
|
||||
if (!on_last && !selected) CHECK(held ? (game >> B_DOWN & 1) || game_stick[1] < -16384 : 1); /* (the game's, up the list) */
|
||||
if (on_last && !selected) CHECK(!(game >> B_DOWN & 1) && game_stick[1] == 0); /* (on the last button: never the game's) */
|
||||
if (entered) words++, at = t;
|
||||
tick();
|
||||
}
|
||||
if (want_ms < 0) {
|
||||
CHECK(words == 0 && !selected);
|
||||
} else {
|
||||
CHECK(words == 1 && last_word == 5 && selected && at >= want_ms && at < want_ms + 32);
|
||||
CHECK(!(presses & HOS_MODS_PRESS_DOWN)); /* (the repeat's Down onto Mods is no press of the entry's: the menu repeats on) */
|
||||
}
|
||||
}
|
||||
int main(void) {
|
||||
down_held_from_above(500, 1000, 0, 500 + 83); /* (the game's repeat onto the last button at 500 ms: a step after it) */
|
||||
down_held_from_above(500, 1000, 1, 500 + 83); /* (the stick's) */
|
||||
down_held_from_above(16, 300, 0, -1); /* (a 300 ms press from the button above: the game's move only) */
|
||||
down_held_from_above(16, 600, 0, 350); /* (held on from the button above: the first delay, then Mods) */
|
||||
down_held_from_above(500, 560, 0, -1); /* (let go before the step) */
|
||||
down_held_from_above(2000, 2400, 0, 2000 + 33); /* (past 1.5 s held: the fast step) */
|
||||
down_from_title(16, 0);
|
||||
down_from_title(150, 0);
|
||||
down_from_title(300, 0);
|
||||
down_from_title(150, 1);
|
||||
down_from_title(300, 1);
|
||||
/* a second Down on Mods: one press of the entry's (on to Quit) */
|
||||
down_from_title(100, 0);
|
||||
presses = 0;
|
||||
read_once(1ULL << B_DOWN, 0), tick();
|
||||
read_once(1ULL << B_DOWN, 0), tick();
|
||||
CHECK(presses == HOS_MODS_PRESS_DOWN);
|
||||
read_once(0, 0), tick();
|
||||
/* the mouse takes Mods with A held (a click's button, or A held as the cursor came): A is no press of the entry's */
|
||||
reset();
|
||||
read_once(1ULL << B_A, 0);
|
||||
selected = menu_open = 1;
|
||||
read_once(1ULL << B_A, 0);
|
||||
CHECK(!(presses & HOS_MODS_PRESS_A));
|
||||
read_once(0, 0), read_once(1ULL << B_A, 0);
|
||||
CHECK(presses & HOS_MODS_PRESS_A);
|
||||
/* the cursor back to the game with Up held: not the game's until let go */
|
||||
presses = 0;
|
||||
read_once(1ULL << B_UP, 0);
|
||||
selected = menu_open = 0;
|
||||
read_once(1ULL << B_UP, 0);
|
||||
CHECK(!(game >> B_UP & 1));
|
||||
read_once(0, 0), read_once(1ULL << B_UP, 0);
|
||||
CHECK(game >> B_UP & 1);
|
||||
/* a key bound to the D-pad's Up that took the cursor back (the menu's while it was open: none in the host's read then,
|
||||
held as it closes): not the game's until let go, or the game's cursor went up a button too */
|
||||
read_once(0, 0);
|
||||
selected = menu_open = 1;
|
||||
read_once(0, 0);
|
||||
selected = menu_open = 0;
|
||||
read_once(1ULL << B_UP, 0);
|
||||
CHECK(!(game >> B_UP & 1));
|
||||
read_once(1ULL << B_UP, 0);
|
||||
CHECK(!(game >> B_UP & 1));
|
||||
read_once(0, 0), read_once(1ULL << B_UP, 0);
|
||||
CHECK(game >> B_UP & 1);
|
||||
if (!fails) puts("the Mods entry's input");
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
"""
|
||||
|
||||
MENU_HOST_FIXTURE = r"""
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
typedef int64_t LONG64;
|
||||
static int fails;
|
||||
#define CHECK(x) do { if (!(x)) { printf("FAIL:%d %s\n", __LINE__, #x); fails++; } } while (0)
|
||||
LONG64 InterlockedCompareExchange64(volatile LONG64 *p, LONG64 v, LONG64 e) { LONG64 o = *p; if (o == e) *p = v; return o; }
|
||||
LONG64 InterlockedExchange64(volatile LONG64 *p, LONG64 v) { LONG64 o = *p; *p = v; return o; }
|
||||
static int64_t now_ns = 5000000000LL;
|
||||
int64_t hos_now_ns(void) { return now_ns; }
|
||||
volatile LONG64 hos_present_count = 100;
|
||||
%(state)s
|
||||
%(func)s
|
||||
/* the list's frame with its last button focused, as mods_list_tick notes it */
|
||||
static void list_frame(void) {
|
||||
InterlockedExchange64(&mods_last_present, InterlockedCompareExchange64(&hos_present_count, 0, 0));
|
||||
InterlockedExchange64(&mods_last_ns, (LONG64)now_ns);
|
||||
}
|
||||
int main(void) {
|
||||
CHECK(!hos_oot_mods_down()); /* (no list yet) */
|
||||
list_frame();
|
||||
now_ns += 16000000, hos_present_count++;
|
||||
CHECK(hos_oot_mods_down()); /* (the frame before, 16 ms ago) */
|
||||
list_frame();
|
||||
now_ns += 200000000, hos_present_count++; /* (the game's next frame 200 ms later: its window behind another one) */
|
||||
CHECK(hos_oot_mods_down());
|
||||
now_ns += 200000000; /* (no present since: still that frame) */
|
||||
CHECK(hos_oot_mods_down());
|
||||
hos_present_count += 2; /* (three frames past the list's) */
|
||||
CHECK(!hos_oot_mods_down());
|
||||
list_frame();
|
||||
hos_present_count += 5, now_ns += 50000000; /* (within 80 ms, as before) */
|
||||
CHECK(hos_oot_mods_down());
|
||||
if (!fails) puts("the list's last frame");
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
"""
|
||||
|
||||
AGE_FIXTURE = r"""
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
static int fails;
|
||||
#define CHECK(x) do { if (!(x)) { std::printf("FAIL:%d %s\n", __LINE__, #x); fails++; } } while (0)
|
||||
static int64_t now = 9000000000LL;
|
||||
int64_t prof_now() { return now; }
|
||||
std::atomic<int64_t> mods_list_ns{0}, mods_list_frame{0};
|
||||
%(state)s
|
||||
%(age)s
|
||||
%(fresh)s
|
||||
int main() {
|
||||
CHECK(!mods_list_fresh());
|
||||
mods_list_frame.store(game_frames.load()), mods_list_ns.store(now); // (a report)
|
||||
now += 100000000;
|
||||
CHECK(mods_list_fresh() && mods_list_age() == 0);
|
||||
now += 135000000, game_frames += 1; // (235 ms on, the game's next frame)
|
||||
CHECK(mods_list_fresh() && mods_list_age() == 0);
|
||||
game_frames += 1;
|
||||
CHECK(mods_list_fresh());
|
||||
game_frames += 1; // (three frames and no report: gone)
|
||||
CHECK(!mods_list_fresh() && mods_list_age() == 235000000);
|
||||
mods_list_frame.store(game_frames.load()), mods_list_ns.store(now);
|
||||
game_frames += 6, now += 100000000; // (fast frames: 150 ms as before)
|
||||
CHECK(mods_list_fresh() && mods_list_age() == 100000000);
|
||||
now += 60000000;
|
||||
CHECK(!mods_list_fresh());
|
||||
if (!fails) std::puts("the list's age");
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
KEYS_FIXTURE = r"""
|
||||
#include <cstdio>
|
||||
#include "vk_menu_keys.h"
|
||||
using namespace mkwvk::menu_keys;
|
||||
static int fails;
|
||||
#define CHECK(x) do { if (!(x)) { std::printf("FAIL:%d %s\n", __LINE__, #x); fails++; } } while (0)
|
||||
int main() {
|
||||
const long long f = 16000000;
|
||||
long long t = 1000000000;
|
||||
bool echo = false;
|
||||
{ // a press seen by its state at one tick, its queued press at the next (the window's thread a little late): one
|
||||
KeyPress k;
|
||||
CHECK(key_press(k, true, false, true, true, t, &echo) && !echo);
|
||||
CHECK(!key_press(k, true, true, true, true, t + f, &echo) && echo); // (on the entries: the same press)
|
||||
CHECK(!key_press(k, false, false, true, true, t + 2 * f, &echo) && !echo);
|
||||
// and A opened the Mods screen at the first tick: its queued press there (taken false) is the same press too
|
||||
CHECK(key_press(k, true, false, true, true, t + 3 * f, &echo));
|
||||
CHECK(!key_press(k, true, true, false, true, t + 4 * f, &echo) && echo);
|
||||
}
|
||||
{ // a tap between two ticks: its state never seen, its queued press counts
|
||||
KeyPress k;
|
||||
CHECK(key_press(k, false, true, true, true, t, &echo) && !echo);
|
||||
CHECK(!key_press(k, false, false, true, true, t + f, &echo));
|
||||
}
|
||||
{ // both at one tick: one press, no queued press still to come
|
||||
KeyPress k;
|
||||
CHECK(key_press(k, true, true, true, true, t, &echo));
|
||||
CHECK(!key_press(k, false, false, true, true, t + f, &echo));
|
||||
CHECK(key_press(k, false, true, true, true, t + 2 * f, &echo) && !echo); // (the next tap)
|
||||
}
|
||||
{ // held from before (the key that brought the cursor onto Mods): its late queued press is no press
|
||||
KeyPress k;
|
||||
key_press(k, true, false, false, true, t, &echo); // (down before the entries had the cursor)
|
||||
CHECK(!key_press(k, true, true, true, true, t + f, &echo));
|
||||
}
|
||||
{ // off the entries (taken false): no echo kept, the menu's own use of the key's queued press stays
|
||||
KeyPress k;
|
||||
CHECK(key_press(k, true, false, false, true, t, &echo));
|
||||
CHECK(!key_press(k, true, true, false, true, t + f, &echo) && !echo);
|
||||
}
|
||||
{ // a queued press long after one counted on the state is a press of its own
|
||||
KeyPress k;
|
||||
CHECK(key_press(k, true, false, true, true, t, &echo));
|
||||
CHECK(!key_press(k, false, false, true, true, t + f, &echo));
|
||||
CHECK(key_press(k, false, true, true, true, t + kEchoNs + f, &echo) && !echo);
|
||||
}
|
||||
if (!fails) std::puts("a key's press, by its state and the host's queue");
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def fill(template, **parts):
|
||||
"""(the template's %(name)s places filled: its printf formats are left as they are)"""
|
||||
for k, v in parts.items():
|
||||
template = template.replace("%(" + k + ")s", v)
|
||||
return template
|
||||
|
||||
|
||||
def run(cxx, source, name, tmp, lang, extra=()):
|
||||
src = Path(tmp) / (name + (".c" if lang == "c" else ".cpp"))
|
||||
exe = Path(tmp) / (name + ".exe")
|
||||
src.write_text(source, encoding="utf-8")
|
||||
std = ["-x", "c", "-std=c11"] if lang == "c" else ["-std=c++20"]
|
||||
build = subprocess.run([cxx] + std + ["-O1", "-Wall", "-Wextra", "-Werror", "-Wno-unused-function", "-I" + str(VK)] +
|
||||
list(extra) + [str(src), "-o", str(exe)], capture_output=True, text=True)
|
||||
check(build.returncode == 0, name + " does not build:\n" + build.stdout + build.stderr)
|
||||
r = subprocess.run([str(exe)], capture_output=True, text=True)
|
||||
check(r.returncode == 0, name + ":\n" + r.stdout + r.stderr)
|
||||
print(r.stdout.strip())
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--cxx", default="clang++")
|
||||
args = parser.parse_args()
|
||||
hid = (ROOT / "host" / "nn_hid.c").read_text(encoding="utf-8")
|
||||
oot = (ROOT / "host" / "oot_menu.c").read_text(encoding="utf-8")
|
||||
menu = (VK / "vk_menu.cpp").read_text(encoding="utf-8")
|
||||
|
||||
func = block(hid, "static void mods_input(uint64_t *buttons_io, int32_t stick[4]) {")
|
||||
check("mods_input(&buttons, stick);" in block(hid, "static void npad_states(Ctx *c) {"), "npad_states does not take the Mods entry's input")
|
||||
enum = block(hid, "enum { B_A = 0")
|
||||
win = oot # (the Windows half's come first: the other half's hos_oot_mods_down is a one-line stub after them)
|
||||
state = "\n".join(re.search(r"^static volatile LONG64 " + n + r";[^\n]*$", win, re.M).group(0)
|
||||
for n in ("mods_last_ns", "mods_last_present"))
|
||||
down = block(win, "int hos_oot_mods_down(void) {")
|
||||
check("InterlockedExchange64(&mods_last_present, InterlockedCompareExchange64(&hos_present_count, 0, 0));" in
|
||||
block(win, "static void mods_list_tick(uint64_t screen, int title, ModsCall *call) {"),
|
||||
"the list's frame does not note the game's presents")
|
||||
age = block(menu, "int64_t mods_list_age() {")
|
||||
fresh = re.search(r"^bool mods_list_fresh\(\) \{[^\n]*\}$", menu, re.M)
|
||||
check(fresh is not None, "mods_list_fresh is not the list's age against 150 ms")
|
||||
game_frames = re.search(r"^std::atomic<int64_t> game_frames\{0\};", menu, re.M)
|
||||
check(game_frames is not None, "game_frames is not where mods_list_age reads it")
|
||||
with tempfile.TemporaryDirectory(prefix="mods-entry-input-") as tmp:
|
||||
run(args.cxx, fill(HID_FIXTURE, enum=enum, func=func), "hid", tmp, "c")
|
||||
run(args.cxx, fill(MENU_HOST_FIXTURE, state=state, func=down), "oot", tmp, "c")
|
||||
run(args.cxx, fill(AGE_FIXTURE, state=game_frames.group(0), age=age, fresh=fresh.group(0)), "age", tmp, "c++")
|
||||
run(args.cxx, KEYS_FIXTURE, "keys", tmp, "c++")
|
||||
|
||||
# the menu: the host's report of the directions held (each read), repeated as a pad's held direction
|
||||
opt = block(menu, "void menu_option_set(int id, int value) {")
|
||||
check("mods_press.fetch_or(value & 0xff, std::memory_order_relaxed);" in opt and
|
||||
"mods_held_dirs.store(value >> HOS_MODS_HELD_SHIFT & HOS_MODS_PRESS_DIRS, std::memory_order_relaxed);" in opt,
|
||||
"the menu does not keep the directions the host tells as held")
|
||||
tick = block(menu, "void menu_tick() {")
|
||||
rep = tick[tick.index("// holding an arrow or the D-pad repeats it"):tick.index("if (open_now.load() && listening != 1) {")]
|
||||
check("const bool mods_here = page == kModsRowPage || page == kModsPage;" in rep and "(host_held >> (i - 1) & 1)" in rep and
|
||||
"t - mods_held_ns.load(std::memory_order_relaxed) < 250000000LL" in rep,
|
||||
"a direction a test's script holds on Mods is not repeated as a pad's")
|
||||
check("next_repeat[i] = t + 350000000LL" in rep and "33000000LL : 83000000LL" in rep, "the repeat's rate changed")
|
||||
# (the keys bound to the game's D-pad, movement and A on the entries: pressed and held as the menu's own, the Down that
|
||||
# came onto Mods taken away with the pad's)
|
||||
keys = tick[tick.index("uint32_t game_keys = 0, game_keys_new = 0;"):tick.index("// holding an arrow or the D-pad repeats it")]
|
||||
check("{HOS_SW_UP, HOS_KEY_MOVE_UP}, {HOS_SW_DOWN, HOS_KEY_MOVE_DOWN}" in keys and "{HOS_SW_A, -1}" in keys and
|
||||
"const bool row = open_now.load() && page == kModsRowPage && listening == 0;" in keys and
|
||||
"if (went) game_keys_new |= vk_places[m];" in keys,
|
||||
"the keys bound to the game's D-pad, movement and A do not act on the Mods entries")
|
||||
# ((a review of 63a5020) one press from one place: the key's state and its queued press as one, the menu's own use of
|
||||
# the same key (E, its next tab) not taken there too, and its queued press after A opened the Mods screen not again)
|
||||
check("const bool q = own >= 0 ? key_queued[own] : queue && host->take_key_press(vk) && mine;" in keys and
|
||||
"menu_keys::key_press(gk_key[vk], down, q, row, queue, t, &echo);" in keys and
|
||||
"if (echo && own >= 0) press[own] = false;" in keys and
|
||||
re.search(r"if \(row\) \{[^}]*if \(own >= 0\) press\[own\] = false;", keys) is not None,
|
||||
"a game key on the entries is still read two ways (its state for A, its queued press as the menu's next tab)")
|
||||
check("key_queued[i] = mine && queued;" in tick and "g < gk_n ? gk_q[g] : host->take_key_press(vk) && mine;" in tick,
|
||||
"the queued presses the game keys read are not the ones the menu and the L, R and B keys read")
|
||||
check(tick.index("uint32_t game_keys = 0, game_keys_new = 0;") < tick.index("bool tab_right = press[11] || press[12]"),
|
||||
"the game keys are read after the tabs are taken from the menu's keys")
|
||||
# ((a review of beb9b9e) the held Down's repeat onto Mods, word 5: the menu repeats on from it at the step)
|
||||
check("entered_by_down = enter == 1 || enter == 5;" in tick and "mods_down_repeat_ns = enter == 5 ? prof_now() : 0;" in tick and
|
||||
"held_since[i] = t - 350000000LL, next_repeat[i] = t + 83000000LL, mods_down_repeat_ns = 0;" in rep,
|
||||
"the menu does not go on repeating a held Down that came onto Mods by repeat")
|
||||
check("held[i] || (game_keys >> i & 1) ||" in rep, "a game key held on Mods does not repeat")
|
||||
check(tick.index("press[i] |= (game_keys_new >> i & 1) != 0;") < tick.index("if (entered_by_down) press[2] = false;"),
|
||||
"the key's Down that came onto Mods is taken again as the entry's own")
|
||||
check('logf("menu: the host\'s word %d for the Mods entry not taken: %s", enter,' in tick,
|
||||
"an enter word the menu does not take leaves no line")
|
||||
check("title_anim.step(now, sel, std::min<int64_t>(age, mods_entry::kListShownNs));" in
|
||||
block(menu, "void draw_title_mods(ui::Ctx& c, bool sel, float cx, float cy, float k, float pitch) {"),
|
||||
"the title's entry does not take the list's age by the game's frames (a slow frame blinks it)")
|
||||
print("PASS: the Mods entry's input: no Down taken twice, held ones repeated, slow frames keep the list")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
165
tests/test_mods_grid.py
Normal file
165
tests/test_mods_grid.py
Normal file
@@ -0,0 +1,165 @@
|
||||
"""The Mods entry where the game's list is, whatever the window's shape (gpu/vk/game_grid.h, vk_menu.cpp draw_mods_row_shut,
|
||||
draw_menu and menu_tick's mouse; no game).
|
||||
|
||||
(Triforce, 11-19) The lab's "Title in a 16:9 window (1600x900, 21:9 picture letterboxed): Mods drawn below the picture,
|
||||
larger, far from the list": the entry was drawn on a 16:9 column of the window's whole height, which is where the game's
|
||||
layouts are only when the picture fills the window's height. The game lays its lists out on a 3840 x 2160 grid in the
|
||||
picture's middle 16:9 (its layouts squeezed into it on a wider picture, host/oot_wide_hud.h), the picture between black bars
|
||||
as the present puts it (vk_present_rect.h). This compiles game_grid.h alone and checks the grid and where the title's
|
||||
entry (its list's last button at -800 units, the entry a pitch of 120 under it) lands, in the picture and under the list:
|
||||
|
||||
- 16:9 window, 21:9 picture (bars above and below): the grid is the picture's height, its middle 16:9; the entry inside
|
||||
the picture (it was 40 px under it in 1600 x 900);
|
||||
- 21:9 window, 21:9 picture: the window's height, its middle 16:9 (as before);
|
||||
- 16:9 window, 16:9 picture: the whole window (as before); 32:9 picture in 16:9 and in 32:9 windows; a window taller than
|
||||
the picture's 16:9 (bars at the sides and at the top and bottom both);
|
||||
- 16:10 picture (narrower than 16:9): the whole picture, the layouts squeezed across (kx under 1), not cut;
|
||||
- no picture known yet: the window's column, as before;
|
||||
- the map's way back (the mouse) undoes it;
|
||||
- ((11-19) a review of 0653792) on a 16:9 grid the column on whole pixels and not stretched (the text sharp), in odd
|
||||
window sizes too; only a 16:10 grid is squeezed.
|
||||
|
||||
And reads the source: the shut entry and the open menu's Mods page (Mods, Quit and its dialog) drawn on the grid from the
|
||||
last present's picture and shape, the mouse taken back through the same map.
|
||||
|
||||
python -I -B tests/test_mods_grid.py [--cxx clang++]
|
||||
"""
|
||||
import argparse
|
||||
import subprocess
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
VK = ROOT / "gpu" / "vk"
|
||||
RUN_ALL_ARGS = ["--cxx", "{cxx}"]
|
||||
|
||||
|
||||
def check(ok, why):
|
||||
if not ok:
|
||||
raise SystemExit("FAIL: " + why)
|
||||
|
||||
|
||||
def block(text, head):
|
||||
start = text.index(head)
|
||||
end = text.index("{", start) + 1
|
||||
depth = 1
|
||||
while depth:
|
||||
depth += (text[end] == "{") - (text[end] == "}")
|
||||
end += 1
|
||||
return text[start:end]
|
||||
|
||||
|
||||
PROGRAM = r"""
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdint>
|
||||
#include "game_grid.h"
|
||||
using namespace mkwvk;
|
||||
static int fails = 0;
|
||||
#define CHECK(x) do { if (!(x)) { std::printf("FAIL:%d %s\n", __LINE__, #x); fails++; } } while (0)
|
||||
static bool near(float a, float b, float tol = 1.0f) { return std::fabs(a - b) <= tol; }
|
||||
// (a place of the grid's units (x right, y up from its middle) in the window, as ui::at on the grid's column, then put)
|
||||
static void at(const game_grid::Place& g, float ux, float uy, float* x, float* y) {
|
||||
const game_grid::Map m = game_grid::map_of(g);
|
||||
const float cw = game_grid::column_w(g), unit = g.h / 720.0f;
|
||||
*x = m.x(cw * 0.5f + ux * unit / 3), *y = m.y(g.h * 0.5f - uy * unit / 3);
|
||||
}
|
||||
int main() {
|
||||
const double r21 = 64.0 / 27.0, r32 = 32.0 / 9.0, r1610 = 16.0 / 10.0;
|
||||
float x, y;
|
||||
// 16:9 window (1600 x 900), 21:9 picture: bars above and below; the grid the picture's height in its middle
|
||||
game_grid::Place g = game_grid::of(3416, 1440, 1600, 900, r21);
|
||||
CHECK(near(g.h, 675) && near(g.y, 112) && near(g.w, 1200) && near(g.x, 200));
|
||||
at(g, 0, -800 - 120, &x, &y); // (the title's entry: its list's last button at -800, a pitch under it)
|
||||
CHECK(near(x, 800) && y > g.y && y < g.y + g.h && near(y, 112 + 337.5f + 920 * 675.0f / 2160, 1.5f));
|
||||
CHECK(y < 112 + 675); // (inside the picture: it was 40 px under it, at 833)
|
||||
float lx, ly;
|
||||
at(g, 0, -800, &lx, &ly);
|
||||
CHECK(near(y - ly, 120 * 675.0f / 2160, 1.0f)); // (a pitch of the list's own under its last button)
|
||||
// 21:9 window, 21:9 picture: the window's height, its middle 16:9
|
||||
g = game_grid::of(3416, 1440, 2560, 1080, r21);
|
||||
CHECK(near(g.h, 1080) && near(g.y, 0) && near(g.w, 1920) && near(g.x, 320));
|
||||
// a 1720 x 720 window (wider than 21:9): pillarboxed picture, the grid its middle 16:9 at the window's height
|
||||
g = game_grid::of(3416, 1440, 1720, 720, r21);
|
||||
CHECK(near(g.h, 720) && near(g.y, 0) && near(g.w, 1280) && near(g.x, 220));
|
||||
// 16:9 picture in a 16:9 window: the whole window
|
||||
g = game_grid::of(2560, 1440, 1920, 1080, 0);
|
||||
CHECK(near(g.x, 0) && near(g.y, 0) && near(g.w, 1920) && near(g.h, 1080));
|
||||
CHECK(near(game_grid::map_of(g).kx, 1, 0.001f));
|
||||
// 32:9 picture in a 16:9 window and in a 32:9 one
|
||||
g = game_grid::of(5120, 1440, 1920, 1080, r32);
|
||||
CHECK(near(g.h, 540) && near(g.y, 270) && near(g.w, 960) && near(g.x, 480));
|
||||
g = game_grid::of(5120, 1440, 5120, 1440, r32);
|
||||
CHECK(near(g.h, 1440) && near(g.w, 2560) && near(g.x, 1280));
|
||||
// a window taller than 16:9 (4:3) with a 16:9 picture: bars above and below, the whole picture
|
||||
g = game_grid::of(2560, 1440, 1600, 1200, 0);
|
||||
CHECK(near(g.w, 1600) && near(g.h, 900) && near(g.y, 150) && near(g.x, 0));
|
||||
// 16:10 picture in a 16:10 window: the whole picture, squeezed across (the layouts keep the picture's height)
|
||||
g = game_grid::of(2304, 1440, 1920, 1200, r1610);
|
||||
CHECK(near(g.w, 1920) && near(g.h, 1200) && near(g.x, 0) && near(g.y, 0));
|
||||
game_grid::Map m = game_grid::map_of(g);
|
||||
CHECK(m.kx < 0.95f && near(m.kx, 1920.0f / std::floor(1200 * 16.0f / 9 + 0.5f), 0.001f));
|
||||
at(g, 1920, 0, &x, &y);
|
||||
CHECK(near(x, 1920)); // (the grid's right edge at the picture's)
|
||||
// no picture known yet: the window's column of its whole height, as before
|
||||
g = game_grid::of(0, 0, 2560, 1080, 0);
|
||||
CHECK(near(g.h, 1080) && near(g.w, 1920) && near(g.x, 320) && near(g.y, 0));
|
||||
// ((Triforce, 11-19) a 16:9 grid in a wider picture (or a 16:9 one): the column on whole pixels, not stretched, so the
|
||||
// text drawn on it (on whole pixels already) stays sharp; in the grid's middle within half a pixel. 1600 x 900 with a
|
||||
// 21:9 picture was 200.889 across and 1.00019 wide, a 1601 x 901 window half a pixel off)
|
||||
{
|
||||
const struct { uint32_t pw, ph, ww, wh; double r; } cases[] = {
|
||||
{3416, 1440, 1600, 900, r21}, {3416, 1440, 1601, 901, r21}, {3416, 1440, 1920, 1080, r21}, {3416, 1440, 1919, 1079, r21},
|
||||
{5120, 1440, 1920, 1080, r32}, {5120, 1440, 1601, 901, r32}, {3416, 1440, 2560, 1080, r21}, {3416, 1440, 1720, 720, r21},
|
||||
{2560, 1440, 1920, 1080, 0}, {2560, 1440, 1601, 901, 0}, {2560, 1440, 1600, 1200, 0}};
|
||||
for (const auto& k : cases) {
|
||||
g = game_grid::of(k.pw, k.ph, k.ww, k.wh, k.r);
|
||||
const game_grid::Map w = game_grid::map_of(g);
|
||||
const float cw = game_grid::column_w(g);
|
||||
CHECK(w.kx == 1.0f && w.ox == std::round(w.ox) && w.oy == std::round(w.oy));
|
||||
CHECK(near(w.ox + cw * 0.5f, g.x + g.w * 0.5f, 0.5f) && near(w.oy, g.y, 0.5f));
|
||||
}
|
||||
}
|
||||
// the mouse back through the map
|
||||
m = game_grid::map_of(game_grid::of(3416, 1440, 1600, 900, r21));
|
||||
CHECK(near(m.back_x(m.x(123)), 123, 0.01f) && near(m.back_y(m.y(45)), 45, 0.01f));
|
||||
if (!fails) std::puts("the game's grid in the window");
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--cxx", default="clang++")
|
||||
args = parser.parse_args()
|
||||
menu = (VK / "vk_menu.cpp").read_text(encoding="utf-8")
|
||||
shut = block(menu, "void draw_mods_row_shut(ui::Ctx& c) {")
|
||||
check("const game_grid::Place g = menu_grid(c.w, c.h);" in shut and "ui::Ctx k = grid_ctx(c, g);" in shut and
|
||||
"put_on_grid(c.d, vtx0, cmd0, game_grid::map_of(g), window_clip);" in shut,
|
||||
"the entry while the menu is shut is not drawn on the game's grid (a 16:9 column of the window's height)")
|
||||
check("std::floor(c.h * 16.0f / 9.0f" not in shut, "the shut entry still takes the window's height")
|
||||
grid = block(menu, "game_grid::Place menu_grid(float w, float h) {")
|
||||
check("present_sizes.load(" in grid and "host->aspect_ratio()" in grid and "game_grid::of(" in grid,
|
||||
"the grid is not taken from the last present's picture and its shape")
|
||||
ctx = block(menu, "ui::Ctx grid_ctx(const ui::Ctx& c, const game_grid::Place& g) {")
|
||||
check("k.h = g.h, k.w = game_grid::column_w(g);" in ctx and "k.s = ui::unit(g.h, 0, false, false, &k.safe);" in ctx,
|
||||
"the entry's sizes are not the grid's")
|
||||
dm = block(menu, "void draw_menu(ui::Ctx& c, bool perf_under) {")
|
||||
check("if (row) {" in dm and "k = grid_ctx(c, g), k.over_game = false;" in dm and "menu_map = game_grid::map_of(g);" in dm and
|
||||
"put_on_grid(c.d, vtx0, cmd0, menu_map, window_clip, perf0, perf1);" in dm, "the open menu's Mods page is not drawn on the game's grid")
|
||||
tick = block(menu, "void menu_tick() {")
|
||||
check("mx = (int)std::floor(menu_map.back_x((float)ix)), my = (int)std::floor(menu_map.back_y((float)iy));" in tick,
|
||||
"the mouse is not taken back through the map the menu was drawn with")
|
||||
with tempfile.TemporaryDirectory(prefix="mods-grid-") as tmp:
|
||||
src, exe = Path(tmp) / "grid.cpp", Path(tmp) / "grid.exe"
|
||||
src.write_text(PROGRAM, encoding="utf-8")
|
||||
subprocess.run([args.cxx, "-std=c++20", "-O1", "-Wall", "-Wextra", "-Werror", "-I" + str(VK), str(src), "-o", str(exe)], check=True)
|
||||
r = subprocess.run([str(exe)], capture_output=True, text=True)
|
||||
check(r.returncode == 0, "the grid:\n" + r.stdout)
|
||||
print(r.stdout.strip())
|
||||
print("PASS: the Mods entry on the game's grid in every window shape")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
564
tests/test_mods_title_entry.py
Normal file
564
tests/test_mods_title_entry.py
Normal file
@@ -0,0 +1,564 @@
|
||||
"""The Mods entry under the title's list drawn and animated as the game's own entries (gpu/vk/mods_entry_anim.h,
|
||||
vk_game_tex.h make_title_band and make_title_skin, vk_menu.cpp draw_title_mods and menu_tick, vk_imgui.cpp; no game).
|
||||
|
||||
(Triforce, 11-19) His "make it the same as the other options, with the green filigree, the same animations: when you
|
||||
select it, it just pops in". Each entry of the title's list is the part PaCommonBtnTitle_00 of the Title archive's layout,
|
||||
which plays its own Select, UnSelect, LoopRandom and Decide. This compiles mods_entry_anim.h and vk_game_tex.h's
|
||||
make_title_band with made-up textures and checks:
|
||||
|
||||
- the layout's curves as read from the part: Select over 1 frame, UnSelect over 8 (half way at 4, not gone after 1),
|
||||
LoopRandom 0.6, 0.5, 0.6 over 40 frames, Decide's filigree from 1 to 0.85 between frames 8 and 16 and its sparkle from
|
||||
frame 2 to 16; a step key (two at one frame) is a step;
|
||||
- the entry's state from drawing to drawing: chosen in a frame, let go over 8, a change back half way starts from where it
|
||||
is (no jump), the entry rising with the list over 15 frames and going over 8 once the list has not been seen for 150 ms
|
||||
(mods_list_fresh's); a game frame late (a 70 ms gap in the host's reports: the 30 fps cap, a hitch) leaves it as it is,
|
||||
and the list back after it went goes on from where the entry was, not from nothing;
|
||||
- the band: (7,4,4) at 0.96 where its shape is whole, thinner (0.58) where the gradient is, nothing outside the shape; the
|
||||
sparkle the noise inside the shape only.
|
||||
- ((Triforce, 11-19) the lab's "much weaker dark shadow than the game's entries ... its glow is fainter than the game's
|
||||
Options glow") the dark edge (T_BtnSh_00) and the glow (P_BtnGlow_00) as text_spread.h has them, fitted to the game's
|
||||
own entries: out from a stroke the edge dark at 6 units and gone by 15, the glow strong at 9 and still there at 21.
|
||||
- ((Triforce, 11-20) the lab's second check: not chosen, "paler and greyer than New Game ... its dark edge weaker" in the
|
||||
1720x720 and 1600x900 windows) at 1440, 900, 720 and 674 picture lines, on a model glyph drawn as draw_title_mods draws
|
||||
it (the copies at their offsets from the text's whole pixel, the text kTextWeight times, the shots' HDR capture): the
|
||||
edge beside the strokes near black (0.9 and over, the game's 0.93-0.96), the strokes no thinner in units than at 1440,
|
||||
the edge gone by 15 units; and the entry as it was (140e05e's rings, snapped, the text once) misses at every size.
|
||||
- ((Triforce, 11-20, a review of cb644b1) the hard shadow (kShadowCore) fades with the text, its 16 copies together the
|
||||
fade's amount of their full darkness (not 0.98 black under text at 0.5); the chosen text drawn kTextWeight times too, its
|
||||
strokes as solid at 720 and 674 lines as at 1440.
|
||||
- ((Triforce, 11-20, lab check 3, shots052c) not chosen, per shape and output: on the model glyph (its strokes 4 to 5.5
|
||||
units) in the five shapes the lab ran (3440x1440, 1680x1050 with a 16:10 picture squeezed across by 0.9, 1720x720,
|
||||
1600x900 with a 21:9 picture of 674 lines, all HDR, and 1720x720 with HDR off) against the game's New Game, Options and
|
||||
Continue measured in the same shots: in HDR the strokes at least half as much bolder than 26670c0's as the game's are
|
||||
(26% at 1440, 31% at 674) and no more than 0.15 of a pixel past the game's, no wider in SDR; the hard shadow softer 3
|
||||
units out in the windows and the 16:10 picture and as it was in the fullscreen; with HDR off the edge as dark as the HDR
|
||||
picture's (each black copy darker: text_spread.h kLookSdr), where 26670c0's was a third as dark. The text's copies fade
|
||||
together (the fade's amount where the text is whole) at every size; the copies a frame counted (159 black, 4 of the text).
|
||||
|
||||
And reads the source for what only the game shows: the title textures read after the menu's own (one missing leaves the
|
||||
skin as it was); the entry drawn with the band, the filigree mirrored on the left and breathing with LoopRandom, the text at
|
||||
65 x 0.8 units in the layout's cream (white when chosen, over its blue glow), no pulsing copies; A or a click on it plays
|
||||
the system menu's "decide" at once and opens the Mods screen after Decide's 16 frames, not twice; the entry drawn on while
|
||||
it fades after its list; the mouse moving up off it gives the cursor back.
|
||||
|
||||
python -I -B tests/test_mods_title_entry.py [--cxx clang++]
|
||||
"""
|
||||
import argparse
|
||||
import subprocess
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
VK = ROOT / "gpu" / "vk"
|
||||
RUN_ALL_ARGS = ["--cxx", "{cxx}"]
|
||||
|
||||
|
||||
def check(ok, why):
|
||||
if not ok:
|
||||
raise SystemExit("FAIL: " + why)
|
||||
|
||||
|
||||
def function(text, head):
|
||||
start = text.index(head)
|
||||
end = text.index("{", start) + 1
|
||||
depth = 1
|
||||
while depth:
|
||||
depth += (text[end] == "{") - (text[end] == "}")
|
||||
end += 1
|
||||
return text[start:end]
|
||||
|
||||
|
||||
PROGRAM = r"""
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <vector>
|
||||
#include "mods_entry_anim.h"
|
||||
#include "vk_game_tex.h"
|
||||
#include "text_spread.h"
|
||||
using namespace mods_entry;
|
||||
// ((Triforce, 11-19) the dark edge's or the glow's alpha at d units out from the edge of a stroke (a half plane of text,
|
||||
// x under 0): each copy a ring's radius r round, at its angle, covers the place when r cos(angle) > d; the copies over it)
|
||||
// ((Triforce, 11-19) as it is drawn (text_spread::ring_drawn: whole steps of 255, the copies as many as keep the coverage),
|
||||
// or with fit set the fitted rings' own float alpha, the entry's fade amount over them)
|
||||
static float spread_at(const text_spread::Spread& s, float d, float amount = 1, bool fit = false) {
|
||||
float keep = d < 0 ? 1 - (fit ? s.centre * amount : (float)text_spread::centre_drawn(s, amount) / 255) : 1;
|
||||
for (int i = 0; i < s.rings; i++) {
|
||||
const text_spread::Drawn dr = text_spread::ring_drawn(s, i, amount);
|
||||
const float r = text_spread::ring_radius(s, i);
|
||||
const float a = fit ? text_spread::ring_alpha(s, i) * amount : (float)dr.alpha / 255;
|
||||
const int n = fit ? text_spread::ring_copies(s, i) : dr.copies;
|
||||
for (int j = 0; j < n; j++)
|
||||
if (r * std::cos(6.2831853f * (float)j / (float)n) > d) keep *= 1 - a;
|
||||
}
|
||||
return 1 - keep;
|
||||
}
|
||||
// (over a pixel of the lab's shots, 3 units: the half plane's edge at a single d is sharper than any pixel, and a ring of
|
||||
// a few copies more or fewer moves which of them pass it)
|
||||
static float spread_px(const text_spread::Spread& s, float d, float amount, bool fit) {
|
||||
float sum = 0;
|
||||
for (int i = 0; i <= 12; i++) sum += spread_at(s, d - 1.5f + 0.25f * (float)i, amount, fit);
|
||||
return sum / 13;
|
||||
}
|
||||
// ((Triforce, 11-20, lab check 3) the entry not chosen as drawn in one of the lab's shapes, on a model glyph: two stems of
|
||||
// the Cetra Display "Normal" text at the entry's size (sw units wide: ImGui draws its strokes 4 to 5.5, 40 high, 12 apart,
|
||||
// as in "M" or "n"), each pixel's coverage the stems' area in it. lines: the picture's (2160 / lines units a pixel down); kx: the grid's
|
||||
// squeeze across (0.9 on a 16:10 picture: the stems and every copy's offset across with it, as put_on_grid moves the
|
||||
// drawing); hdr: the shots' HDR capture (the overlay in PQ code values: a black copy of alpha a darkens 1 - (1 - a)^2) or
|
||||
// SDR (8-bit code values: a). The black copies (the core and the soft edge) and the text's own (its weight: in place or
|
||||
// out across, each at its alpha) at their offsets from the text's whole pixel, the entry at a part of a pixel (fx, fy),
|
||||
// over a background of 110 (the wheat and grass round the list in the shots)
|
||||
struct Copy { float dx, dy; int a; };
|
||||
struct Shape {
|
||||
float solid; // (pixels across a stem where the text shows solid: 0.72 of its brightness and over)
|
||||
float darkest; // (the darkest of the background within 15 units of the strokes, of 1)
|
||||
float at3, at6, at9; // (the background's darkness 3, 6 and 9 units out from a stem's side, along its middle)
|
||||
};
|
||||
static float overlap(float a0, float a1, float b0, float b1) { return std::max(0.0f, std::min(a1, b1) - std::max(a0, b0)); }
|
||||
static Shape shape_model(float lines, float kx, bool hdr, const std::vector<Copy>& black, const std::vector<Copy>& text, float sw, float fx, float fy) {
|
||||
const float u = 2160.0f / lines, ux = u / kx; // (units a pixel down and across)
|
||||
const float sh = 40.0f, gap = 12.0f, bg = 110;
|
||||
const int W = (int)std::ceil(90 / ux), H = (int)std::ceil(90 / u);
|
||||
const float tx = std::floor(W * 0.5f - (sw + gap * 0.5f) / ux) + fx, ty = std::floor(H * 0.5f - sh * 0.5f / u) + fy;
|
||||
auto cover = [&](int x, int y, float ox, float oy) { // (of pixel (x, y): the stems with their top left at (ox, oy))
|
||||
float c = 0;
|
||||
for (int s = 0; s < 2; s++) {
|
||||
const float l = ox + s * (sw + gap) / ux;
|
||||
c += overlap((float)x, x + 1.0f, l, l + sw / ux) * overlap((float)y, y + 1.0f, oy, oy + sh / u);
|
||||
}
|
||||
return std::min(1.0f, c);
|
||||
};
|
||||
std::vector<float> keep((size_t)W * H, 1.0f), through((size_t)W * H, 1.0f);
|
||||
for (const Copy& k : black)
|
||||
for (int y = 0; y < H; y++)
|
||||
for (int x = 0; x < W; x++) keep[(size_t)y * W + x] *= 1 - (float)k.a / 255.0f * cover(x, y, tx + k.dx / ux, ty + k.dy / u);
|
||||
for (const Copy& k : text)
|
||||
for (int y = 0; y < H; y++)
|
||||
for (int x = 0; x < W; x++) through[(size_t)y * W + x] *= 1 - (float)k.a / 255.0f * cover(x, y, tx + k.dx / ux, ty + k.dy / u);
|
||||
auto lum = [&](int x, int y) {
|
||||
const float k = keep[(size_t)y * W + x], c = 1 - through[(size_t)y * W + x];
|
||||
return bg * (hdr ? k * k : k) * (1 - c) + 255 * c;
|
||||
};
|
||||
Shape e{0, 0, 0, 0, 0};
|
||||
const int mid = (int)(ty + sh * 0.5f / u);
|
||||
int runs = 0, run = 0;
|
||||
float len = 0;
|
||||
for (int x = 0; x < W; x++) {
|
||||
if (lum(x, mid) >= 0.72f * 255) run++;
|
||||
else if (run) runs++, len += (float)run, run = 0;
|
||||
}
|
||||
e.solid = runs ? len / (float)runs : 0;
|
||||
for (int y = 0; y < H; y++)
|
||||
for (int x = 0; x < W; x++) {
|
||||
if (cover(x, y, tx, ty) > 0) continue;
|
||||
const float px = x + 0.5f, py = y + 0.5f;
|
||||
float d = 1e9f; // (units to the nearest stem)
|
||||
for (int s = 0; s < 2; s++) {
|
||||
const float l = tx + s * (sw + gap) / ux;
|
||||
const float ddx = std::max({0.0f, l - px, px - (l + sw / ux)}) * ux, ddy = std::max({0.0f, ty - py, py - (ty + sh / u)}) * u;
|
||||
d = std::min(d, std::hypot(ddx, ddy));
|
||||
}
|
||||
if (d <= 15) e.darkest = std::max(e.darkest, 1 - lum(x, y) / bg);
|
||||
}
|
||||
// (out from the left stem's left side along its middle, between pixels as the picture's filter reads it)
|
||||
auto row_at = [&](float units) {
|
||||
const float x = tx - units / ux - 0.5f;
|
||||
const int x0 = (int)std::floor(x);
|
||||
const float t = x - x0;
|
||||
return 1 - ((1 - t) * lum(x0, mid) + t * lum(x0 + 1, mid)) / bg;
|
||||
};
|
||||
e.at3 = row_at(3), e.at6 = row_at(6), e.at9 = row_at(9);
|
||||
return e;
|
||||
}
|
||||
// (over the entry's places in a pixel, where the window puts the list, and the strokes' widths of "Mods")
|
||||
static Shape shape_avg(float lines, float kx, bool hdr, const std::vector<Copy>& black, const std::vector<Copy>& text) {
|
||||
Shape s{0, 0, 0, 0, 0};
|
||||
const float fs[4] = {0.0f, 0.3f, 0.55f, 0.8f}, sws[4] = {4.0f, 4.5f, 5.0f, 5.5f};
|
||||
for (float sw : sws)
|
||||
for (float fx : fs)
|
||||
for (float fy : fs) {
|
||||
const Shape e = shape_model(lines, kx, hdr, black, text, sw, fx, fy);
|
||||
s.solid += e.solid / 64, s.darkest += e.darkest / 64, s.at3 += e.at3 / 64, s.at6 += e.at6 / 64, s.at9 += e.at9 / 64;
|
||||
}
|
||||
return s;
|
||||
}
|
||||
// ((Triforce, 11-20) the model glyph's stems drawn weight times over themselves on their whole pixel, at grid_h lines: their
|
||||
// width in units where the text shows solid (0.72 and over, as Edge's weight), over the entry's places in a pixel; the
|
||||
// background's own brightness left out (the chosen text is over the blue glow, not the wheat))
|
||||
static float solid_units(float grid_h, int weight) {
|
||||
const float u = 2160.0f / grid_h, sw = 4.5f, gap = 12.0f;
|
||||
float sum = 0;
|
||||
for (int i = 0; i < 16; i++) {
|
||||
const float l0 = 4 + (float)i / 16; // (pixels: the left stem's left side)
|
||||
for (int x = 0; x < (int)std::ceil(80 / u); x++) {
|
||||
float c = 0;
|
||||
for (int s = 0; s < 2; s++) {
|
||||
const float l = l0 + s * (sw + gap) / u;
|
||||
c += overlap((float)x, x + 1.0f, l, l + sw / u);
|
||||
}
|
||||
if (1 - std::pow(1 - std::min(1.0f, c), (float)weight) >= 0.72f) sum += u * 0.5f / 16; // (two stems)
|
||||
}
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
static std::vector<Copy> copies_of(std::initializer_list<text_spread::Spread> spreads, float amount = 1) {
|
||||
std::vector<Copy> v;
|
||||
for (const text_spread::Spread& s : spreads) text_spread::each_copy(s, amount, [&](float dx, float dy, int a) { v.push_back({dx, dy, a}); });
|
||||
return v;
|
||||
}
|
||||
static std::vector<Copy> text_of(const text_spread::Weight& w, float lines, float amount = 1) {
|
||||
std::vector<Copy> v;
|
||||
text_spread::each_weight_copy(w, lines, amount, [&](float dx, float dy, int a) { v.push_back({dx, dy, a}); });
|
||||
return v;
|
||||
}
|
||||
// (where the text is whole: how opaque its copies together are, of 1 (those in place and those out across all over it))
|
||||
static float text_whole(const std::vector<Copy>& text) {
|
||||
float through = 1;
|
||||
for (const Copy& k : text) through *= 1 - (float)k.a / 255.0f;
|
||||
return 1 - through;
|
||||
}
|
||||
static int fails = 0;
|
||||
#define CHECK(x) do { if (!(x)) { std::printf("FAIL:%d %s\n", __LINE__, #x); fails++; } } while (0)
|
||||
static bool near(float a, float b, float tol = 0.01f) { return std::fabs(a - b) <= tol; }
|
||||
int main() {
|
||||
// the layout's curves
|
||||
CHECK(near(curve(kSelect, 0), 0) && near(curve(kSelect, 1), 1) && near(curve(kSelect, 5), 1));
|
||||
CHECK(near(curve(kUnSelect, 0), 1) && near(curve(kUnSelect, 4), 0.5f) && near(curve(kUnSelect, 8), 0));
|
||||
CHECK(curve(kUnSelect, 1) > 0.9f); // (not gone after a frame: the fade the game's own entries show)
|
||||
CHECK(near(curve(kLoop, 0), 0.6f) && near(curve(kLoop, 20), 0.5f) && near(curve(kLoop, 40), 0.6f));
|
||||
CHECK(near(curve(kDecideDeco, 4), 1) && near(curve(kDecideDeco, 8), 1) && near(curve(kDecideDeco, 16), 0.85f));
|
||||
CHECK(curve(kDecideDeco, 12) < 1 && curve(kDecideDeco, 12) > 0.85f);
|
||||
CHECK(near(curve(kDecideGlow, 16), 0.95f) && near(curve(kDecideFlash, 2), 0) && near(curve(kDecideFlash, 16), 1));
|
||||
CHECK(near(curve(kListIn, 0), 0) && near(curve(kListIn, 15), 1) && near(curve(kListIn, 7.5f), 0.275f)); // (slow to start: its slopes)
|
||||
const Key step[] = {{0, 0, 0}, {5, 0, 0}, {5, 1, 0}, {9, 1, 0}};
|
||||
CHECK(near(curve(step, 4, 5), 0) && near(curve(step, 4, 5.01f), 1));
|
||||
CHECK(kDecideNs == 16 * kFrameNs && kListGoneNs == 150000000 && kListShownNs == kListGoneNs + 8 * kFrameNs);
|
||||
CHECK(in_at(0) == 0 && near(curve(kListIn, frames(in_at(0.275f))), 0.275f) && near(curve(kListIn, frames(in_at(1))), 1));
|
||||
// the entry from drawing to drawing (now in ns; the list told each frame unless said)
|
||||
Anim a;
|
||||
int64_t t = 1000000000;
|
||||
a.step(t, false, 0);
|
||||
CHECK(near(a.focus, 0) && near(a.shown, 0)); // (the list just came: the entry rises with it)
|
||||
a.step(t + 15 * kFrameNs, false, 0);
|
||||
CHECK(near(a.shown, 1));
|
||||
t += 20 * kFrameNs;
|
||||
a.step(t, true, 0); // (the cursor onto Mods)
|
||||
a.step(t + kFrameNs, true, 0);
|
||||
CHECK(near(a.focus, 1));
|
||||
a.step(t + 2 * kFrameNs, false, 0); // (and off it: UnSelect)
|
||||
a.step(t + 3 * kFrameNs, false, 0);
|
||||
CHECK(a.focus > 0.9f && a.focus < 1);
|
||||
a.step(t + 6 * kFrameNs, false, 0);
|
||||
CHECK(near(a.focus, 0.5f));
|
||||
a.step(t + 7 * kFrameNs, true, 0); // (back half way: from where it is, no jump down or up first)
|
||||
CHECK(a.focus >= 0.49f);
|
||||
a.step(t + 8 * kFrameNs, true, 0);
|
||||
CHECK(near(a.focus, 1));
|
||||
a.step(t + 9 * kFrameNs, false, 0);
|
||||
a.step(t + 17 * kFrameNs, false, 0);
|
||||
CHECK(near(a.focus, 0));
|
||||
CHECK(near(a.loop(a.since_ns + 20 * kFrameNs), 0.5f) && near(a.loop(a.since_ns + 40 * kFrameNs), 0.6f));
|
||||
// ((11-19) a game frame late: 70 ms with no report, then reports again: the entry stays, no blink)
|
||||
a.step(t + 18 * kFrameNs, false, 70000000);
|
||||
CHECK(near(a.shown, 1));
|
||||
a.step(t + 19 * kFrameNs, false, 0);
|
||||
CHECK(near(a.shown, 1));
|
||||
// the list gone: shown on for 150 ms, then down over 8 frames
|
||||
a.step(t + 20 * kFrameNs, false, kListGoneNs - kFrameNs);
|
||||
CHECK(near(a.shown, 1));
|
||||
a.step(t + 21 * kFrameNs, false, kListGoneNs + 4 * kFrameNs);
|
||||
CHECK(near(a.shown, 0.5f));
|
||||
a.step(t + 22 * kFrameNs, false, kListShownNs);
|
||||
CHECK(near(a.shown, 0));
|
||||
a.step(t + 23 * kFrameNs, false, 0); // (and back: rises again, from nothing as it is)
|
||||
CHECK(near(a.shown, 0));
|
||||
a.step(t + 30 * kFrameNs, false, 0);
|
||||
CHECK(a.shown > 0.1f && a.shown < 0.9f);
|
||||
{ // (gone half way and back: on from where it was, not from nothing)
|
||||
Anim b;
|
||||
b.step(t, false, 0), b.step(t + 20 * kFrameNs, false, 0);
|
||||
b.step(t + 21 * kFrameNs, false, kListGoneNs + 4 * kFrameNs);
|
||||
CHECK(near(b.shown, 0.5f));
|
||||
b.step(t + 22 * kFrameNs, false, 0);
|
||||
CHECK(near(b.shown, 0.5f, 0.03f));
|
||||
b.step(t + 40 * kFrameNs, false, 0);
|
||||
CHECK(near(b.shown, 1));
|
||||
}
|
||||
// Decide
|
||||
const Decide none = decide_at(-1), mid = decide_at(12 * kFrameNs), end = decide_at(30 * kFrameNs);
|
||||
CHECK(near(none.deco, 1) && near(none.glow, 1) && near(none.flash, 0));
|
||||
CHECK(mid.deco < 1 && mid.flash > 0 && near(end.deco, 0.85f) && near(end.glow, 0.95f) && near(end.flash, 1));
|
||||
// the band and the sparkle from made-up masks: the shape whole, then whole with the gradient, then none
|
||||
using namespace mkwvk::game_tex;
|
||||
auto mask = [](std::initializer_list<int> v) {
|
||||
Image im;
|
||||
im.w = (uint32_t)v.size(), im.h = 1, im.mask = true;
|
||||
for (int x : v) im.rgba.insert(im.rgba.end(), {255, 255, 255, (unsigned char)x});
|
||||
return im;
|
||||
};
|
||||
Image band, sparkle;
|
||||
make_title_band(mask({255, 255, 0}), mask({0, 255, 255}), mask({200, 100, 50, 25}), &band, &sparkle);
|
||||
CHECK(band.w == 3 && band.h == 1 && !band.mask && sparkle.mask);
|
||||
CHECK(band.rgba[0] == 7 && band.rgba[1] == 4 && band.rgba[2] == 4 && band.rgba[3] == 245); // (0.96)
|
||||
CHECK(band.rgba[7] == 147); // (0.96 x 0.6 where the gradient is whole)
|
||||
CHECK(band.rgba[11] == 0); // (outside the shape)
|
||||
CHECK(sparkle.rgba[3] == 200 && sparkle.rgba[7] == 25 && sparkle.rgba[11] == 0); // (the noise 3 texels a texel along, in the shape)
|
||||
// ((Triforce, 11-19) the lab's "much weaker dark shadow than the game's entries ... its glow is fainter than the game's
|
||||
// Options glow": the dark edge and the glow as fitted to the game's own entries (text_spread.h). Out from a stroke's
|
||||
// edge, in units (3 a pixel of the lab's 720-line shots): the edge dark at 6 units, gone by 15; the glow strong at 9,
|
||||
// still there at 21, gone by 33. Before: one shadow copy (no edge at the sides at all), the glow gone at 15)
|
||||
using text_spread::kGlow;
|
||||
using text_spread::kLookHdr;
|
||||
using text_spread::kLookSdr;
|
||||
const text_spread::Spread& kShadow = kLookHdr.shadow;
|
||||
CHECK(spread_at(kGlow, 3) > 0.85f && spread_at(kGlow, 9) > 0.6f && spread_at(kGlow, 21) > 0.1f && spread_at(kGlow, 33) < 0.01f);
|
||||
// ((11-19, a review of 3d1a417) what is drawn is the fit: each copy's alpha cut to a whole step of 255 drew the shadow
|
||||
// at 0.313 for 0.362 at 6 units and the glow at 0.115 for 0.177 at 21, nothing at 27; and as the entry fades in)
|
||||
for (float amount : {1.0f, 0.6f, 0.25f})
|
||||
for (float d = 0; d <= 30; d += 3) {
|
||||
const float gl = spread_px(kGlow, d, amount, true);
|
||||
for (const text_spread::Spread* sp : {&kLookHdr.shadow, &kLookSdr.shadow}) {
|
||||
const float sh = spread_px(*sp, d, amount, true);
|
||||
CHECK(near(spread_px(*sp, d, amount, false), sh, 0.01f + 0.04f * sh));
|
||||
}
|
||||
CHECK(near(spread_px(kGlow, d, amount, false), gl, 0.01f + 0.04f * gl));
|
||||
}
|
||||
CHECK(spread_at(kGlow, 27) > 0.02f && text_spread::ring_drawn(kGlow, 9, 1).alpha == 1 && text_spread::ring_drawn(kGlow, 9, 1).copies == 48 &&
|
||||
text_spread::ring_drawn(kGlow, 8, 1).copies == 77); // (the outer rings at 1 of 255, as many copies as their 0.77 and 1.36)
|
||||
CHECK(text_spread::centre_drawn(kGlow, 1) == 255 && text_spread::ring_drawn(kGlow, 0, 0).alpha == 0);
|
||||
CHECK(text_spread::ring_copies(kGlow, 9) == 63 && text_spread::ring_copies(kShadow, 0) == 8); // (a copy about every 3 units)
|
||||
CHECK(near(text_spread::ring_alpha(kGlow, 0), 18.01f / 255, 0.001f) && near(kGlow.down, 0) && near(kGlow.centre, 1));
|
||||
// (the chosen text: kTextWeight times over itself, each at weight_alpha)
|
||||
CHECK(text_spread::kTextWeight == 2 && near(text_spread::weight_alpha(1), 1, 1e-6f) && near(text_spread::weight_alpha(0), 0, 1e-6f));
|
||||
for (float a : {0.1f, 0.5f, 0.9f}) // (fading: the text whole where it is whole, at the fade's alpha)
|
||||
CHECK(near(1 - std::pow(1 - text_spread::weight_alpha(a), (float)text_spread::kTextWeight), a, 1e-4f));
|
||||
// ((Triforce, 11-20, lab check 3) the text not chosen per output: HDR (the shots' PQ capture) and SDR (8-bit code values)
|
||||
// have their own black copies, the SDR ones darker each (about 1 - (1 - a)^2 of HDR's: the lab's "edge much too weak ...
|
||||
// Mods reads pale" with HDR off); the same places (the core 2.55 units down, 14 times; the soft edge's rings)
|
||||
CHECK(&text_spread::look_of(true) == &kLookHdr && &text_spread::look_of(false) == &kLookSdr);
|
||||
CHECK(kLookHdr.core.repeat == kLookSdr.core.repeat && near(kLookHdr.core.down, kLookSdr.core.down) && kLookHdr.shadow.rings == kLookSdr.shadow.rings &&
|
||||
near(kLookHdr.shadow.down, kLookSdr.shadow.down) && near(kLookHdr.shadow.sigma, kLookSdr.shadow.sigma));
|
||||
CHECK(text_spread::centre_drawn(kLookSdr.core, 1) > text_spread::centre_drawn(kLookHdr.core, 1) + 40 &&
|
||||
text_spread::ring_drawn(kLookSdr.shadow, 0, 1).alpha > text_spread::ring_drawn(kLookHdr.shadow, 0, 1).alpha);
|
||||
// ((Triforce, 11-20, a review of cb644b1) the hard shadow fades with the text: where the text is solid its copies
|
||||
// together are the fade's amount of their full darkness, as the text's alpha is; each at amount x 0.45 they stacked to
|
||||
// 0.98 black at 0.5 and 0.86 at 0.25 (the list rising, going, UnSelect over the blue glow). Each copy a whole step of 255.
|
||||
// ((11-20, lab check 3) and the text's own copies, in place and out across, together the fade's amount where it is whole
|
||||
// (each_weight_copy): no brighter step through the fades, at every size and in both outputs)
|
||||
for (const text_spread::Look* look : {&kLookHdr, &kLookSdr}) {
|
||||
const text_spread::Spread& core = look->core;
|
||||
const int n = core.repeat;
|
||||
auto core_dark = [&](float amount) { return 1 - std::pow(1 - (float)text_spread::centre_drawn(core, amount) / 255, (float)n); };
|
||||
const float full = core_dark(1);
|
||||
CHECK(full > 0.995f);
|
||||
for (float a : {0.1f, 0.25f, 0.5f, 0.6f, 0.9f}) {
|
||||
if (getenv("TITLE_ENTRY_DEBUG")) std::printf("core at %.2f: %d of 255 a copy, %.3f dark\n", a, text_spread::centre_drawn(core, a), core_dark(a));
|
||||
CHECK(near(core_dark(a), a * full, 0.025f));
|
||||
for (float lines : {1440.0f, 1050.0f, 720.0f, 674.0f}) {
|
||||
CHECK(near(text_whole(text_of(look->weight, lines, a)), a, 0.012f)); // (the text's)
|
||||
CHECK(near(core_dark(a), text_whole(text_of(look->weight, lines, a)), 0.03f));
|
||||
}
|
||||
int same = 0;
|
||||
text_spread::each_copy(core, a, [&](float dx, float dy, int q) { same += dx == 0 && near(dy, core.down) && q == text_spread::centre_drawn(core, a); });
|
||||
CHECK(same == n);
|
||||
}
|
||||
CHECK(text_spread::centre_drawn(core, 0) == 0 && text_of(look->weight, 720, 0).empty());
|
||||
for (float lines : {1440.0f, 720.0f}) CHECK(near(text_whole(text_of(look->weight, lines, 1)), 1, 1e-6f));
|
||||
}
|
||||
CHECK(text_spread::centre_drawn(kGlow, 0.5f) == 128 && text_spread::centre_drawn(kGlow, 0.25f) == 64); // (one copy: as before)
|
||||
// ((Triforce, 11-20, a review of cb644b1) the text chosen at the game's weight too (the same font and size as the unchosen
|
||||
// text, T_Btn_02): the strokes as solid in units at 720 and 674 lines as at 1440; drawn once, 1 whole pixel at 720 lines)
|
||||
{
|
||||
const float full = solid_units(1440, text_spread::kTextWeight);
|
||||
for (float h : {720.0f, 674.0f}) {
|
||||
if (getenv("TITLE_ENTRY_DEBUG"))
|
||||
std::printf("%4.0f lines, chosen: solid %.2f units drawn %d times, %.2f once (1440: %.2f)\n", h, solid_units(h, text_spread::kTextWeight),
|
||||
text_spread::kTextWeight, solid_units(h, 1), full);
|
||||
CHECK(solid_units(h, text_spread::kTextWeight) >= full - 0.05f);
|
||||
CHECK(solid_units(h, 1) < full - 1);
|
||||
}
|
||||
}
|
||||
{ // ((Triforce, 11-20, lab check 3) the cost: copies of "Mods" a frame, not chosen (the chosen glow's are as before)
|
||||
for (const text_spread::Look* look : {&kLookHdr, &kLookSdr}) {
|
||||
int n = 0;
|
||||
for (const text_spread::Spread* sp : {&look->core, &look->shadow}) text_spread::each_copy(*sp, 1, [&](float, float, int) { n++; });
|
||||
const int text = (int)text_of(look->weight, 1440, 1).size();
|
||||
if (getenv("TITLE_ENTRY_DEBUG")) std::printf("%s: %d black copies and %d of the text a frame\n", look == &kLookHdr ? "HDR" : "SDR", n, text);
|
||||
CHECK(n <= 165 && text <= 4);
|
||||
int gone = 0;
|
||||
text_spread::each_copy(look->shadow, 0, [&](float, float, int) { gone++; }); // (gone with the entry)
|
||||
CHECK(gone == 0);
|
||||
}
|
||||
}
|
||||
{ // ((Triforce, 11-20, lab check 3) the shapes the lab ran (shots052c), each against the game's own New Game, Options
|
||||
// and Continue in the same shots: fullscreen 3440x1440 (1440 lines), the 1680x1050 window with a 16:10 picture
|
||||
// (1050 lines, squeezed across by 0.9), the 1720x720 window (720), the 1600x900 window with the 21:9 picture (674),
|
||||
// all HDR, and the 1720x720 window with HDR off. 26670c0's look: the text twice in place, a hard shadow of 16 copies of
|
||||
// 115 2.5 units down and a soft edge of 9.49 (HDR's fit, in SDR too)
|
||||
const text_spread::Spread core0{0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0, 115.0f / 255.0f, 2.5f, 16};
|
||||
const text_spread::Spread shadow0{9.49f / 255.0f, 10.9f, 1.2f, 1.5f, 2.3f, 7, 0.0f, 1.75f};
|
||||
const std::vector<Copy> black0 = copies_of({core0, shadow0}), text0 = {{0, 0, 255}, {0, 0, 255}};
|
||||
// (the lab's numbers: across a stroke, the mean of the runs of pixels at 0.72 of the text's brightness and over, the
|
||||
// game's three entries' (low, high) and 26670c0's Mods in the same shots)
|
||||
struct Cond { const char* name; float lines, kx; bool hdr; float game_lo, game_hi, mods; };
|
||||
const Cond conds[] = {{"3440x1440", 1440, 1, true, 4.28f, 4.61f, 3.51f}, {"1680x1050 16:10", 1050, 1680.0f / 1867.0f, true, 2.60f, 2.79f, 2.44f},
|
||||
{"1720x720", 720, 1, true, 2.03f, 2.08f, 1.82f}, {"1600x900 21:9", 674, 1, true, 2.00f, 2.06f, 1.54f},
|
||||
{"1720x720 SDR", 720, 1, false, 1.68f, 1.80f, 1.84f}};
|
||||
Shape now[5], before[5];
|
||||
for (int i = 0; i < 5; i++) {
|
||||
const Cond& c = conds[i];
|
||||
const text_spread::Look& look = text_spread::look_of(c.hdr);
|
||||
now[i] = shape_avg(c.lines, c.kx, c.hdr, copies_of({look.core, look.shadow}), text_of(look.weight, c.lines));
|
||||
before[i] = shape_avg(c.lines, c.kx, c.hdr, black0, text0);
|
||||
if (getenv("TITLE_ENTRY_DEBUG"))
|
||||
std::printf("%-16s now: solid %.2f px, darkest %.3f, %.3f %.3f %.3f at 3, 6, 9 units; 26670c0: %.2f, %.3f, %.3f %.3f %.3f\n", c.name,
|
||||
now[i].solid, now[i].darkest, now[i].at3, now[i].at6, now[i].at9, before[i].solid, before[i].darkest, before[i].at3,
|
||||
before[i].at6, before[i].at9);
|
||||
// (the strokes: as the lab would measure them, 26670c0's Mods times the model's gain over 26670c0. In HDR the game's
|
||||
// are bolder than 26670c0's in every shape (by 26% at 1440 lines, 31% at 674): at least half of that, and no more
|
||||
// than 0.15 of a pixel past the game's. With HDR off the game's are 1.74 for 26670c0's 1.84: no wider)
|
||||
const float gain = now[i].solid / before[i].solid, as_shot = c.mods * gain;
|
||||
if (c.hdr) {
|
||||
const float short_by = (c.game_lo + c.game_hi) * 0.5f / c.mods;
|
||||
if (getenv("TITLE_ENTRY_DEBUG")) std::printf(" strokes %.2f as shot (the game's %.2f-%.2f), %.0f%% bolder for the game's %.0f%%\n", as_shot, c.game_lo, c.game_hi, 100 * (gain - 1), 100 * (short_by - 1));
|
||||
CHECK(gain - 1 >= 0.5f * (short_by - 1));
|
||||
CHECK(as_shot <= c.game_hi + 0.15f && as_shot >= c.game_lo - 0.25f);
|
||||
} else
|
||||
CHECK(gain <= 1.0f);
|
||||
}
|
||||
// (the edge, as the lab saw it. The 1720x720 window: "a hard, near-black drop shadow under the strokes, darker and
|
||||
// crisper than New Game's soft halo", 3 units out 0.37-0.53 dark for New Game's 0.20-0.42 (the 1600x900 window and
|
||||
// 16:10 alike): softer there now, still near black next to the strokes. Fullscreen: "the edge is OK": as it was)
|
||||
for (int i : {1, 2, 3}) CHECK(now[i].at3 <= before[i].at3 - 0.03f && now[i].darkest >= 0.8f);
|
||||
CHECK(std::fabs(now[0].at3 - before[0].at3) <= 0.03f && std::fabs(now[0].at6 - before[0].at6) <= 0.03f && now[0].darkest >= 0.99f);
|
||||
for (int i : {0, 1, 2, 3}) CHECK(std::fabs(now[i].at6 - before[i].at6) <= 0.03f && now[i].at9 <= 0.34f);
|
||||
// (HDR off: "the edge much too weak (6 units 0.09-0.31 dark for New Game's 0.41-0.53; 3 units -0.11-0.30 for 0.08-0.40),
|
||||
// Mods reads pale": in 8-bit code values the black copies darken a third as much as the HDR shots show them. Now as the
|
||||
// HDR picture's edge at 720 lines, near black next to the strokes)
|
||||
CHECK(now[4].at6 >= before[4].at6 + 0.15f && now[4].at3 >= before[4].at3 + 0.15f && now[4].darkest >= 0.88f && before[4].darkest < 0.8f);
|
||||
CHECK(std::fabs(now[4].at6 - now[2].at6) <= 0.05f && std::fabs(now[4].at9 - now[2].at9) <= 0.05f);
|
||||
}
|
||||
if (!fails) std::puts("the title entry's curves, state and band");
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--cxx", default="clang++")
|
||||
args = parser.parse_args()
|
||||
tex = (VK / "vk_game_tex.h").read_text(encoding="utf-8")
|
||||
imgui = (VK / "vk_imgui.cpp").read_text(encoding="utf-8")
|
||||
menu = (VK / "vk_menu.cpp").read_text(encoding="utf-8")
|
||||
host = (ROOT / "host" / "oot_menu.c").read_text(encoding="utf-8")
|
||||
|
||||
# the textures: the title archive's, after the menu's own; one missing keeps the skin
|
||||
art = function(imgui, "void art_thread() {")
|
||||
check('"UI/Layout2Archive/Title.Product.100.Nin_Ounce_NVN2.bntx.zs"' in art and "game_tex::make_title_skin(std::move(bytes), skin_)" in art,
|
||||
"the title list's textures are not read")
|
||||
check(art.index("make_skin(") < art.index("make_title_skin(") and "art_state.store(ok || title ? 2 : 4" in art,
|
||||
"the title's textures are not read after the menu's, or one set missing throws the other away")
|
||||
skin = function(tex, "inline bool make_title_skin(")
|
||||
for name in ("CtrlGuideBG_00", "CtrlGuideBGGrd_00", "DecideNoise_01", "TitleBtnDeco_00", "TitleBtnDecoGlow_00"):
|
||||
check('"%s"' % name in skin, "make_title_skin does not read " + name)
|
||||
check(skin.index("return false") < skin.index("skin.images.push_back"), "make_title_skin changes the skin before it has every texture")
|
||||
|
||||
# the drawing: the part's look, the layout's colours, no pulse
|
||||
draw = function(menu, "void draw_title_mods(")
|
||||
for part in ('ui::art("title_band")', 'ui::art("title_decide")', 'ui::art("TitleBtnDeco_00")', 'ui::art("TitleBtnDecoGlow_00")',
|
||||
"title_anim.step(now, sel,", "title_anim.loop(now)", "side < 0);", "mods_entry::decide_at(",
|
||||
"kTitleText * ui::kType * k"):
|
||||
check(part in draw, "draw_title_mods does not draw " + part)
|
||||
check("c.pulse" not in draw, "the title's entry still pulses with the options' cursor, not the game's LoopRandom")
|
||||
# ((11-19) the dark edge and the glow: the text's own shape spread, text_spread.h's rings, under the text)
|
||||
check('#include "text_spread.h"' in menu and "spread(look.shadow, ui::rgba(0, 0, 0), a);" in draw and
|
||||
"spread(text_spread::kGlow, kTitleGlow, f * show);" in draw, "the title entry's shadow and glow are not the game's")
|
||||
# ((Triforce, 11-20, lab check 3) not chosen: the look of the window's output (HDR10 or SDR), its core and soft edge, then
|
||||
# the text's weight copies; the chosen text over its glow as before)
|
||||
unsel_text = "text_spread::each_weight_copy(look.weight, ui::lu(c, 2160 * k), a,"
|
||||
check("const text_spread::Look& look = text_spread::look_of(dev.hdr);" in draw,
|
||||
"the title entry not chosen is drawn with the HDR fit whatever the output (with HDR off its edge a third as dark)")
|
||||
check(draw.index("spread(look.core, ui::rgba(0, 0, 0), a);") < draw.index("spread(look.shadow, ui::rgba(0, 0, 0), a);") < draw.index(unsel_text) and
|
||||
draw.index("spread(text_spread::kGlow, kTitleGlow, f * show);") <
|
||||
draw.index("for (int i = 0; i < text_spread::kTextWeight; i++) c.d->AddText(c.f.body, px, at, ink_sel, label);"),
|
||||
"the title entry's text is not over its shadow and glow")
|
||||
# ((11-20, a review of cb644b1) the chosen text at the game's weight too: drawn kTextWeight times, each at weight_alpha)
|
||||
check("const ImU32 ink_sel = ui::alpha(kTitleInkSel, text_spread::weight_alpha(f * show));" in draw and
|
||||
"ui::alpha(kTitleInkSel, f * show), label);" not in draw,
|
||||
"the chosen title entry's text is drawn once, thinner than the game's chosen Continue and Options (and than Mods not chosen)")
|
||||
check("text_spread::each_copy(sp, amount * own," in draw and "ui::lu(c, dx * k)" in draw and "ui::lu(c, dy * k)" in draw,
|
||||
"the copies are not drawn as text_spread.h has them (whole steps of 255, the copies keeping the coverage)")
|
||||
# ((11-20) the lab's "paler and greyer ... its dark edge weaker" in the windows: the text at the game's weight over the
|
||||
# hard shadow, each copy at its own offset from the text's whole pixel (not snapped: an offset under a pixel went to 0 or 1))
|
||||
# ((Triforce, 11-20, lab check 3) the weight by the text's size, its copies across at their offsets (a part of a unit,
|
||||
# not snapped), in the layout's cream at each copy's alpha
|
||||
weight = draw[draw.index(unsel_text):]
|
||||
weight = weight[:weight.index("});") + 3]
|
||||
check("c.d->AddText(c.f.body, px, ImVec2(at.x + ui::lu(c, dx * k), at.y + ui::lu(c, dy * k)), ink_rgb | (ImU32)q << IM_COL32_A_SHIFT, label);" in weight and
|
||||
"const ImU32 ink_rgb = kTitleInk & ~IM_COL32_A_MASK;" in draw and
|
||||
draw.rindex("c.d->Flags |= ImDrawListFlags_TextNoPixelSnap;", 0, draw.index(unsel_text)) > draw.index("spread(look.shadow, ui::rgba(0, 0, 0), a);"),
|
||||
"the title entry's text is not drawn at the game's weight (text_spread::each_weight_copy, its copies across not snapped)")
|
||||
check("const ImVec2 at(std::floor(m.x - tw * 0.5f), std::floor(ui::mid_top(c.f.body, px, ty)));" in draw and
|
||||
"c.d->Flags |= ImDrawListFlags_TextNoPixelSnap;" in draw and "c.d->Flags = flags;" in draw,
|
||||
"the shadow's and glow's copies are still snapped to whole pixels each, not put at their offsets from the text")
|
||||
check("ui::alpha(col, text_spread::ring_alpha" not in draw, "a ring's alpha is still cut to a whole step of 255 (ui::alpha)")
|
||||
check("constexpr float kTitleText = 65 * 0.8f," in menu, "the title entry's text is not the layout's 65 x 0.8 units")
|
||||
check("kTitleInk = ui::rgba(255, 254, 228)" in menu and "kTitleDecoInk = ui::rgba(131, 115, 22)" in menu,
|
||||
"the title entry's colours are not the layout's materials' (T_Btn_01, P_Deco_*_00)")
|
||||
# ((Triforce, 11-20, lab check 3: "in 16:10 Mods is not squeezed across") the entry, its copies with it, put on the game's
|
||||
# grid as the game's panes: squeezed across by the grid's kx (0.9 at 16:10) wherever it is drawn, the menu shut or open
|
||||
shut = function(menu, "void draw_mods_row_shut(ui::Ctx& c) {")
|
||||
check("ui::Ctx k = grid_ctx(c, g);" in shut and "put_on_grid(c.d, vtx0, cmd0, game_grid::map_of(g), window_clip);" in shut,
|
||||
"the title entry with the menu shut is not put on the game's grid (squeezed across on a 16:10 picture)")
|
||||
dm = function(menu, "void draw_menu(ui::Ctx& c, bool perf_under) {")
|
||||
check("k = grid_ctx(c, g), k.over_game = false;" in dm and "menu_map = game_grid::map_of(g);" in dm and
|
||||
"put_on_grid(c.d, vtx0, cmd0, menu_map, window_clip," in dm,
|
||||
"the title entry chosen is not drawn on the game's grid")
|
||||
grid = (VK / "game_grid.h").read_text(encoding="utf-8")
|
||||
check("m.kx = cw > 0 ? g.w / cw : 1.0f;" in grid and "float x(float px) const { return ox + px * kx; }" in grid,
|
||||
"the game's grid narrower than 16:9 is not squeezed across")
|
||||
row = function(menu, "void draw_mods_row(ui::Ctx& c, bool sel) {")
|
||||
check("draw_title_mods(c, sel, cx, cy, k, pitch);" in row and "(x1 - x0) / 60.0f" in row,
|
||||
"draw_mods_row does not draw the title's entry as the part, at the list's scale")
|
||||
|
||||
# the input: Decide before the Mods screen, its sound once at the press
|
||||
tick = function(menu, "void menu_tick() {")
|
||||
check("else if (mods_title_list()) mods_decide_ns = prof_now(), mods_sound(HOS_MENU_SOUND_SYS_DECIDE), changed = true;" in tick,
|
||||
"A on the title's entry does not play Decide with the system menu's sound")
|
||||
check("const bool decide = enter == 2 && mods_title_list();" in tick and "if (decide) mods_decide_ns = prof_now();" in tick,
|
||||
"a click on the title's entry does not play Decide")
|
||||
decide = tick[tick.index("page == kModsRowPage && mods_decide_ns) {"):]
|
||||
decide = decide[:decide.index("} else if (open_now.load() && page == kModsRowPage) {")]
|
||||
check("prof_now() - mods_decide_ns >= mods_entry::kDecideNs" in decide and "page = kModsPage" in decide and
|
||||
"mods_decided = true" in decide and "press[" not in decide, "the Mods screen does not open after Decide, or input is taken meanwhile")
|
||||
check("if (!mods_decided) mods_sound(HOS_MENU_SOUND_SYS_DECIDE);" in tick and "mods_decided = false;" in tick,
|
||||
"the decide sound plays again when the Mods screen opens after Decide")
|
||||
check("my < e[1] && my > e[1] - (quit_here ? 6 : 4) * e[4]) mods_row_sel = 0, press[1] = true;" in tick,
|
||||
"the mouse moving up off the title's entry does not give the cursor back")
|
||||
check(tick.count("(mods_list_fresh() || mods_title_fading())") == 0 and
|
||||
menu.count("mods_row = !open && !start && (mods_list_fresh() || mods_title_fading());") == 1 and
|
||||
menu.count("mods_row = !open && (mods_list_fresh() || mods_title_fading());") == 1,
|
||||
"the title's entry is not drawn on while it fades after its list (menu_record, menu_record_image)")
|
||||
|
||||
# the host: the entry taken across the line; the mouse onto it takes the cursor
|
||||
check("mods_entry = (Rect){mx - 550, my - pitch / 2, mx + 550, my + pitch / 2};" in host,
|
||||
"the title's Mods entry is not taken across the line as the game's rows are")
|
||||
check("const int onto = mods_entry_hit(hit.x, hit.y) ? 1 : quit_entry_hit(hit.x, hit.y) ? 4 : 0;" in
|
||||
function(host, "static void mouse_tick_locked(Ctx *c, uint64_t screen) {"),
|
||||
"the mouse onto the title's Mods entry does not take the cursor")
|
||||
|
||||
with tempfile.TemporaryDirectory(prefix="mods-title-entry-") as tmp:
|
||||
src, exe = Path(tmp) / "entry.cpp", Path(tmp) / "entry.exe"
|
||||
src.write_text(PROGRAM, encoding="utf-8")
|
||||
inc = [VK, ROOT / "gpu" / "third_party" / "suyu", VK / "compat", ROOT / "gpu" / "compat"]
|
||||
subprocess.run([args.cxx, "-std=c++20", "-O1", "-Wall", "-Wextra", "-I" + str(VK), *("-isystem" + str(p) for p in inc[1:]),
|
||||
str(src), "-o", str(exe)], check=True)
|
||||
r = subprocess.run([str(exe)], capture_output=True, text=True)
|
||||
check(r.returncode == 0, "the title entry as made:\n" + r.stdout)
|
||||
print("PASS: the Mods entry under the title's list: the game's look, its animations, Decide, the mouse")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -10,10 +10,11 @@ ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def preset_exempt(menu, value):
|
||||
"""the menu's row for opts.<value> leaves the quality preset alone (Row::preset_exempt, which set_row checks)"""
|
||||
"""the menu has no quality preset that a change of the row's could reset ((Triforce, options_version 7) the Quality preset
|
||||
row is gone, and with it the memory budget it set: the card's own), and the row is on its tab"""
|
||||
start = menu.index("&opts.%s," % value, menu.index("Row rows[] = {"))
|
||||
row = menu[start:menu.index("},", start)]
|
||||
return row.rstrip().endswith(", true") and "if (!r.preset_exempt)" in menu
|
||||
return bool(row) and "opts.preset" not in menu and "void apply_preset" not in menu
|
||||
|
||||
|
||||
def read(*parts):
|
||||
|
||||
@@ -25,6 +25,10 @@ for its left half (On, up to where the halves meet, past the value's middle) and
|
||||
choice's value Left or Right of its middle, on a name or a row of no kind A. A row scrolled away past the list is not
|
||||
pointed at, the header (our tabs', the renderer's) is neither pointed at nor clicked, the right button is B, and the wheel
|
||||
gives the focus to the row past the list's foot (the list's view, not the screen's).
|
||||
(Triforce, 11-19) The Mods entry under the title's list is told to the renderer a pitch under the last row, and the mouse
|
||||
takes it across the line as the game's own rows: moved onto its word it takes the cursor (as the pad's Down), a click there
|
||||
opens it. On the pause menu's System page the mouse moved onto Mods or Quit under its buttons takes the cursor as well,
|
||||
as the game's own buttons do on hover.
|
||||
python -I -B tests/test_oot_menu_mouse.py (Windows: the feature's; elsewhere it is skipped)
|
||||
"""
|
||||
import shutil
|
||||
@@ -73,6 +77,7 @@ static uint64_t heap_top = FAKE_BASE + 0x1000;
|
||||
static int64_t clock_ns = 1000000000LL;
|
||||
void hos_log(const char *fmt, ...) { va_list a; va_start(a, fmt); vfprintf(stderr, fmt, a); va_end(a); fputc(10, stderr); }
|
||||
int64_t hos_now_ns(void) { return clock_ns; }
|
||||
volatile LONG64 hos_present_count; /* (display.c's: the game's presents, which hos_oot_mods_down counts) */
|
||||
void hos_oot_menu_focus(Ctx *c, uint64_t screen, uint64_t pane, uint64_t lr);
|
||||
void hos_oot_menu_tick(Ctx *c, uint64_t screen);
|
||||
|
||||
@@ -83,8 +88,14 @@ static int pointer_hidden; /* (the cursor hidden while the pad is in use: the
|
||||
static int menu_frees, menu_gone; /* (the game's menus' mouse: freed for a menu's frame; their close told) */
|
||||
void hos_mouse_game_menu(void) { menu_frees++; }
|
||||
void hos_mouse_game_menu_gone(void) { menu_gone++; }
|
||||
void rx_option_set(int id, int value) { (void)id, (void)value; } /* (the Options screen named: the renderer's) */
|
||||
int rx_option(int id, int otherwise) { (void)id; return otherwise; } /* ((Triforce) the Mods entry's: never selected here) */
|
||||
/* (the renderer's options: the Options screen named; (Triforce) the Mods entry's list told, and the host's words on it) */
|
||||
static int mods_box_said[5], mods_enter_said, mods_selected, game_options_said;
|
||||
void rx_option_set(int id, int value) {
|
||||
if (id >= HOS_OPT_MODS_X0 && id <= HOS_OPT_MODS_PITCH) mods_box_said[id - HOS_OPT_MODS_X0] = value;
|
||||
if (id == HOS_OPT_MODS_ENTER) mods_enter_said = value;
|
||||
if (id == HOS_OPT_GAME_OPTIONS) game_options_said = value;
|
||||
}
|
||||
int rx_option(int id, int otherwise) { return id == HOS_OPT_MODS_SELECTED ? mods_selected : otherwise; }
|
||||
int hos_mouse_wheel_take(void) { const int w = wheel_next; wheel_next = 0; return w; } /* (the wheel only, mouse kept) */
|
||||
int hos_mouse_game_pointer(int *x, int *y, int *w, int *h, uint32_t *pressed, int *wheel) {
|
||||
*x = ptr_x, *y = ptr_y, *w = 3840, *h = 2160, *pressed = pressed_next, *wheel = wheel_next;
|
||||
@@ -392,6 +403,86 @@ int main(void) {
|
||||
focused(o_toggle, 0);
|
||||
(void)o_away;
|
||||
|
||||
/* ((Triforce, 11-19) The title's list with the Mods entry under it (mods_list_tick; the renderer draws it): four marks
|
||||
110 apart, the game's cursor on the last (its focus controller's entry). The entry is told a pitch under the last mark,
|
||||
and taken across the line as the game's own rows are (1100 wide, a pitch high): the mouse moved onto its word, well
|
||||
off the 60 x 60 mark's square, takes the cursor as the pad's Down does (the renderer's word 1); a click there opens it
|
||||
(2). With Mods chosen the mouse moving over it says nothing again */
|
||||
clock_ns += 300000000LL;
|
||||
const uint64_t tl = screen_new(0x84c106e8ULL);
|
||||
button_new(tl, 0, -500, 60, 60), button_new(tl, 0, -610, 60, 60), button_new(tl, 0, -720, 60, 60);
|
||||
const uint64_t t3 = button_new(tl, 0, -830, 60, 60);
|
||||
{
|
||||
const uint64_t mgr = alloc(128), ctrl = alloc(256), e = alloc(64);
|
||||
put64(get64(tl + 32) + 96, mgr), put64(mgr + 40, ctrl), put64(ctrl + 120, e), put64(e + 24, t3), put64(e + 32, tl);
|
||||
}
|
||||
focused(t3, 3);
|
||||
frame(tl, 0, -830);
|
||||
frame(tl, 0, -830);
|
||||
CHECK(mods_box_said[4] == 110 && mods_box_said[2] == -860 && mods_box_said[3] == -800); /* (the last mark's box, the pitch) */
|
||||
mods_enter_said = 0;
|
||||
reset();
|
||||
frame(tl, 230, -950); /* (the word, 230 right of the entry's middle: under no game row) */
|
||||
CHECK(mods_enter_said == 1 && focus_calls == 0);
|
||||
mods_enter_said = 0;
|
||||
pressed_next = HOS_MOUSE_LEFT;
|
||||
frame(tl, 230, -950);
|
||||
CHECK(mods_enter_said == 2 && taps[0] == 0); /* a click on it: open, not the game's A */
|
||||
mods_enter_said = 0;
|
||||
frame(tl, -400, -980);
|
||||
CHECK(mods_enter_said == 1); /* (the entry's lower half, left of its middle) */
|
||||
mods_enter_said = 0;
|
||||
frame(tl, 0, -1010);
|
||||
CHECK(mods_enter_said == 0); /* below it: nothing */
|
||||
mods_selected = 1;
|
||||
frame(tl, 230, -950);
|
||||
CHECK(mods_enter_said == 0); /* chosen already */
|
||||
mods_selected = 0;
|
||||
|
||||
/* ((Triforce, 11-19) The pause menu's System page: its buttons (Pa_Button_*) in the left column, 200 apart, the game's
|
||||
cursor on the last; Mods a pitch under it and Quit under Mods. The mouse moved onto Mods takes the cursor (1), onto
|
||||
Quit too (4), as the game's buttons above take it on hover; a click on Quit opens its dialog (3) */
|
||||
clock_ns += 300000000LL;
|
||||
const uint64_t ps = screen_new(0x84c0baa8ULL);
|
||||
uint64_t sys[4];
|
||||
for (int i = 0; i < 4; i++) {
|
||||
sys[i] = button_new(ps, -1000, 300 - 200.0f * i, 672, 144);
|
||||
const uint64_t name = alloc(32);
|
||||
memcpy(GP(name), "Pa_Button_00", 13);
|
||||
put64(sys[i] + 0x18, name);
|
||||
}
|
||||
{ /* (the System page's name, as the pause menu's focus handler reads it: pane+32 -> +128 -> +248 -> +24) */
|
||||
const uint64_t obj = alloc(256), p1 = alloc(512), p2 = alloc(64), page = alloc(32);
|
||||
memcpy(GP(page), "PaSystemMenu_00", 16);
|
||||
put64(p2 + 24, page), put64(p1 + 248, p2), put64(obj + 128, p1), put64(sys[3] + 32, obj);
|
||||
const uint64_t mgr = alloc(128), ctrl = alloc(256), e = alloc(64);
|
||||
put64(get64(ps + 32) + 96, mgr), put64(mgr + 40, ctrl), put64(ctrl + 120, e), put64(e + 24, sys[3]), put64(e + 32, ps);
|
||||
}
|
||||
focused(sys[3], 3);
|
||||
hos_oot_menu_focus(&ctx, ps, sys[3], 0);
|
||||
frame(ps, -1000, 0);
|
||||
frame(ps, -1000, 0);
|
||||
CHECK(mods_box_said[4] == 200 && mods_box_said[2] == -372 && mods_box_said[3] == -228); /* (the last button's box, the pitch) */
|
||||
mods_enter_said = 0;
|
||||
reset();
|
||||
frame(ps, -1100, -500); /* (Mods: under no game button) */
|
||||
CHECK(mods_enter_said == 1 && focus_calls == 0);
|
||||
mods_enter_said = 0;
|
||||
frame(ps, -1100, -700); /* (Quit) */
|
||||
CHECK(mods_enter_said == 4 && focus_calls == 0);
|
||||
mods_enter_said = 0;
|
||||
pressed_next = HOS_MOUSE_LEFT;
|
||||
frame(ps, -1100, -700);
|
||||
CHECK(mods_enter_said == 3 && taps[0] == 0); /* a click on Quit: its dialog, not the game's A */
|
||||
mods_enter_said = 0;
|
||||
frame(ps, -1100, -900);
|
||||
CHECK(mods_enter_said == 0); /* below Quit: nothing */
|
||||
mods_selected = 1;
|
||||
frame(ps, -1100, -500);
|
||||
frame(ps, -1100, -700);
|
||||
CHECK(mods_enter_said == 0); /* chosen already */
|
||||
mods_selected = 0;
|
||||
|
||||
/* Back in play (R let go): only the HUD's screen runs, no menu's. The window is told the menus have closed once
|
||||
50 ms of frames have had none: the camera gets its mouse back then, not 300 ms on */
|
||||
clock_ns += 300000000LL;
|
||||
@@ -402,6 +493,29 @@ int main(void) {
|
||||
CHECK(menu_gone == 0); /* (the first frames: not yet 50 ms) */
|
||||
for (int i = 0; i < 4; i++) frame(hud, 0, 0);
|
||||
CHECK(menu_gone > 0);
|
||||
|
||||
/* ((Triforce, 11-20, a review of 1104352) The Options screen told as 1 from the title (no pause menu ran before it), as 2
|
||||
chosen from the pause menu (its screen ran just before), for the whole of that run even with the pause menu's updates
|
||||
stopped under it; a new run later with no pause menu before it: 1 again */
|
||||
clock_ns += 2000000000LL;
|
||||
const uint64_t opts = screen_new(0x84c0f108ULL);
|
||||
game_options_said = 0;
|
||||
frame(opts, 0, 0);
|
||||
CHECK(game_options_said == 1); /* (the title's Options) */
|
||||
clock_ns += 300000000LL;
|
||||
frame(hud, 0, 0);
|
||||
frame(ps, -1000, 0); /* (the pause menu, Options chosen on it) */
|
||||
frame(opts, 0, 0);
|
||||
CHECK(game_options_said == 2);
|
||||
for (int i = 0; i < 60; i++) frame(opts, 0, 0); /* (a second of it alone) */
|
||||
CHECK(game_options_said == 2);
|
||||
clock_ns += 300000000LL; /* (closed; the pause menu back, then play, then the title's Options) */
|
||||
frame(ps, -1000, 0);
|
||||
clock_ns += 1000000000LL;
|
||||
frame(hud, 0, 0);
|
||||
clock_ns += 300000000LL;
|
||||
frame(opts, 0, 0);
|
||||
CHECK(game_options_said == 1);
|
||||
if (!fails) printf("PASS\n");
|
||||
return fails != 0;
|
||||
}
|
||||
@@ -456,6 +570,22 @@ int main(void) {
|
||||
memcpy(GP(options), &other_vt, 8);
|
||||
hos_oot_menu_tick(&ctx, options);
|
||||
CHECK(told == 2 && !hos_oot_options_front());
|
||||
/* ((Triforce, 11-20, a review of 1104352) chosen from the pause menu (its screen, 0x84c0baa8, ran just before): told as
|
||||
2 for that run, the pause menu's updates stopped under it or not; a later run with none before it: 1 */
|
||||
memcpy(GP(options), &options_vt, 8);
|
||||
const uint64_t pause = FAKE_BASE + 0x3000, pause_vt = 0x84c0baa8ULL;
|
||||
memcpy(GP(pause), &pause_vt, 8);
|
||||
now_ns += 300000000;
|
||||
hos_oot_menu_tick(&ctx, pause);
|
||||
CHECK(told == 2); /* (the pause menu is not the Options screen) */
|
||||
now_ns += 16000000;
|
||||
hos_oot_menu_tick(&ctx, options);
|
||||
CHECK(told == 3 && told_value == 2);
|
||||
for (int i = 0; i < 60; i++) now_ns += 16000000, hos_oot_menu_tick(&ctx, options);
|
||||
CHECK(told == 63 && told_value == 2);
|
||||
now_ns += 1000000000; /* (closed, back in play, then the title's Options) */
|
||||
hos_oot_menu_tick(&ctx, options);
|
||||
CHECK(told == 64 && told_value == 1);
|
||||
if (!fails) printf("PASS\n");
|
||||
return fails != 0;
|
||||
}
|
||||
|
||||
145
tests/test_oot_tex_compact.py
Normal file
145
tests/test_oot_tex_compact.py
Normal file
@@ -0,0 +1,145 @@
|
||||
"""The game's texture data compaction goes through the host, which counts its cycles and may hold them to a pace
|
||||
(host/oot_tex_compact.c, nx2/oot_patches.py patch_tex_compact, HOS_OOT_TEX_COMPACT_MS; no game).
|
||||
|
||||
1. The rule of when an ask with the compaction idle runs the game's step (hos_oot_tex_compact_runs, cut out of the host's file
|
||||
and compiled alone): always with the switch unset or 0, never with -1, and with a pace only once the time of the next
|
||||
cycle has come.
|
||||
2. The host's call (source): the state is read before the game's step; only an idle compaction is ever held, and held as the
|
||||
planner's "nothing to move" (the result 0); otherwise the game's own step runs; a cycle started sets the next one's time.
|
||||
3. The lift's patch: the one call of the step in the compaction thread's handler is made through the host, once, with its
|
||||
declaration; a text patched before is left as it is; a text with the call twice, or without it, is not touched; and it is
|
||||
among the supported build's patches, with a warning when its place is not found.
|
||||
|
||||
python -I -B tests/test_oot_tex_compact.py [--cc gcc]
|
||||
"""
|
||||
import argparse
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
RUN_ALL_ARGS = ["--cc", "gcc"]
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "nx2"))
|
||||
|
||||
|
||||
def block(text, marker):
|
||||
start = text.index(marker)
|
||||
end = text.index("{", start) + 1
|
||||
depth = 1
|
||||
while depth:
|
||||
depth += (text[end] == "{") - (text[end] == "}")
|
||||
end += 1
|
||||
return text[start:end]
|
||||
|
||||
|
||||
def in_order(text, parts, where):
|
||||
at = 0
|
||||
for part in parts:
|
||||
found = text.find(part, at)
|
||||
if found < 0:
|
||||
raise SystemExit("%s: %r is missing, or not after the part before it (update the test with the code)" % (where, part))
|
||||
at = found + len(part)
|
||||
|
||||
|
||||
RULE_TEST = r'''
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#define CHECK(x) do { if (!(x)) { fprintf(stderr, "FAIL:%d %s\n", __LINE__, #x); exit(1); } } while (0)
|
||||
RULE
|
||||
int main(void) {
|
||||
/* (unset or 0: as shipped, whatever the clock) */
|
||||
CHECK(hos_oot_tex_compact_runs(0, 0, 0) && hos_oot_tex_compact_runs(0, 5, 1000));
|
||||
/* (-1: no cycle is started) */
|
||||
CHECK(!hos_oot_tex_compact_runs(-1, 0, 0) && !hos_oot_tex_compact_runs(-1, 1000, 5));
|
||||
/* (a pace: only once the next cycle's time has come) */
|
||||
CHECK(!hos_oot_tex_compact_runs(1000, 999, 1000) && hos_oot_tex_compact_runs(1000, 1000, 1000));
|
||||
CHECK(hos_oot_tex_compact_runs(1000, 1001, 1000) && hos_oot_tex_compact_runs(250, 1, 0));
|
||||
puts("PASS rule: as shipped unless set, never with -1, a pace by the next cycle's time");
|
||||
return 0;
|
||||
}
|
||||
'''
|
||||
|
||||
# (what, the rule's text, its replacement): each must make the rule's test fail
|
||||
MUTATIONS = [
|
||||
("as shipped unless set", " if (!ms) return 1;\n", ""),
|
||||
("-1 starts none", " if (ms < 0) return 0;\n", ""),
|
||||
("held until the next cycle's time", " return now >= next;", " return 1;"),
|
||||
("run once the time has come", " return now >= next;", " return now > next;"),
|
||||
]
|
||||
|
||||
|
||||
def check_source(host):
|
||||
call = block(host, "void hos_oot_tex_compact(Ctx *c, A64Fn game) {")
|
||||
in_order(call, ["const uint64_t mgr = c->x[0];", "const uint64_t rec = recomp_load64(c, mgr + COMPACT);",
|
||||
"idle = readable(rec) && (uint8_t)recomp_load8(c, rec + STATE) == IDLE;",
|
||||
"if (idle && !hos_oot_tex_compact_runs(ms, now, next)) {", "c->x[0] = 0;", "} else {", "game(c);",
|
||||
"if (idle && (c->x[0] & 1)) {", "if (ms > 0) next = now + (int64_t)ms * 1000000;"], "oot_tex_compact.c hos_oot_tex_compact")
|
||||
if call.count("game(c);") != 1 or call.count("c->x[0] = 0;") != 1:
|
||||
raise SystemExit("oot_tex_compact.c: the game's step is called, or its result set, in a place this test does not know")
|
||||
if 'getenv("HOS_OOT_TEX_COMPACT_MS")' not in host:
|
||||
raise SystemExit("oot_tex_compact.c: the switch is not read")
|
||||
|
||||
|
||||
def check_patch():
|
||||
import oot_patches
|
||||
old, new, decl = oot_patches.TEX_COMPACT_OLD, oot_patches.TEX_COMPACT_NEW, oot_patches.TEX_COMPACT_DECL
|
||||
if "0x807da430ULL; f_807da480(c);" not in old or "hos_oot_tex_compact(c, f_807da480);" not in new or "0x807da430ULL" not in new:
|
||||
raise SystemExit("oot_patches.py: the compaction's call is not the handler's one call of the step")
|
||||
head = '#include "a64.h"\nvoid f_807da3f0(Ctx *__restrict A64_NOESC c) {\n'
|
||||
text = head + old + "\n}\nvoid other(Ctx *c) {\nc->x[30] = 0x807d88a4ULL; f_807da480(c);\n}\n"
|
||||
out, found = oot_patches.patch_tex_compact(text)
|
||||
if found != 1 or new not in out or old in out or out.count(decl) != 1 or "0x807d88a4ULL; f_807da480(c);" not in out:
|
||||
raise SystemExit("patch_tex_compact: the handler's call is not made through the host, or another caller's is")
|
||||
again, found = oot_patches.patch_tex_compact(out)
|
||||
if found != 1 or again != out:
|
||||
raise SystemExit("patch_tex_compact: a text patched before is patched again")
|
||||
for bad in (head + "}\n", head + old + "\n" + old + "\n}\n", old + "\n"): # (no call, the call twice, no include to declare at)
|
||||
out, found = oot_patches.patch_tex_compact(bad)
|
||||
if found or out != bad:
|
||||
raise SystemExit("patch_tex_compact: a text without the one call and the one include is touched")
|
||||
src = (ROOT / "nx2" / "oot_patches.py").read_text(encoding="utf-8")
|
||||
apply = src[src.index("def apply(gen, *, protect_hearts=False, required=False):"):]
|
||||
in_order(apply, ["if protect_hearts: # (found by address: the supported build's functions)",
|
||||
"compacted, found = patch_tex_compact(out)", "tex_compact_sites += found", "out = compacted",
|
||||
"if protect_hearts and tex_compact_sites != 1:"], "oot_patches.py apply")
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument("--cc", default="gcc")
|
||||
a = p.parse_args()
|
||||
host = (ROOT / "host" / "oot_tex_compact.c").read_text(encoding="utf-8")
|
||||
check_source(host)
|
||||
check_patch()
|
||||
print("PASS sources: only an idle compaction is held, as the planner's nothing to move; the lift's one call through the host")
|
||||
rule = block(host, "int hos_oot_tex_compact_runs(int ms, int64_t now, int64_t next) {")
|
||||
with tempfile.TemporaryDirectory(prefix="oot-tex-compact-") as tmp:
|
||||
d = Path(tmp)
|
||||
|
||||
def run(name, text):
|
||||
c, exe = d / (name + ".c"), d / (name + ".exe")
|
||||
c.write_text(RULE_TEST.replace("RULE", text), encoding="utf-8")
|
||||
r = subprocess.run([a.cc, "-std=gnu11", "-O1", "-Wall", "-Wextra", "-Werror", str(c), "-o", str(exe)],
|
||||
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
|
||||
if r.returncode:
|
||||
return None, r.stdout
|
||||
r = subprocess.run([str(exe)], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, timeout=60)
|
||||
return r.returncode == 0, r.stdout
|
||||
ok, out = run("rule", rule)
|
||||
if not ok:
|
||||
raise SystemExit("the rule's test failed:\n" + out)
|
||||
print(out.strip())
|
||||
for i, (what, old, new) in enumerate(MUTATIONS):
|
||||
if rule.count(old) != 1:
|
||||
raise SystemExit("mutation %r: its text is not once in the rule (update the test with the host's file)" % what)
|
||||
ok, out = run("mutant%d" % i, rule.replace(old, new))
|
||||
if ok: # (a mutant that does not build has failed too)
|
||||
raise SystemExit("mutation %r: the rule's test still passed without it" % what)
|
||||
print("PASS mutations: %d parts of the rule, each taken out, fail its test" % len(MUTATIONS))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
550
tests/test_options_tabs_grid.py
Normal file
550
tests/test_options_tabs_grid.py
Normal file
@@ -0,0 +1,550 @@
|
||||
"""Our options' tabs inside the game's own Options screen on the game's grid, over the game's panes, in every window shape
|
||||
(gpu/vk/game_grid.h column_of, vk_menu.cpp draw_menu, draw_game_tab, draw_fps, prebake and the game tab's mouse; no game).
|
||||
|
||||
(Triforce, 11-19) The lab's check of 662cfef, a 1600 x 900 window showing a letterboxed 21:9 picture: on every Triforce tab
|
||||
inside the game's Options page "the game's own Default Settings (X) / Back (A) footer and the left edge of its help box show
|
||||
through mid-screen beside our panel"; not in the 1720 x 720 window or fullscreen. Our tabs' page (its opaque column, its
|
||||
help box, the dark band behind the guides that hides the game's) was drawn on a 16:9 column of the window's whole height
|
||||
(1600 x 900 from the top), while the game draws its Options panes on its 3840 x 2160 grid in the picture (1200 x 675, 112
|
||||
down). Where the picture fills the window's height (1720 x 720, 3440 x 1440) the two are the same, which is why only the
|
||||
letterboxed window showed it. Also "our help box draws over part of the stats panel" (fullscreen): the Full panel was drawn
|
||||
under the whole page; on the game's own tab it is over the game's panes and under our header, and now on ours too.
|
||||
|
||||
1. game_grid.h alone: column_of over the game's panes puts a place of the game's layout (its footer's guides, its help
|
||||
box's left edge, its header's foot, the grid's corners) where the game's grid has it, within a pixel, for a 16:9 window
|
||||
with a 21:9 picture, 21:9 windows, fullscreen 3440 x 1440, 32:9 in 16:9 and 32:9 windows, a 16:10 picture (squeezed
|
||||
across), a 4:3 window with a 16:9 picture (bars above and below) and with a 4:3 picture (squeezed); over play, and with
|
||||
no picture known yet, the window's column as before. The old column (the window's, its whole height) is checked to miss
|
||||
the game's footer in the lab's window by far, as the shots show.
|
||||
2. The draw list as draw_menu leaves it, with Dear ImGui itself and the functions taken from vk_menu.cpp (clip_now,
|
||||
push_window_clip, put_on_grid, header_layer): the page put on the grid, the window's clip rectangle kept, a page's own
|
||||
rectangles moved with it and not cut on a squeezed grid wider than the window, the Full panel's vertices left in the
|
||||
window's pixels, and the order drawn: the page, the Full panel, our header. ((11-20, a review of c3d2d32) A dialog
|
||||
over the page (dim_page, panel_between): its dim over the whole window, over the header too; and the FPS counter's
|
||||
text under our header on a 16:10 grid, with Dear ImGui's own font: every glyph dropped with the window's clip as it
|
||||
was, all there with push_window_clip. (11-20, lab check 3) The Full panel over a dialog's dim and under its box,
|
||||
inside the game's Options screen and over play (bright, as over the game's own dialogs and Quit's), under the pages
|
||||
over play with no dialog; inside the game's Options screen the dim black over the bars above and below the picture,
|
||||
over play (our own background over the bars) one rectangle over the whole window, a review of 408e2dc.)
|
||||
3. The source: draw_menu, draw_game_tab, draw_fps, prebake and the game tab's mouse on that column and map; the restart
|
||||
question's, the Mods dialogs' and the keyboard's dim through dim_page.
|
||||
|
||||
python -I -B tests/test_options_tabs_grid.py [--cxx clang++]
|
||||
"""
|
||||
import argparse
|
||||
import subprocess
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
VK = ROOT / "gpu" / "vk"
|
||||
IMGUI = ROOT / "third_party" / "imgui"
|
||||
RUN_ALL_ARGS = ["--cxx", "{cxx}"]
|
||||
|
||||
|
||||
def check(ok, why):
|
||||
if not ok:
|
||||
raise SystemExit("FAIL: " + why)
|
||||
|
||||
|
||||
def block(text, head):
|
||||
start = text.index(head)
|
||||
end = text.index("{", start) + 1
|
||||
depth = 1
|
||||
while depth:
|
||||
depth += (text[end] == "{") - (text[end] == "}")
|
||||
end += 1
|
||||
return text[start:end]
|
||||
|
||||
|
||||
GRID = r"""
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdint>
|
||||
#include "game_grid.h"
|
||||
using namespace mkwvk;
|
||||
static int fails = 0;
|
||||
#define CHECK(x) do { if (!(x)) { std::printf("FAIL:%d %s\n", __LINE__, #x); fails++; } } while (0)
|
||||
static bool near(float a, float b, float tol) { return std::fabs(a - b) <= tol; }
|
||||
// (where the game draws a place of its layout (units from the middle, y up): its grid, 3840 x 2160 units over the place)
|
||||
static void game_at(const game_grid::Place& g, float ux, float uy, float* x, float* y) {
|
||||
*x = g.x + g.w * 0.5f + ux * g.w / 3840, *y = g.y + g.h * 0.5f - uy * g.h / 2160;
|
||||
}
|
||||
// (where our page draws it: ui::at on the column (unit h / 720, 3 layout units a point), then put through the map)
|
||||
static void our_at(const game_grid::Column& c, float ux, float uy, float* x, float* y) {
|
||||
const float unit = c.h / 720.0f;
|
||||
*x = c.map.x(c.w * 0.5f + ux * unit / 3), *y = c.map.y(c.h * 0.5f - uy * unit / 3);
|
||||
}
|
||||
int main() {
|
||||
const double r21 = 64.0 / 27.0, r32 = 32.0 / 9.0, r1610 = 16.0 / 10.0;
|
||||
// (the places our plates must cover: the game's guides (Default Settings, Back) at the foot's right, 62 up; its help
|
||||
// box's plate from 440 right of the middle; the header's foot at 880 up; the grid's corners)
|
||||
const float places[][2] = {{1000, -1018}, {1500, -1018}, {1840, -1018}, {440, -90}, {456, 300}, {0, 880}, {-1920, 1080},
|
||||
{1920, -1080}, {-730, 0}};
|
||||
const struct { uint32_t pw, ph, ww, wh; double r; const char* what; } cases[] = {
|
||||
{3416, 1440, 1600, 900, r21, "16:9 window, 21:9 picture between bars above and below (the lab's)"},
|
||||
{3416, 1440, 1720, 720, r21, "1720 x 720 window, 21:9 picture"},
|
||||
{3416, 1440, 3440, 1440, r21, "fullscreen 3440 x 1440, 21:9"},
|
||||
{3416, 1440, 2560, 1080, r21, "21:9 window"},
|
||||
{5120, 1440, 1920, 1080, r32, "32:9 picture in a 16:9 window"},
|
||||
{5120, 1440, 5120, 1440, r32, "32:9 window"},
|
||||
{2304, 1440, 1920, 1200, r1610, "16:10 picture in a 16:10 window (squeezed across)"},
|
||||
{2560, 1440, 1600, 1200, 0, "4:3 window, 16:9 picture between bars"},
|
||||
{1600, 1200, 1600, 1200, 0, "4:3 window, its own 4:3 picture (squeezed across)"},
|
||||
{2560, 1440, 1601, 901, 0, "an odd 16:9 window"},
|
||||
};
|
||||
for (const auto& k : cases) {
|
||||
const game_grid::Place g = game_grid::of(k.pw, k.ph, k.ww, k.wh, k.r);
|
||||
const game_grid::Column c = game_grid::column_of(g, (float)k.ww, (float)k.wh, true);
|
||||
for (const auto& p : places) {
|
||||
float gx, gy, ox, oy;
|
||||
game_at(g, p[0], p[1], &gx, &gy);
|
||||
our_at(c, p[0], p[1], &ox, &oy);
|
||||
if (!near(gx, ox, 1.0f) || !near(gy, oy, 1.0f)) {
|
||||
std::printf("FAIL: %s: the game's (%g, %g) at (%.1f, %.1f), ours at (%.1f, %.1f)\n", k.what, p[0], p[1], gx, gy, ox, oy);
|
||||
fails++;
|
||||
}
|
||||
}
|
||||
// (the mouse: back through the same map onto the column's pixels)
|
||||
CHECK(near(c.map.back_x(c.map.x(321)), 321, 0.01f) && near(c.map.back_y(c.map.y(123)), 123, 0.01f));
|
||||
// (over play: the window's column of its whole height, as before)
|
||||
const game_grid::Column play = game_grid::column_of(g, (float)k.ww, (float)k.wh, false);
|
||||
const float w = std::fmin((float)k.ww, std::floor(k.wh * 16.0f / 9.0f + 0.5f));
|
||||
CHECK(play.w == w && play.h == (float)k.wh && play.map.ox == std::floor((k.ww - w) * 0.5f) && play.map.oy == 0 && play.map.kx == 1);
|
||||
}
|
||||
// no picture known yet: the window's column, as before, not squeezed in a narrow window
|
||||
{
|
||||
const game_grid::Place g = game_grid::of(0, 0, 1600, 1200, 0);
|
||||
const game_grid::Column c = game_grid::column_of(g, 1600, 1200, true);
|
||||
CHECK(!g.picture && c.w == 1600 && c.h == 1200 && c.map.ox == 0 && c.map.oy == 0 && c.map.kx == 1);
|
||||
const game_grid::Column w = game_grid::column_of(game_grid::of(0, 0, 2560, 1080, 0), 2560, 1080, true);
|
||||
CHECK(w.w == 1920 && w.h == 1080 && w.map.ox == 320 && w.map.kx == 1);
|
||||
}
|
||||
// the old column in the lab's window: the window's 16:9 of its whole height from its top. The game's guides at its foot
|
||||
// (1500, -1018) are 112 + 675 * (1080 + 1018) / 2160 = 768 down; our band behind the guides (prompt_bar: from 160
|
||||
// units over the foot) began at 900 - 160 * 900 / 2160 = 833: the guides were above it, over the game's picture, beside
|
||||
// our panel. Now the band's top is at the game's 160 units over its foot, 112 + 675 - 50 = 737, over the guides
|
||||
{
|
||||
const game_grid::Place g = game_grid::of(3416, 1440, 1600, 900, r21);
|
||||
float gx, gy;
|
||||
game_at(g, 1500, -1018, &gx, &gy);
|
||||
const float old_band = 900 - 160 * 900.0f / 2160;
|
||||
CHECK(near(gy, 768.3f, 1.0f) && gy < old_band - 50);
|
||||
float ox, oy;
|
||||
our_at(game_grid::column_of(g, 1600, 900, true), 0, -1080 + 160, &ox, &oy);
|
||||
CHECK(near(oy, 112 + 675 - 50, 1.0f) && oy < gy);
|
||||
}
|
||||
if (!fails) std::puts("our tabs' column on the game's grid in every window shape");
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
"""
|
||||
|
||||
DRAW = r"""
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <vector>
|
||||
#include "imgui.h"
|
||||
#include "imgui_internal.h"
|
||||
#include "game_grid.h"
|
||||
namespace ui { struct Ctx { ImDrawList* d; float w = 0, h = 0; }; }
|
||||
namespace mkwvk {
|
||||
game_grid::Map menu_map;
|
||||
float menu_window_w = 0, menu_window_h = 0;
|
||||
game_grid::Place grid_now; // (the picture the dims are cut at: menu_grid's, from the present)
|
||||
bool embed_open = false; // (inside the game's Options screen: the game's picture and its black bars under our page)
|
||||
[[maybe_unused]] constexpr int kModsRowPage = 9;
|
||||
int page = 0;
|
||||
game_grid::Place menu_grid(float, float) { return grid_now; }
|
||||
// (the Full panel as draw_perf draws it: at the window's top right, in its pixels; tagged PERF, 6)
|
||||
void draw_perf(ui::Ctx& c) { c.d->AddRectFilled(ImVec2(c.w - 390, 12), ImVec2(c.w - 12, 700), IM_COL32(6, 0, 0, 255)); }
|
||||
%FUNCS%
|
||||
}
|
||||
using namespace mkwvk;
|
||||
static int fails = 0;
|
||||
#define CHECK(x) do { if (!(x)) { std::printf("FAIL:%d %s\n", __LINE__, #x); fails++; } } while (0)
|
||||
static bool near(float a, float b, float tol = 0.02f) { return std::fabs(a - b) <= tol; }
|
||||
static bool same(const ImVec4& a, const ImVec4& b, float tol = 0.02f) {
|
||||
return near(a.x, b.x, tol) && near(a.y, b.y, tol) && near(a.z, b.z, tol) && near(a.w, b.w, tol);
|
||||
}
|
||||
// (each rectangle in its own red: the order the GPU draws them in, by the commands and their indices)
|
||||
enum { BAR = 0, PRE = 1, BODY, BODY2, BODY3, HEAD, PERF, AFTER, DIM, BOX, TEXT }; // (BAR: black, a dim over the bars)
|
||||
static ImU32 tag(int t) { return IM_COL32(t, 0, 0, 255); }
|
||||
static std::vector<int> order(const ImDrawList& d) {
|
||||
std::vector<int> out;
|
||||
for (const ImDrawCmd& c : d.CmdBuffer)
|
||||
for (unsigned i = 0; i < c.ElemCount; i++) {
|
||||
const int t = (int)(d.VtxBuffer[(int)(c.VtxOffset + d.IdxBuffer[(int)(c.IdxOffset + i)])].col & 0xff);
|
||||
if (out.empty() || out.back() != t) out.push_back(t);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
static const ImDrawCmd* cmd_of(const ImDrawList& d, int t) {
|
||||
for (const ImDrawCmd& c : d.CmdBuffer)
|
||||
for (unsigned i = 0; i < c.ElemCount; i++)
|
||||
if ((int)(d.VtxBuffer[(int)(c.VtxOffset + d.IdxBuffer[(int)(c.IdxOffset + i)])].col & 0xff) == t) return &c;
|
||||
return nullptr;
|
||||
}
|
||||
static ImVec2 min_of(const ImDrawList& d, int t) {
|
||||
ImVec2 m(1e9f, 1e9f);
|
||||
for (const ImDrawVert& v : d.VtxBuffer)
|
||||
if ((int)(v.col & 0xff) == t) m.x = std::fmin(m.x, v.pos.x), m.y = std::fmin(m.y, v.pos.y);
|
||||
return m;
|
||||
}
|
||||
static ImVec2 max_of(const ImDrawList& d, int t) {
|
||||
ImVec2 m(-1e9f, -1e9f);
|
||||
for (const ImDrawVert& v : d.VtxBuffer)
|
||||
if ((int)(v.col & 0xff) == t) m.x = std::fmax(m.x, v.pos.x), m.y = std::fmax(m.y, v.pos.y);
|
||||
return m;
|
||||
}
|
||||
// (a page as draw_menu draws it over the game's Options screen, the Full panel between the page and its header when perf)
|
||||
static void draw_page(ImDrawList& d, const game_grid::Column& col, float W, float H, bool perf, int* p0, int* p1) {
|
||||
ui::Ctx c{&d};
|
||||
d.AddRectFilled(ImVec2(5, 5), ImVec2(20, 20), tag(PRE)); // (drawn before the page: the dim, the window's)
|
||||
const int vtx0 = d.VtxBuffer.Size, cmd0 = d.CmdBuffer.Size;
|
||||
const ImVec4 window_clip = clip_now(&d);
|
||||
if (perf) d.ChannelsSplit(2), header_split = &d;
|
||||
push_window_clip(&d, col.map, W, H);
|
||||
d.AddRectFilled(ImVec2(0, 0), ImVec2(10, 10), tag(BODY)); // (the column's corner)
|
||||
d.PushClipRect(ImVec2(col.w * 0.5f, 50), ImVec2(col.w, col.h), true); // (the help box's own clip: to the column's right edge)
|
||||
d.AddRectFilled(ImVec2(col.w * 0.5f, 50), ImVec2(col.w + 40, 60), tag(BODY2));
|
||||
d.PopClipRect();
|
||||
header_layer(c, true);
|
||||
d.AddRectFilled(ImVec2(0, 0), ImVec2(col.w, col.h * 200 / 2160), tag(HEAD)); // (the header, 200 units)
|
||||
header_layer(c, false);
|
||||
d.AddRectFilled(ImVec2(col.w - 300, col.h - 40), ImVec2(col.w, col.h), tag(BODY3)); // (the guides' band)
|
||||
d.PopClipRect();
|
||||
*p0 = *p1 = 0;
|
||||
if (perf) {
|
||||
d.ChannelsSetCurrent(0);
|
||||
*p0 = d.VtxBuffer.Size;
|
||||
d.AddRectFilled(ImVec2(W - 390, 12), ImVec2(W - 12, 700), tag(PERF)); // (the Full panel: the window's top right)
|
||||
*p1 = d.VtxBuffer.Size;
|
||||
d.ChannelsMerge();
|
||||
header_split = nullptr;
|
||||
}
|
||||
put_on_grid(&d, vtx0, cmd0, col.map, window_clip, *p0, *p1);
|
||||
d.AddRectFilled(ImVec2(30, 30), ImVec2(40, 40), tag(AFTER)); // (drawn after: the counter, a notice)
|
||||
}
|
||||
// ((Triforce, 11-20, a review of c3d2d32) a page with a dialog over it as draw_menu and draw_mods (mods_dialog,
|
||||
// mods_keyboard) or draw_ask draw it: the header, then the dialog's dim (dim_page) and its box, then the guides. perf: the
|
||||
// Full panel waits (panel_wait) in a list split in two: inside the game's Options screen (inside) the page in channel 0
|
||||
// and the header in 1; over play the pages in 1, channel 0 left for the panel under them. ((11-20) dialog false: none)
|
||||
static void page_dialog(ImDrawList& d, const game_grid::Column& col, float W, float H, bool inside, bool dialog, int* p0, int* p1) {
|
||||
ui::Ctx win{&d, W, H}, c{&d, col.w, col.h};
|
||||
menu_map = col.map, menu_window_w = W, menu_window_h = H;
|
||||
d.AddRectFilled(ImVec2(5, 5), ImVec2(20, 20), tag(PRE));
|
||||
const int vtx0 = d.VtxBuffer.Size, cmd0 = d.CmdBuffer.Size;
|
||||
const ImVec4 window_clip = clip_now(&d);
|
||||
d.ChannelsSplit(2), panel_split = &d, panel_wait = {&win, window_clip, 0, 0};
|
||||
if (inside) header_split = &d;
|
||||
else d.ChannelsSetCurrent(1);
|
||||
push_window_clip(&d, col.map, W, H);
|
||||
d.AddRectFilled(ImVec2(0, 0), ImVec2(10, 10), tag(BODY));
|
||||
header_layer(c, true);
|
||||
d.AddRectFilled(ImVec2(0, 0), ImVec2(col.w, col.h * 200 / 2160), tag(HEAD));
|
||||
header_layer(c, false);
|
||||
if (dialog) dim_page(c, tag(DIM));
|
||||
d.AddRectFilled(ImVec2(col.w * 0.25f, col.h * 0.3f), ImVec2(col.w * 0.75f, col.h * 0.7f), tag(BOX));
|
||||
d.AddRectFilled(ImVec2(col.w - 300, col.h - 40), ImVec2(col.w, col.h), tag(BODY3));
|
||||
d.PopClipRect();
|
||||
panel_between(&d), *p0 = panel_wait.v0, *p1 = panel_wait.v1;
|
||||
put_on_grid(&d, vtx0, cmd0, col.map, window_clip, *p0, *p1);
|
||||
}
|
||||
static bool covers(const ImDrawList& d, int over, int under) {
|
||||
const ImVec2 a = min_of(d, over), b = max_of(d, over), p = min_of(d, under), q = max_of(d, under);
|
||||
return a.x <= p.x + 0.02f && a.y <= p.y + 0.02f && b.x >= q.x - 0.02f && b.y >= q.y - 0.02f;
|
||||
}
|
||||
static int index_of(const std::vector<int>& v, int t) {
|
||||
for (size_t i = 0; i < v.size(); i++)
|
||||
if (v[i] == t) return (int)i;
|
||||
return -1;
|
||||
}
|
||||
int main() {
|
||||
ImDrawListSharedData shared;
|
||||
const double r21 = 64.0 / 27.0, r1610 = 16.0 / 10.0;
|
||||
// the lab's window: 1600 x 900, a 21:9 picture between bars; the grid 1200 x 675 at (200, 112)
|
||||
{
|
||||
const float W = 1600, H = 900;
|
||||
const game_grid::Column col = game_grid::column_of(game_grid::of(3416, 1440, 1600, 900, r21), W, H, true);
|
||||
const float oy = col.map.oy;
|
||||
CHECK(col.map.ox == 200 && (oy == 112 || oy == 113) && col.map.kx == 1 && col.w == 1200 && near(col.h, 675, 0.5f));
|
||||
ImDrawList d(&shared);
|
||||
d._ResetForNewFrame();
|
||||
d.PushClipRect(ImVec2(0, 0), ImVec2(W, H));
|
||||
int p0, p1;
|
||||
draw_page(d, col, W, H, true, &p0, &p1);
|
||||
const std::vector<int> want = {PRE, BODY, BODY2, BODY3, PERF, HEAD, AFTER};
|
||||
CHECK(order(d) == want); // (the page, then the Full panel over it, then our header over the panel)
|
||||
CHECK(near(min_of(d, BODY).x, 200) && near(min_of(d, BODY).y, oy)); // (the column's corner on the grid's)
|
||||
CHECK(near(min_of(d, HEAD).y, oy) && near(max_of(d, HEAD).x, 1400)); // (the header over the game's, on the picture)
|
||||
CHECK(near(max_of(d, BODY3).y, oy + col.h) && near(max_of(d, BODY3).x, 1400)); // (the guides' band at the picture's foot)
|
||||
CHECK(near(min_of(d, PERF).x, W - 390) && near(min_of(d, PERF).y, 12)); // (the panel where the window has it)
|
||||
CHECK(near(min_of(d, PRE).x, 5) && near(min_of(d, AFTER).x, 30)); // (before and after: not moved)
|
||||
const ImVec4 win(0, 0, W, H);
|
||||
CHECK(same(cmd_of(d, PRE)->ClipRect, win) && same(cmd_of(d, PERF)->ClipRect, win) && same(cmd_of(d, AFTER)->ClipRect, win));
|
||||
CHECK(same(cmd_of(d, BODY)->ClipRect, win) && same(cmd_of(d, HEAD)->ClipRect, win)); // (the window's, put back)
|
||||
CHECK(same(cmd_of(d, BODY2)->ClipRect, ImVec4(200 + 600, oy + 50, 1400, oy + col.h))); // (the help box's, moved)
|
||||
}
|
||||
// a 16:10 picture: the grid the whole window, the column (2133 wide) squeezed into it. A page's clip rectangle to the
|
||||
// column's right edge reaches the window's (the window's rectangle as it is, 1920 in the column's pixels, would have cut
|
||||
// it at 1920 x 0.9 = 1728)
|
||||
{
|
||||
const float W = 1920, H = 1200;
|
||||
const game_grid::Column col = game_grid::column_of(game_grid::of(2304, 1440, 1920, 1200, r1610), W, H, true);
|
||||
CHECK(col.w == 2133 && col.map.kx < 0.95f);
|
||||
ImDrawList d(&shared);
|
||||
d._ResetForNewFrame();
|
||||
d.PushClipRect(ImVec2(0, 0), ImVec2(W, H));
|
||||
int p0, p1;
|
||||
draw_page(d, col, W, H, false, &p0, &p1);
|
||||
const std::vector<int> want = {PRE, BODY, BODY2, HEAD, BODY3, AFTER}; // (no panel: drawn in order, nothing split)
|
||||
CHECK(order(d) == want);
|
||||
CHECK(near(cmd_of(d, BODY2)->ClipRect.z, W, 0.5f) && near(cmd_of(d, BODY2)->ClipRect.x, W * 0.5f, 0.5f));
|
||||
CHECK(near(max_of(d, BODY3).x, W, 0.5f) && near(max_of(d, HEAD).x, W, 0.5f));
|
||||
}
|
||||
// a 16:9 picture in a 16:10 window: bars above and below; the column as wide as the window, lower than its top. Its own
|
||||
// rectangles move down with it (the old rule kept every rectangle from the window's left edge to its right one)
|
||||
{
|
||||
const float W = 1920, H = 1200;
|
||||
const game_grid::Column col = game_grid::column_of(game_grid::of(2560, 1440, 1920, 1200, 0), W, H, true);
|
||||
CHECK(col.w == 1920 && col.map.oy == 60 && col.map.ox == 0);
|
||||
ImDrawList d(&shared);
|
||||
d._ResetForNewFrame();
|
||||
d.PushClipRect(ImVec2(0, 0), ImVec2(W, H));
|
||||
const int vtx0 = d.VtxBuffer.Size, cmd0 = d.CmdBuffer.Size;
|
||||
const ImVec4 window_clip = clip_now(&d);
|
||||
push_window_clip(&d, col.map, W, H);
|
||||
d.PushClipRect(ImVec2(0, 100), ImVec2(col.w, 200), true);
|
||||
d.AddRectFilled(ImVec2(0, 100), ImVec2(col.w, 200), tag(BODY));
|
||||
d.PopClipRect();
|
||||
d.PopClipRect();
|
||||
put_on_grid(&d, vtx0, cmd0, col.map, window_clip);
|
||||
CHECK(same(cmd_of(d, BODY)->ClipRect, ImVec4(0, 160, W, 260)));
|
||||
}
|
||||
// ((Triforce, 11-20, a review of c3d2d32) a dialog over the Mods page with the Full panel on, inside the game's Options
|
||||
// screen and over play (the lab's 1600 x 900 window, 21:9 picture): the dim over the page and the header alike, across
|
||||
// the whole window (before: the dim in channel 0 under the header in channel 1). ((11-20) The panel then over the dim and
|
||||
// under the box, bright as over the game's own dialogs and Quit's (26670c0 dimmed it under the restart question and the
|
||||
// Mods dialogs); the dim's colour over the picture only, black over the bars above and below it (lab check 3: "the black
|
||||
// bars turn dark brown"). With no dialog: the panel between the page and its header inside, under the pages over play.
|
||||
// ((11-20, a review of 408e2dc) Over play the bars are not the game's black: draw_menu covered the whole window with our
|
||||
// own background and our page and header are on the window's column, over the bars too. There the dim is one rectangle
|
||||
// in its colour over the whole window, as on 26670c0; cut black at the picture's edges it left a straight step of the
|
||||
// tint across our background and header at y 112 and 787)
|
||||
for (bool inside : {true, false})
|
||||
for (bool dialog : {true, false}) {
|
||||
const float W = 1600, H = 900;
|
||||
const game_grid::Place g = game_grid::of(3416, 1440, 1600, 900, r21);
|
||||
const game_grid::Column col = game_grid::column_of(g, W, H, inside);
|
||||
grid_now = g, embed_open = inside, mkwvk::page = 0;
|
||||
ImDrawList d(&shared);
|
||||
d._ResetForNewFrame();
|
||||
d.PushClipRect(ImVec2(0, 0), ImVec2(W, H));
|
||||
int p0, p1;
|
||||
page_dialog(d, col, W, H, inside, dialog, &p0, &p1);
|
||||
const std::vector<int> o = order(d);
|
||||
const std::vector<int> want = dialog ? (inside ? std::vector<int>{PRE, BODY, HEAD, DIM, BAR, PERF, BOX, BODY3}
|
||||
: std::vector<int>{PRE, BODY, HEAD, DIM, PERF, BOX, BODY3})
|
||||
: inside ? std::vector<int>{PRE, BODY, BOX, BODY3, PERF, HEAD}
|
||||
: std::vector<int>{PRE, PERF, BODY, HEAD, BOX, BODY3};
|
||||
CHECK(o == want);
|
||||
if (o != want) {
|
||||
for (int t : o) std::printf(" %d", t);
|
||||
std::printf(" (inside %d, dialog %d)\n", (int)inside, (int)dialog);
|
||||
}
|
||||
CHECK(header_split == nullptr && panel_split == nullptr && panel_wait.window == nullptr);
|
||||
CHECK(!dialog || (index_of(o, HEAD) < index_of(o, DIM) && index_of(o, DIM) < index_of(o, PERF) && index_of(o, PERF) < index_of(o, BOX)));
|
||||
CHECK(near(min_of(d, PERF).x, W - 390) && near(min_of(d, PERF).y, 12)); // (the panel where the window has it)
|
||||
CHECK(same(cmd_of(d, PERF)->ClipRect, ImVec4(0, 0, W, H)));
|
||||
if (!dialog) continue;
|
||||
// (inside: the dim's colour over the picture, 1600 x 675 from 112 down; black at its alpha over the bars, to the
|
||||
// window's edges. Over play: the dim's colour over the whole window, our header in the top bar under it, no black)
|
||||
CHECK(g.pic_h == 675 && g.pic_y == 112);
|
||||
if (inside) {
|
||||
CHECK(near(min_of(d, DIM).x, 0) && near(min_of(d, DIM).y, g.pic_y) && near(max_of(d, DIM).x, W) && near(max_of(d, DIM).y, g.pic_y + g.pic_h));
|
||||
CHECK(near(min_of(d, BAR).y, 0) && near(max_of(d, BAR).y, H) && near(min_of(d, BAR).x, 0) && near(max_of(d, BAR).x, W));
|
||||
} else {
|
||||
CHECK(near(min_of(d, DIM).x, 0) && near(min_of(d, DIM).y, 0) && near(max_of(d, DIM).x, W) && near(max_of(d, DIM).y, H));
|
||||
CHECK(index_of(o, BAR) < 0);
|
||||
}
|
||||
CHECK(covers(d, DIM, HEAD) && same(cmd_of(d, DIM)->ClipRect, ImVec4(0, 0, W, H)));
|
||||
CHECK(near(min_of(d, BOX).x, col.map.ox + col.w * 0.25f, 0.5f)); // (the box on the column)
|
||||
}
|
||||
// a squeezed grid (16:10): the picture the whole window, no bars; the dim the whole window, the panel over it
|
||||
{
|
||||
const float W = 1920, H = 1200;
|
||||
const game_grid::Place g = game_grid::of(2304, 1440, 1920, 1200, r1610);
|
||||
const game_grid::Column col = game_grid::column_of(g, W, H, true);
|
||||
grid_now = g, embed_open = true, mkwvk::page = 0;
|
||||
ImDrawList d(&shared);
|
||||
d._ResetForNewFrame();
|
||||
d.PushClipRect(ImVec2(0, 0), ImVec2(W, H));
|
||||
int p0, p1;
|
||||
page_dialog(d, col, W, H, true, true, &p0, &p1);
|
||||
const std::vector<int> want = {PRE, BODY, HEAD, DIM, PERF, BOX, BODY3};
|
||||
CHECK(order(d) == want);
|
||||
CHECK(near(min_of(d, DIM).x, 0, 0.5f) && near(max_of(d, DIM).x, W, 0.5f) && near(min_of(d, DIM).y, 0, 0.5f) && near(max_of(d, DIM).y, H, 0.5f));
|
||||
}
|
||||
// ((Triforce, 11-20, a review of c3d2d32) the FPS counter under our header (draw_fps) on a squeezed grid: a 1680 x 1050
|
||||
// window, a 16:10 picture; the column 1867 wide, x 0.9. The counter at the column's right, about 1753 to 1828 in its
|
||||
// pixels, past the window's 1680: with Dear ImGui's own text, a glyph past the clip's right edge is dropped as it is
|
||||
// added (ImFont::RenderText), so with the window's clip as it is no glyph is left; with the window's clip in the
|
||||
// column's pixels (push_window_clip, as draw_fps has it now) they are all there, inside the window after the squeeze
|
||||
{
|
||||
ImGuiContext* ctx = ImGui::CreateContext();
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
io.IniFilename = nullptr, io.LogFilename = nullptr; // (no files of its own where the test runs)
|
||||
io.DisplaySize = ImVec2(1680, 1050);
|
||||
io.BackendFlags |= ImGuiBackendFlags_RendererHasTextures;
|
||||
ImFont* font = io.Fonts->AddFontDefault();
|
||||
ImGui::NewFrame();
|
||||
const float W = 1680, H = 1050;
|
||||
const game_grid::Column col = game_grid::column_of(game_grid::of(2304, 1440, 1680, 1050, r1610), W, H, true);
|
||||
CHECK(col.w == 1867 && near(col.map.kx, 0.9f, 0.001f));
|
||||
auto counter = [&](bool push, ImVec2* lo, ImVec2* hi) {
|
||||
ImDrawList d(ImGui::GetDrawListSharedData());
|
||||
d._ResetForNewFrame();
|
||||
d.PushTexture(io.Fonts->TexRef);
|
||||
d.PushClipRect(ImVec2(0, 0), ImVec2(W, H));
|
||||
const int vtx0 = d.VtxBuffer.Size, cmd0 = d.CmdBuffer.Size;
|
||||
const ImVec4 window_clip = clip_now(&d);
|
||||
if (push) push_window_clip(&d, col.map, W, H);
|
||||
d.AddText(font, 24, ImVec2(1753, 80), tag(TEXT), "60 FPS");
|
||||
if (push) d.PopClipRect();
|
||||
put_on_grid(&d, vtx0, cmd0, col.map, window_clip);
|
||||
int n = 0;
|
||||
for (const ImDrawVert& v : d.VtxBuffer) n += (int)(v.col & 0xff) == TEXT;
|
||||
*lo = min_of(d, TEXT), *hi = max_of(d, TEXT);
|
||||
CHECK(!n || same(cmd_of(d, TEXT)->ClipRect, window_clip));
|
||||
return n;
|
||||
};
|
||||
ImVec2 lo, hi;
|
||||
CHECK(counter(false, &lo, &hi) == 0); // (the window's clip as it was: every glyph dropped, no counter)
|
||||
const int n = counter(true, &lo, &hi);
|
||||
CHECK(n >= 4 * 5); // (its glyphs, "60 FPS": five at least)
|
||||
CHECK(lo.x >= 1753 * 0.9f - 1 && hi.x <= W && hi.x > W - 200); // (inside the window, at its right)
|
||||
ImGui::EndFrame();
|
||||
ImGui::DestroyContext(ctx);
|
||||
}
|
||||
if (!fails) std::puts("the page on the grid, the window's clip kept, the panel between the page and our header");
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--cxx", default="clang++")
|
||||
args = parser.parse_args()
|
||||
menu = (VK / "vk_menu.cpp").read_text(encoding="utf-8")
|
||||
|
||||
# 3. the source
|
||||
dm = block(menu, "void draw_menu(ui::Ctx& c, bool perf_under) {")
|
||||
check("const bool on_game = !row && pages_on_game();" in dm and "const game_grid::Column col = pages_column(c.w, c.h, on_game);" in dm and
|
||||
"ui::Ctx k = column_ctx(c, col);" in dm and "menu_map = col.map;" in dm,
|
||||
"draw_menu: our tabs over the game's Options screen are not on the game's grid (the window's column of its whole height)")
|
||||
check("std::floor(c.h * 16.0f / 9.0f" not in dm, "draw_menu still lays its pages on the window's height")
|
||||
check("if (on_game) push_window_clip(c.d, menu_map, c.w, c.h);" in dm and "if (on_game) c.d->PopClipRect();" in dm,
|
||||
"draw_menu: a squeezed grid's page is cut at the window's width in the column's pixels")
|
||||
# ((11-20) the panel waits on every page but the Mods entry's, over play too, so that a dialog's dim can go under it)
|
||||
check("const bool perf_between = perf_under && !row;" in dm and "draw_perf(c);" not in dm and
|
||||
"c.d->ChannelsSplit(2), panel_split = c.d, panel_wait = {&c, window_clip, 0, 0};" in dm and
|
||||
"if (embed_open) header_split = c.d;" in dm and "else c.d->ChannelsSetCurrent(1);" in dm,
|
||||
"draw_menu: the Full panel does not wait for the page's end or a dialog's dim (still drawn under the page first)")
|
||||
between = dm[dm.index("int perf0 = 0, perf1 = 0;"):]
|
||||
check(between.index("panel_between(c.d);") < between.index("perf0 = panel_wait.v0, perf1 = panel_wait.v1;"),
|
||||
"draw_menu: the Full panel is not drawn between the page and its header")
|
||||
pb = block(menu, "void panel_between(ImDrawList* d) {")
|
||||
check(pb.index("d->ChannelsSetCurrent(0);") < pb.index("panel_draw(d);") < pb.index("d->ChannelsMerge();") <
|
||||
pb.index("panel_split = header_split = nullptr;"), "panel_between: the Full panel is not drawn between the page and its header")
|
||||
pd = block(menu, "void panel_draw(ImDrawList* d) {")
|
||||
check(pd.index("panel_wait.v0 = d->VtxBuffer.Size;") < pd.index("draw_perf(*panel_wait.window);") < pd.index("panel_wait.v1 = d->VtxBuffer.Size;"),
|
||||
"panel_draw: the Full panel's vertices are not kept out of the grid's move")
|
||||
check("put_on_grid(c.d, vtx0, cmd0, menu_map, window_clip, perf0, perf1);" in dm,
|
||||
"draw_menu: the Full panel's vertices are moved with the page")
|
||||
check(dm.index("menu_window_w = c.w, menu_window_h = c.h;") < dm.index("else if (page == 5) draw_ask(k);"),
|
||||
"draw_menu: the dialogs' dim does not know the window")
|
||||
# ((11-20, a review of c3d2d32) a dialog's dim over the whole window, over the page's header and the Full panel too: the
|
||||
# restart question, the Mods page's dialogs and its keyboard)
|
||||
dp = block(menu, "void dim_page(ui::Ctx& c, ImU32 col) {")
|
||||
check(dp.index("panel_merge(c.d);") < dp.index("dim_window(c.d, menu_map, game_black ? menu_grid(w, h) : game_grid::Place{}, w, h, col);") <
|
||||
dp.index("panel_over(c.d);"),
|
||||
"dim_page: the dim is not the whole window's over the page and its header, under the Full panel")
|
||||
for head, dim in (("void draw_ask(ui::Ctx& c) {", "dim_page(c, ui::rgba(8, 5, 2, 110));"),
|
||||
("void mods_dialog(ui::Ctx& c, const char* title,", "dim_page(c, ui::rgba(8, 5, 2, 120));"),
|
||||
("void mods_keyboard(ui::Ctx& c) {", "dim_page(c, ui::rgba(8, 5, 2, 120));")):
|
||||
body = block(menu, head)
|
||||
check(dim in body and "AddRectFilled(ImVec2(0, 0), ImVec2(c.w, c.h)" not in body,
|
||||
head + " its dim is the column's alone, under the header and the Full panel inside the game's Options screen")
|
||||
opts = block(menu, "void draw_options(ui::Ctx& c) {")
|
||||
check(opts.index("header_layer(c, true);") < opts.index("ui::banner(c, hh);") < opts.index("draw_tabs(c, cur_tab") <
|
||||
opts.index("header_layer(c, false);") < opts.index("caption(c, hx0, hx1"), "draw_options: the header is not drawn over the Full panel")
|
||||
tb = block(menu, "float title_banner(ui::Ctx& c, const char* title, const char* right) {")
|
||||
check(tb.index("header_layer(c, true);") < tb.index("ui::banner(c, 0, title);") < tb.index("header_layer(c, false);"),
|
||||
"title_banner: the header is not drawn over the Full panel")
|
||||
pog = block(menu, "bool pages_on_game() {")
|
||||
check("embed_open ||" in pog and "game_options_shown()" in pog, "pages_on_game does not follow the game's Options screen")
|
||||
tab = block(menu, "void draw_game_tab(ui::Ctx& c) {")
|
||||
check("const game_grid::Column col = pages_column(c.w, c.h, true);" in tab and "ui::Ctx k = column_ctx(c, col);" in tab and
|
||||
"game_tab_map = col.map, hits_game_tab = true;" in tab and "put_on_grid(c.d, vtx0, cmd0, col.map, window_clip);" in tab,
|
||||
"draw_game_tab: the header over the game's own tab is not on the game's grid")
|
||||
check("std::floor(c.h * 16.0f / 9.0f" not in tab, "draw_game_tab still lays the header on the window's height")
|
||||
tick = block(menu, "void menu_tick() {")
|
||||
check("hits.at(game_tab_map.back_x((float)ix), game_tab_map.back_y((float)iy))" in tick,
|
||||
"the game's own tab does not take the mouse back through the map its tabs were drawn with")
|
||||
fps = block(menu, "void draw_fps(ui::Ctx& window, bool under_banner) {")
|
||||
check("const bool on_game = under_banner ? pages_on_game() : true;" in fps and
|
||||
"if (on_game) c.d->PopClipRect(), put_on_grid(c.d, vtx0, cmd0, col.map, window_clip);" in fps,
|
||||
"draw_fps: the counter under our header is not on the grid with the header")
|
||||
check(fps.index("const ImVec4 window_clip = clip_now(c.d);") < fps.index("if (on_game) push_window_clip(c.d, col.map, window.w, window.h);") <
|
||||
fps.index("edged(digits, big, x, my, fps_text, ui::kInk)"),
|
||||
"draw_fps: the counter is cut at the window's width in the column's pixels (gone on a 16:10 or 4:3 picture)")
|
||||
check("const float ph = pages_h(c.w, c.h);" in block(menu, "void prebake(const ui::Ctx& c) {") and
|
||||
"const float ph = pages_h((float)w, (float)h);" in block(menu, "bool prebake_needed(uint32_t w, uint32_t h) {"),
|
||||
"prebake: the pages' glyphs are not baked at the grid's size they open at inside the game's Options screen")
|
||||
|
||||
funcs = "\n".join([
|
||||
"ImDrawList* header_split = nullptr;",
|
||||
block(menu, "void header_layer(const ui::Ctx& c, bool on) {"),
|
||||
block(menu, "ImVec4 clip_now(const ImDrawList* d) {"),
|
||||
block(menu, "void put_on_grid(ImDrawList* d, int vtx0, int cmd0, const game_grid::Map& m, const ImVec4& keep, int skip0 = 0, int skip1 = 0) {"),
|
||||
block(menu, "void push_window_clip(ImDrawList* d, const game_grid::Map& m, float window_w, float window_h) {"),
|
||||
block(menu, "struct PanelWait {") + ";",
|
||||
"PanelWait panel_wait;",
|
||||
"ImDrawList* panel_split = nullptr;",
|
||||
block(menu, "void panel_draw(ImDrawList* d) {"),
|
||||
block(menu, "void panel_between(ImDrawList* d) {"),
|
||||
block(menu, "void panel_merge(ImDrawList* d) {"),
|
||||
block(menu, "void panel_over(ImDrawList* d) {"),
|
||||
block(menu, "void dim_window(ImDrawList* d, const game_grid::Map& m, const game_grid::Place& g, float w, float h, ImU32 col) {"),
|
||||
block(menu, "void dim_page(ui::Ctx& c, ImU32 col) {"),
|
||||
])
|
||||
with tempfile.TemporaryDirectory(prefix="options-tabs-grid-") as tmp:
|
||||
tmp = Path(tmp)
|
||||
# 1. the grid alone
|
||||
src, exe = tmp / "grid.cpp", tmp / "grid.exe"
|
||||
src.write_text(GRID, encoding="utf-8")
|
||||
subprocess.run([args.cxx, "-std=c++20", "-O1", "-Wall", "-Wextra", "-Werror", "-I" + str(VK), str(src), "-o", str(exe)], check=True)
|
||||
r = subprocess.run([str(exe)], capture_output=True, text=True)
|
||||
check(r.returncode == 0, "the column:\n" + r.stdout)
|
||||
print(r.stdout.strip())
|
||||
# 2. the draw list, with Dear ImGui
|
||||
src, obj, exe = tmp / "draw.cpp", tmp / "draw.o", tmp / "draw.exe"
|
||||
src.write_text(DRAW.replace("%FUNCS%", funcs), encoding="utf-8")
|
||||
inc = ["-I" + str(VK), "-I" + str(IMGUI)]
|
||||
subprocess.run([args.cxx, "-std=c++20", "-O1", "-Wall", "-Wextra", "-Werror", "-Wno-missing-field-initializers", *inc,
|
||||
"-c", str(src), "-o", str(obj)], check=True)
|
||||
objs = [str(obj)]
|
||||
for name in ("imgui.cpp", "imgui_draw.cpp", "imgui_widgets.cpp", "imgui_tables.cpp"):
|
||||
o = tmp / (name + ".o")
|
||||
subprocess.run([args.cxx, "-std=c++20", "-O0", *inc, "-c", str(IMGUI / name), "-o", str(o)], check=True)
|
||||
objs.append(str(o))
|
||||
subprocess.run([args.cxx, *objs, "-o", str(exe)], check=True)
|
||||
r = subprocess.run([str(exe)], capture_output=True, text=True)
|
||||
check(r.returncode == 0, "the draw list:\n" + r.stdout + r.stderr)
|
||||
print(r.stdout.strip())
|
||||
print("PASS: our tabs inside the game's Options screen on the game's grid, the Full panel between the page and our header")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -55,6 +55,8 @@ def block(text, marker):
|
||||
FIXTURE = r"""
|
||||
#include "ini_merge.h"
|
||||
#include "file_whole.h"
|
||||
#include "merged_rows.h" // ((Triforce, options_version 7) the lines save no longer writes, and the file's version)
|
||||
namespace merged_rows = mkwvk::merged_rows;
|
||||
#include <cstdarg>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
|
||||
@@ -38,6 +38,7 @@ int up_now = 0; // (the Upscaler shown: 0 the game's own, 1 DLSS, 2 DLAA)
|
||||
int upscaler() { return up_now; }
|
||||
}
|
||||
#include "gpu/vk/upscaler_rows.h"
|
||||
#include "gpu/vk/merged_rows.h" // ((Triforce, options_version 7) the Output resolution's handheld profile, 7)
|
||||
using namespace mkwvk;
|
||||
namespace ur = upscaler_rows;
|
||||
''' + host[host.index("int hos_ini_option(const char *key, int otherwise);"):host.index("HLE(_ZN2nn2oe16GetOperationModeEv)")] + menu[
|
||||
@@ -50,9 +51,12 @@ int main(int argc, char **argv) {
|
||||
assert(output_mode() == mode);
|
||||
assert(hos_output_size(0) == w && hos_output_size(1) == h);
|
||||
assert(hos_rt_pool_size(305ull << 20) == ((mode == 2 ? 687ull : mode == 4 ? 610ull : mode == 5 || mode == 6 ? 900ull : 512ull) << 20)); // (512 MB at least: nn_applet.c)
|
||||
assert(kLastOutput == 6);
|
||||
assert(output_choice(-1) == 0 && output_choice(4) == 4 && output_choice(5) == 5 && output_choice(6) == 6 && output_choice(7) == 0);
|
||||
assert(step_output_choice(3, -1) == 3);
|
||||
// ((Triforce, options_version 7) 7 is 1536x864, the handheld profile, the smallest: first in the row)
|
||||
assert(kLastOutput == 7 && merged_rows::kHandheldOutput == 7);
|
||||
assert(output_choice(-1) == 0 && output_choice(4) == 4 && output_choice(5) == 5 && output_choice(6) == 6 && output_choice(7) == 7 &&
|
||||
output_choice(8) == 0);
|
||||
assert(step_output_choice(7, -1) == 7 && step_output_choice(7, 1) == 3 && step_output_choice(3, -1) == 7);
|
||||
assert(strcmp(tx_output_res(7), "1536x864 (handheld)") == 0);
|
||||
assert(step_output_choice(3, 1) == 0 && step_output_choice(0, -1) == 3);
|
||||
assert(step_output_choice(0, 1) == 1 && step_output_choice(1, -1) == 0);
|
||||
assert(step_output_choice(1, 1) == 2 && step_output_choice(2, -1) == 1);
|
||||
@@ -63,6 +67,7 @@ int main(int argc, char **argv) {
|
||||
opts.output_res = mode;
|
||||
opts.handheld = handheld();
|
||||
assert(strcmp(tx_output_res(mode), argv[4]) == 0);
|
||||
if (opts.handheld) opts.output_res = 7; // (the menu's row: the handheld profile, as menu_init reads it, merged_rows.h migrate)
|
||||
unsigned scene_w, scene_h;
|
||||
game_size(1.0f, scene_w, scene_h);
|
||||
assert(scene_w == (opts.handheld ? 1536 : mode ? w : 2048));
|
||||
@@ -76,8 +81,8 @@ int main(int argc, char **argv) {
|
||||
game_size(ur::percent(m[0]) / 100.0f, scene_w, scene_h);
|
||||
assert(scene_w == m[1] && scene_h == m[2] && scene_w * 1080 == scene_h * 1920);
|
||||
}
|
||||
up_now = ur::DLAA;
|
||||
assert(strcmp(tx_resolution(1), "Native (DLAA)") == 0);
|
||||
up_now = ur::DLAA; // ((Triforce, options_version 7) the Render resolution's Native (100%) step)
|
||||
assert(strcmp(tx_resolution(1), "Native (100%)") == 0);
|
||||
up_now = ur::GAME;
|
||||
}
|
||||
}
|
||||
@@ -95,6 +100,9 @@ int main(int argc, char **argv) {
|
||||
(4, 0, None, 4, 5120, 1440, "5120x1440"),
|
||||
(6, 0, None, 6, 5120, 2160, "5120x2160"),
|
||||
(1, 0, "6", 6, 5120, 2160, "5120x2160"),
|
||||
# ((Triforce, options_version 7) the handheld profile as the Output resolution's 7, saved or for a run)
|
||||
(1, 0, "7", 0, 2560, 1440, "2048x1152"),
|
||||
(8, 0, None, 0, 2560, 1440, "2048x1152"),
|
||||
)
|
||||
with tempfile.TemporaryDirectory(prefix="output-resolution-") as tmp:
|
||||
work = Path(tmp)
|
||||
|
||||
@@ -546,16 +546,22 @@ def check_source():
|
||||
check("presenting = true;" in block(pace, "int frame_start() {") and "if (presenting && ns > 0)" in block(pace, "void steady_held(int64_t ns) {"),
|
||||
"a hold on the present thread is counted as the presenting thread's")
|
||||
menu = (ROOT / "gpu/vk/vk_menu.cpp").read_text(encoding="utf-8")
|
||||
row = re.search(r'\{TAB_DISPLAY, "Steady frame rate", &opts\.steady_fps, 0, 2, 1, tx_steady_fps,(.*?)\n nullptr, true, true\},', menu, re.S)
|
||||
check(row is not None, "the Display tab has no Steady frame rate row (Off, Any rate, Refresh steps; read at the start)")
|
||||
check(menu.index('"Game frame rate cap"') < menu.index('"Steady frame rate"') < menu.index('"Reflex frame limit"'),
|
||||
"the Steady frame rate row is not beside the Game frame rate cap")
|
||||
# ((Triforce, options_version 7) Steady frame rate is the Frame pacing row's two Steady values (merged_rows.h); its value keeps
|
||||
# its key, steady_frame_rate, in a row no tab shows, and the Frame pacing row takes the restart for it)
|
||||
row = re.search(r'\{TAB_HIDDEN, "Steady frame rate", &opts\.steady_fps, 0, 2, 1, tx_steady_fps, nullptr\},', menu)
|
||||
check(row is not None, "the Steady frame rate's value is not kept under its key, 0 to 2")
|
||||
pacing = re.search(r'\{TAB_GRAPHICS, "Frame pacing", &merged\.pacing, 0, 3, 1, tx_pacing,(.*?)\n hn_pacing, true\},', menu, re.S)
|
||||
check(pacing is not None, "the Graphics tab has no Frame pacing row of four values taking a restart")
|
||||
check(menu.index('"Frame rate cap", &opts.fps_cap') < menu.index('"Frame pacing", &merged.pacing'),
|
||||
"the Frame pacing row is not in the Frame rate cap's group")
|
||||
check("if (r.value == &merged.pacing) return opts.steady_fps;" in block(menu, "int restart_value_of(const Row& r) {"),
|
||||
"the Frame pacing row asks for a restart for more than its Steady values")
|
||||
check('return v == 1 ? "Any rate" : v == 2 ? "Refresh steps" : "Off";' in block(menu, "const char* tx_steady_fps(int v) {"),
|
||||
"the row's values are not Off, Any rate, Refresh steps")
|
||||
check("opts.steady_fps" not in block(menu, "const char* ini_key(const Row& r) {"), "the row's key is not its name's, steady_frame_rate")
|
||||
check("int steady_fps = 0;" in (ROOT / "gpu/vk/vk_menu.h").read_text(encoding="utf-8"), "the row is not off by default")
|
||||
check("| Steady frame rate | Off, Any rate, Refresh steps" in (ROOT / "readme.md").read_text(encoding="utf-8"),
|
||||
"readme.md's settings table has no Steady frame rate row")
|
||||
check("| Frame pacing | Off, Even, Steady (any rate), Steady (refresh steps)" in (ROOT / "readme.md").read_text(encoding="utf-8"),
|
||||
"readme.md's settings table has no Frame pacing row with Steady")
|
||||
guide = (ROOT / "docs/development.md").read_text(encoding="utf-8")
|
||||
check("| `steady_frame_rate` | 0 Off, 1 any rate" in guide and "| `HOS_FPS_STEADY=0`, `=1`, `=2` |" in guide,
|
||||
"docs/development.md has no rows for steady_frame_rate and HOS_FPS_STEADY")
|
||||
|
||||
63
tests/test_pad_kind.py
Normal file
63
tests/test_pad_kind.py
Normal file
@@ -0,0 +1,63 @@
|
||||
"""((Triforce) 11-20, ticket "Controls not working properly") host/pad_kind.h: the controllers left out of the game's input
|
||||
(instruments and dance mats), and hos_sdl.c's list asking it for each one.
|
||||
|
||||
python -I -B tests/test_pad_kind.py [--cc gcc]
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
|
||||
C = r"""
|
||||
#include "pad_kind.h"
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
static int fails;
|
||||
#define CHECK(c, what) do { if (!(c)) { printf("FAIL %s\n", what); fails++; } } while (0)
|
||||
int main(void) {
|
||||
CHECK(pad_kind_left_out(6, NULL) && !strcmp(pad_kind_left_out(6, NULL), "a guitar"), "SDL's guitar type");
|
||||
CHECK(pad_kind_left_out(7, "x") != NULL, "a drum kit by type");
|
||||
CHECK(pad_kind_left_out(5, NULL) != NULL, "a dance mat by type");
|
||||
CHECK(pad_kind_left_out(1, "(Guitar Hero )") != NULL, "the ticket's guitar, by its name (typed as a gamepad)");
|
||||
CHECK(pad_kind_left_out(0, "Rock Band Drums") != NULL, "drums by name");
|
||||
CHECK(pad_kind_left_out(1, "Nintendo Switch Pro Controller") == NULL, "a Switch Pro controller is used");
|
||||
CHECK(pad_kind_left_out(1, "DualSense Wireless Controller") == NULL, "a DualSense is used");
|
||||
CHECK(pad_kind_left_out(1, "Xbox Series X Controller") == NULL, "an Xbox pad is used");
|
||||
CHECK(pad_kind_left_out(2, "Logitech G29") == NULL, "a wheel is left as it was");
|
||||
CHECK(pad_kind_left_out(0, NULL) == NULL, "nothing known: used");
|
||||
if (fails) return 1;
|
||||
puts("pad kind: all checks passed");
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument("--cc", default=os.environ.get("CC", "gcc"))
|
||||
a = p.parse_args()
|
||||
src = (ROOT / "host" / "hos_sdl.c").read_text(encoding="utf-8")
|
||||
for need, why in (('#include "pad_kind.h"', "hos_sdl.c includes the rule"),
|
||||
("if (!pad_left_out((int)got[i], (int32_t)got[i]))", "SDL3's list asks it"),
|
||||
("if (!pad_left_out(j, id))", "SDL2's list asks it"),
|
||||
('"SDL_GetJoystickTypeForID" : "SDL_JoystickGetDeviceType"', "the type is looked up in both SDLs"),
|
||||
('getenv("HOS_SDL_ALL_PADS")', "HOS_SDL_ALL_PADS=1 keeps every controller")):
|
||||
if need not in src:
|
||||
sys.exit("FAIL: host/hos_sdl.c: %s" % why)
|
||||
with tempfile.TemporaryDirectory(prefix="pad-kind-") as tmp:
|
||||
c = Path(tmp) / "t.c"
|
||||
c.write_text(C, encoding="utf-8")
|
||||
exe = Path(tmp) / "t.exe"
|
||||
subprocess.run([a.cc, "-std=c11", "-Wall", "-Wextra", "-Werror", "-I", str(ROOT / "host"), str(c), "-o", str(exe)], check=True)
|
||||
r = subprocess.run([str(exe)], capture_output=True, text=True)
|
||||
print(r.stdout.strip())
|
||||
if r.returncode:
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
240
tests/test_pause_mods_anim.py
Normal file
240
tests/test_pause_mods_anim.py
Normal file
@@ -0,0 +1,240 @@
|
||||
"""The Mods and Quit entries under the pause menu's System list, and Quit's dialog, as the game's own buttons and dialogs
|
||||
(gpu/vk/focus_anim.h, vk_ui.h cursor and button, vk_menu.cpp draw_mods_row, draw_quit_ask and menu_tick, host/nn_hid.c,
|
||||
host/menu_sound.c; no game).
|
||||
|
||||
(Triforce, 11-19) His "In the pause menu, the mods and quit tabs do not have any sound effects when selecting them, have no
|
||||
animations either. And when scrolling with the controller, the mods tab gets skipped over and goes straight to quit ... The
|
||||
quit menu submenu also has no animations and sound effects". The System list's buttons are the part PaCommonBtnThin_00 of
|
||||
the Common archive's layout, and the game's dialogs SystemWindow_00 with three of them. This compiles focus_anim.h alone
|
||||
and checks:
|
||||
|
||||
- the parts' curves as read from the layouts: the cursor's alpha from 0 to 1 over Select's first 4 frames, from 1 to 0
|
||||
over UnSelect's first 8; the window's alpha from 0 to 1 over In's 15 frames (slow to start), its rise from 38 units
|
||||
under its place to it over 20 (18 under at frame 5), its Out a straight fade over 2;
|
||||
- a button's cursor from drawing to drawing: there at once when settled (a still), faded in and out over the frames, a
|
||||
change back half way from where it is; the window takes input once its In has played.
|
||||
|
||||
And reads the source for what only the game shows: the cursor drawn with its amount (the line's and the glow's alpha), the
|
||||
button with it; Mods and Quit stepping their cursor every drawing, also while the menu is shut (their fade after the
|
||||
cursor went back to the game's list); the dialog's question and buttons risen and everything faded from its window's
|
||||
state, drawn on through its Out; no input while its In plays; both ways of opening it (A on Quit, a click on Quit) starting
|
||||
the In; B and Cancel playing the Out; ((11-19) a click is A on the dialog's own buttons only, Mods and Quit under its dim
|
||||
are not there for the mouse while it is open or closing; the mouse moved onto Quit gives it the cursor with the system
|
||||
menu's tick, as onto Mods, and moved up off the entries onto the game's buttons gives the game its cursor back); the
|
||||
controller's Down that brought the cursor onto Mods not taken again as the
|
||||
entry's own Down (on to Quit), and the host's stick Down at the menu's own half travel; the system menu's tick replaced by
|
||||
the decide of the same press (the sound's side is tests/menu_sound_test.c's), no cursor sound after Quit Game's decide.
|
||||
|
||||
python -I -B tests/test_pause_mods_anim.py [--cxx clang++]
|
||||
"""
|
||||
import argparse
|
||||
import re
|
||||
import subprocess
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
VK = ROOT / "gpu" / "vk"
|
||||
RUN_ALL_ARGS = ["--cxx", "{cxx}"]
|
||||
|
||||
|
||||
def check(ok, why):
|
||||
if not ok:
|
||||
raise SystemExit("FAIL: " + why)
|
||||
|
||||
|
||||
def function(text, head):
|
||||
start = text.index(head)
|
||||
end = text.index("{", start) + 1
|
||||
depth = 1
|
||||
while depth:
|
||||
depth += (text[end] == "{") - (text[end] == "}")
|
||||
end += 1
|
||||
return text[start:end]
|
||||
|
||||
|
||||
PROGRAM = r"""
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include "focus_anim.h"
|
||||
using namespace focus_anim;
|
||||
static int fails = 0;
|
||||
#define CHECK(x) do { if (!(x)) { std::printf("FAIL:%d %s\n", __LINE__, #x); fails++; } } while (0)
|
||||
static bool near(float a, float b, float tol = 0.01f) { return std::fabs(a - b) <= tol; }
|
||||
int main() {
|
||||
// the layouts' curves
|
||||
CHECK(near(curve(kSelect, 0), 0) && near(curve(kSelect, 2), 0.5f) && near(curve(kSelect, 4), 1) && near(curve(kSelect, 8), 1));
|
||||
CHECK(near(curve(kUnSelect, 0), 1) && near(curve(kUnSelect, 4), 0.5f) && near(curve(kUnSelect, 8), 0) && near(curve(kUnSelect, 14), 0));
|
||||
CHECK(curve(kUnSelect, 1) > 0.9f); // (not gone after a frame: the fade the game's own buttons show)
|
||||
CHECK(kSelectNs == 8 * kFrameNs && kUnSelectNs == 14 * kFrameNs && kInNs == 20 * kFrameNs && kOutNs == 2 * kFrameNs);
|
||||
// the window: In and Out
|
||||
Window w = window_at(0);
|
||||
CHECK(near(w.alpha, 0) && near(w.drop, 38));
|
||||
w = window_at(5 * kFrameNs);
|
||||
CHECK(near(w.drop, 18) && w.alpha > 0 && w.alpha < 0.3f); // (slow to start: its slopes 0.02 and 0.14)
|
||||
w = window_at(15 * kFrameNs);
|
||||
CHECK(near(w.alpha, 1) && w.drop > 0 && w.drop < 3);
|
||||
w = window_at(20 * kFrameNs);
|
||||
CHECK(near(w.alpha, 1) && near(w.drop, 0));
|
||||
w = window_at(60 * kFrameNs);
|
||||
CHECK(near(w.alpha, 1) && near(w.drop, 0));
|
||||
CHECK(near(window_at(0, true).alpha, 1) && near(window_at(kFrameNs, true).alpha, 0.5f) && near(window_at(2 * kFrameNs, true).alpha, 0));
|
||||
CHECK(near(window_at(0, true).drop, 0));
|
||||
CHECK(!window_ready(0) && !window_ready(19 * kFrameNs) && window_ready(20 * kFrameNs));
|
||||
// a button's cursor from drawing to drawing
|
||||
Focus f;
|
||||
int64_t t = 1000000000;
|
||||
f.step(t, false);
|
||||
CHECK(near(f.shown, 0));
|
||||
f.step(t + kFrameNs, true); // (the cursor onto it: Select)
|
||||
CHECK(near(f.shown, 0));
|
||||
f.step(t + 3 * kFrameNs, true);
|
||||
CHECK(near(f.shown, 0.5f));
|
||||
f.step(t + 5 * kFrameNs, true);
|
||||
CHECK(near(f.shown, 1));
|
||||
f.step(t + 6 * kFrameNs, false); // (and off it: UnSelect)
|
||||
f.step(t + 7 * kFrameNs, false);
|
||||
CHECK(f.shown > 0.9f && f.shown < 1);
|
||||
f.step(t + 10 * kFrameNs, false);
|
||||
CHECK(near(f.shown, 0.5f));
|
||||
f.step(t + 11 * kFrameNs, true); // (back half way: from where it is, no jump down or up first)
|
||||
CHECK(f.shown >= 0.49f);
|
||||
f.step(t + 15 * kFrameNs, true);
|
||||
CHECK(near(f.shown, 1));
|
||||
f.step(t + 16 * kFrameNs, false);
|
||||
f.step(t + 24 * kFrameNs, false);
|
||||
CHECK(near(f.shown, 0));
|
||||
f.step(t + 25 * kFrameNs, true, true); // (settled: a still, a dialog just opened)
|
||||
CHECK(near(f.shown, 1));
|
||||
f.step(t + 25 * kFrameNs, true);
|
||||
CHECK(near(f.shown, 1));
|
||||
f.step(t + 26 * kFrameNs, false, true);
|
||||
CHECK(near(f.shown, 0));
|
||||
Focus first; // (its first drawing: as it stands, not faded in from nothing)
|
||||
first.step(t, true);
|
||||
CHECK(near(first.shown, 1));
|
||||
if (!fails) std::puts("the System list's buttons' and the dialog's curves and state");
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--cxx", default="clang++")
|
||||
args = parser.parse_args()
|
||||
ui = (VK / "vk_ui.h").read_text(encoding="utf-8")
|
||||
menu = (VK / "vk_menu.cpp").read_text(encoding="utf-8")
|
||||
hid = (ROOT / "host" / "nn_hid.c").read_text(encoding="utf-8")
|
||||
sound = (ROOT / "host" / "menu_sound.c").read_text(encoding="utf-8")
|
||||
events = (VK / "menu_sound_events.h").read_text(encoding="utf-8")
|
||||
|
||||
# the cursor and the button with an amount
|
||||
cursor = function(ui, "inline void cursor(Ctx& c, ImVec2 a, ImVec2 b, float k = 1) {")
|
||||
check("if (k <= 0) return;" in cursor and "(0.50f + 0.35f * c.pulse) * k" in cursor and "alpha(kCursor, k)" in cursor,
|
||||
"the cursor's line and glow are not drawn with its amount")
|
||||
button = function(ui, "inline void button(Ctx& c, ImVec2 a0, ImVec2 b0, const char* label, float focus) {")
|
||||
check("if (focus > 0) cursor(c, a0 + ImVec2(lu(c, 8), lu(c, 8)), b0 - ImVec2(lu(c, 8), lu(c, 8)), focus);" in button,
|
||||
"the button does not draw its cursor with its amount")
|
||||
check("inline void button(Ctx& c, ImVec2 a0, ImVec2 b0, const char* label, bool sel) { button(c, a0, b0, label, sel ? 1.0f : 0.0f); }" in ui,
|
||||
"the other buttons (draw_ask's) no longer draw their cursor whole")
|
||||
|
||||
# Mods and Quit: their cursor stepped every drawing, also while the menu is shut
|
||||
check('#include "focus_anim.h"' in menu, "vk_menu.cpp does not use focus_anim.h")
|
||||
row = function(menu, "void draw_mods_row(ui::Ctx& c, bool sel) {")
|
||||
pause = row[:row.index("draw_title_mods(")]
|
||||
check("mods_focus[i].step(now, sel && mods_row_sel == i, !ease_live || still);" in pause and
|
||||
"ui::button(c, a, b, names[i], mods_focus[i].shown);" in pause,
|
||||
"Mods and Quit do not fade their cursor in and out (it pops)")
|
||||
check("draw_mods_row(k, false);" in function(menu, "void draw_mods_row_shut(ui::Ctx& c) {"),
|
||||
"the entries are not drawn while the menu is shut (no fade after the cursor went back to the game's list)")
|
||||
|
||||
# the dialog: In and Out, its buttons' cursor
|
||||
ask = function(menu, "void draw_quit_ask(ui::Ctx& c) {")
|
||||
check("quit_ask ? focus_anim::window_at(now - quit_open_ns) : focus_anim::window_at(now - quit_shut_ns, true)" in ask,
|
||||
"the dialog does not play the window's In and Out")
|
||||
check(ask.index("const int vtx_in = c.d->VtxBuffer.Size;") < ask.index("\"Quit the game?\""),
|
||||
"the dialog's question and buttons are not the part that rises (N_In_00)")
|
||||
# ((11-19) the lab's "the Quit banner text shows on top of the game's tab strip before the banner plate": SystemWindow_00 has
|
||||
# no banner (N_In_00 alone, its In that pane's alpha and height); the dim over the whole window, on the same alpha)
|
||||
check("ui::banner(" not in ask, "Quit's dialog draws a banner of its own over the pause menu's header (SystemWindow_00 has none)")
|
||||
check("const int vtx0 = c.d->VtxBuffer.Size;" in ask and
|
||||
ask.index("const int vtx0 = c.d->VtxBuffer.Size;") < ask.index("dim_window(c.d, menu_map, menu_grid(menu_window_w, menu_window_h), menu_window_w, menu_window_h, ui::rgba(8, 5, 2, 220));") <
|
||||
ask.index("const int vtx_in = c.d->VtxBuffer.Size;"), "the dim is not the window's, faded with the dialog")
|
||||
check("c.d->VtxBuffer[i].pos.y += drop;" in ask and "c.d->VtxBuffer[i].col = ui::alpha(c.d->VtxBuffer[i].col, w.alpha);" in ask,
|
||||
"the dialog is not risen and faded as drawn")
|
||||
check("quit_focus[i].step(now, i == quit_sel, settle || quit_fresh);" in ask and "ui::button(c, a, b, labels[i], quit_focus[i].shown);" in ask,
|
||||
"the dialog's buttons do not fade their cursor as the System list's")
|
||||
dm = function(menu, "void draw_menu(ui::Ctx& c, bool perf_under) {")
|
||||
check("if (row) { // (the entries: drawn above; Quit's dialog over them, and its Out; its dim the window's)" in dm and
|
||||
" if (quit_ask || quit_closing())" in dm and
|
||||
"draw_quit_ask(k);" in dm and dm.index("menu_window_w = c.w, menu_window_h = c.h;") < dm.index("draw_quit_ask(k);"),
|
||||
"the dialog is not drawn through its Out, or its dim is not the whole window's")
|
||||
# ((11-19) the performance panel over the dialog's dim, as over the game's own dialogs: drawn after the menu on Mods' page)
|
||||
for fn in ("void menu_record(VkCommandBuffer cmd, uint32_t index, uint32_t w, uint32_t h) {",
|
||||
"void menu_record_image(VkCommandBuffer cmd, VkImage image, VkImageView view, uint32_t w, uint32_t h) {"):
|
||||
rec = function(menu, fn)
|
||||
check("const bool over_row = open && page == kModsRowPage;" in rec and "if (open) draw_menu(c, full && !over_row);" in rec and
|
||||
rec.index("if (open) draw_menu(c, full && !over_row);") < rec.index("if (full && over_row) draw_perf(c);"),
|
||||
"the performance panel is under Quit's dim (" + fn.split("(")[0] + ")")
|
||||
# ((11-19) the mouse over the dialog: its buttons only, Mods and Quit under the dim gone from the hit map; none on its Out)
|
||||
check("hits.clear(0, 0, c.w, c.h);" in ask and ask.index("hits.clear(0, 0, c.w, c.h);") < ask.index("for (int i = 0; i < 3; i++) {"),
|
||||
"Mods and Quit under the dialog's dim still take clicks (a second click on Quit's place is A on Quit Game)")
|
||||
check("if (quit_ask) hits.add(a.x, a.y, b.x, b.y, menu_hit::kButton, 10 + i);" in ask, "the dialog's buttons take clicks while its Out plays")
|
||||
|
||||
# the input
|
||||
tick = function(menu, "void menu_tick() {")
|
||||
enter = tick[tick.index("bool entered_by_down = false;"):tick.index("if (!open_now.load() || page != kModsPage) {")]
|
||||
check("entered_by_down = enter == 1 || enter == 5;" in enter and "if (enter == 3) quit_open();" in enter,
|
||||
"the enter word does not tell of a Down, or a click on Quit does not open its dialog with its In")
|
||||
check("mods_row_sel = enter == 3 || enter == 4 ? 1 : 0," in enter and "const bool clicked = enter == 2 || enter == 3;" in enter and
|
||||
"mods_sound(clicked ? HOS_MENU_SOUND_SYS_DECIDE : HOS_MENU_SOUND_SYS_CURSOR);" in enter,
|
||||
"the mouse moved onto Quit (the host's 4) does not give it the cursor with the system menu's tick")
|
||||
clear = tick.index("if (entered_by_down) press[2] = false;")
|
||||
feeds = [tick.index("press[1] |= pad(HOS_PAD_UP) || pad(HOS_PAD_LS_UP), press[2] |= pad(HOS_PAD_DOWN) || pad(HOS_PAD_LS_DOWN);"),
|
||||
tick.index("press[1] |= (mp & HOS_MODS_PRESS_UP) != 0, press[2] |= (mp & HOS_MODS_PRESS_DOWN) != 0;")]
|
||||
on_to_quit = tick.index("} else if (press[2] && quit_here && mods_row_sel == 0) { // (Down from Mods: Quit)")
|
||||
check(max(feeds) < clear < on_to_quit, "the Down that brought the cursor onto Mods is taken again as the entry's own (on to Quit)")
|
||||
check(not re.search(r"press\[2\] \|= |press\[2\] = true", tick[clear + 40:on_to_quit]), "a Down is put back after the enter's was taken away")
|
||||
rows = tick[tick.index("} else if (open_now.load() && page == kModsRowPage) {"):tick.index("} else if (open_now.load() && page == kModsPage) {")]
|
||||
check("const bool quit_ready = quit_ask && focus_anim::window_ready(prof_now() - quit_open_ns);" in rows and
|
||||
"if (quit_ready && hit.index >= 10" in rows, "the dialog takes the mouse while its In plays")
|
||||
check("if ((ptr.pressed & HOS_MOUSE_LEFT) && (!quit_ask || hit.index >= 10)) press[7] = true;" in rows,
|
||||
"with the dialog open a click on Mods or Quit is A on the dialog")
|
||||
check("} else if (moved && !quit_ask && !quit_closing()) {" in rows and
|
||||
"my < e[1] && my > e[1] - (quit_here ? 6 : 4) * e[4]) mods_row_sel = 0, press[1] = true;" in rows,
|
||||
"the mouse moved up off Mods or Quit onto the System page's buttons does not give the game its cursor back")
|
||||
check("if (i == 0) mods_entry_px[0] = a.x, mods_entry_px[1] = a.y, mods_entry_px[2] = b.x, mods_entry_px[3] = b.y;" in pause and
|
||||
"mods_entry_px[4] = ui::lu(c, pitch);" in pause, "the System page's Mods box is not kept for the mouse")
|
||||
wait = rows[rows.index("} else if (quit_ask && !quit_ready) {"):rows.index("} else if (quit_ask) {")]
|
||||
check("press[7] = false" in wait and "press[5]" in wait and "press[2]" in wait, "the dialog takes presses while its In plays")
|
||||
check("if (mods_row_sel == 1) quit_open(), mods_sound(HOS_MENU_SOUND_SYS_DECIDE), changed = true;" in rows,
|
||||
"A on Quit does not open its dialog with its In and the system menu's decide")
|
||||
check("if (quit_sel == 2) quit_cancel();" in rows and "quit_cancel(), mods_sound(HOS_MENU_SOUND_CANCEL)" in rows,
|
||||
"Cancel and B do not close the dialog with its Out")
|
||||
check("quit_ask = true" not in tick and "quit_ask = false" not in tick, "the dialog is opened or closed past its In and Out")
|
||||
check("else if (!after.open && !quit_ended) mods_sound(HOS_MENU_SOUND_SYS_CURSOR);" in tick and "quit_ended = true" in rows,
|
||||
"Quit Game's decide is followed by the cursor's sound")
|
||||
# (the sounds reach the host: the queue takes the system menu's)
|
||||
check("constexpr int kFanfare = 8, kSysCursor = 9, kSysDecide = 10, kLast = kSysDecide;" in events and "sound > kLast" in events,
|
||||
"the sounds' queue drops the system menu's cursor and decide")
|
||||
|
||||
# the host: the stick's Down onto Mods where the menu's bits have it; the system tick replaced by its decide
|
||||
check("const int down = (int)(buttons >> B_DOWN & 1) || stick[1] < -16384;" in hid and "if (s[1] < -16384) menu |= 1ULL << HOS_PAD_LS_DOWN;" in hid,
|
||||
"the stick's Down onto Mods is not where the menu's pad bits have it (a later read is a Down of the entry's)")
|
||||
play = function(sound, "void hos_menu_sound_play(int id, int64_t now_ns) {")
|
||||
check("was == HOS_MENU_SOUND_SYS_CURSOR" in play, "the system menu's tick is not replaced by the decide of the same press")
|
||||
check("if (id == HOS_MENU_SOUND_CURSOR && now_ns - atomic_load(&last_start_ns) < CURSOR_GAP_NS) return;" in play,
|
||||
"the options' tick gap changed")
|
||||
|
||||
with tempfile.TemporaryDirectory(prefix="pause-mods-anim-") as tmp:
|
||||
src, exe = Path(tmp) / "anim.cpp", Path(tmp) / "anim.exe"
|
||||
src.write_text(PROGRAM, encoding="utf-8")
|
||||
subprocess.run([args.cxx, "-std=c++20", "-O1", "-Wall", "-Wextra", "-Werror", "-I" + str(VK), str(src), "-o", str(exe)], check=True)
|
||||
r = subprocess.run([str(exe)], capture_output=True, text=True)
|
||||
check(r.returncode == 0, "the buttons' and the dialog's animations as made:\n" + r.stdout)
|
||||
print("PASS: Mods and Quit under the System list, Quit's dialog: the game's animations, the controller's Down, the sounds")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -102,11 +102,13 @@ def check_source():
|
||||
raise SystemExit("pcache_init reads the cache's file past the bounded read")
|
||||
if "ci.initialDataSize = data.size();" not in init:
|
||||
raise SystemExit("the cache is not made from what the bounded read gave")
|
||||
# ((Triforce, 11-18) what is for other shaders is read only when carried (pcache_bound::carried, with the bound), else not at all)
|
||||
carry = "const bool carried = pcache_bound::carried(pcache_same, (uint64_t)std::max<int64_t>(sz, 0), carry, pcache_bound_bytes, ram);"
|
||||
# ((Triforce, 11-18) what is for other shaders is read only when carried: over the stamp change at an update's preparation
|
||||
# (pcache_carry.h, tests/test_pcache_carry.py), or outside it by v0.5.2's size and RAM rule (pcache_bound::carried, with the
|
||||
# bound, where pcache_carry::plain_carry lets it: not over the preparation's own carry); else not at all
|
||||
carry = "pcache_bound::carried(pcache_same, (uint64_t)std::max<int64_t>(sz, 0), carry, pcache_bound_bytes, ram);"
|
||||
if carry not in init or init.index(setb) > init.index(carry):
|
||||
raise SystemExit("pcache_init does not decide the carry with the bound set, or not by pcache_bound::carried")
|
||||
if init.index("if (!pcache_same && !carried) {", init.index(carry)) > init.index(readb):
|
||||
if init.index("if (!pcache_same && !pcache_carried && !carried) {", init.index(carry)) > init.index(readb):
|
||||
raise SystemExit("a file for other shaders that is not carried is read")
|
||||
save = between(draw, "void pipeline_cache_save(bool force) {", "\n}\n")
|
||||
ask = "if (!pcache_bound::within(n, pcache_bound_bytes)) {"
|
||||
|
||||
547
tests/test_pcache_carry.py
Normal file
547
tests/test_pcache_carry.py
Normal file
@@ -0,0 +1,547 @@
|
||||
"""The pipeline cache's file carried over a stamp change at an update's preparation, capped at 1.25 x its base
|
||||
(gpu/vk/pcache_carry.h; vk_draw.cpp pcache_init, pipeline_cache_save, pcache_carry_rebuild; vk_main.cpp; no game/GPU).
|
||||
|
||||
The header is compiled and run as it is: the cap, the history beside the file (its side file only when written for the
|
||||
file's own stamp, else one fresh set of the file's size), when a file for other shaders is carried (an update's
|
||||
preparation, the switch on, within the bound, at most the cap), the session's history (fresh, the file's own, one carry
|
||||
more), which saves a carried session writes, how the base follows the saves of a file never carried into and stays put
|
||||
once carried into (so the cap is cumulative over the carries, not a quarter more each time), and the side file's bytes.
|
||||
What a carried cache may hold (the cap, or the file's bound where lower) and the refusal kept for these shaders
|
||||
(<file>.nocarry). Then the source: pcache_init decides the carry before the bounded read and still checks the device's
|
||||
header after it, pipeline_cache_save asks the carry's limit before the bound and before it fetches the data and writes
|
||||
the history with the .for, the preparation looks at a carried cache's size while it builds and stops building into it
|
||||
past its limit, and builds again into a fresh cache: the carried run's compute pipelines from the program cache, then the
|
||||
stage libraries, nothing translated again (vk_draw.cpp's carry part itself is run by tests/test_pipeline_cache_save.py,
|
||||
cases carry-cap, carry-bound, carry-check and carry-early). The early drop: the projection of a carried cache's growth over a
|
||||
sample of the stage libraries' whole order (every 32nd program, built first), and when it drops the carry before it gets past
|
||||
(the sample, the margin), with the RX 7900 XT's update of 11-18 (dropped), a carry whose misses are all in the order's head,
|
||||
the notes' programs (not: a projection from the head would have dropped it), and a mostly-hit carry (not); warm_libraries
|
||||
builds the sample first, the others waiting for its projection, before the look past the limit, and a cache dropped so is
|
||||
not written.
|
||||
python -I -B tests/test_pcache_carry.py --cxx clang++
|
||||
"""
|
||||
import argparse
|
||||
import subprocess
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
RUN_ALL_ARGS = ["--cxx", "{cxx}"]
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
FIXTURE = r"""
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
#include "pcache_carry.h"
|
||||
#define CHECK(x) do { if (!(x)) { std::printf("line %d: %s\n", __LINE__, #x); return 1; } } while (0)
|
||||
using namespace pcache_carry;
|
||||
int main() {
|
||||
const uint64_t MB = 1ull << 20;
|
||||
// (the switch: on unless 0)
|
||||
CHECK(on(nullptr) && on("1") && !on("0"));
|
||||
// (the cap: 1.25 x the base, never wrapping)
|
||||
CHECK(cap(1000) == 1250 && cap(2048 * MB) == 2560 * MB && cap(0) == 0 && cap(~0ull) == ~0ull);
|
||||
CHECK(fits(1250, 1000) && !fits(1251, 1000) && fits(0, 0) && !fits(1, 0));
|
||||
|
||||
const char* A = "aaaaaaaaaaaaaaaa";
|
||||
const char* B = "bbbbbbbbbbbbbbbb";
|
||||
Side side;
|
||||
std::memcpy(side.stamp, A, 16);
|
||||
side.base = 1000, side.carried = 2;
|
||||
// (the history: the side file only when it was written for the file's own stamp; else one fresh set of the file's size)
|
||||
Side h = history(true, side, A, 1200);
|
||||
CHECK(h.base == 1000 && h.carried == 2);
|
||||
h = history(true, side, B, 1200);
|
||||
CHECK(h.base == 1200 && h.carried == 0 && !std::memcmp(h.stamp, B, 16));
|
||||
h = history(false, side, A, 1200);
|
||||
CHECK(h.base == 1200 && h.carried == 0);
|
||||
h = history(true, side, nullptr, 1200); // (no .for beside the file)
|
||||
CHECK(h.base == 1200 && h.carried == 0);
|
||||
Side zero = side;
|
||||
zero.base = 0;
|
||||
CHECK(history(true, zero, A, 700).base == 700);
|
||||
|
||||
// (a file for other shaders is carried only at an update's preparation, with the switch on, within the bound, at most the
|
||||
// cap of its history; nothing of a header's size or less)
|
||||
CHECK(may_carry(true, true, false, true, 1250, side));
|
||||
CHECK(!may_carry(true, true, false, true, 1251, side));
|
||||
CHECK(!may_carry(false, true, false, true, 1100, side));
|
||||
CHECK(!may_carry(true, false, false, true, 1100, side));
|
||||
CHECK(!may_carry(true, true, false, false, 1100, side));
|
||||
CHECK(!may_carry(true, true, false, true, 32, history(false, side, A, 32)));
|
||||
CHECK(may_carry(true, true, false, true, 1200, history(false, side, A, 1200))); // (a file of before this rule: one set)
|
||||
CHECK(!may_carry(true, true, false, true, 1100, zero));
|
||||
// (refused for these shaders already, <file>.nocarry: a preparation begun again after a kill starts fresh)
|
||||
CHECK(!may_carry(true, true, true, true, 1100, side));
|
||||
// ((11-19) v0.5.2's carry outside the preparation: asked for a plain start only; not when .nocarry names these shaders
|
||||
// and the file has no .for (warm_libraries dropped it: read again it loops, over the bound and never written), nor for a
|
||||
// carried save cut short, nor at the preparation, nor for a file read as carried or resumed already)
|
||||
CHECK(plain_carry(false, false, false, false, false));
|
||||
CHECK(!plain_carry(false, false, false, true, false));
|
||||
CHECK(!plain_carry(false, false, false, false, true));
|
||||
CHECK(!plain_carry(true, false, false, false, false));
|
||||
CHECK(!plain_carry(false, true, false, false, false) && !plain_carry(false, false, true, false, false));
|
||||
|
||||
// (the session: fresh is nothing; the file's own keeps its history; carried counts one carry more)
|
||||
CHECK(session(Start::Fresh, side).base == 0 && session(Start::Fresh, side).carried == 0);
|
||||
CHECK(session(Start::Same, side).base == 1000 && session(Start::Same, side).carried == 2);
|
||||
CHECK(session(Start::Carried, side).base == 1000 && session(Start::Carried, side).carried == 3);
|
||||
|
||||
// (a carried session's saves only up to the cap; any other session's as before)
|
||||
const Side carried = session(Start::Carried, side);
|
||||
CHECK(save_ok(true, 1250, carried, 0) && !save_ok(true, 1251, carried, 0));
|
||||
CHECK(save_ok(false, 5000, carried, 0) && save_ok(false, 5000, Side{}, 0));
|
||||
|
||||
// (what a carried cache may hold: the cap, or the file's bound where that is lower; 0 is no bound)
|
||||
CHECK(limit(1000, 0) == 1250 && limit(1000, 1100) == 1100 && limit(1000, 2000) == 1250 && limit(1000, 1250) == 1250);
|
||||
// (over the bound and under the cap is past what it may hold: never left over the bound unwritten, with no rebuild)
|
||||
CHECK(over(true, 1101, carried, 1100) && !over(true, 1100, carried, 1100) && !save_ok(true, 1101, carried, 1100));
|
||||
CHECK(over(true, 1251, carried, 4000) && !over(true, 1250, carried, 4000));
|
||||
// (a session not carried: the bound's own rule as before, never over here)
|
||||
CHECK(!over(false, 1u << 30, carried, 1100) && save_ok(false, 1u << 30, carried, 1100));
|
||||
// (2 GB bound, a 1.8 GB file carried: past 2 GB is past, under its 2.25 GB cap)
|
||||
Side big;
|
||||
big.base = 1843 * MB;
|
||||
CHECK(fits(1843 * MB, big.base) && over(true, 2049 * MB, big, 2048 * MB) && !over(true, 2048 * MB, big, 2048 * MB));
|
||||
CHECK(kCheckMs > 0 && kCheckMs <= 60000);
|
||||
|
||||
// (the base follows the saves of a file never carried into, and stays put once carried into)
|
||||
Side s = saved(Side{}, 900, B);
|
||||
CHECK(s.base == 900 && s.carried == 0 && !std::memcmp(s.stamp, B, 16));
|
||||
s = saved(s, 1000, B);
|
||||
CHECK(s.base == 1000);
|
||||
s = saved(s, 800, B);
|
||||
CHECK(s.base == 1000);
|
||||
Side c = saved(carried, 1200, B);
|
||||
CHECK(c.base == 1000 && c.carried == 3 && !std::memcmp(c.stamp, B, 16));
|
||||
|
||||
// (cumulative: a set of 1000 carried at 1100, then at 1250, never past 1250 whatever the updates; refused, a fresh set
|
||||
// starts again with its own base)
|
||||
Side f = saved(Side{}, 1000, A);
|
||||
Side one = saved(session(Start::Carried, history(true, f, A, 1000)), 1100, B);
|
||||
CHECK(one.base == 1000 && one.carried == 1);
|
||||
CHECK(may_carry(true, true, false, true, 1100, history(true, one, B, 1100)));
|
||||
Side two = saved(session(Start::Carried, history(true, one, B, 1100)), 1250, A);
|
||||
CHECK(two.base == 1000 && two.carried == 2);
|
||||
CHECK(may_carry(true, true, false, true, 1250, history(true, two, A, 1250)));
|
||||
CHECK(!save_ok(true, 1300, session(Start::Carried, history(true, two, A, 1250)), 0));
|
||||
const Side play = saved(session(Start::Same, history(true, two, A, 1250)), 1300, A); // (play's growth on a carried file)
|
||||
CHECK(play.base == 1000 && !may_carry(true, true, false, true, 1300, history(true, play, A, 1300)));
|
||||
const Side fresh = saved(session(Start::Fresh, two), 1200, B);
|
||||
CHECK(fresh.base == 1200 && fresh.carried == 0);
|
||||
|
||||
// (open: a carried session's history until its preparation goes through to its end; the file's own keeps it, its saves
|
||||
// too, and a fresh one is not)
|
||||
CHECK(session(Start::Carried, side).open == 1 && session(Start::Fresh, two).open == 0);
|
||||
CHECK(two.open == 1 && session(Start::Same, two).open == 1 && saved(session(Start::Same, two), 1250, A).open == 1);
|
||||
CHECK(saved(session(Start::Fresh, two), 1200, B).open == 0);
|
||||
CHECK(history(true, two, A, 1250).open == 1 && history(true, two, B, 1250).open == 0 && history(false, two, A, 1250).open == 0);
|
||||
// (resumed: a file for these shaders whose history is open, at an update's preparation with the switch on, is read as
|
||||
// carried; stopped at 2.9 GB of a 2.6 GB base, it is capped at 3.25 GB as the carried run was)
|
||||
CHECK(resumed(true, true, true, two) && !resumed(false, true, true, two) && !resumed(true, false, true, two));
|
||||
CHECK(!resumed(true, true, false, two) && !resumed(true, true, true, fresh));
|
||||
const Side stopped = saved(session(Start::Carried, history(true, saved(Side{}, 2600 * MB, A), A, 2600 * MB)), 2900 * MB, B);
|
||||
CHECK(stopped.open == 1 && stopped.base == 2600 * MB && stopped.carried == 1);
|
||||
const Side again = session(Start::Same, history(true, stopped, B, 2900 * MB));
|
||||
CHECK(resumed(true, true, true, history(true, stopped, B, 2900 * MB)) && again.carried == 1 && again.open == 1);
|
||||
CHECK(!over(true, 3250 * MB, again, 4096 * MB) && over(true, 3251 * MB, again, 4096 * MB));
|
||||
Side done = again;
|
||||
done.open = 0;
|
||||
CHECK(!resumed(true, true, true, done));
|
||||
// (begun: a carried save cut before its .for, the side file written first with these shaders' stamp and open. The .for
|
||||
// names the old stamp, or there is none: that session's history, read as resumed. Not when the .for names these shaders
|
||||
// (the history's own rule), the side file is shut, another stamp's, or has no base)
|
||||
CHECK(begun(true, stopped, B, A) && begun(true, stopped, B, nullptr) && !begun(true, stopped, B, B));
|
||||
CHECK(!begun(false, stopped, B, A) && !begun(true, done, B, A) && !begun(true, stopped, A, B));
|
||||
Side nobase = stopped;
|
||||
nobase.base = 0;
|
||||
CHECK(!begun(true, nobase, B, A) && resumed(true, true, true, stopped) && history(true, stopped, A, 2600 * MB).open == 0);
|
||||
|
||||
// (the side file's bytes: as written, read back; another magic or a short file is none)
|
||||
uint8_t raw[kSideBytes];
|
||||
put(two, raw);
|
||||
Side back;
|
||||
CHECK(get(raw, sizeof raw, &back) && back.base == two.base && back.carried == two.carried && !std::memcmp(back.stamp, A, 16));
|
||||
CHECK(back.open == two.open);
|
||||
Side shut = two;
|
||||
shut.open = 0;
|
||||
put(shut, raw);
|
||||
CHECK(get(raw, sizeof raw, &back) && back.open == 0);
|
||||
put(two, raw);
|
||||
CHECK(!get(raw, sizeof raw - 1, &back));
|
||||
raw[0] ^= 1;
|
||||
CHECK(!get(raw, sizeof raw, &back));
|
||||
|
||||
// (the early drop: the switch, on unless 0)
|
||||
CHECK(project_on(nullptr) && project_on("1") && !project_on("0"));
|
||||
CHECK(kProjectLibs == 1500 && kSampleStride == 32 && kProjectNum == 2 * kProjectDen);
|
||||
// (the sample's order: every 32nd program of the warm's order first, in their order, then the others in theirs; every
|
||||
// program once)
|
||||
CHECK(sample_count(0) == 0 && sample_count(1) == 1 && sample_count(32) == 1 && sample_count(33) == 2);
|
||||
CHECK(sample_count(42532) == 1330);
|
||||
const uint64_t totals[] = {1, 2, 31, 32, 33, 63, 64, 65, 1000, 42532};
|
||||
for (uint64_t t : totals) {
|
||||
std::vector<char> seen(t, 0);
|
||||
const uint64_t m = sample_count(t);
|
||||
uint64_t prev = 0;
|
||||
for (uint64_t c = 0; c < t; c++) {
|
||||
const uint64_t i = sample_order(c, t);
|
||||
CHECK(i < t && !seen[i]);
|
||||
seen[i] = 1;
|
||||
CHECK((c < m) == (i % kSampleStride == 0));
|
||||
CHECK(!c || c == m || i > prev);
|
||||
prev = i;
|
||||
}
|
||||
}
|
||||
CHECK(sample_order(0, 42532) == 0 && sample_order(1329, 42532) == 42528 && sample_order(1330, 42532) == 1);
|
||||
CHECK(sample_order(1330 + 30, 42532) == 31 && sample_order(1330 + 31, 42532) == 33 && sample_order(42531, 42532) == 42531);
|
||||
// (the projection: the growth per program done times the programs left, on top of what it holds; nothing grown, nothing
|
||||
// done or nothing left: what it holds)
|
||||
CHECK(projected(1000, 900, 10, 100) == 1900 && projected(1000, 900, 50, 100) == 1100);
|
||||
CHECK(projected(900, 900, 10, 100) == 900 && projected(800, 900, 10, 100) == 800);
|
||||
CHECK(projected(1000, 900, 0, 100) == 1000 && projected(1000, 900, 100, 100) == 1000);
|
||||
CHECK(projected(~0ull - 1, 0, 1, ~0ull) == ~0ull); // (never wrapping)
|
||||
// (the margin: the projected growth at least twice the room at the start, 100 from 900 under 1000)
|
||||
CHECK(drop_early(950, 900, 1, 4, 1500, 1000) && !drop_early(949, 900, 1, 4, 1500, 1000));
|
||||
// (the sample: 1500 stage libraries at least)
|
||||
CHECK(!drop_early(950, 900, 1, 4, 1499, 1000));
|
||||
// (no room at the start, no growth, nothing left: never on the projection; over says it when past)
|
||||
CHECK(!drop_early(1100, 1000, 1, 4, 1500, 1000) && !drop_early(900, 900, 1, 4, 1500, 1000));
|
||||
CHECK(!drop_early(1000, 900, 4, 4, 1500, 1000));
|
||||
|
||||
// (the warm as warm_libraries takes it with a carried cache: its sample built first, in sample_order, with libs_each
|
||||
// stage libraries a program, then its projection, once; and where the whole warm ends. grow(i): what program i of the
|
||||
// warm's order adds to the cache)
|
||||
const auto sampled = [](uint64_t from, uint64_t total, uint64_t lim_, uint64_t libs_each, auto grow) {
|
||||
const uint64_t m = sample_count(total);
|
||||
uint64_t now = from;
|
||||
for (uint64_t c = 0; c < m; c++) now += grow(sample_order(c, total));
|
||||
return drop_early(now, from, m, total, m * libs_each, lim_);
|
||||
};
|
||||
const auto ends = [](uint64_t from, uint64_t total, auto grow) {
|
||||
uint64_t now = from;
|
||||
for (uint64_t i = 0; i < total; i++) now += grow(i);
|
||||
return now;
|
||||
};
|
||||
|
||||
// (the RX 7900 XT's update of 11-18: base 2021349 KB (1973 MB), its limit 2467 MB under the file's bound of 4086 MB; the
|
||||
// cache at 2469 MB after 36,906 of the 91,632 stage libraries, 16,018 of 42,532 programs: 496 MB for those, nearly every
|
||||
// library a miss. Past, and over its margin at that rate)
|
||||
const uint64_t KB = 1024;
|
||||
Side rx;
|
||||
rx.base = 2021349 * KB;
|
||||
const uint64_t lim = limit(rx.base, 4086 * MB);
|
||||
CHECK(lim >> 20 == 2467);
|
||||
CHECK(over(true, 2469 * MB, rx, 4086 * MB));
|
||||
CHECK(drop_early(2469 * MB, rx.base, 16018, 42532, 36906, lim));
|
||||
CHECK(projected(2469 * MB, rx.base, 16018, 42532) >> 20 > 3250); // (some 3290 MB at that rate)
|
||||
const uint64_t T = 42532, named = 9420; // (its programs, and those a state list loaded or the notes name, first)
|
||||
const uint64_t miss = 496 * MB / 16018; // (that run's growth per program)
|
||||
const auto all = [&](uint64_t) -> uint64_t { return miss; };
|
||||
// (every program a miss: past its limit by the warm's end, and dropped once its sample is built, 1,330 programs, some
|
||||
// 2,900 libraries: about four minutes at that run's 12-15 a second, rather than after 34)
|
||||
CHECK(ends(rx.base, T, all) > lim && sampled(rx.base, T, lim, 2, all));
|
||||
// (the head alone a miss, the rest hits: it would end at some 2266 MB, under its limit, and is not dropped. A projection
|
||||
// from the head, as the warm takes it, would have dropped it at the first look past 1500 libraries, 709 programs at 120 s
|
||||
// in that run: 4.5 times its growth, and the ~70,000 libraries that hit compiled cold into the fresh cache)
|
||||
const auto head = [&](uint64_t i) -> uint64_t { return i < named ? miss : 0; };
|
||||
CHECK(ends(rx.base, T, head) <= lim && !sampled(rx.base, T, lim, 2, head));
|
||||
CHECK(drop_early(rx.base + 709 * miss, rx.base, 709, T, 1517, lim));
|
||||
// (the rest a miss, the head hits: past its limit by the end, dropped)
|
||||
const auto tail = [&](uint64_t i) -> uint64_t { return i < named ? 0 : miss; };
|
||||
CHECK(ends(rx.base, T, tail) > lim && sampled(rx.base, T, lim, 2, tail));
|
||||
// (a stretch of hits as that run had, the rest misses: 6,000 programs from 6,000, dropped. 12,000 from 6,000 ends past
|
||||
// its limit too, but its growth is under the margin: left to the look past the limit, as before the early drop)
|
||||
const auto stretch = [&](uint64_t i) -> uint64_t { return i >= 6000 && i < 12000 ? 0 : miss; };
|
||||
CHECK(ends(rx.base, T, stretch) > lim && sampled(rx.base, T, lim, 2, stretch));
|
||||
const auto longer = [&](uint64_t i) -> uint64_t { return i >= 6000 && i < 18000 ? 0 : miss; };
|
||||
CHECK(ends(rx.base, T, longer) > lim && !sampled(rx.base, T, lim, 2, longer));
|
||||
// (a mostly-hit carry: 5% of its base over the whole warm, 99 MB. Not dropped, at an even rate, nor with all of it in the
|
||||
// head)
|
||||
const uint64_t whole = rx.base / 20;
|
||||
CHECK(!sampled(rx.base, T, lim, 2, [&](uint64_t) -> uint64_t { return whole / T; }));
|
||||
CHECK(!sampled(rx.base, T, lim, 2, [&](uint64_t i) -> uint64_t { return i < named ? whole / named : 0; }));
|
||||
// (a later carry with little room: 60 MB, and 45 MB of growth all in the head. It fits, and is not dropped; from the head it
|
||||
// would have been)
|
||||
Side later;
|
||||
later.base = 2000 * MB;
|
||||
const uint64_t lim2 = limit(later.base, 0), from2 = lim2 - 60 * MB;
|
||||
const auto small = [&](uint64_t i) -> uint64_t { return i < named ? 45 * MB / named : 0; };
|
||||
CHECK(ends(from2, T, small) <= lim2 && !sampled(from2, T, lim2, 2, small));
|
||||
CHECK(drop_early(from2 + 709 * (45 * MB / named), from2, 709, T, 1517, lim2));
|
||||
// (a warm too small for its sample to hold 1500 libraries: only past its limit)
|
||||
CHECK(!sampled(rx.base, 20000, lim, 2, all));
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def between(text, start, end):
|
||||
a = text.index(start)
|
||||
return text[a:text.index(end, a)]
|
||||
|
||||
|
||||
def need(where, text, parts):
|
||||
for p in parts:
|
||||
if p not in text:
|
||||
raise SystemExit(f"{where}: missing {p!r}")
|
||||
|
||||
|
||||
def in_order(where, text, parts):
|
||||
at = -1
|
||||
for p in parts:
|
||||
i = text.find(p, at + 1)
|
||||
if i < 0:
|
||||
raise SystemExit(f"{where}: {p!r} missing or out of order")
|
||||
at = i
|
||||
|
||||
|
||||
def check_source():
|
||||
draw = (ROOT / "gpu/vk/vk_draw.cpp").read_text(encoding="utf-8")
|
||||
init = between(draw, "void pcache_init() {", "\n}\n")
|
||||
# (decided before the bounded read, by the header's rule, at Setup's preparation only, with the switch)
|
||||
in_order("vk_draw.cpp pcache_init", init, [
|
||||
'fopen((pcache_path + ".base").c_str(), "rb")',
|
||||
"pcache_bound_bytes = pcache_bound::bytes(",
|
||||
# (a carried save cut before its .for: that session's history, pcache_carry::begun)
|
||||
"pcache_carry::begun(side_read, side_had, pcache_for, for_read ? had_for : nullptr);",
|
||||
"history = begun ? side_had",
|
||||
"pcache_carry::history(",
|
||||
"pcache_carried = !pcache_same && !begun && pcache_carry::may_carry(pcache_carry::on(getenv(\"RX_VK_PCACHE_CARRY\"))",
|
||||
'getenv("HOOKSHOT_PREPARE_ONLY") != nullptr',
|
||||
"pcache_bound::within((uint64_t)sz, pcache_bound_bytes)",
|
||||
# (these shaders' file whose carried preparation was stopped: carried still, capped; refused by .nocarry, not read)
|
||||
"pcache_carry::resumed(pcache_carry::on(getenv(\"RX_VK_PCACHE_CARRY\")), getenv(\"HOOKSHOT_PREPARE_ONLY\") != nullptr,",
|
||||
"pcache_same || begun, history);",
|
||||
"if (resumed && !carry_refused) pcache_carried = true;",
|
||||
# ((Triforce) v0.5.2's carry by the file's size and the RAM (pcache_bound.h carried), outside Setup's preparation;
|
||||
# (11-19) not over .nocarry (a file warm_libraries dropped) nor for a carried save cut short
|
||||
"carried = pcache_carry::plain_carry(getenv(\"HOOKSHOT_PREPARE_ONLY\") != nullptr, pcache_carried, resumed, carry_refused, begun) &&",
|
||||
"pcache_bound::carried(pcache_same,",
|
||||
"if (resumed && carry_refused) {",
|
||||
"} else if (!pcache_same && !pcache_carried && !carried) {",
|
||||
"pcache_bound::read(pcache_path.c_str(), 32, pcache_bound_bytes, data, &len)",
|
||||
# (the device's header is checked on a carried file as on any: another device's or driver's data is dropped)
|
||||
"dev.props.pipelineCacheUUID",
|
||||
"data.clear();",
|
||||
"vkCreatePipelineCache(dev.device, &ci, nullptr, &pcache)",
|
||||
"if (!with_data) pcache_carried = false;",
|
||||
"pcache_carried && !resumed ? Start::Carried : Start::Same;",
|
||||
"pcache_side = pcache_carry::session(how, history);",
|
||||
"if (with_data && carried) pcache_side.carried++;",
|
||||
'logf("vk: pipeline cache carried over a stamp change (%zu MB, base %llu MB)',
|
||||
"pcache_play_open(pcache_same);",
|
||||
])
|
||||
# (the play file keeps its own rule: for one stamp)
|
||||
if "pcache_play_open(pcache_same || pcache_carried)" in init:
|
||||
raise SystemExit("the play file is carried too")
|
||||
need("vk_draw.cpp pcache_init", init, ['fopen((pcache_path + ".nocarry").c_str(), "rb")',
|
||||
'getenv("HOOKSHOT_PREPARE_ONLY") != nullptr, carry_refused,',
|
||||
# (a carried file's first save writes it, with the new stamp, even with nothing added)
|
||||
"pcache_saved_size = pcache_carried ? 0 : held;"])
|
||||
save = between(draw, "void pipeline_cache_save(bool force) {", "\n}\n")
|
||||
# (the carry's limit before the bound's own refusal: over the bound a carried cache asks for the rebuild, not the old file)
|
||||
in_order("vk_draw.cpp pipeline_cache_save", save, [
|
||||
"if (!pcache_carry_save_ok(n)) return;",
|
||||
"if (!pcache_bound::within(n, pcache_bound_bytes)) {",
|
||||
"std::vector<uint8_t> data(n);",
|
||||
"if (ok && !keep_old) ok = pcache_carry_saving(n, want);",
|
||||
"MoveFileExA(tmp.c_str(), pcache_path.c_str(),",
|
||||
"if (!keep_old) {",
|
||||
'file_writers::write_whole(pcache_path + ".for", want, 16);',
|
||||
"pcache_carry_saved(n, want);",
|
||||
])
|
||||
past = between(draw, "bool pcache_carry_past(size_t n) {", "\n}\n")
|
||||
in_order("vk_draw.cpp pcache_carry_past", past, [
|
||||
"pcache_carry::over(pcache_carried, n, pcache_side, pcache_bound_bytes)",
|
||||
"pcache_carry_over.exchange(true)",
|
||||
"pcache_carry_refused();",
|
||||
])
|
||||
refused = between(draw, "void pcache_carry_refused() {", "\n}\n")
|
||||
need("vk_draw.cpp pcache_carry_refused", refused, ["program_cache_stamp()",
|
||||
'file_writers::write_whole(pcache_path + ".nocarry", stamp, 16)'])
|
||||
# (and a cache dropped early, under its limit, is not written either)
|
||||
need("vk_draw.cpp pcache_carry_save_ok", draw, [
|
||||
"bool pcache_carry_save_ok(size_t n) { return !pcache_carry_over.load() && !pcache_carry_past(n); }"])
|
||||
# (the early drop: a carried cache only, its limit, not on Intel while workers build, the rule of the header, then as past it)
|
||||
early = between(draw, "bool pcache_carry_early(size_t from, size_t done, size_t total, size_t libs) {", "\n}\n")
|
||||
in_order("vk_draw.cpp pcache_carry_early", early, [
|
||||
'pcache_carry::project_on(getenv("RX_VK_PCACHE_CARRY_PROJECT"))',
|
||||
"if (!pcache_carried) return false;",
|
||||
"lim = pcache_carry::limit(pcache_side.base, pcache_bound_bytes);",
|
||||
"if (dev.props.vendorID == 0x8086) return false;",
|
||||
"vkGetPipelineCacheData(dev.device, use.cache, &n, nullptr)",
|
||||
"if (n > lim || !pcache_carry::drop_early(n, from, done, total, libs, lim)) return false;",
|
||||
"if (pcache_carry_over.exchange(true)) return true;",
|
||||
'logf("vk: the pipeline cache carried over a stamp change would grow to about %llu MB at this rate',
|
||||
"RX_VK_PCACHE_CARRY_PROJECT=0: only when it is past",
|
||||
"pcache_carry_refused();",
|
||||
"return true;",
|
||||
])
|
||||
held = between(draw, "bool pcache_carry_held(size_t* n) {", "\n}\n")
|
||||
# (and so the warm's own order unless the projection is made: switched off, not carried, Intel)
|
||||
in_order("vk_draw.cpp pcache_carry_held", held, ["*n = 0;",
|
||||
'pcache_carry::project_on(getenv("RX_VK_PCACHE_CARRY_PROJECT"))',
|
||||
"if (!pcache_carried) return false;",
|
||||
"if (dev.props.vendorID == 0x8086) return false;",
|
||||
"vkGetPipelineCacheData(dev.device, use.cache, n, nullptr) == VK_SUCCESS"])
|
||||
side = between(draw, "void pcache_carry_saved(size_t n, const char* stamp) {", "\n}\n")
|
||||
need("vk_draw.cpp pcache_carry_saved", side, ["pcache_carry::saved(pcache_side, n, stamp)",
|
||||
'file_writers::write_whole(pcache_path + ".base", out, sizeof out)'])
|
||||
# (the libraries' pass: nothing into a carried cache past what it may hold; looked at while it builds; and the carry's
|
||||
# look before the bound's branch, which would count the part as done with the old file on the disk)
|
||||
warm = between(draw, "bool warm_libraries(void (*progress)(size_t done, size_t total)) {", "\n}\n")
|
||||
in_order("vk_draw.cpp warm_libraries", warm, [
|
||||
"pcache_init();",
|
||||
"if (pcache_carry_check(false)) {",
|
||||
"return false;",
|
||||
# (the early drop: the carried cache's size before the workers begin; its sample, every 32nd of the order, built first
|
||||
# and the others waiting for its projection, so that the growth is the sample's alone; the projection once the sample is
|
||||
# done, before the look past its limit)
|
||||
"const bool carry_projected = pcache_carry_held(&carry_from);",
|
||||
"const size_t carry_sample = carry_projected ? (size_t)pcache_carry::sample_count(total) : 0;",
|
||||
"std::atomic<bool> carry_sampled{!carry_projected};",
|
||||
"if (prepare_stopped() || pcache_carry_over.load(std::memory_order_relaxed)) return;",
|
||||
"const size_t claim = next++;",
|
||||
"if (claim >= total) return;",
|
||||
"const size_t i = carry_projected ? (size_t)pcache_carry::sample_order(claim, total) : claim;",
|
||||
"if (claim >= carry_sample && !carry_sampled.load()) {",
|
||||
"while (!carry_sampled.load() && !prepare_stopped() && !pcache_carry_over.load(std::memory_order_relaxed))",
|
||||
"if (prepare_stopped() || pcache_carry_over.load(std::memory_order_relaxed)) return;",
|
||||
"if (i < loaded.size()) warm(*loaded[i], slot);",
|
||||
"program_cache_borrow(keys[i - loaded.size()]",
|
||||
"threads.emplace_back(worker, (int)i);",
|
||||
"while (done.load() < total && !prepare_stopped() && !pcache_carry_over.load()) {",
|
||||
"if (!carry_sampled.load() && done.load() >= carry_sample) {",
|
||||
"pcache_carry_early(carry_from, done.load(), total, libs.load());",
|
||||
"carry_sampled = true;",
|
||||
"std::chrono::milliseconds(pcache_carry::kCheckMs)",
|
||||
"pcache_carry_check(true);",
|
||||
"for (std::thread& t : threads) t.join();",
|
||||
"if (prepare_stopped()) {",
|
||||
"if (pcache_carry_check(false)) {",
|
||||
"return false;",
|
||||
"if (gpl_libs_cached()) {",
|
||||
"!pcache_bound::within(held, pcache_bound_bytes)",
|
||||
"warm_unsaved = true;",
|
||||
"const bool saved = pcache_saved_now();",
|
||||
])
|
||||
run = between(draw, "bool prepare_run(void (*progress)(size_t done, size_t total), bool background) {", "\n}\n")
|
||||
# (the run into the fresh cache: the compute pipelines first, from the program cache, then the driver's part of the
|
||||
# translated shaders, nothing translated again; the carried run's warm names its compute programs, builds nothing into a
|
||||
# cache past what it may hold, and is looked at while it builds and once its workers are joined)
|
||||
in_order("vk_draw.cpp prepare_run", run, [
|
||||
"const PrepareWhy why = prepare_check(",
|
||||
"if (!background && prepare_cs_again.exchange(false) && !warm_kept_computes(progress)) return false;",
|
||||
"if (why == PrepareWhy::None && !getenv(\"RX_VK_PREPARE_AGAIN\")) {",
|
||||
# (recorded as made, a carried cache found warm is written with the new stamp: no record says made over the old file)
|
||||
"lib_check_cold(path, warmed);",
|
||||
"if (!cold && !background && pcache_carried && prepared_for.warmed == warmed) pcache_saved_now();",
|
||||
"if (!cold && (prepared_for.warmed == warmed || background)) return false;",
|
||||
"if (cold && !prepare_stopped() && !warm_reset && !pcache_carry_over.load()) lib_check_made(path, warmed, false);",
|
||||
"const auto warm_compute = [&](Program& p) {",
|
||||
"prepare_cs_keys.insert(p.key);",
|
||||
"if (pcache_carry_over.load(std::memory_order_relaxed)) return;",
|
||||
"if (prepare_compute_pipeline(p)) libs++;",
|
||||
"pcache_carry_check(true);",
|
||||
"for (std::thread& t : threads) t.join();",
|
||||
"if (!background) pcache_carry_check(false);",
|
||||
"prepared_for.warmed = 0;",
|
||||
"prepared_write(path, prepared_for);",
|
||||
"if (!warm_libraries(progress)) {",
|
||||
"return false;",
|
||||
])
|
||||
kept = between(draw, "bool warm_kept_computes(void (*progress)(size_t done, size_t total)) {", "\n}\n")
|
||||
in_order("vk_draw.cpp warm_kept_computes", kept, [
|
||||
"keys.assign(prepare_cs_keys.begin(), prepare_cs_keys.end());",
|
||||
"program_cache_borrow(keys[i], [&](Program& p) {",
|
||||
"p.compute",
|
||||
"prepare_compute_pipeline(p)",
|
||||
])
|
||||
if "seed_compute" in kept or "seed_program" in kept or "translate" in kept.replace("nothing translated", ""):
|
||||
raise SystemExit("warm_kept_computes translates again")
|
||||
build = between(draw, "bool prepare_compute_pipeline(Program& p) {", "\n}\n")
|
||||
need("vk_draw.cpp prepare_compute_pipeline", build, ["pin_subgroup(ci.stage, p.workgroup[0]);",
|
||||
"guarded_compute(pcache, &ci, &pl)",
|
||||
'if (getenv("RX_VK_NOOPT")) ci.flags |= VK_PIPELINE_CREATE_DISABLE_OPTIMIZATION_BIT;'])
|
||||
rebuild = between(draw, "bool pcache_carry_rebuild() {", "\n}\n")
|
||||
in_order("vk_draw.cpp pcache_carry_rebuild", rebuild, [
|
||||
"if (!pcache_carry_over.load() || !pcache || pcache_door.closed() || prepare_stopped()) return false;",
|
||||
"vkCreatePipelineCache(dev.device, &ci, nullptr, &fresh)", # (a fresh one first: never left without a cache)
|
||||
"while (pcache_door.inside()) Sleep(1);",
|
||||
"pcache = fresh;",
|
||||
"vkDestroyPipelineCache(dev.device, merged, nullptr);",
|
||||
"pcache_saved_size = 0;",
|
||||
"pcache_carried = false;",
|
||||
"pcache_carry::session(pcache_carry::Start::Fresh, pcache_side)",
|
||||
"pcache_carry_over = false;",
|
||||
"prepare_cs_again = !prepare_cs_keys.empty();",
|
||||
# (the stamp kept: the next run goes to the driver's part alone, and translates nothing again)
|
||||
"had.warmed = 0;",
|
||||
"prepared_write(path, had);",
|
||||
"return true;",
|
||||
])
|
||||
if "had.stamp = 0" in rebuild:
|
||||
raise SystemExit("the rebuild sends the next run down the whole path (translation again, no compute pipelines)")
|
||||
main = (ROOT / "gpu/vk/vk_main.cpp").read_text(encoding="utf-8")
|
||||
prep = between(main, "if (prepare_only()) {", "return true;")
|
||||
in_order("vk_main.cpp the preparation", prep, [
|
||||
"bool prepared = prepare_run(progress, false);",
|
||||
"if (pcache_carry_rebuild()) {",
|
||||
"fflush(stdout);",
|
||||
"prepared = prepare_run(progress, false);",
|
||||
"if (prepared && !prepare_stopped()) predict_run(progress);",
|
||||
"precompile_run(progress);",
|
||||
"pipeline_cache_save(true);",
|
||||
])
|
||||
# (the carried history is no longer open only once the preparation went through to its end and saved: not after a stop)
|
||||
end = main[main.index("if (prepare_only()) {"):]
|
||||
end = end[:end.index("remove(skipped_path().c_str());")]
|
||||
in_order("vk_main.cpp the preparation's end", end, ["pipeline_cache_save(true);", "if (prepare_stopped()) {", "return true;",
|
||||
"pcache_carry_done();"])
|
||||
done = between(draw, "void pcache_carry_close() {", "\n}\n")
|
||||
in_order("vk_draw.cpp pcache_carry_close", done, [
|
||||
"if (pcache_carry_over.load()) return;",
|
||||
"if (!pcache_carried || !pcache_side.open) return;",
|
||||
"pcache_side.open = 0;",
|
||||
"if (std::memcmp(pcache_side.stamp, stamp, 16)) return;",
|
||||
'file_writers::write_whole(pcache_path + ".base", out, sizeof out);',
|
||||
])
|
||||
need("vk_draw.cpp pcache_carry_done", draw, ["void pcache_carry_done() { pcache_carry_close(); }"])
|
||||
need("vk_internal.h", (ROOT / "gpu/vk/vk_internal.h").read_text(encoding="utf-8"), ["bool pcache_carry_rebuild();",
|
||||
"void pcache_carry_done();"])
|
||||
dev_md = (ROOT / "docs/development.md").read_text(encoding="utf-8")
|
||||
if "`RX_VK_PCACHE_CARRY=0`" not in dev_md:
|
||||
raise SystemExit("RX_VK_PCACHE_CARRY is not in docs/development.md's switches")
|
||||
# (the early drop's switch, in the row after the carry's)
|
||||
if "| `RX_VK_PCACHE_CARRY_PROJECT=0` |" not in dev_md or \
|
||||
dev_md.index("| `RX_VK_PCACHE_CARRY_PROJECT=0` |") < dev_md.index("`RX_VK_PCACHE_CARRY=0`"):
|
||||
raise SystemExit("RX_VK_PCACHE_CARRY_PROJECT is not in docs/development.md's switches after RX_VK_PCACHE_CARRY")
|
||||
# (the compute pass and the precompile keep the look past the limit alone, pcache_carry.h)
|
||||
for fn in ("bool prepare_run(void (*progress)(size_t done, size_t total), bool background) {",
|
||||
"void precompile_run(void (*progress)(size_t done, size_t total)) {"):
|
||||
if "pcache_carry_early(" in between(draw, fn, "\n}\n"):
|
||||
raise SystemExit(f"vk_draw.cpp {fn.split('(')[0]}: projected on programs done that build nothing into the cache")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--cxx", default="g++")
|
||||
args = parser.parse_args()
|
||||
check_source()
|
||||
with tempfile.TemporaryDirectory(prefix="pcache-carry-") as tmp:
|
||||
tmp = Path(tmp)
|
||||
(tmp / "t.cpp").write_text(FIXTURE, encoding="utf-8")
|
||||
exe = tmp / "pcache-carry"
|
||||
subprocess.run([args.cxx, "-std=c++20", "-Wall", "-Wextra", "-Werror", "-I" + str(ROOT / "gpu/vk"), str(tmp / "t.cpp"),
|
||||
"-o", str(exe)], check=True)
|
||||
r = subprocess.run([str(exe)], capture_output=True, text=True)
|
||||
if r.returncode:
|
||||
raise SystemExit(f"pcache_carry.h: {r.stdout.strip()}")
|
||||
print("PASS: the pipeline cache is carried over a stamp change at an update's preparation up to 1.25 x its base, "
|
||||
"cumulatively, and built again into a fresh cache past it")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -98,11 +98,14 @@ def check_source():
|
||||
draw = (ROOT / "gpu/vk/vk_draw.cpp").read_text(encoding="utf-8")
|
||||
# (every creation given the cache: through the gate. Left as they were: the prepare's and warm pass's, before play and
|
||||
# joined before it begins)
|
||||
allowed_raw = ("void warm_libraries(", "bool prepare_run(")
|
||||
# ((Triforce) and prepare_compute_pipeline: prepare_run's warm, and the carry's rebuild of it (warm_kept_computes), both
|
||||
# in prepare_run before play)
|
||||
allowed_raw = ("void warm_libraries(", "bool prepare_run(", "bool prepare_compute_pipeline(")
|
||||
for m in re.finditer(r"guarded_compute\((pcache\b[^,]*),", draw):
|
||||
if m.group(1) == "pcache_use().cache":
|
||||
continue
|
||||
owner = max((draw.rfind("\n" + f, 0, m.start()), f) for f in ("bool prepare_run(", "void precompile_run(",
|
||||
"bool prepare_compute_pipeline(",
|
||||
"void warm_libraries(", "bool fallback_compute_pipelines(",
|
||||
"VkPipeline clear_pipeline(", "void dispatch("))
|
||||
if owner[1] not in allowed_raw:
|
||||
@@ -114,7 +117,7 @@ def check_source():
|
||||
if "vkCreateGraphicsPipelines(dev.device, pcache," in draw or "vkCreateComputePipelines(dev.device, pcache," in draw:
|
||||
raise SystemExit("a pipeline is made with the cache past its gate")
|
||||
pre = between(draw, "void precompile_run(", "\n}\n")
|
||||
if "guarded_compute(pcache_use().cache, &ci, &made)" not in pre:
|
||||
if "cached_compute(pcache_use().cache, &ci, &made)" not in pre:
|
||||
raise SystemExit("the precompile's computes, which may run on after the game starts, do not take the gate")
|
||||
build = between(draw, "VkPrimitiveTopology topo, int part, bool* cold) {", "\n}\n")
|
||||
# ((Triforce) cached_graphics: the guard's creation through the play cache, tests/test_pcache_play.py)
|
||||
|
||||
@@ -121,13 +121,16 @@ SAVE = r"""
|
||||
#ifdef _WIN32
|
||||
#include <windows.h>
|
||||
#else
|
||||
constexpr unsigned MOVEFILE_REPLACE_EXISTING = 1;
|
||||
constexpr unsigned MOVEFILE_REPLACE_EXISTING = 1, MOVEFILE_WRITE_THROUGH = 8;
|
||||
int MoveFileExA(const char* from, const char* to, unsigned) { std::remove(to); return std::rename(from, to) == 0; }
|
||||
#endif
|
||||
#include "file_whole.h" // ((Triforce, handoff §8) the .for files whole)
|
||||
#include "warm_checkpoint.h" // ((Triforce) a checkpoint's fetch with room: not here, pcache_checkpoint_now unset)
|
||||
using VkResult = int;
|
||||
using VkPipelineCache = int;
|
||||
constexpr VkResult VK_SUCCESS = 0;
|
||||
constexpr VkResult VK_SUCCESS = 0, VK_INCOMPLETE = 5;
|
||||
thread_local bool pcache_checkpoint_now = false;
|
||||
bool pcache_file_flush(FILE* f) { return std::fflush(f) == 0; }
|
||||
struct { int device = 1; } dev;
|
||||
VkPipelineCache pcache_play_cache = 0;
|
||||
std::string pcache_play_path;
|
||||
|
||||
@@ -75,28 +75,34 @@ def check_source():
|
||||
check('const char* tx_perf(int v) { return v == 1 ? "On" : v >= 2 ? "Full" : "Off"; }' in menu, "the row's values are not Off, On, Full")
|
||||
check("show_fps" not in block(menu, "const char* ini_key(const Row& r) {"), "the row's key is no longer its name's")
|
||||
check(re.search(r"\n int show_fps = 0;", menu_h) is not None, "the overlay is not off by default")
|
||||
# ((Triforce) 11-17, the tabs in sections: the last row of the Display tab's Frame rate, before High dynamic range)
|
||||
check(menu.index('{TAB_DISPLAY, "VSync"') < menu.index('{TAB_DISPLAY, "FPS counter"') < menu.index('{TAB_DISPLAY, "High dynamic range"'),
|
||||
"the row is not where it was")
|
||||
# ((Triforce, options_version 7) the Display tab's Overlay group, after RenoDX's rows)
|
||||
check(menu.index('MENU_HEADING(TAB_DISPLAY, "Overlay")') < menu.index('{TAB_DISPLAY, "FPS counter"') <
|
||||
menu.index('MENU_HEADING(TAB_GRAPHICS, "Upscaling")'), "the row is not in the Display tab's Overlay group")
|
||||
# (the counter itself for 1 and for 2: menu_record's `fps` is the row not 0; the FPS-only mode as it was)
|
||||
# (Full is NX2navi's panel alone, in the counter's place (its perf_draw: mode 2 draws perf_full_draw and returns), and under
|
||||
# an open menu (its BringWindowToDisplayBack): draw_menu draws it over its dim, before its pages; the game tab's header over
|
||||
# it. tests/test_fps_overlay_order.py runs menu_record for the order)
|
||||
# it; (Triforce, 11-19) over the Mods entry's Quit dialog and its dim instead. tests/test_fps_overlay_order.py runs
|
||||
# menu_record for the order)
|
||||
for name in ("void menu_record(VkCommandBuffer cmd, uint32_t index, uint32_t w, uint32_t h) {",
|
||||
"void menu_record_image(VkCommandBuffer cmd, VkImage image, VkImageView view, uint32_t w, uint32_t h) {"):
|
||||
record = block(menu, name)
|
||||
check("const bool fps = opts.show_fps && !start;" in record or "const bool fps = opts.show_fps && !startup_on.load(std::memory_order_acquire);" in record,
|
||||
"the counter's and the panel's switch is not the row")
|
||||
check("const bool full = fps && opts.show_fps == 2;" in record and "if (open) draw_menu(c, full);" in record and
|
||||
"if (full) draw_perf(c);" in record and "if (fps && !full) draw_fps(c, open || game_tab);" in record,
|
||||
check("const bool full = fps && opts.show_fps == 2;" in record and "if (open) draw_menu(c, full && !over_row);" in record and
|
||||
"if (full) draw_perf(c);" in record and "if (full && over_row) draw_perf(c);" in record and
|
||||
"if (fps && !full) draw_fps(c, (open && page != kModsRowPage) || game_tab);" in record,
|
||||
"Full does not draw the panel alone, under the menu (%s)" % name[:24])
|
||||
check(record.index("if (full) draw_perf(c);") < record.index("if (game_tab) draw_game_tab(c);"), "the game tab's header is not over the panel")
|
||||
check(record.count("draw_perf(") == 1, "the panel is drawn twice")
|
||||
check(record.count("draw_perf(") == 2, "the panel is drawn more than under the menu and over the Mods entry's dialog")
|
||||
record = block(menu, "void menu_record(VkCommandBuffer cmd, uint32_t index, uint32_t w, uint32_t h) {")
|
||||
check(record.index("bugshot_record(") < record.index("ui::begin("), "a bug capture's picture is taken after the overlays could be drawn")
|
||||
dm = block(menu, "void draw_menu(ui::Ctx& c, bool perf_under) {")
|
||||
check(dm.index("ui::kDimAlpha));") < dm.index("if (perf_under) draw_perf(c);") < dm.index("const int vtx0 = c.d->VtxBuffer.Size"),
|
||||
"the panel is not over the menu's dim and under its pages (nor kept out of the column's move)")
|
||||
# ((Triforce, 11-19) the panel waits (panel_wait) in the list split in two and is drawn between the pages and the header
|
||||
# (panel_between), so that a dialog's dim can go under it; its vertices are kept out of the column's move (put_on_grid))
|
||||
check(dm.index("ui::kDimAlpha));") < dm.index("const int vtx0 = c.d->VtxBuffer.Size") <
|
||||
dm.index("panel_wait = {&c, window_clip, 0, 0};") < dm.index("panel_between(c.d);") and
|
||||
"put_on_grid(c.d, vtx0, cmd0, menu_map, window_clip, perf0, perf1);" in dm,
|
||||
"the panel is not over the menu's dim and under its pages' header (nor kept out of the column's move)")
|
||||
check("void draw_menu(ui::Ctx& c, bool perf_under = false);" in menu, "draw_menu's other callers ask for the panel")
|
||||
check("fps_drawn" not in menu, "the panel still moves for the counter, which Full does not draw")
|
||||
|
||||
@@ -264,7 +270,7 @@ def check_source():
|
||||
"label(kPerfSetting[i])", "if (names) {", "divider();", "v.gpu_name), y += px + item;", "v.cpu_name);"],
|
||||
"the panel's parts are not in NX2navi's order")
|
||||
# (every text through the edge: none drawn bare; the edge the FPS counter's own)
|
||||
check(draw.count("AddText(") == 0 and "edged_text(c, f, px, ImVec2(x, ui::mid_top(f, px, y)), col, t);" in block(menu, "void draw_fps(ui::Ctx& c, bool under_banner) {"),
|
||||
check(draw.count("AddText(") == 0 and "edged_text(c, f, px, ImVec2(x, ui::mid_top(f, px, y)), col, t);" in block(menu, "void draw_fps(ui::Ctx& window, bool under_banner) {"),
|
||||
"the panel's texts, or the counter's, are not drawn with the one edge")
|
||||
edge = block(menu, "void edged_text(ui::Ctx& c, ImFont* f, float px, ImVec2 p, ImU32 col, const char* t) {")
|
||||
check("const float e = std::max(1.0f, px * 0.05f);" in edge and "ui::rgba(20, 14, 6, 150)" in edge, "the edge is not the HUD's thin soft one")
|
||||
@@ -284,7 +290,7 @@ def check_source():
|
||||
"the panel's text size is not baked at once when it changes")
|
||||
check("ImFont* font = c.f.body ? c.f.body : c.f.strong; // (draw_perf's)" in block(menu, "void bake_perf(const ui::Ctx& c, float px) {") and
|
||||
"ImFont* font = c.f.body ? c.f.body : c.f.strong;" in draw, "the panel's glyphs are baked in another font than draw_perf's")
|
||||
check(record.index("prebake(c);") < record.index("if (open) draw_menu(c, full);"), "the bake is not before the drawing")
|
||||
check(record.index("prebake(c);") < record.index("if (open) draw_menu(c, full && !over_row);"), "the bake is not before the drawing")
|
||||
check("if (r == kPerfFG && !v.fg) continue;" in draw, "the FG row shows without frame generation")
|
||||
check("if (v.setting[i][0]) label(kPerfSetting[i])" in draw, "a setting without a value is not left out")
|
||||
# (no panel of its own making: the options' plate, separator and font; the game's art read at run time from the player's
|
||||
@@ -305,7 +311,7 @@ def check_source():
|
||||
box = block(ui_h, "inline void box(Ctx& c, ImVec2 a, ImVec2 b, float opacity = 1) {")
|
||||
check("nine(c, t, a - ImVec2(m, m), b + ImVec2(m, m), 133, 133, alpha(IM_COL32_WHITE, opacity));" in box and
|
||||
"c.d->AddRectFilled(a, b, alpha(kBox, opacity));" in box, "the caption plate is not drawn at the opacity asked for")
|
||||
sep = block(ui_h, "inline void separator(Ctx& c, float x0, float x1, float y, ImU32 col = rgba(104, 80, 46), ImU32 line_col = 0) {")
|
||||
sep = block(ui_h, "inline void separator(Ctx& c, float x0, float x1, float y, ImU32 col = kSeparator, ImU32 line_col = 0) {")
|
||||
check("if (!line_col) line_col = col;" in sep and sep.count("line_col") >= 6, "the separator's lines do not take their tint")
|
||||
for t in ("alpha(label_col", "alpha(value_col", "alpha(ui::kInk", "alpha(ui::kAccent"):
|
||||
check(t not in draw, "the panel's text is see-through too")
|
||||
|
||||
@@ -32,6 +32,34 @@ def save_function(path):
|
||||
return source[start:end]
|
||||
|
||||
|
||||
def checkpoint_function(path):
|
||||
"""(Triforce) vk_draw.cpp's pcache_checkpoint_save, as it is (gpu/vk/warm_checkpoint.h): the preparation's checkpoint save
|
||||
through pipeline_cache_save, always the source under test's own"""
|
||||
source = path.read_text(encoding='utf-8')
|
||||
marker = 'size_t pcache_checkpoint_save() {'
|
||||
if source.count(marker) != 1:
|
||||
raise AssertionError('expected exactly one checkpoint save function')
|
||||
start = source.index(marker)
|
||||
end = source.index('{', start) + 1
|
||||
depth = 1
|
||||
while depth:
|
||||
depth += (source[end] == '{') - (source[end] == '}')
|
||||
end += 1
|
||||
return source[start:end]
|
||||
|
||||
|
||||
def carry_part(path):
|
||||
"""(Triforce) vk_draw.cpp's carry part (pcache_carry_past, pcache_carry_save_ok, pcache_carry_check, pcache_carry_held,
|
||||
pcache_carry_early, pcache_carry_saved),
|
||||
as it is: always the source under test's own, also for the optional original's save function"""
|
||||
source = path.read_text(encoding='utf-8')
|
||||
start_mark = "// ---- (Triforce) The carry's state and its rules in use"
|
||||
end_mark = "// ---- (Triforce) The carry's part ends ----"
|
||||
if source.count(start_mark) != 1 or source.count(end_mark) != 1:
|
||||
raise AssertionError('expected exactly one carry part')
|
||||
return source[source.index(start_mark):source.index(end_mark)]
|
||||
|
||||
|
||||
class PipelineCacheSaveTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
@@ -48,6 +76,9 @@ class PipelineCacheSaveTests(unittest.TestCase):
|
||||
directory = cls.directory / name
|
||||
directory.mkdir()
|
||||
(directory / 'pipeline_cache_save.inc').write_text(save_function(source), encoding='utf-8')
|
||||
(directory / 'pcache_carry_part.inc').write_text(carry_part(ROOT / 'gpu/vk/vk_draw.cpp'), encoding='utf-8')
|
||||
(directory / 'pcache_checkpoint_save.inc').write_text(checkpoint_function(ROOT / 'gpu/vk/vk_draw.cpp'),
|
||||
encoding='utf-8')
|
||||
executable = directory / 'check.exe'
|
||||
command = [compiler, '-std=c++20', '-O1', '-Wall', '-Wextra', '-Werror', '-pthread',
|
||||
'-I' + str(directory), '-I' + str(ROOT / 'gpu/vk'), str(ROOT / 'tests/pipeline_cache_save_test.cpp'),
|
||||
@@ -112,6 +143,51 @@ class PipelineCacheSaveTests(unittest.TestCase):
|
||||
# gpu/vk/pcache_bound.h: the file keeps its last save, which the next start reads.
|
||||
self.check_case('over-bound')
|
||||
|
||||
def test_carried_cache_is_not_written_past_its_cap(self):
|
||||
# (Triforce) gpu/vk/pcache_carry.h: carried over a stamp change, up to 1.25 x its base; a fresh cache after.
|
||||
self.check_case('carry-cap')
|
||||
|
||||
def test_carried_cache_over_the_bound_is_past_what_it_may_hold(self):
|
||||
# (Triforce) Over the bound and under the cap: a rebuild is asked, not the bound's silent refusal with the old file.
|
||||
self.check_case('carry-bound')
|
||||
|
||||
def test_carried_history_is_open_until_the_preparation_is_done(self):
|
||||
# (Triforce) pcache_carry.h Side::open: a stopped carried preparation's save stays capped when begun again.
|
||||
self.check_case('carry-done')
|
||||
|
||||
def test_checkpoint_keeps_a_carried_preparation_capped(self):
|
||||
# (Triforce) gpu/vk/warm_checkpoint.h: a checkpoint mid-warm in a carried session saves under the new stamp with its
|
||||
# history open, as a stopped one's save, so the start after a crash there is carried still and capped; the RAM, the
|
||||
# cap and nothing new each leave the file as it was.
|
||||
self.check_case('checkpoint')
|
||||
|
||||
def test_checkpoint_fetches_a_growing_cache_with_room(self):
|
||||
# (Triforce) gpu/vk/warm_checkpoint.h: the workers build while a checkpoint fetches; fetched with room, the cap and the
|
||||
# bound looked at again on what was fetched, asked again past the room, flushed and put in place written through.
|
||||
self.check_case('checkpoint-grow')
|
||||
|
||||
def test_checkpoint_gives_up_on_a_stop_and_a_short_disk(self):
|
||||
# (Triforce) a stop asked before the fetch or in the write, the disk short of room: nothing written, no .tmp left.
|
||||
self.check_case('checkpoint-stop')
|
||||
|
||||
def test_carried_history_is_written_before_the_data(self):
|
||||
# (Triforce) gpu/vk/pcache_carry.h begun: a carried save cut before its .for is read as that session's, capped.
|
||||
self.check_case('carry-begun')
|
||||
|
||||
def test_own_marker_names_a_file_of_the_part_alone(self):
|
||||
# (Triforce) <file>.own: a checkpoint's file before a crash is not taken for an older build's (warm_libraries).
|
||||
self.check_case('own')
|
||||
|
||||
def test_carried_cache_size_is_looked_at_while_preparing(self):
|
||||
# (Triforce) pcache_carry_check: only a carried cache is asked; not on Intel while workers build; once past, it stays.
|
||||
self.check_case('carry-check')
|
||||
|
||||
def test_carried_cache_is_dropped_early_on_its_projection(self):
|
||||
# (Triforce) pcache_carry_early: a carried cache that would grow past what it may hold by the margin is dropped as past
|
||||
# it once its sample is built, and not saved; a sample too small, under the margin, past it already, on Intel or
|
||||
# switched off it is not (and on Intel or switched off no sample is taken: the warm keeps its own order).
|
||||
self.check_case('carry-early')
|
||||
|
||||
def test_save_in_play_waits_while_the_copy_does_not_fit_in_ram(self):
|
||||
# (Triforce) gpu/vk/mem_parts.h copy_fits: the whole cache fetched in play is what Windows pages out with the RAM
|
||||
# short; the save waits for the next check, and the one at the game's close does not ask.
|
||||
|
||||
@@ -83,7 +83,11 @@ def main():
|
||||
# ci/made identities are checked at the boundary as well as inside the API spy.
|
||||
armed=arm.replace('VkPipeline made = VK_NULL_HANDLE;', 'VkPipeline made = VK_NULL_HANDLE; expected_ci=&ci; expected_out=&made;')
|
||||
assert armed != arm
|
||||
cpp=HEAD+wrapper+'\nvoid actual_arm(Program&program,Pre*pre){std::vector<Program*>computes{&program};size_t i=0;'+armed+'\ncompleted=true;}\n'+r'''
|
||||
# (the arm creates through cached_compute and the cache's gate; with no play cache cached_create is the guarded creation
|
||||
# itself (tests/test_pcache_play.py runs its routes), so both are modeled as that)
|
||||
shims='\nstruct PcacheUseFx{VkPipelineCache cache;};PcacheUseFx pcache_use(){return {pcache};}\n' \
|
||||
'VkResult cached_compute(VkPipelineCache c,const VkComputePipelineCreateInfo*ci,VkPipeline*pl){return guarded_compute(c,ci,pl);}\n'
|
||||
cpp=HEAD+wrapper+shims+'\nvoid actual_arm(Program&program,Pre*pre){std::vector<Program*>computes{&program};size_t i=0;'+armed+'\ncompleted=true;}\n'+r'''
|
||||
int main(int argc,char**argv){
|
||||
SetErrorMode(SEM_FAILCRITICALERRORS|SEM_NOGPFAULTERRORBOX|SEM_NOOPENFILEERRORBOX);
|
||||
CHECK(argc==2);int which=std::atoi(argv[1]);Program program;Pre pre;
|
||||
|
||||
@@ -64,15 +64,73 @@ class PrepareShadersTests(unittest.TestCase):
|
||||
self.assertIn("exit status 5", not_prepared(lines)[0])
|
||||
|
||||
def test_a_silent_hang_is_stopped_and_not_a_failed_build(self):
|
||||
# (prints its stage, then nothing: as a driver deadlock or a crash dialog left open. silence is 15 minutes in a build)
|
||||
# (prints its stage, then nothing: as a driver deadlock or a crash dialog left open. silence is 15 minutes in a build;
|
||||
# a hang does not answer the stop request either, and is killed stop_wait seconds after it)
|
||||
started = time.monotonic()
|
||||
code, lines = prepared(stub("import time; print('@@stage shaders Preparing shaders', flush=True); time.sleep(120)"),
|
||||
silence=1)
|
||||
with tempfile.TemporaryDirectory(prefix="hookshot-prepare-") as folder:
|
||||
stop = os.path.join(folder, make_game.PREPARE_STOP)
|
||||
code, lines = prepared(stub("import time; print('@@stage shaders Preparing shaders', flush=True); time.sleep(120)"),
|
||||
silence=1, stop=stop, stop_wait=1)
|
||||
self.assertFalse(os.path.exists(stop)) # (the request written for it is not left behind)
|
||||
self.assertLess(time.monotonic() - started, 30)
|
||||
self.assertIsNone(code)
|
||||
self.assertEqual(lines[0], "@@stage shaders Preparing shaders")
|
||||
self.assertIn("printed nothing for 1 seconds and was stopped", not_prepared(lines)[0])
|
||||
|
||||
def test_a_silent_run_is_asked_to_stop_before_it_is_killed(self):
|
||||
# ((Triforce, 11-18) the game answers triforce_prepare.stop as a closed window: it ends its driver's part cleanly. Here a
|
||||
# stand-in that waits for the request, then says it ended by itself, in a file a kill would never write)
|
||||
with tempfile.TemporaryDirectory(prefix="hookshot-prepare-") as folder:
|
||||
stop, ended = os.path.join(folder, make_game.PREPARE_STOP), os.path.join(folder, "ended")
|
||||
code = ("import os, time\nprint('@@stage shaders Preparing shaders', flush=True)\n"
|
||||
"while not os.path.exists(%r): time.sleep(0.05)\nopen(%r, 'w').close()" % (stop, ended))
|
||||
started = time.monotonic()
|
||||
code, lines = prepared(stub(code), silence=1, stop=stop, stop_wait=60)
|
||||
self.assertLess(time.monotonic() - started, 30)
|
||||
self.assertTrue(os.path.exists(ended), "the run was killed, not asked to stop")
|
||||
self.assertFalse(os.path.exists(stop))
|
||||
self.assertIsNone(code)
|
||||
self.assertEqual(len(not_prepared(lines)), 1)
|
||||
|
||||
def test_a_stale_stop_request_is_removed_before_the_run(self):
|
||||
with tempfile.TemporaryDirectory(prefix="hookshot-prepare-") as folder:
|
||||
stop = os.path.join(folder, make_game.PREPARE_STOP)
|
||||
open(stop, "w").close()
|
||||
code, lines = prepared(stub("import os; print(os.path.exists(%r))" % stop), stop=stop)
|
||||
self.assertEqual((code, lines), (0, ["False"]))
|
||||
self.assertFalse(os.path.exists(stop))
|
||||
|
||||
def test_the_stop_request_is_the_games_and_the_builders(self):
|
||||
# (the file's name and the stopped run's line are the game's own; the builder's Cancel sets the event the game opens)
|
||||
main = (ROOT / "gpu" / "vk" / "vk_main.cpp").read_text(encoding="utf-8")
|
||||
runner = (ROOT / "builder" / "HookshotBuilder" / "Runner.cs").read_text(encoding="utf-8")
|
||||
self.assertIn('"%s"' % make_game.PREPARE_STOP, main)
|
||||
self.assertIn('printf("%s (' % make_game.NOT_PREPARED, main)
|
||||
self.assertEqual(make_game.PREPARE_STOP_WAIT, 60)
|
||||
default = make_game.prepare_shaders.__defaults__
|
||||
self.assertIn(make_game.PREPARE_STOP_WAIT, default)
|
||||
# (the event's name is the builder's run's own, passed to the game through make_game.py's environment, which keeps it;
|
||||
# not an RX_VK_ name, which the shaders' stamp would take)
|
||||
self.assertIn('const char* name = getenv("TRIFORCE_PREPARE_STOP");', main)
|
||||
self.assertIn('if (name && !strncmp(name, "Local\\\\TriforcePrepareStop.", 26)) event_ = CreateEventA(nullptr, TRUE, FALSE, name);',
|
||||
main)
|
||||
self.assertEqual(len("Local\\TriforcePrepareStop."), 26)
|
||||
self.assertIn('readonly string stopEvent = @"Local\\TriforcePrepareStop." + Guid.NewGuid().ToString("N");', runner)
|
||||
self.assertIn('si.Environment["TRIFORCE_PREPARE_STOP"] = stopEvent;', runner)
|
||||
self.assertIn("Process.Start(Info(tools, args, workers, ngxSdk, stopEvent))", runner)
|
||||
self.assertEqual(make_game.game_env({"TRIFORCE_PREPARE_STOP": "x"}), {"TRIFORCE_PREPARE_STOP": "x"})
|
||||
cancel = runner[runner.index("public Task Cancel()"):runner.index("public static async Task<(bool Ok, string Text)> Check(")]
|
||||
self.assertIn("EventWaitHandle.TryOpenExisting(stopEvent, out var stop)", cancel)
|
||||
self.assertLess(cancel.index("stop.Set()"), cancel.index("p.WaitForExit(30000)"))
|
||||
self.assertLess(cancel.index("p.WaitForExit(30000)"), cancel.index("Kill(entireProcessTree: true)"))
|
||||
window = (ROOT / "builder" / "HookshotBuilder" / "MainWindow.xaml.cs").read_text(encoding="utf-8")
|
||||
self.assertIn("runner?.Cancel().Wait();", window)
|
||||
# (a Cancel whose preparation stopped well still reaches make_game.py's @@done: it is a Cancel all the same, back to
|
||||
# the files, not "Your game is ready" with shortcuts made and the build's files freed)
|
||||
self.assertIn('Finished?.Invoke(cancelled ? "cancelled" :', runner)
|
||||
ended = window[window.index("void Ended(string? failure)"):window.index("void LogToggled(")]
|
||||
self.assertLess(ended.index('if (failure == "cancelled")'), ended.index("if (finished.Length > 0)"))
|
||||
|
||||
def test_steady_output_is_not_silence(self):
|
||||
code, lines = prepared(stub("import time\nfor i in range(6):\n print('@@progress %.3f' % (i / 6), flush=True); "
|
||||
"time.sleep(0.4)"), silence=1)
|
||||
|
||||
@@ -54,23 +54,27 @@ def check_source():
|
||||
"prepare_threads::translate(all, amd_older, e && atoi(e) > 0)"])
|
||||
need("vk_draw.cpp: prepare_run()", block(draw, "bool prepare_run(void (*progress)(size_t done, size_t total), bool background) {"),
|
||||
["background ? std::clamp(cpus / 4, 2u, 4u) : prepare_translate_workers()"])
|
||||
# (the preparation before the title: the count is the rule's, and the workers stay below normal priority)
|
||||
# (the preparation before the title: the count is the rule's, and the workers below normal priority but in a start that
|
||||
# only prepares: prepare_priority, tests/test_prepare_timing.py)
|
||||
for name, marker in [("state_list_prepare", "void state_list_prepare(void (*progress)(size_t done, size_t total)) {"),
|
||||
("warm_libraries", "bool warm_libraries(void (*progress)(size_t done, size_t total)) {")]:
|
||||
body = block(draw, marker)
|
||||
need("vk_draw.cpp: %s()" % name, body,
|
||||
["const unsigned workers = prepare_workers();", "for (unsigned i = 0; i < workers; i++) threads.emplace_back(",
|
||||
"SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL);"])
|
||||
"SetThreadPriority(GetCurrentThread(), prepare_priority());"])
|
||||
if "cpus / 2" in body or "hardware_concurrency" in body:
|
||||
raise SystemExit("vk_draw.cpp: %s() counts its workers itself again" % name)
|
||||
prepare = block(draw, "bool prepare_run(void (*progress)(size_t done, size_t total), bool background) {")
|
||||
need("vk_draw.cpp: prepare_run()", prepare,
|
||||
# (behind the game: its own count and idle priority, as before)
|
||||
# ((Triforce, v0.5.2) before the title: prepare_workers's, fewer on AMD's older driver: prepare_translate_workers)
|
||||
["const unsigned workers = background ? std::clamp(cpus / 4, 2u, 4u) : prepare_translate_workers();",
|
||||
"SetThreadPriority(GetCurrentThread(), background ? THREAD_PRIORITY_IDLE : THREAD_PRIORITY_BELOW_NORMAL);",
|
||||
"SetThreadPriority(GetCurrentThread(), background ? THREAD_PRIORITY_IDLE : prepare_priority());",
|
||||
"for (unsigned i = 0; i < workers; i++) threads.emplace_back(worker);"])
|
||||
if "cpus / 2" in prepare:
|
||||
raise SystemExit("vk_draw.cpp: prepare_run() starts half the processors' workers again")
|
||||
need("vk_draw.cpp: prepare_translate_workers()", block(draw, "unsigned prepare_translate_workers() {"),
|
||||
["const unsigned all = prepare_workers();", "prepare_threads::translate(all, amd_older, e && atoi(e) > 0)"])
|
||||
# (not asked to change: the predicted pipelines' pass and the precompile)
|
||||
need("vk_draw.cpp: predict_run()", block(draw, "void predict_run(void (*progress)(size_t done, size_t total)) {"),
|
||||
["for (unsigned i = 0; i < std::clamp(cpus / 2, 1u, 32u); i++) threads.emplace_back(worker);"])
|
||||
|
||||
124
tests/test_prepare_timing.py
Normal file
124
tests/test_prepare_timing.py
Normal file
@@ -0,0 +1,124 @@
|
||||
"""The shader preparation says how its workers' time went, and a start that only prepares runs them at normal priority.
|
||||
|
||||
A cold driver's part (gpu/vk/vk_draw.cpp warm_libraries) on AMD 26.10.1 made ~91,600 stage libraries in 5608 s on 16 workers,
|
||||
16 a second, and nothing in the log said whether those workers compiled or waited on one another. warm_libraries and
|
||||
precompile_run log now, beside what they did: libraries (pipelines) a second, the summed thread milliseconds of each kind of
|
||||
build (the libraries' pre-raster, fragment and shading rate parts; the precompile's compute, mesh fallback and graphics
|
||||
pipelines), and the workers' share of a processor over the time they ran beside the process's share of every processor.
|
||||
Only clocks are read around the builds: each build is the call it was.
|
||||
|
||||
The workers of the preparation before the title (prepare_run, warm_libraries, state_list_prepare, predict_run) ran below
|
||||
normal priority; in a start that only prepares (HOOKSHOT_PREPARE_ONLY: Setup's build and update) they run at normal, but only
|
||||
in a process known to be below normal already (Windows: the below normal or idle class; elsewhere a nice value above 0), so
|
||||
that they stay below every program of normal priority. The game's own starts keep below normal, the preparation behind the
|
||||
game idle, and precompile_run's workers the priority they had. The timing line every two minutes is written only after
|
||||
progress, so that a warm stuck in one build still goes silent for Setup's silence watch.
|
||||
|
||||
Source checks, no game or GPU: python -I -B tests/test_prepare_timing.py
|
||||
"""
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def between(text, start, end):
|
||||
a = text.index(start)
|
||||
return text[a:text.index(end, a)]
|
||||
|
||||
|
||||
def need(where, text, needles):
|
||||
for needle in needles:
|
||||
if needle not in text:
|
||||
raise SystemExit("FAIL: " + where + " no longer has: " + needle)
|
||||
|
||||
|
||||
def main():
|
||||
draw = (ROOT / "gpu/vk/vk_draw.cpp").read_text(encoding="utf-8")
|
||||
|
||||
# ---- the priority: normal only where the start only prepares and the process is known to be below normal (Windows:
|
||||
# the below normal or idle class; elsewhere a nice value above 0, as the Linux builder sets none)
|
||||
prio = between(draw, "int prepare_priority() {", "\n}\n")
|
||||
need("prepare_priority()", prio, [
|
||||
'if (!getenv("HOOKSHOT_PREPARE_ONLY")) return (int)THREAD_PRIORITY_BELOW_NORMAL;',
|
||||
"GetPriorityClass(GetCurrentProcess())",
|
||||
"if (cls != BELOW_NORMAL_PRIORITY_CLASS && cls != IDLE_PRIORITY_CLASS) return (int)THREAD_PRIORITY_BELOW_NORMAL;",
|
||||
"getpriority(PRIO_PROCESS, 0)",
|
||||
"if (errno != 0 || nice_now <= 0) return (int)THREAD_PRIORITY_BELOW_NORMAL;",
|
||||
"return (int)THREAD_PRIORITY_NORMAL;"])
|
||||
normal = prio.index("return (int)THREAD_PRIORITY_NORMAL;")
|
||||
if not prio.index("HOOKSHOT_PREPARE_ONLY") < prio.index("#ifdef _WIN32") < prio.index("GetPriorityClass") < \
|
||||
prio.index("#else") < prio.index("getpriority(PRIO_PROCESS, 0)") < prio.index("#endif") < normal or \
|
||||
prio.count("THREAD_PRIORITY_NORMAL;") != 1:
|
||||
raise SystemExit("FAIL: prepare_priority() can give normal priority without knowing the process is below normal")
|
||||
if "<sys/resource.h>" not in draw[:draw.index("int prepare_priority() {")]:
|
||||
raise SystemExit("FAIL: vk_draw.cpp does not include <sys/resource.h> for getpriority off Windows")
|
||||
main_cpp = (ROOT / "gpu/vk/vk_main.cpp").read_text(encoding="utf-8")
|
||||
need("vk_main.cpp", main_cpp, ['bool prepare_only() { return getenv("HOOKSHOT_PREPARE_ONLY") != nullptr; }'])
|
||||
for name, marker, count in [
|
||||
("state_list_prepare", "void state_list_prepare(void (*progress)(size_t done, size_t total)) {", 2),
|
||||
("warm_libraries", "bool warm_libraries(void (*progress)(size_t done, size_t total)) {", 1),
|
||||
("predict_run", "void predict_run(void (*progress)(size_t done, size_t total)) {", 1),
|
||||
# (the pipeline cache carry's rebuild of the compute pipelines, prepare_run's foreground: pcache_carry.h)
|
||||
("warm_kept_computes", "bool warm_kept_computes(void (*progress)(size_t done, size_t total)) {", 1)]:
|
||||
body = between(draw, marker, "\n}\n")
|
||||
if body.count("SetThreadPriority(GetCurrentThread(), prepare_priority());") != count or \
|
||||
"THREAD_PRIORITY_BELOW_NORMAL" in body or "THREAD_PRIORITY_NORMAL" in body:
|
||||
raise SystemExit("FAIL: %s(): its workers do not take prepare_priority()" % name)
|
||||
prepare = between(draw, "bool prepare_run(void (*progress)(size_t done, size_t total), bool background) {", "\n}\n")
|
||||
need("prepare_run()", prepare,
|
||||
["SetThreadPriority(GetCurrentThread(), background ? THREAD_PRIORITY_IDLE : prepare_priority());"])
|
||||
pre = between(draw, "void precompile_run(void (*progress)(size_t done, size_t total)) {", "\n}\n")
|
||||
if "SetThreadPriority" in pre or "prepare_priority" in pre:
|
||||
raise SystemExit("FAIL: precompile_run()'s workers had no priority of their own and were to stay so")
|
||||
if draw.count("prepare_priority()") != 7: # (the definition and the six workers above, nowhere in play)
|
||||
raise SystemExit("FAIL: prepare_priority() is used past the preparation's workers (%d)" % draw.count("prepare_priority()"))
|
||||
|
||||
# ---- the timing: clocks around the same builds
|
||||
times = between(draw, "struct PrepTimes {", "\n};\n")
|
||||
need("PrepTimes", times, ["thread_cpu_us()", "process_cpu_us()", "void tick() {", "~Worker() { tick(); }",
|
||||
"std::string kind_text(int kind, const char* name) const {",
|
||||
"std::string cpu_text(unsigned workers) const {"])
|
||||
need("thread_cpu_us()", between(draw, "uint64_t thread_cpu_us() {", "\n}\n"),
|
||||
["GetThreadTimes(GetCurrentThread(), &c, &e, &k, &u)", "CLOCK_THREAD_CPUTIME_ID"])
|
||||
need("process_cpu_us()", between(draw, "uint64_t process_cpu_us() {", "\n}\n"),
|
||||
["GetProcessTimes(GetCurrentProcess(), &c, &e, &k, &u)", "CLOCK_PROCESS_CPUTIME_ID"])
|
||||
|
||||
warm = between(draw, "bool warm_libraries(void (*progress)(size_t done, size_t total)) {", "\n}\n")
|
||||
need("warm_libraries()", warm, [
|
||||
"PrepTimes times;", "PrepTimes::Worker timed(times);", "timed.tick();",
|
||||
"const VkPipeline lib = build_graphics(p, *blank, at, VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, part);",
|
||||
"times.add(rate ? 2 : part - 1, built_from);",
|
||||
'times.kind_text(0, "pre-raster")', 'times.kind_text(1, "fragment")', 'times.kind_text(2, "shading rate")',
|
||||
"times.cpu_text(workers)", 'timing(" so far");', 'timing("");'])
|
||||
a, b, c = (warm.index(t) for t in ("const auto built_from = std::chrono::steady_clock::now();",
|
||||
"const VkPipeline lib = build_graphics(", "times.add(rate ? 2 : part - 1, built_from);"))
|
||||
if not a < b < c or "vkDestroyPipeline(dev.device, lib, nullptr);" not in warm[c:] or "libs++;" not in warm[c:]:
|
||||
raise SystemExit("FAIL: warm_libraries() times something else than each library's build, or no longer lets it go")
|
||||
# (the line every two minutes only after progress: Setup's silence watch, make_game.py PREPARE_SILENCE, reads the same
|
||||
# pipe, and a warm stuck in one build must still go silent for it)
|
||||
so_far = warm.index('timing(" so far");')
|
||||
guard = warm.rfind("if (now_done != timing_done) {", 0, so_far)
|
||||
if guard < 0 or "timing_done = now_done;" not in warm[so_far:so_far + 120] or \
|
||||
warm.rfind("const size_t now_done = done.load();", 0, guard) < 0 or warm.count('timing(" so far");') != 1:
|
||||
raise SystemExit("FAIL: warm_libraries() logs its timing every two minutes without progress: a stuck warm never goes "
|
||||
"silent for Setup's silence watch")
|
||||
join = warm.index("for (std::thread& t : threads) t.join();")
|
||||
if not join < warm.index('timing("");') < warm.index("if (prepare_stopped()) {", join):
|
||||
raise SystemExit("FAIL: warm_libraries()'s last timing line is not after its workers, for a stopped part too")
|
||||
|
||||
need("precompile_run()", pre, [
|
||||
"PrepTimes::Worker timed(pre->times);", "timed.tick();", "pre->times.add(0, built_from);",
|
||||
"pre->times.add(1, built_from);", "pre->times.add(2, built_from);",
|
||||
"const VkPipeline made = build_graphics(*p, n.s, note_targets(n), (VkPrimitiveTopology)n.topo);",
|
||||
"if (cached_compute(pcache_use().cache, &ci, &made) != VK_SUCCESS) made = VK_NULL_HANDLE;",
|
||||
"fallback_compute_pipelines(p);", 'logf("vk: precompile: timing:',
|
||||
"tm.cpu_text((unsigned)threads.size())"])
|
||||
line = pre.index('logf("vk: precompile: timing:')
|
||||
if not pre.index("for (std::thread& t : threads) t.join();") < line < pre.index("delete pre;") or \
|
||||
pre.index("for (std::thread& t : threads) t.detach();") < line:
|
||||
raise SystemExit("FAIL: precompile_run() reads its timing after the workers' state is freed or let go")
|
||||
print("ok: the preparation's timing is logged around the same builds, and only a start that only prepares runs at normal")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -138,7 +138,9 @@ int main(int argc, char** argv) {
|
||||
if prepare.count("warm_libraries(progress)") != 2:
|
||||
raise SystemExit("prepare_run: wanted warm_libraries after the translation and on the path with no translation")
|
||||
alone = prepare[:prepare.index("seed_open();\n if (!programs)")]
|
||||
if "warm_libraries(progress)" not in alone or "if (prepared_for.warmed == warmed || background) return false;" not in alone:
|
||||
# ((Triforce) or when the stamp is the same and a sample finds the libraries gone from the cache: tests/test_lib_check.py)
|
||||
if "warm_libraries(progress)" not in alone or \
|
||||
"if (!cold && (prepared_for.warmed == warmed || background)) return false;" not in alone:
|
||||
raise SystemExit("prepare_run does not make the driver's part alone when only its stamp differs")
|
||||
at = 0
|
||||
for _ in range(2): # (closed in the libraries: not written down as warmed)
|
||||
@@ -150,10 +152,36 @@ int main(int argc, char** argv) {
|
||||
cleared = prepare.index("prepared_for.warmed = 0;\n")
|
||||
if prepare.index("prepared_write(path, prepared_for);", cleared) > prepare.index("if (!warm_libraries(progress)) {", cleared):
|
||||
raise SystemExit("prepare_run: the translation is not written down before the libraries are made")
|
||||
stamp = block(draw, "uint64_t warmed_stamp(")
|
||||
stamp = block(draw, "uint64_t warmed_stamp_of(")
|
||||
for part in ("program_cache_stamp()", "pipelineCacheUUID", "driverVersion", "libraries", "kWarmRecipe"):
|
||||
if part not in stamp:
|
||||
raise SystemExit("warmed_stamp leaves out " + part)
|
||||
# ((Triforce) the words added where they apply alone: every other device's stamp is what it was, nothing made again there)
|
||||
if "if (patches) {" not in stamp or "if (rate) add(&kRateRecipe, sizeof kRateRecipe);" not in stamp or \
|
||||
stamp.index("add(v, sizeof v);") > stamp.index("if (patches) {"):
|
||||
raise SystemExit("warmed_stamp_of: the module patches' and the rate's words are not added after the others, and only "
|
||||
"where they apply")
|
||||
if "return warmed_stamp_of(libraries, module_patches(), false);" not in block(draw, "uint64_t warmed_stamp(") or \
|
||||
"return warmed_stamp_of(libraries, module_patches(), libraries && dev.foliage_rate);" not in \
|
||||
block(draw, "uint64_t libraries_stamp("):
|
||||
raise SystemExit("warmed_stamp / libraries_stamp: wanted the modules' patches in both and the rate's libraries in the "
|
||||
"driver's part's alone")
|
||||
# ((Triforce, 11-19) and bit 2, the water's simplification (shader_water_mode, the RX 470 .. 590 port that came without a
|
||||
# new stamp): those cards warm their driver's part again once)
|
||||
if "return (dev.fixes.nan_bits && nan_selects ? 1u : 0u) | (shader_water_mode() ? 2u : 0u);" not in block(draw, "uint32_t module_patches("):
|
||||
raise SystemExit("module_patches is not the NaN selects' rewrite as make_module decides it, with the water's bit")
|
||||
# ((Triforce) and the pipeline cache's <file>.own, which names it (pcache_own_stamp: what a file of the part's own holds,
|
||||
# warm_checkpoint.h); nothing there says the part is made)
|
||||
own = 'uint64_t pcache_own_stamp() { return libraries_stamp(gpl_wanted() && !getenv("RX_VK_NO_WARM")); }'
|
||||
if "const uint64_t warmed = libraries_stamp(libraries);" not in prepare or "libraries_stamp(" in draw.replace(
|
||||
"uint64_t libraries_stamp(", "").replace("const uint64_t warmed = libraries_stamp(libraries);", "").replace(own, ""):
|
||||
raise SystemExit("the driver's part's stamp (libraries_stamp) is used past prepare_run, or prepare_run does not use it")
|
||||
carry = prepare.index("warm_skip_carry(warming + \".skip\", libraries, warmed);")
|
||||
if carry > prepare.index("gpl_skip_set(gpl_rules::skip_read(warming + \".skip\", warmed));"):
|
||||
raise SystemExit("prepare_run reads the skip list before what the stamp it was carries over")
|
||||
carried = block(draw, "void warm_skip_carry(")
|
||||
if "if (!gpl_rules::skip_read(skip, now).empty()) return;" not in carried or "gpl_rules::skip_add(skip, now, ids);" not in carried:
|
||||
raise SystemExit("warm_skip_carry does not carry the list over only where the new stamp has none")
|
||||
warm = block(draw, "bool warm_libraries(")
|
||||
for call in ("program_cache_keys(", "program_cache_borrow(", "pipe_notes_read()", "ub_thread_off();", "prepare_stopped()"):
|
||||
if call not in warm:
|
||||
|
||||
@@ -124,7 +124,12 @@ def check_source(src):
|
||||
"if (held || present_after_hold()) after_hold = true;",
|
||||
"c.reset = in.reset || after_hold ?"])
|
||||
temporal = (src / "gpu/vk/vk_temporal.cpp").read_text(encoding="utf-8")
|
||||
need("vk_temporal.cpp", temporal, ["const bool reset = !last || now - last > 2 || present_held_last();"])
|
||||
# ((Triforce) a camera cut starts one too: tests/test_fsr3_history.py)
|
||||
need("vk_temporal.cpp", temporal, ["const bool reset = !last || now - last > 2 || present_held_last() || cut;"])
|
||||
# ((Triforce) AMD FSR 3.1's own inputs as well: frames drawn during a hold are not carried into its history)
|
||||
inputs = (src / "gpu/vk/vk_fsr3_inputs.cpp").read_text(encoding="utf-8")
|
||||
need("vk_fsr3_inputs.cpp prepare", block(inputs, "bool prepare(VkCommandBuffer cmd, Texture* in, VkImageView in_view, Frame& out, bool linear) {"),
|
||||
["const bool held = !gap && present_held_last();", "const bool reset = gap || held || cut;"])
|
||||
|
||||
dev = (src / "docs/development.md").read_text(encoding="utf-8")
|
||||
for switch in ("RX_VK_HOLD_MS", "RX_VK_UPLOAD_NEW_MS", "RX_VK_UPLOAD_NEW_MB"):
|
||||
|
||||
@@ -445,9 +445,9 @@ DENIED = [r"\bShader::", r"\busing\s+namespace\b", r"\bEnv\b",
|
||||
r"fallback_task|stages)\s*(?:=[^=]|\+=|\.push_back|\.emplace_back|\.clear|\.resize)"]
|
||||
FIRSTS = ["spirv_crc32", "DiskRecord", "disk_init", "ra_mu", "program_cache_load_some"]
|
||||
HOST_CALLS = {"gpu_read", "gpu_guest", "gpu_ptr", "guest_base", "guest_size", "depth_minus_w"}
|
||||
# (vk_bank.cpp's marked parts, by the first name each defines. None on this branch: epicmemes46's 5df76bb marks the samplers'
|
||||
# generation for its texture LOD bias (sampler_bias_changed), which this branch has not taken; with it, ["sampler_bias_changed"])
|
||||
BANK_FIRSTS = []
|
||||
# (vk_bank.cpp's marked parts, by the first name each defines: the samplers' generation moved for the texture LOD bias, which only
|
||||
# vk_draw.cpp's sampler_for reads)
|
||||
BANK_FIRSTS = ["sampler_bias_changed"]
|
||||
MARKED = {"vk_shader.cpp": FIRSTS, "vk_bank.cpp": BANK_FIRSTS}
|
||||
# (what a translation reaches in vk_bank.cpp, at the least: what vk_shader.cpp calls, and what those read)
|
||||
BANK_REACHED = {"seed_cs_control", "compute_ssbo_table", "seed_cs_buffer_word", "texture_slot_version", "registrations_generation",
|
||||
|
||||
@@ -9,8 +9,18 @@ Game-free. The table (nx2/prompt_keys.py) is checked against the sources it foll
|
||||
that way, and host/prompts.c points the same code points at the movement keys (cmap4_bind's moves);
|
||||
- no code point of the font is given two meanings.
|
||||
The row: Auto's choice (host/prompts.c auto_face, compiled and run): the first controller's face from its name, the
|
||||
keyboard and mouse with no controller, the Switch's for XInput's nameless one; the row's names end with "Keyboard & mouse",
|
||||
its default is still Auto, and the documents name the new choice.
|
||||
Xbox's for XInput's nameless one, with no controller the device used last in the run before (prompts_auto.txt), else the
|
||||
keyboard and mouse; the row's names end with "Keyboard & mouse", its default is still Auto, and the documents name the new
|
||||
choice.
|
||||
(Triforce, 11-19) Following the device used last (host/prompts.c device_face, follow_record and pad_font_due, compiled
|
||||
and run): which face a device is, when prompts_auto.txt gets it (3 s of a controller, 30 s of the keys used in 5 s of
|
||||
them: a key pressed once and the game left alone is not), and when the overlay shows the font of the controller used last
|
||||
(at once the first, another face once it has been the last for a second: two controllers given the same presses do not
|
||||
make it flicker); and the sources that feed and read them: host/nn_hid.c's device used last and its uses, the captured
|
||||
mouse only past an eighth of the stick, host/pad_sdl.c's scans and the controller used last's name, Auto's wait by the
|
||||
scans, Auto's memory in the user's folder (Setup makes prompts/ again at an update), a font a face built once a run and
|
||||
tried again when not written, the host interface's prompt_pad_face and the overlay's font of it (gpu/vk/vk_imgui.cpp:
|
||||
one a face, made once), and pad_name's names of it.
|
||||
|
||||
python -I -B tests/test_prompt_keys_table.py [--cc gcc]
|
||||
"""
|
||||
@@ -166,32 +176,140 @@ def main():
|
||||
check(re.search(r"^\| `button_prompts` \|.*6 Keyboard & mouse", dev, re.M) is not None,
|
||||
"docs/development.md's options table has no button_prompts with 6 Keyboard & mouse")
|
||||
|
||||
# Auto's choice
|
||||
# Auto's choice, and following the device used last
|
||||
harness = "\n".join([
|
||||
"#include <ctype.h>", "#include <stdio.h>", "#include <stdlib.h>", "#include <string.h>", '#include "gpu/vk/vk_api.h"',
|
||||
"#include <ctype.h>", "#include <stdint.h>", "#include <stdio.h>", "#include <stdlib.h>", "#include <string.h>",
|
||||
'#include "gpu/vk/vk_api.h"',
|
||||
block(prompts, "static int contains("),
|
||||
block(prompts, "static int auto_face("),
|
||||
block(prompts, "static int device_face("),
|
||||
re.search(r"typedef struct \{ int held, recorded; int64_t held_ns; int active; \} Follow;", prompts).group(0),
|
||||
re.search(r"#define KEYS_ACTIVE \d+", prompts).group(0),
|
||||
block(prompts, "static int follow_record("),
|
||||
re.search(r"#define PAD_HOLD_NS \d+LL", prompts).group(0),
|
||||
block(prompts, "static int pad_font_due("),
|
||||
"int main(int argc, char **argv) {",
|
||||
" (void)argc;",
|
||||
" printf(\"%d\\n\", auto_face(argv[1], atoi(argv[2])));",
|
||||
' if (!strcmp(argv[1], "auto")) printf("%d\\n", auto_face(argv[2], atoi(argv[3]), atoi(argv[4])));',
|
||||
' else if (!strcmp(argv[1], "device")) printf("%d\\n", device_face(atoi(argv[2]), argv[3]));',
|
||||
' else if (!strcmp(argv[1], "due"))',
|
||||
' printf("%d\\n", pad_font_due(atoi(argv[2]), atoi(argv[3]), atoi(argv[4]), atoll(argv[5]) * 1000000LL,',
|
||||
' (unsigned)atoi(argv[6])));',
|
||||
" else { /* follow: what prompts_auto.txt had, then a face, its time in ms and whether its device was used, each */",
|
||||
" Follow f = {-1, atoi(argv[2]), 0, 0};",
|
||||
" for (int i = 3; i + 2 < argc; i += 3)",
|
||||
' if (follow_record(&f, atoi(argv[i]), atoll(argv[i + 1]) * 1000000LL, atoi(argv[i + 2])))',
|
||||
' printf("%s %d\\n", argv[i + 1], f.recorded);',
|
||||
" }",
|
||||
" return 0;",
|
||||
"}", ""])
|
||||
want = [("", 0, "KEYBOARD"), ("", 1, "SWITCH"), ("Xbox Series X Controller", 0, "XBOX"), ("8BitDo Pro 2", 0, "XBOX"),
|
||||
("DualSense Wireless Controller", 0, "PS5"), ("PS4 Controller", 0, "PS4"), ("Steam Deck", 0, "STEAMDECK"),
|
||||
("Nintendo Switch Pro Controller", 0, "SWITCH"), ("Xbox 360 Controller", 1, "XBOX")]
|
||||
F = {n[len("HOS_PROMPT_"):]: i for i, n in enumerate(faces)}
|
||||
want = [("", 0, -1, "KEYBOARD"), ("", 1, -1, "XBOX"), ("Xbox Series X Controller", 0, -1, "XBOX"),
|
||||
("8BitDo Pro 2", 0, -1, "XBOX"), ("DualSense Wireless Controller", 0, -1, "PS5"), ("PS4 Controller", 0, -1, "PS4"),
|
||||
("Steam Deck", 0, -1, "STEAMDECK"), ("Nintendo Switch Pro Controller", 0, -1, "SWITCH"),
|
||||
("Xbox 360 Controller", 1, -1, "XBOX"),
|
||||
# (none there: the last run's device; a controller there, or XInput's, before it; nothing sensible: the keys)
|
||||
("", 0, F["XBOX"], "XBOX"), ("", 0, F["PS5"], "PS5"), ("", 0, F["KEYBOARD"], "KEYBOARD"), ("", 1, F["PS5"], "XBOX"),
|
||||
("DualSense Wireless Controller", 0, F["XBOX"], "PS5"), ("", 0, 99, "KEYBOARD")]
|
||||
devices = [(0, "", -1), (1, "Xbox Series X Controller", F["KEYBOARD"]), (2, "", F["XBOX"]),
|
||||
(2, "Xbox Wireless Controller", F["XBOX"]), (2, "DualSense Wireless Controller", F["PS5"]),
|
||||
(2, "Nintendo Switch Pro Controller", F["SWITCH"])]
|
||||
K_, X, P = F["KEYBOARD"], F["XBOX"], F["PS5"]
|
||||
keys_used = [x for t in range(0, 30001, 250) for x in (K_, t, 1)] # (the keys used at every look for 30 s)
|
||||
follows = [
|
||||
# (a controller for 3 s is recorded, and once only)
|
||||
([-1, X, 0, 1, X, 1000, 0, X, 2999, 0, X, 3000, 0, X, 9000, 0], ["3000 %d" % X]),
|
||||
# (the keys need 30 s: a key between a controller's presses, or one to close the game, keeps the controller's)
|
||||
([X, K_, 0, 1, K_, 20000, 1, X, 21000, 1, K_, 22000, 1, K_, 51999, 1], []),
|
||||
([X] + keys_used, ["30000 %d" % K_]),
|
||||
# ((11-19) and used in 5 s of them: a key pressed once, or the mouse bumped, then the game left alone is not the keys)
|
||||
([X, K_, 0, 1, K_, 30000, 0, K_, 90000, 0], []),
|
||||
([X, K_, 0, 1, K_, 250, 1, K_, 500, 1, K_, 40000, 0], []),
|
||||
([X] + [x for t in range(0, 4751, 250) for x in (K_, t, 1)] + [K_, 30000, 0], ["30000 %d" % K_]),
|
||||
# (what the file already has is not written again; another controller after 3 s is)
|
||||
([X, X, 0, 1, X, 60000, 0, P, 61000, 1, P, 64000, 0], ["64000 %d" % P]),
|
||||
# (no device yet: nothing)
|
||||
([-1, -1, 0, 0, -1, 90000, 0], []),
|
||||
]
|
||||
# (served, face, shown, held ms, failed): the first controller's font at once; another face's once it has been the one
|
||||
# used last for a second, not at each press of two controllers taking turns
|
||||
dues = [((K_, X, -1, 0, 0), 1), ((K_, X, X, 5000, 0), 0), ((K_, P, X, 0, 0), 0), ((K_, P, X, 999, 0), 0),
|
||||
((K_, P, X, 1000, 0), 1), ((K_, K_, -1, 5000, 0), 0), ((K_, -1, -1, 0, 0), 0), ((X, P, -1, 0, 0), 0),
|
||||
((K_, X, -1, 0, 1 << X), 0), ((F["SWITCH"], X, -1, 0, 0), 0)]
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
c, exe = Path(tmp) / "auto.c", Path(tmp) / "auto"
|
||||
c.write_text(harness, encoding="utf-8")
|
||||
subprocess.run([a.cc, "-std=c11", "-Wall", "-Wextra", "-Werror", "-I", str(ROOT), str(c), "-o", str(exe)], check=True)
|
||||
for name, xinput, face in want:
|
||||
got = int(subprocess.run([str(exe), name, str(xinput)], check=True, capture_output=True, text=True).stdout)
|
||||
check(faces[got] == "HOS_PROMPT_" + face, "Auto with controller %r%s: %s, not %s"
|
||||
% (name, " and XInput's" if xinput else "", faces[got], face))
|
||||
|
||||
def run(*args):
|
||||
return subprocess.run([str(exe)] + [str(x) for x in args], check=True, capture_output=True, text=True).stdout
|
||||
|
||||
for name, xinput, remembered, face in want:
|
||||
got = int(run("auto", name, xinput, remembered))
|
||||
check(faces[got] == "HOS_PROMPT_" + face, "Auto with controller %r%s, the last run's face %d: %s, not %s"
|
||||
% (name, " and XInput's" if xinput else "", remembered, faces[got], face))
|
||||
for device, name, face in devices:
|
||||
got = int(run("device", device, name))
|
||||
check(got == face, "device %d (%r) is face %d, not %d" % (device, name, got, face))
|
||||
for seq, writes in follows:
|
||||
got = run("follow", *seq).split("\n")[:-1]
|
||||
check(got == writes, "following %s writes %s, not %s" % (seq, got, writes))
|
||||
for args, due in dues:
|
||||
got = int(run("due", *args))
|
||||
check(got == due, "the overlay's font for served %d, face %d, shown %d, held %d ms, failed %d: %d, not %d"
|
||||
% (args + (got, due)))
|
||||
choose = block(prompts, "static int choose_face(")
|
||||
check("auto_face(name, xinput)" in choose and "!name[0] && hos_xinput_connected()" in choose,
|
||||
"choose_face does not ask auto_face, or asks XInput while SDL names a controller")
|
||||
check("auto_face(name, xinput, remembered)" in choose and "!name[0] && hos_xinput_connected()" in choose and
|
||||
"name[0] || xinput ? -1 : remembered_face(dir)" in choose,
|
||||
"choose_face does not ask auto_face, asks XInput while SDL names a controller, or the last run's device before both")
|
||||
check("hos_sdl_pad_scans()" in choose and "scans < 0 || scans >= AUTO_SCANS" in choose and "i < 60" in choose,
|
||||
"Auto's wait is not SDL's scans, at most 3 s, and none without SDL")
|
||||
check("int hos_xinput_connected(void) {" in hid, "host/nn_hid.c has no hos_xinput_connected")
|
||||
print("ok: %d keys with an icon each, the controls' tables agree, and Auto chooses %d cases right" % (len(keys), len(want)))
|
||||
# (the device used last: a controller where its presses count, the keys and the mouse where theirs do; stored only)
|
||||
reader = block(hid, "static void read_input(")
|
||||
check("player_used(), device_used(2);" in reader and "if (bound_down(i, 0)) *buttons |= 1ULL << i, player_used(), device_used(1);"
|
||||
in reader and "if (bound_down(i, 1)) *buttons |= 1ULL << i, device_used(1);" in reader and
|
||||
"if (mouse[2] > 4096 || mouse[2] < -4096 || mouse[3] > 4096 || mouse[3] < -4096) device_used(1);" in reader and "if (keys[0] || keys[1] || cx || cy) device_used(1);" in reader,
|
||||
"host/nn_hid.c read_input does not say which device was used last")
|
||||
check(not re.search(r"\b(fopen|hos_log|Sleep)\(", block(hid, "static void device_used(")),
|
||||
"device_used does more than store the device")
|
||||
check("InterlockedIncrement(&input_uses[device]);" in block(hid, "static void device_used(") and
|
||||
"unsigned hos_input_uses(int device) {" in hid, "host/nn_hid.c does not count each device's uses")
|
||||
pad = (ROOT / "host/pad_sdl.c").read_text(encoding="utf-8")
|
||||
check("void hos_sdl_pad_last_name(char *out, size_t cap) {" in pad and "pads[i].used_ns > pads[last].used_ns" in pad,
|
||||
"host/pad_sdl.c does not name the controller used last")
|
||||
check("InterlockedIncrement(&scans)" in pad and pad.count("InterlockedExchange(&scans, -1);") == 3 and
|
||||
"scans < SCANS_FAST ? 250000000LL : 1000000000LL" in pad,
|
||||
"host/pad_sdl.c does not count its scans, quickly at first, or say when SDL will not run")
|
||||
follow = block(prompts, "static DWORD WINAPI follow_main(void *arg) {")
|
||||
check("follow_main" in block(prompts, "static int setup(") and 'snprintf(file, sizeof file, "External.pad.%d.bfotf.zs", face);' in follow
|
||||
and "const int got = built >> face & 1 ? 1 : build_font(dir, face, file, 1, out, sizeof out);" in follow,
|
||||
"host/prompts.c does not follow the device used last, or build the overlay's font of it once a face")
|
||||
check("pad_font_due(served, face, (int)pad_face_shown, now - seen_ns, failed) && now >= retry_ns[face]" in follow and
|
||||
"else if (got < 0) failed |= 1u << face;" in follow and "else retry_ns[face] = now + 2000000000LL;" in follow,
|
||||
"a face's font not written is not tried again, or one the folder has none of is")
|
||||
check("const int active = device >= 1 && device <= 2 && used != uses[device];" in follow and
|
||||
"follow_record(&follow, face, now, active)" in follow, "follow_main does not tell follow_record whether the device was used")
|
||||
# ((11-19) Auto's memory beside the saves: Setup makes prompts/ again from nothing at an update)
|
||||
check('snprintf(out, cap, "%s/prompts_auto.txt", hos_user_dir ? hos_user_dir : "user");' in block(prompts, "static void auto_path(")
|
||||
and "auto_path(path, sizeof path);" in block(prompts, "static int remembered_face(") and "auto_path(path, sizeof path);" in follow
|
||||
and "prompts/auto.txt" not in follow, "Auto's device used last is kept in prompts/, which Setup makes again at an update")
|
||||
check(re.search(r"int \(\*prompt_pad_face\)\(void\);\s*\} MkwVkHost;", api) is not None and
|
||||
"#define MKWVK_API_VERSION 15" in api, "gpu/vk/vk_api.h has no prompt_pad_face last, at version 15")
|
||||
check("hos_bench_state, hos_prompts_pad_face,\n};" in (ROOT / "host/rx_backend.c").read_text(encoding="utf-8"),
|
||||
"host/rx_backend.c does not give the back end hos_prompts_pad_face")
|
||||
imgui = (ROOT / "gpu/vk/vk_imgui.cpp").read_text(encoding="utf-8")
|
||||
check('"prompts/External.pad." + std::to_string(pad) + ".bfotf.zs"' in imgui and
|
||||
"glyphs_follow();\n ImGui_ImplVulkan_NewFrame();" in imgui and "std::thread(read_glyphs).detach()" in block(imgui, "void glyphs_follow("),
|
||||
"the overlay does not read the controller used last's icons, or not again on its own thread")
|
||||
gf = block(imgui, "void glyphs_follow(")
|
||||
check("fonts_.glyph = pad_glyphs[pad], glyph_pad.store(pad, std::memory_order_relaxed);" in gf and
|
||||
gf.index("if (pad_glyphs[pad]) {") < gf.index("std::thread(read_glyphs)") and
|
||||
"if (pad >= 0 && pad < HOS_PROMPT_N) pad_glyphs[pad] = fonts_.glyph;" in block(imgui, "void load_glyphs("),
|
||||
"a controller face shown again adds another font to the atlas")
|
||||
check("face = host->prompt_pad_face();" in block(menu, "const char* pad_name(int p)"),
|
||||
"pad_name does not name the controller used last's buttons with the keys' face")
|
||||
print("ok: %d keys with an icon each, the controls' tables agree, Auto chooses %d cases right, and the device used last "
|
||||
"is followed in %d" % (len(keys), len(want), len(devices) + len(follows) + len(dues)))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -17,9 +17,11 @@ class RecompLauncherJsonTests(unittest.TestCase):
|
||||
menu = (ROOT / "gpu" / "vk" / "vk_menu.cpp").read_text(encoding="utf-8")
|
||||
rows = {re.sub(" ", "_", name.lower()) for name in re.findall(r'\{TAB_[A-Z]+, "([^"]+)"', menu)}
|
||||
# (vk_menu.cpp ini_key: the rows whose key is not their name, renamed rows keeping the key an options file has:
|
||||
# output_res, resolution, upscaling, frame_rate_cap, dlss)
|
||||
# output_res, resolution, frame_rate_cap, dlss, and (Triforce, options_version 7) its table of the rows renamed as
|
||||
# their groups came, {"<name>", "<key>"})
|
||||
ini_key = menu.split("const char* ini_key(const Row& r) {", 1)[1].split("\n}", 1)[0]
|
||||
rows |= set(re.findall(r'return "([a-z_0-9]+)";', ini_key))
|
||||
rows |= set(re.findall(r'\{"[^"]+", "([a-z_0-9-]+)"\}', ini_key))
|
||||
keys = {key for setting in manifest["settings"] for choice in setting["choices"] for key in choice["set"]}
|
||||
self.assertTrue(keys)
|
||||
self.assertEqual(keys - rows, set())
|
||||
|
||||
@@ -31,7 +31,8 @@ static void write(T& t, uint64_t f) { // (as texture_written: prev before last
|
||||
t.prev = redrawn::prev_on_write(t.prev, t.last, t.gpu && !t.released, f);
|
||||
t.last = f, t.gpu = true, t.released = false;
|
||||
}
|
||||
static bool redrawn_now(const T& t, uint64_t f) { return redrawn::drawn_before(t.prev, t.last, t.gpu && !t.released, f); }
|
||||
static bool redrawn_now(const T& t, uint64_t f) { return redrawn::drawn_before(t.prev, t.last, t.gpu && !t.released, f, 1); }
|
||||
static bool redrawn_in(const T& t, uint64_t f, uint64_t w) { return redrawn::drawn_before(t.prev, t.last, t.gpu && !t.released, f, w); }
|
||||
int main() {
|
||||
{ // (a scene target, drawn every frame from frame 10 on)
|
||||
T s;
|
||||
@@ -73,6 +74,25 @@ int main() {
|
||||
write(r, 202);
|
||||
CHECK(redrawn_now(r, 202) && redrawn_now(r, 203));
|
||||
}
|
||||
{ // ((Triforce, 11-19) the window: a target drawn every second or third frame counts as drawn again; a first compose never)
|
||||
T a;
|
||||
write(a, 300);
|
||||
CHECK(redrawn_in(a, 302, 4) && redrawn_in(a, 304, 4) && !redrawn_in(a, 305, 4));
|
||||
CHECK(!redrawn_in(a, 302, 1)); // (v0.5.2's rule)
|
||||
write(a, 302);
|
||||
CHECK(redrawn_in(a, 302, 4)); // (its second draw in frame 302: the write in 300 is within the window)
|
||||
T fresh;
|
||||
CHECK(!redrawn_in(fresh, 400, 4));
|
||||
write(fresh, 400);
|
||||
CHECK(!redrawn_in(fresh, 400, 4)); // (a text box's first compose, its later draws in the same frame too)
|
||||
CHECK(redrawn::kWindow == 4);
|
||||
T z; // (a window of 0 taken as 1)
|
||||
write(z, 10);
|
||||
CHECK(redrawn_in(z, 11, 0) && !redrawn_in(z, 12, 0));
|
||||
T future; // (a last write marked after this frame: not before it)
|
||||
write(future, 900);
|
||||
CHECK(!redrawn_in(future, 899, 4));
|
||||
}
|
||||
if (!fails) std::printf("PASS\n");
|
||||
return fails != 0;
|
||||
}
|
||||
@@ -101,9 +121,14 @@ class RedrawnTests(unittest.TestCase):
|
||||
self.assertRegex(tex, r"tex->prev_written = redrawn::prev_on_write\(tex->prev_written, tex->last_written, "
|
||||
r"tex->gpu_written && !tex->released, frame_no\);\n tex->last_written = frame_no;")
|
||||
# (the draw's decision: every colour target and the depth target redrawn, no memory written)
|
||||
self.assertIn("bool may = !program_writes_memory(p);", draw)
|
||||
self.assertIn("may = texture_redrawn(at.color[i]);", draw)
|
||||
self.assertIn("may = texture_redrawn(at.depth);", draw)
|
||||
self.assertIn("bool may = redrawn_off || big || !program_writes_memory(p);", draw)
|
||||
self.assertIn("for (int i = 0; i < at.n && may && !redrawn_off && !big; i++) may = texture_redrawn(at.color[i]);", draw)
|
||||
self.assertIn("if (may && !redrawn_off && !big) may = texture_redrawn(at.depth);", draw)
|
||||
# ((Triforce, 11-19) only small targets under the rule: the text boxes and labels are 262x104 .. 656x113 and 90x34 .. 631x94
|
||||
self.assertIn("return v >= 0 ? (uint64_t)v : 100000ull;", draw)
|
||||
self.assertGreater(100000, 656 * 113)
|
||||
self.assertGreater(100000, 631 * 94)
|
||||
self.assertLessEqual(100000, 480 * 270)
|
||||
# (the one gate every deferral path checks, set from it)
|
||||
self.assertIn("upload_defer_ok = !compute && draw_may_defer;", draw)
|
||||
self.assertEqual(len(re.findall(r"upload_defer_ok = !compute", draw)), 1)
|
||||
|
||||
@@ -31,15 +31,16 @@ ROOT = Path(__file__).resolve().parents[1]
|
||||
# (the row's name, its field of Options, lowest, highest, step, the function that words its value, its default, the
|
||||
# tonemapper it shows with: None any, 1 PsychoV35, 2 RenoDRT). NX2navi's menu: runtime/ui/menu.cpp row_hdr
|
||||
NEW_ROWS = [
|
||||
("RenoDX gamma correction", "rdx_gamma", 0, 2, 1, "tx_rdx_gamma", 0, None),
|
||||
("RenoDX match tone slope", "rdx_match_slope", 0, 1, 1, "tx_onoff", 1, 1),
|
||||
("RenoDX tone slope", "rdx_tone_slope", 0, 100, 1, "tx_rdx_grade", 50, 1),
|
||||
("RenoDX hue clip", "rdx_hue_clip", 0, 100, 5, "tx_percent", 50, 1),
|
||||
("RenoDX highlight saturation", "rdx_highlight_sat", 0, 100, 1, "tx_rdx_grade", 50, 2),
|
||||
("RenoDX blowout", "rdx_blowout", 0, 100, 1, "tx_rdx_grade", 0, 2),
|
||||
("RenoDX flare", "rdx_flare", 0, 100, 1, "tx_rdx_grade", 0, 2),
|
||||
("RenoDX hue correction", "rdx_hue", 0, 100, 5, "tx_percent", 100, 2),
|
||||
("RenoDX color grading", "rdx_grade", 0, 100, 5, "tx_percent", 100, 2),
|
||||
# ((Triforce, options_version 7) under the RenoDX group's heading their names lost "RenoDX "; their keys stayed: ini_key)
|
||||
("Gamma correction", "rdx_gamma", 0, 2, 1, "tx_rdx_gamma", 0, None),
|
||||
("Match tone slope", "rdx_match_slope", 0, 1, 1, "tx_onoff", 1, 1),
|
||||
("Tone slope", "rdx_tone_slope", 0, 100, 1, "tx_rdx_grade", 50, 1),
|
||||
("Hue clip", "rdx_hue_clip", 0, 100, 5, "tx_percent", 50, 1),
|
||||
("Highlight saturation", "rdx_highlight_sat", 0, 100, 1, "tx_rdx_grade", 50, 2),
|
||||
("Blowout", "rdx_blowout", 0, 100, 1, "tx_rdx_grade", 0, 2),
|
||||
("Flare", "rdx_flare", 0, 100, 1, "tx_rdx_grade", 0, 2),
|
||||
("Hue correction", "rdx_hue", 0, 100, 5, "tx_percent", 100, 2),
|
||||
("Color grading", "rdx_grade", 0, 100, 5, "tx_percent", 100, 2),
|
||||
]
|
||||
KEYS = {"rdx_tonemap": "renodx_tonemapper", "rdx_gamma": "renodx_gamma_correction", "rdx_match_slope": "renodx_match_tone_slope",
|
||||
"rdx_tone_slope": "renodx_tone_slope", "rdx_hue_clip": "renodx_hue_clip",
|
||||
@@ -94,7 +95,7 @@ def check_rows(menu, header):
|
||||
order = re.findall(r'\{(TAB_\w+), "([^"]+)", &opts\.(\w+),', table)
|
||||
names = [name for _, name, _ in order]
|
||||
# (the tonemapper row has RenoDRT)
|
||||
row = re.search(r'\{TAB_DISPLAY, "RenoDX tonemapper", &opts\.rdx_tonemap, 0, 2, 1, tx_rdx_tonemap,(.*?)\},\n', table, re.S)
|
||||
row = re.search(r'\{TAB_DISPLAY, "Tonemapper", &opts\.rdx_tonemap, 0, 2, 1, tx_rdx_tonemap,(.*?)\},\n', table, re.S)
|
||||
check(row and "RenoDRT" in row.group(1) and row.group(1).rstrip().endswith("nullptr, false, true"),
|
||||
"the RenoDX tonemapper row is not Vanilla, PsychoV35, RenoDRT, changing at once")
|
||||
check(re.search(r'const char\* tx_rdx_tonemap\(int v\) \{ return v == 2 \? "RenoDRT" : v \? "PsychoV35" : "Vanilla"; \}', menu),
|
||||
@@ -102,7 +103,7 @@ def check_rows(menu, header):
|
||||
check(re.search(r'const char\* tx_rdx_gamma\(int v\) \{ return v == 1 \? "2\.2" : v == 2 \? "BT\.1886 \(2\.4\)" : "Off"; \}', menu),
|
||||
"tx_rdx_gamma does not name Off (0), 2.2 (1) and BT.1886 (2.4) (2)")
|
||||
check(re.search(r"int rdx_tonemap = 1;", header), "the tonemapper's default is no longer PsychoV35: an options file from before would change")
|
||||
first, last = names.index("RenoDX tonemapper"), names.index("RenoDX bloom")
|
||||
first, last = names.index("Tonemapper"), names.index("Bloom")
|
||||
for name, field, lo, hi, step, text, default, _ in NEW_ROWS:
|
||||
row = re.search(r'\{TAB_DISPLAY, "%s", &opts\.%s, (-?\d+), (-?\d+), (\d+), (\w+),(.*?)\},\n' % (re.escape(name), field), table, re.S)
|
||||
check(row, "vk_menu.cpp has no Display row \"%s\" on opts.%s" % (name, field))
|
||||
@@ -157,7 +158,7 @@ int main() {
|
||||
const Row r{w.name, w.value};
|
||||
CHECK(!std::strcmp(ini_key(r), w.key));
|
||||
}
|
||||
const Row tonemapper{"RenoDX tonemapper", &opts.rdx_tonemap};
|
||||
const Row tonemapper{"Tonemapper", &opts.rdx_tonemap};
|
||||
CHECK(!std::strcmp(ini_key(tonemapper), "renodx_tonemapper"));
|
||||
/* every one of them is a RenoDX row (hidden without HDR Native and RenoDX HDR), and no other row is */
|
||||
for (const Want& w : news) CHECK(rdx_row(w.value));
|
||||
@@ -371,11 +372,13 @@ def check_binding(source):
|
||||
|
||||
def check_docs():
|
||||
readme = (ROOT / "readme.md").read_text(encoding="utf-8")
|
||||
row = re.search(r"^\| RenoDX HDR \|(.*)\|$", readme, re.M)
|
||||
check(row, "readme.md's settings table has no RenoDX HDR row")
|
||||
for word in ("Vanilla", "PsychoV35", "RenoDRT", "gamma correction", "tone slope", "hue clip", "highlight saturation", "blowout", "flare",
|
||||
"hue correction", "colour grading"):
|
||||
check(word in row.group(1), "readme.md's RenoDX HDR row does not name: " + word)
|
||||
# ((Triforce, options_version 7) RenoDX is the HDR row's Native + RenoDX, and its rows a group of their own)
|
||||
row = re.search(r"^\| RenoDX \|(.*)\|$", readme, re.M)
|
||||
check(row, "readme.md's settings table has no RenoDX row")
|
||||
check("Native + RenoDX" in readme[readme.index("| HDR |"):readme.index("| RenoDX |")], "readme.md's HDR row has no Native + RenoDX")
|
||||
for word in ("Vanilla", "PsychoV35", "RenoDRT", "Gamma correction", "Tone slope", "Hue clip", "Highlight saturation", "Blowout", "Flare",
|
||||
"Hue correction", "Color grading"):
|
||||
check(word in row.group(1), "readme.md's RenoDX row does not name: " + word)
|
||||
guide = (ROOT / "docs/development.md").read_text(encoding="utf-8")
|
||||
for line in ("| `renodx_tonemapper` | 0 Vanilla, 1 PsychoV35, 2 RenoDRT |",
|
||||
"| `renodx_gamma_correction` | 0 Off, 1 2.2, 2 BT.1886 (2.4) |"):
|
||||
|
||||
@@ -86,15 +86,19 @@ int main(int argc, char** argv) {
|
||||
CHECK(replay_threads::of_row(8, 0) == 0 && replay_threads::of_row(8, 2) == 2 && replay_threads::of_row(8, 3) == 3 && replay_threads::of_row(9, 3) == 0);
|
||||
/* and with no key the row is Automatic (replay_threads.h: the audit's holes closed, the owner's choice) */
|
||||
CHECK(replay_threads::kDefaultRow == replay_threads::kRowAutomatic);
|
||||
/* why, for the log's line ((Triforce) 11-17: one reason, none on every PC, and that the row still sets a count) */
|
||||
/* why, for the log's line: one reason for each outcome */
|
||||
using replay_threads::why;
|
||||
for (unsigned n : {4u, 8u, 12u, 16u, 32u})
|
||||
CHECK(std::strstr(why(n, false), "none") && std::strstr(why(n, true), "none") && std::strstr(why(n, false), "row"));
|
||||
/* Automatic's rule ((Triforce) 11-17): none on every PC, whatever its processors or driver (replay_threads.h automatic) */
|
||||
CHECK(std::strstr(why(8, false), "four cores or fewer") && std::strstr(why(12, false), "2 with") && std::strstr(why(16, false), "3 with"));
|
||||
CHECK(std::strstr(why(32, true), "AMD") && std::strstr(why(4, true), "AMD"));
|
||||
/* Automatic's rule: by the cores (half the logical processors), none on AMD's driver for RDNA 1 and 2 */
|
||||
using replay_threads::automatic;
|
||||
CHECK(automatic(0, false) == 0 && automatic(1, false) == 0 && automatic(4, false) == 0 && automatic(8, false) == 0 && automatic(9, false) == 0);
|
||||
CHECK(automatic(10, false) == 2 && automatic(12, false) == 2 && automatic(15, false) == 2);
|
||||
CHECK(automatic(16, false) == 3 && automatic(24, false) == 3 && automatic(32, false) == 3 && automatic(128, false) == 3);
|
||||
for (unsigned n = 0; n <= 256; n++) {
|
||||
CHECK(automatic(n, true) == 0);
|
||||
CHECK(automatic(n, false) == 0);
|
||||
CHECK(automatic(n, false) == 0 || automatic(n, false) == 2 || automatic(n, false) == 3); /* (never a count nobody measured) */
|
||||
if (n) CHECK(automatic(n, false) >= automatic(n - 1, false));
|
||||
}
|
||||
CHECK(hn_replay_threads(3, 0) && hn_replay_threads(3, 1) && !hn_replay_threads(3, 2) && !hn_replay_threads(0, 2));
|
||||
CHECK(hn_replay_threads(8, 0) && hn_replay_threads(8, 1) && hn_replay_threads(8, 2) && !hn_replay_threads(8, 3));
|
||||
@@ -153,16 +157,18 @@ def main():
|
||||
"Used with DLSS or FSR on too" in row.group(0),
|
||||
"the Replay helper threads row is not a Developer row of the Debug tab that takes a restart and says what Off is")
|
||||
check(rows.index('"Developer", nullptr') < rows.index('"Descriptor reuse", &opts.descriptor_reuse') < rows.index('"Sampler cache", &opts.sampler_cache')
|
||||
< rows.index('"Replay helper threads", &opts.replay_threads') < rows.index('{TAB_SYSTEM, "Restart"'),
|
||||
< rows.index('"Replay helper threads", &opts.replay_threads'), # ((Triforce, v0.5.2) no Restart row after it: the pause menu's Quit
|
||||
"the Replay helper threads row is not beside Descriptor reuse and Sampler cache, under the Developer heading")
|
||||
for tab in ("TAB_DISPLAY", "TAB_GRAPHICS", "TAB_AUDIO", "TAB_CONTROLS", "TAB_SYSTEM"):
|
||||
check('{%s, "Replay helper threads"' % tab not in rows, "the Replay helper threads row is on a tab players see")
|
||||
# the lab's other switch stays a switch
|
||||
check("RX_VK_EVENT_EARLY" not in menu and "event_early" not in menu.lower() and "RX_VK_EVENT_EARLY" in replay,
|
||||
"RX_VK_EVENT_EARLY has a row, or is gone from vk_replay.cpp")
|
||||
# the Debug tab draws a row of more than two values as a choice (its Developer rows were Off and On alone)
|
||||
draw = function(menu, "void draw_debug_rows(")
|
||||
check("if (r.value && r.hi - r.lo > r.step) {" in draw and "choice_cell(c, va, vb, r.text(*r.value), selected, !fixed, !fixed, fixed);" in draw,
|
||||
# the Debug tab draws a row of more than two values as a choice (its Developer rows were Off and On alone). ((Triforce,
|
||||
# 11-17) The tab is drawn by draw_options' own loop now: only a row of On and Off is halves there)
|
||||
draw = function(menu, "void draw_options(")
|
||||
check("} else if (r.text == tx_onoff && !fixed) {" in draw and "choice_cell(c, va, vb, r.text(*r.value), selected, left, right, fixed);" in draw
|
||||
and "if (cur_tab == TAB_DEBUG) listed = debug_list(list);" in draw,
|
||||
"the Debug tab draws the Replay helper threads row as Off and On halves")
|
||||
guide = (ROOT / "docs/development.md").read_text(encoding="utf-8")
|
||||
check("| `replay_helper_threads` | 0 Off, 1 to 7 the parallel replay tried on 2 to 8 threads, 8 Automatic (the default" in guide and
|
||||
|
||||
@@ -140,9 +140,8 @@ def check_source():
|
||||
menu_h = (vk / "vk_menu.h").read_text(encoding="utf-8")
|
||||
check('"RivaTuner limit"' not in menu and "opts.rtss" not in menu and "int rtss" not in menu_h, "the RivaTuner limit row is still there")
|
||||
check('mine |= key == "rivatuner_limit";' in block(menu, "void save() {"), "an old rivatuner_limit= line is written back")
|
||||
check("RivaTuner" in block(menu, "const char* hn_reflex_limit(int v, int variant) {") and
|
||||
"Where RivaTuner Statistics Server is the game's limiter it holds the frames instead." in menu,
|
||||
"the Reflex frame limit row does not say that RivaTuner wins")
|
||||
# ((Triforce, options_version 7) no Reflex frame limit row: the Low latency row's line in the readme says RivaTuner wins)
|
||||
check('"Reflex frame limit"' not in menu, "the Reflex frame limit row is still there")
|
||||
# ((Triforce) NX2navi's full overlay: its Frame limit row names who holds the frames, vk_pace.cpp's owner, after the rate)
|
||||
check("const int holder = mkwvk::pace::owner();" in menu and '" (RivaTuner)" : " (NVIDIA Reflex)"' in menu,
|
||||
"the overlay's Frame limit line does not say who holds the frames (vk_pace.cpp)")
|
||||
|
||||
@@ -209,7 +209,7 @@ def main():
|
||||
("/* TX_SENS */", block(menu, "const char* tx_sens(")),
|
||||
("/* THE_ROW */", row.group(0)),
|
||||
("/* STOPS */", block(menu, "bool stops_at_ends(")),
|
||||
("/* INI_KEY */", block(menu, "bool ini_row(") + "\n" + block(menu, "const char* ini_key(")),
|
||||
("/* INI_KEY */", "bool is_merged(const int*) { return false; } /* ((Triforce, options_version 7) no merged row here */\n" + block(menu, "bool ini_row(") + "\n" + block(menu, "const char* ini_key(")),
|
||||
("/* LOAD_LOOP */", loop)):
|
||||
cxx = cxx.replace(marker, text)
|
||||
c = C.replace("/* CURVE */", block(pad, "static unsigned rumble_curve(")).replace(
|
||||
|
||||
@@ -58,19 +58,23 @@ FIXTURE = r"""
|
||||
Options opts;
|
||||
%(tabs)s
|
||||
%(row)s
|
||||
int saves = 0, presets = 0;
|
||||
int saves = 0;
|
||||
void save() { saves++; }
|
||||
void apply_pad_layout(int) {}
|
||||
void apply_preset(int) { presets++; }
|
||||
void sync_preset_budgets(int) {}
|
||||
/* (stand-ins for the rest of set_row, which the Rumble strength row never reaches: the Upscaler's rows, the restart offer) */
|
||||
/* (stand-ins for the rest of set_row, which the Rumble strength row never reaches: the Upscaler's rows, the merged rows
|
||||
((Triforce, options_version 7) merged_rows.h), the restart offer) */
|
||||
bool row_fixed(const int*) { return false; }
|
||||
int upscaler() { return 0; }
|
||||
namespace ur {
|
||||
int step_upscaler(int, int, bool) { return 0; }
|
||||
int step(int, int v, int dir) { return v + dir; }
|
||||
struct Scaling { int upscaler, resolution; };
|
||||
Scaling step_engine(int, int v, int, unsigned) { return {0, v}; }
|
||||
Scaling step_resolution(int, int v, int dir) { return {0, v + dir}; }
|
||||
int snap(int, int v) { return v; }
|
||||
}
|
||||
bool is_merged(const int*) { return false; }
|
||||
int merged_step(const int*, int v, int) { return v; }
|
||||
void merged_store(const int*) {}
|
||||
void merged_sync() {}
|
||||
namespace mr { constexpr int kMax = 8; }
|
||||
void restart_values(int*) {}
|
||||
struct { void note(const int*) {} } restart_state;
|
||||
@@ -93,7 +97,6 @@ int main() {
|
||||
CHECK(r.lo == 0 && r.hi == 300 && r.step == 25);
|
||||
CHECK(opts.rumble == 100);
|
||||
CHECK(!std::strcmp(ini_key(r), "rumble_strength"));
|
||||
opts.preset = 3;
|
||||
/* the arrows (and clicks): Off stays Off, 300%% stays 300%% */
|
||||
opts.rumble = 0;
|
||||
arrow(r, false);
|
||||
@@ -112,8 +115,8 @@ int main() {
|
||||
CHECK(opts.rumble == 300);
|
||||
set_row(r, -25, -1);
|
||||
CHECK(opts.rumble == 0);
|
||||
/* it is a control: the quality preset stays */
|
||||
CHECK(opts.preset == 3 && presets == 0 && saves > 0);
|
||||
/* each change saved ((Triforce, options_version 7) no quality preset to keep any more) */
|
||||
CHECK(saves > 0);
|
||||
/* an ini's value: on the steps, within the range */
|
||||
static const int in[] = {-10, 0, 12, 13, 60, 63, 100, 137, 138, 150, 151, 163, 287, 288, 300, 301, 999};
|
||||
static const int out[] = {0, 0, 0, 25, 50, 75, 100, 125, 150, 150, 150, 175, 275, 300, 300, 300, 300};
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user