mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-06 04:55:44 +00:00
Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
53fdc2c9ad | ||
|
|
e9877e27f7 | ||
|
|
b67a69542c | ||
|
|
02e7eff284 | ||
|
|
439d9afe5e |
No files matched your search
@@ -166,14 +166,21 @@ object SteamTouchConfig {
|
||||
|
||||
fun steamRoot(context: Context) = com.droiddeck.launcher.session.SessionPrefs.activeSteamRoot(context)
|
||||
|
||||
private fun controllerConfigs(context: Context) = File(steamRoot(context), "steamapps/common/Steam Controller Configs")
|
||||
|
||||
fun configDir(context: Context): File? {
|
||||
val base = File(steamRoot(context), "steamapps/common/Steam Controller Configs")
|
||||
val base = controllerConfigs(context)
|
||||
val account = accountId(context)
|
||||
if (account != null) File(base, "$account/config").takeIf { it.isDirectory }?.let { return it }
|
||||
return base.listFiles()?.filter { it.name.all(Char::isDigit) && File(it, "config").isDirectory }
|
||||
?.maxByOrNull { it.lastModified() }?.let { File(it, "config") }
|
||||
}
|
||||
|
||||
private fun writableConfigDir(context: Context): File? {
|
||||
val account = accountId(context) ?: return configDir(context)
|
||||
return File(controllerConfigs(context), "$account/config").apply { mkdirs() }.takeIf { it.isDirectory }
|
||||
}
|
||||
|
||||
private fun accountId(context: Context): Long? = try {
|
||||
val users = KeyValues.parse(File(steamRoot(context), "config/loginusers.vdf").readText())
|
||||
val node = users.child("users")
|
||||
@@ -197,7 +204,7 @@ object SteamTouchConfig {
|
||||
}
|
||||
return try {
|
||||
val text = file.readText()
|
||||
val kv = KeyValues.parse(text.removePrefix(""))
|
||||
val kv = KeyValues.parse(text)
|
||||
val mappings = kv.child("controller_mappings") ?: kv
|
||||
val layouts = mappings.string("touch_layout")?.let { hex -> decodeLayouts(hexToBytes(hex)) }
|
||||
Log.i(TAG, "steam touch: app $appId uses ${file.path} (${layouts?.layouts?.size ?: 0} layouts)")
|
||||
@@ -389,8 +396,9 @@ object SteamTouchConfig {
|
||||
bindings: Map<SteamTouchBindings.Ref, (SteamTouchBindings.Binding) -> SteamTouchBindings.Binding> = emptyMap(),
|
||||
options: Options? = null,
|
||||
): File? {
|
||||
val dir = configDir(context) ?: return null
|
||||
val base = config.text ?: if (config.file == null && bindings.isEmpty()) "\"controller_mappings\"\n{\n\t\"controller_type\"\t\t\"controller_mobile_touch\"\n}\n" else return null
|
||||
val dir = writableConfigDir(context) ?: return null.also { Log.w(TAG, "steam touch: no controller config folder to save app $appId in") }
|
||||
val base = config.text ?: if (config.file == null && bindings.isEmpty()) "\"controller_mappings\"\n{\n\t\"controller_type\"\t\t\"controller_mobile_touch\"\n}\n"
|
||||
else return null.also { Log.w(TAG, "steam touch: ${config.file?.path ?: "default layout"} has no readable text to save into") }
|
||||
val source = bindings.entries.fold(base) { text, (ref, change) ->
|
||||
SteamTouchBindings.rewrite(text, ref, change) ?: text
|
||||
}
|
||||
@@ -408,11 +416,11 @@ object SteamTouchConfig {
|
||||
val existing = Regex("""\n\s*"touch_layout"\s+"[0-9a-fA-F]*"""")
|
||||
val text = if (existing.containsMatchIn(source)) source.replace(existing, "\n$line")
|
||||
else source.replaceFirst(Regex("""("controller_type"\s+"controller_mobile_touch"[^\n]*)"""), "$1\n$line")
|
||||
if (!text.contains("touch_layout")) return null
|
||||
if (!text.contains("touch_layout")) return null.also { Log.w(TAG, "steam touch: ${config.file?.path} is no controller_mobile_touch config") }
|
||||
target.parentFile?.mkdirs()
|
||||
val tmp = File(target.path + ".tmp")
|
||||
tmp.writeText(text)
|
||||
if (!tmp.renameTo(target)) return null
|
||||
if (!tmp.renameTo(target)) return null.also { Log.w(TAG, "steam touch: could not replace ${target.path}") }
|
||||
selectAutosave(dir, key)
|
||||
dropDeviceEntry(dir, key)
|
||||
Log.i(TAG, "steam touch: saved layouts ${sets.keys} for app $appId to ${target.path}")
|
||||
@@ -430,12 +438,13 @@ object SteamTouchConfig {
|
||||
|
||||
private fun selectAutosave(dir: File, key: String) {
|
||||
val file = File(dir, CONFIGSET)
|
||||
val text = if (file.isFile) file.readText() else "\"controller_config\"\n{\n}\n"
|
||||
val entry = "\t\"$key\"\n\t{\n\t\t\"autosave\"\t\t\"1\"\n\t}"
|
||||
val block = Regex("""\n\s*"${Regex.escape(key)}"\s*\{[^}]*\}""", RegexOption.IGNORE_CASE)
|
||||
val next = if (block.containsMatchIn(text)) text.replace(block) { "\n$entry" }
|
||||
else text.substring(0, text.lastIndexOf('}')).trimEnd() + "\n$entry\n}\n"
|
||||
File(file.path + ".tmp").apply { writeText(next) }.renameTo(file)
|
||||
val root = file.takeIf { it.isFile }?.readText()?.let(KeyValues::parse)?.takeIf { it.child("controller_config") != null }
|
||||
?: KeyValues.Node(mutableListOf("controller_config" to KeyValues.Node()))
|
||||
val config = root.child("controller_config") ?: return
|
||||
val entry = key to KeyValues.Node(mutableListOf("autosave" to "1"))
|
||||
val at = config.entries.indexOfFirst { it.first.equals(key, true) && it.second is KeyValues.Node }
|
||||
if (at >= 0) config.entries[at] = entry else config.entries += entry
|
||||
File(file.path + ".tmp").apply { writeText(KeyValues.write(root)) }.renameTo(file)
|
||||
}
|
||||
|
||||
|
||||
@@ -593,34 +602,48 @@ class KeyValues private constructor() {
|
||||
fun string(key: String): String? = entries.firstOrNull { it.first.equals(key, true) && it.second is String }?.second as String?
|
||||
}
|
||||
|
||||
private class Token(val text: String, val quoted: Boolean) {
|
||||
val opens get() = !quoted && text == "{"
|
||||
val closes get() = !quoted && text == "}"
|
||||
}
|
||||
|
||||
companion object {
|
||||
fun write(node: Node): String = write(node, "")
|
||||
|
||||
private fun write(node: Node, indent: String): String = node.entries.joinToString("") { (key, value) ->
|
||||
if (value is Node) "$indent\"${escape(key)}\"\n$indent{\n${write(value, "$indent\t")}$indent}\n"
|
||||
else "$indent\"${escape(key)}\"\t\t\"${escape(value.toString())}\"\n"
|
||||
}
|
||||
|
||||
private fun escape(text: String) = text.replace("\\", "\\\\").replace("\"", "\\\"").replace("\n", "\\n").replace("\t", "\\t")
|
||||
|
||||
fun parse(text: String): Node {
|
||||
val tokens = tokenize(text)
|
||||
val tokens = tokenize(text.removePrefix("\uFEFF"))
|
||||
var i = 0
|
||||
fun node(): Node {
|
||||
val n = Node()
|
||||
while (i < tokens.size) {
|
||||
val t = tokens[i++]
|
||||
if (t == "}" ) return n
|
||||
if (t == "{") continue
|
||||
if (t.closes) return n
|
||||
if (t.opens) continue
|
||||
if (i >= tokens.size) break
|
||||
val next = tokens[i]
|
||||
if (next == "{") { i++; n.entries += t to node() } else { i++; n.entries += t to next }
|
||||
if (next.opens) { i++; n.entries += t.text to node() } else { i++; n.entries += t.text to next.text }
|
||||
}
|
||||
return n
|
||||
}
|
||||
return node()
|
||||
}
|
||||
|
||||
private fun tokenize(text: String): List<String> {
|
||||
val out = mutableListOf<String>()
|
||||
private fun tokenize(text: String): List<Token> {
|
||||
val out = mutableListOf<Token>()
|
||||
var i = 0
|
||||
while (i < text.length) {
|
||||
val c = text[i]
|
||||
when {
|
||||
c.isWhitespace() -> i++
|
||||
c == '/' && i + 1 < text.length && text[i + 1] == '/' -> while (i < text.length && text[i] != '\n') i++
|
||||
c == '{' || c == '}' -> { out += c.toString(); i++ }
|
||||
c == '{' || c == '}' -> { out += Token(c.toString(), false); i++ }
|
||||
c == '"' -> {
|
||||
val sb = StringBuilder()
|
||||
i++
|
||||
@@ -632,13 +655,13 @@ class KeyValues private constructor() {
|
||||
i++
|
||||
}
|
||||
i++
|
||||
out += sb.toString()
|
||||
out += Token(sb.toString(), true)
|
||||
}
|
||||
c == '[' -> { while (i < text.length && text[i] != ']') i++; i++ }
|
||||
else -> {
|
||||
val start = i
|
||||
while (i < text.length && !text[i].isWhitespace() && text[i] != '{' && text[i] != '}' && text[i] != '"') i++
|
||||
out += text.substring(start, i)
|
||||
out += Token(text.substring(start, i), false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -60,6 +60,117 @@ class SteamTouchConfigFilesTest {
|
||||
|
||||
private val template get() = File(steam, "controller_base/templates/controller_mobile_touch_gamepad_joystick.vdf")
|
||||
|
||||
private fun login() = File(steam, "config/loginusers.vdf").apply { parentFile!!.mkdirs() }
|
||||
.writeText("\"users\"\n{\n\t\"76561197960265851\"\n\t{\n\t\t\"MostRecent\"\t\t\"1\"\n\t}\n}\n")
|
||||
|
||||
private fun saveDefault(app: Int): File? {
|
||||
val elements = listOf(SteamTouchConfig.Element(SteamTouchConfig.A, true, 0.5f, 0.6f))
|
||||
return SteamTouchConfig.saveLayouts(context, app, SteamTouchConfig.load(context, app), mapOf(1 to elements))
|
||||
}
|
||||
|
||||
private fun assertSavedA(app: Int, saved: File?) {
|
||||
val loaded = SteamTouchConfig.load(context, app)
|
||||
assertEquals(saved, loaded.file)
|
||||
val a = SteamTouchConfig.elementsFor(loaded, 1, emptyList()).first { it.type == SteamTouchConfig.A }
|
||||
assertEquals(0.5f, a.x, 0.002f)
|
||||
assertEquals(0.6f, a.y, 0.002f)
|
||||
}
|
||||
|
||||
@Test fun savesWhenSteamHasNotCreatedTheAccountsControllerFolder() {
|
||||
File(steam, "steamapps/common/Steam Controller Configs").deleteRecursively()
|
||||
login()
|
||||
val saved = saveDefault(413150)
|
||||
assertEquals(File(dir, "413150/controller_mobile_touch.vdf"), saved)
|
||||
assertSavedA(413150, saved)
|
||||
}
|
||||
|
||||
@Test fun savesIntoTheSignedInAccountNotAnotherAccountsFolder() {
|
||||
dir.parentFile!!.deleteRecursively()
|
||||
val other = File(steam, "steamapps/common/Steam Controller Configs/456/config").apply { mkdirs() }
|
||||
login()
|
||||
val saved = saveDefault(413150)
|
||||
assertEquals(File(dir, "413150/controller_mobile_touch.vdf"), saved)
|
||||
assertFalse(File(other, "413150").exists())
|
||||
assertSavedA(413150, saved)
|
||||
}
|
||||
|
||||
@Test fun withoutAnAccountOrControllerFolderNothingIsWritten() {
|
||||
File(steam, "steamapps/common/Steam Controller Configs").deleteRecursively()
|
||||
assertEquals(null, saveDefault(413150))
|
||||
assertFalse(File(steam, "steamapps/common/Steam Controller Configs").exists())
|
||||
}
|
||||
|
||||
@Test fun anEmptyConfigsetIsRebuiltInsteadOfFailingTheSave() {
|
||||
File(dir, "configset_controller_mobile_touch.vdf").writeText("")
|
||||
val saved = saveDefault(413150)
|
||||
assertEquals(File(dir, "413150/controller_mobile_touch.vdf"), saved)
|
||||
assertTrue(File(dir, "configset_controller_mobile_touch.vdf").readText().contains("\"413150\""))
|
||||
assertSavedA(413150, saved)
|
||||
}
|
||||
|
||||
@Test fun aConfigsetWithOnlyAQuotedBraceIsRebuilt() {
|
||||
File(dir, "configset_controller_mobile_touch.vdf").writeText("\"controller_config\" \"{\"\n")
|
||||
val saved = saveDefault(413150)
|
||||
val root = KeyValues.parse(File(dir, "configset_controller_mobile_touch.vdf").readText()).child("controller_config")
|
||||
assertEquals("1", root?.child("413150")?.string("autosave"))
|
||||
assertSavedA(413150, saved)
|
||||
}
|
||||
|
||||
@Test fun anExistingConfigsetKeepsItsOtherEntries() {
|
||||
configset("configset_controller_mobile_touch.vdf", "8400" to "\"workshop\"\t\t\"7\"")
|
||||
saveDefault(413150)
|
||||
val text = File(dir, "configset_controller_mobile_touch.vdf").readText()
|
||||
assertTrue(text.contains("\"8400\""))
|
||||
assertTrue(text.contains("\"413150\""))
|
||||
}
|
||||
|
||||
private fun withBom(name: String) = File(dir, name).apply { writeText("\uFEFF" + readText()) }
|
||||
|
||||
@Test fun aConfigsetWithAByteOrderMarkKeepsItsOtherEntries() {
|
||||
configset("configset_controller_mobile_touch.vdf", "8400" to "\"workshop\"\t\t\"7\"")
|
||||
withBom("configset_controller_mobile_touch.vdf")
|
||||
val saved = saveDefault(413150)
|
||||
val root = KeyValues.parse(File(dir, "configset_controller_mobile_touch.vdf").readText()).child("controller_config")
|
||||
assertEquals("1", root?.child("413150")?.string("autosave"))
|
||||
assertEquals("7", root?.child("8400")?.string("workshop"))
|
||||
assertSavedA(413150, saved)
|
||||
}
|
||||
|
||||
@Test fun aWorkshopPickInAConfigsetWithAByteOrderMarkIsRead() {
|
||||
val picked = workshop("42", "community")
|
||||
configset("configset_controller_mobile_touch.vdf", "413150" to "\"workshop\"\t\t\"42\"")
|
||||
withBom("configset_controller_mobile_touch.vdf")
|
||||
assertEquals(picked, SteamTouchConfig.load(context, 413150).file)
|
||||
}
|
||||
|
||||
@Test fun aConfigsetMissingItsRootBraceGetsTheEntryAtTheRoot() {
|
||||
File(dir, "configset_controller_mobile_touch.vdf")
|
||||
.writeText("\"controller_config\"\n{\n\t\"8400\"\n\t{\n\t\t\"workshop\"\t\t\"7\"\n\t}\n")
|
||||
val saved = saveDefault(413150)
|
||||
val root = KeyValues.parse(File(dir, "configset_controller_mobile_touch.vdf").readText()).child("controller_config")
|
||||
assertEquals("1", root?.child("413150")?.string("autosave"))
|
||||
assertEquals("7", root?.child("8400")?.string("workshop"))
|
||||
assertEquals(null, root?.child("8400")?.child("413150"))
|
||||
assertSavedA(413150, saved)
|
||||
}
|
||||
|
||||
@Test fun aConfigsetCutOffAfterAKeyGetsTheEntryAtTheRoot() {
|
||||
File(dir, "configset_controller_mobile_touch.vdf").writeText("\"controller_config\"\n{\n\t\"8400\"\n\t{\n\t\t\"workshop\"")
|
||||
val saved = saveDefault(413150)
|
||||
val root = KeyValues.parse(File(dir, "configset_controller_mobile_touch.vdf").readText()).child("controller_config")
|
||||
assertEquals("1", root?.child("413150")?.string("autosave"))
|
||||
assertEquals(null, root?.child("8400")?.child("413150"))
|
||||
assertSavedA(413150, saved)
|
||||
}
|
||||
|
||||
@Test fun aConfigsetWhoseRootIsAQuotedValueIsRebuilt() {
|
||||
File(dir, "configset_controller_mobile_touch.vdf").writeText("\"controller_config\" \"{}\"\n")
|
||||
val saved = saveDefault(413150)
|
||||
val root = KeyValues.parse(File(dir, "configset_controller_mobile_touch.vdf").readText()).child("controller_config")
|
||||
assertEquals("1", root?.child("413150")?.string("autosave"))
|
||||
assertSavedA(413150, saved)
|
||||
}
|
||||
|
||||
private fun shortcut(name: String): Int {
|
||||
val shortcut = 2702387189L.toInt()
|
||||
template.apply { parentFile!!.mkdirs(); writeText(touch("Gamepad with Joystick")) }
|
||||
@@ -67,8 +178,7 @@ class SteamTouchConfigFilesTest {
|
||||
"!! Controller 0 attributes:\n Type: 43\n" +
|
||||
"Loaded Config for Last Resort Path for App ID 2702387189, Controller 0: /root/.local/share/Steam//controller_base/templates/controller_mobile_touch_gamepad_joystick.vdf\n",
|
||||
)
|
||||
File(steam, "config/loginusers.vdf").apply { parentFile!!.mkdirs() }
|
||||
.writeText("\"users\"\n{\n\t\"76561197960265851\"\n\t{\n\t\t\"MostRecent\"\t\t\"1\"\n\t}\n}\n")
|
||||
login()
|
||||
val vdf = java.io.ByteArrayOutputStream().apply {
|
||||
write("\u0000shortcuts\u0000\u00000\u0000\u0002appid\u0000".toByteArray())
|
||||
write(java.nio.ByteBuffer.allocate(4).order(java.nio.ByteOrder.LITTLE_ENDIAN).putInt(shortcut).array())
|
||||
@@ -89,6 +199,16 @@ class SteamTouchConfigFilesTest {
|
||||
assertEquals(saved, SteamTouchConfig.load(context, shortcut).file)
|
||||
}
|
||||
|
||||
@Test fun aSavedShortcutNameWithBracesDoesNotHideTheNextAppsEntry() {
|
||||
val shortcut = shortcut("Game {")
|
||||
SteamTouchConfig.saveLayouts(context, shortcut, SteamTouchConfig.load(context, shortcut), mapOf(1 to emptyList()))
|
||||
val saved = saveDefault(413150)
|
||||
val root = KeyValues.parse(File(dir, "configset_controller_mobile_touch.vdf").readText()).child("controller_config")
|
||||
assertEquals("1", root?.child("game {")?.string("autosave"))
|
||||
assertEquals("1", root?.child("413150")?.string("autosave"))
|
||||
assertSavedA(413150, saved)
|
||||
}
|
||||
|
||||
@Test fun aShortcutNameThatIsNoPlainFolderNameUsesTheAppId() {
|
||||
for (name in listOf("../escape", "a/b", "..", "Tab\tName")) {
|
||||
assertEquals(name, "2702387189", SteamTouchConfig.steamKey(context, shortcut(name)))
|
||||
|
||||
@@ -28,7 +28,6 @@ done
|
||||
python3 "$root/tools/dxvk/check_present_sync.py" "$work/source/src/dxvk/dxvk_presenter.cpp"
|
||||
python3 "$root/tools/dxvk/check_hud_storage_format.py" "$work/source/src/dxvk/hud/shaders/hud_frame_time_eval.comp"
|
||||
python3 "$root/tools/dxvk/check_d3d9_single_sample.py" "$work/source"
|
||||
python3 "$root/tools/dxvk/check_keyed_mutex_fence.py" "$work/source/src/dxvk/dxvk_image.cpp"
|
||||
for arch in 32 64; do
|
||||
meson setup "$work/build$arch" "$work/source" --cross-file "$work/source/build-win$arch.txt" \
|
||||
--buildtype release --prefix "$out" --bindir "x$arch" --libdir "x$arch" -Db_ndebug=if-release --strip
|
||||
|
||||
@@ -1,159 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
import argparse
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
|
||||
def function(text, signature):
|
||||
start = text.index(signature)
|
||||
opening = text.index('{', start)
|
||||
stripped = re.sub(r'//[^\n]*|/\*.*?\*/|"(?:\\.|[^"\\])*"|\'(?:\\.|[^\'\\])*\'',
|
||||
lambda m: ' ' * len(m.group()), text, flags=re.S)
|
||||
depth = 0
|
||||
for index in range(opening, len(stripped)):
|
||||
depth += (stripped[index] == '{') - (stripped[index] == '}')
|
||||
if depth == 0:
|
||||
return text[start:index + 1]
|
||||
raise ValueError('Unterminated source function: ' + signature)
|
||||
|
||||
|
||||
HARNESS = r'''
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <vector>
|
||||
|
||||
using UINT64 = uint64_t;
|
||||
using DWORD = uint32_t;
|
||||
using HRESULT = int32_t;
|
||||
using NTSTATUS = int32_t;
|
||||
using D3DKMT_HANDLE = uint32_t;
|
||||
using VkSemaphore = uint64_t;
|
||||
using VkResult = int;
|
||||
|
||||
constexpr HRESULT S_OK = 0;
|
||||
constexpr HRESULT DXGI_ERROR_INVALID_CALL = 0x887A0001;
|
||||
constexpr HRESULT WAIT_TIMEOUT = 258;
|
||||
constexpr NTSTATUS STATUS_TIMEOUT = 0x102;
|
||||
constexpr DWORD INFINITE = 0xFFFFFFFF;
|
||||
constexpr int VK_STRUCTURE_TYPE_SEMAPHORE_WAIT_INFO = 1;
|
||||
constexpr int VK_STRUCTURE_TYPE_SEMAPHORE_SIGNAL_INFO = 2;
|
||||
|
||||
struct LARGE_INTEGER { int64_t QuadPart; };
|
||||
struct D3DKMT_ACQUIREKEYEDMUTEX { D3DKMT_HANDLE hKeyedMutex; UINT64 Key; LARGE_INTEGER* pTimeout; UINT64 FenceValue; };
|
||||
struct D3DKMT_RELEASEKEYEDMUTEX { D3DKMT_HANDLE hKeyedMutex; UINT64 Key; UINT64 FenceValue; };
|
||||
struct VkSemaphoreWaitInfo { int sType; uint32_t semaphoreCount; const VkSemaphore* pSemaphores; const uint64_t* pValues; };
|
||||
struct VkSemaphoreSignalInfo { int sType; VkSemaphore semaphore; uint64_t value; };
|
||||
|
||||
struct Logger { template<typename... A> static void warn(const char*, A...) { std::puts("warn"); } };
|
||||
|
||||
struct Recorder {
|
||||
NTSTATUS acquireStatus = 0;
|
||||
uint64_t acquireFenceValue = 0;
|
||||
bool timeoutPassed = false;
|
||||
int64_t timeout = 0;
|
||||
uint64_t releasedFenceValue = ~0ull;
|
||||
std::vector<uint64_t> waited, signalled;
|
||||
} rec;
|
||||
|
||||
NTSTATUS D3DKMTAcquireKeyedMutex(D3DKMT_ACQUIREKEYEDMUTEX* a) {
|
||||
rec.timeoutPassed = a->pTimeout != nullptr;
|
||||
rec.timeout = a->pTimeout ? a->pTimeout->QuadPart : 0;
|
||||
a->FenceValue = rec.acquireFenceValue;
|
||||
return rec.acquireStatus;
|
||||
}
|
||||
NTSTATUS D3DKMTReleaseKeyedMutex(D3DKMT_RELEASEKEYEDMUTEX* r) {
|
||||
rec.releasedFenceValue = r->FenceValue;
|
||||
return 0;
|
||||
}
|
||||
|
||||
struct Fence { VkSemaphore handle() const { return 7; } };
|
||||
struct FenceRef {
|
||||
Fence* ptr = nullptr;
|
||||
Fence* operator->() const { return ptr; }
|
||||
explicit operator bool() const { return ptr != nullptr; }
|
||||
};
|
||||
struct Vkd {
|
||||
int device() const { return 0; }
|
||||
VkResult vkWaitSemaphores(int, const VkSemaphoreWaitInfo* i, int) { rec.waited.push_back(*i->pValues); return 0; }
|
||||
VkResult vkSignalSemaphore(int, const VkSemaphoreSignalInfo* i) { rec.signalled.push_back(i->value); return 0; }
|
||||
};
|
||||
struct VkdRef { Vkd* operator->() const { static Vkd v; return &v; } };
|
||||
|
||||
struct DxvkKeyedMutex {
|
||||
HRESULT AcquireSync(UINT64 key, DWORD milliseconds);
|
||||
HRESULT ReleaseSync(UINT64 key);
|
||||
VkdRef m_vkd;
|
||||
FenceRef m_fence;
|
||||
D3DKMT_HANDLE m_kmtLocal = 1;
|
||||
uint64_t m_fenceValue = 0;
|
||||
std::atomic<bool> m_owned = false;
|
||||
};
|
||||
|
||||
@ACQUIRE_SYNC@
|
||||
@RELEASE_SYNC@
|
||||
'''
|
||||
|
||||
MAIN = r'''
|
||||
#define CHECK(cond) do { if (!(cond)) { std::fprintf(stderr, "FAIL line %d: %s\n", __LINE__, #cond); return 2; } } while (0)
|
||||
|
||||
int main() {
|
||||
Fence fence;
|
||||
{
|
||||
rec = Recorder{}; rec.acquireFenceValue = 41;
|
||||
DxvkKeyedMutex m;
|
||||
CHECK(m.AcquireSync(0, 5) == S_OK);
|
||||
CHECK(rec.timeoutPassed && rec.timeout == -50000);
|
||||
CHECK(rec.waited.empty());
|
||||
CHECK(m.ReleaseSync(0) == S_OK);
|
||||
CHECK(rec.signalled.empty());
|
||||
CHECK(rec.releasedFenceValue == 41);
|
||||
}
|
||||
{
|
||||
rec = Recorder{}; rec.acquireFenceValue = 41;
|
||||
DxvkKeyedMutex m; m.m_fence.ptr = &fence;
|
||||
CHECK(m.AcquireSync(3, 5) == S_OK);
|
||||
CHECK(rec.waited.size() == 1 && rec.waited[0] == 41);
|
||||
CHECK(m.ReleaseSync(3) == S_OK);
|
||||
CHECK(rec.signalled.size() == 1 && rec.signalled[0] == 42);
|
||||
CHECK(rec.releasedFenceValue == 42);
|
||||
}
|
||||
{
|
||||
rec = Recorder{};
|
||||
DxvkKeyedMutex m;
|
||||
CHECK(m.AcquireSync(0, INFINITE) == S_OK);
|
||||
CHECK(!rec.timeoutPassed);
|
||||
}
|
||||
{
|
||||
rec = Recorder{}; rec.acquireStatus = STATUS_TIMEOUT;
|
||||
DxvkKeyedMutex m;
|
||||
CHECK(m.AcquireSync(0, 5) == WAIT_TIMEOUT);
|
||||
CHECK(m.ReleaseSync(0) == DXGI_ERROR_INVALID_CALL);
|
||||
}
|
||||
std::puts("PASS: keyed mutex acquire and release with and without a fence");
|
||||
return 0;
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('source', type=Path)
|
||||
args = parser.parse_args()
|
||||
text = args.source.read_text()
|
||||
acquire = function(text, 'HRESULT DxvkKeyedMutex::AcquireSync(')
|
||||
release = function(text, 'HRESULT DxvkKeyedMutex::ReleaseSync(')
|
||||
code = HARNESS.replace('@ACQUIRE_SYNC@', acquire).replace('@RELEASE_SYNC@', release) + MAIN
|
||||
with tempfile.TemporaryDirectory(prefix='dxvk-keyed-mutex-') as directory:
|
||||
cpp = Path(directory) / 'keyed_mutex.cpp'
|
||||
exe = Path(directory) / 'keyed_mutex'
|
||||
cpp.write_text(code)
|
||||
subprocess.run([os.environ.get('HOST_CXX', 'c++'), '-std=c++17', '-Wall', '-Wextra', '-Wno-missing-field-initializers', str(cpp), '-o', str(exe)], check=True)
|
||||
return subprocess.run([str(exe)]).returncode
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(main())
|
||||
@@ -1,111 +0,0 @@
|
||||
diff --git a/src/dxvk/dxvk_image.cpp b/src/dxvk/dxvk_image.cpp
|
||||
index 3b5b739..0b0421e 100644
|
||||
--- a/src/dxvk/dxvk_image.cpp
|
||||
+++ b/src/dxvk/dxvk_image.cpp
|
||||
@@ -43,83 +43,89 @@ namespace dxvk {
|
||||
}
|
||||
|
||||
|
||||
DxvkKeyedMutex::~DxvkKeyedMutex() {
|
||||
if (m_kmtLocal) {
|
||||
D3DKMT_DESTROYKEYEDMUTEX destroy = { };
|
||||
destroy.hKeyedMutex = m_kmtLocal;
|
||||
D3DKMTDestroyKeyedMutex(&destroy);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
HRESULT DxvkKeyedMutex::AcquireSync(UINT64 key, DWORD milliseconds) {
|
||||
if (m_owned.load(std::memory_order_acquire))
|
||||
return DXGI_ERROR_INVALID_CALL;
|
||||
|
||||
LARGE_INTEGER timeout = { };
|
||||
D3DKMT_ACQUIREKEYEDMUTEX acquire = { };
|
||||
acquire.hKeyedMutex = m_kmtLocal;
|
||||
acquire.Key = key;
|
||||
- acquire.pTimeout = &timeout;
|
||||
- timeout.QuadPart = milliseconds * -10000;
|
||||
+ acquire.pTimeout = milliseconds == INFINITE ? nullptr : &timeout;
|
||||
+ timeout.QuadPart = int64_t(milliseconds) * -10000;
|
||||
|
||||
NTSTATUS status = D3DKMTAcquireKeyedMutex(&acquire);
|
||||
if (status == STATUS_TIMEOUT)
|
||||
return WAIT_TIMEOUT;
|
||||
if (status)
|
||||
return DXGI_ERROR_INVALID_CALL;
|
||||
|
||||
- VkSemaphore semaphore = m_fence->handle();
|
||||
- VkSemaphoreWaitInfo info = { VK_STRUCTURE_TYPE_SEMAPHORE_WAIT_INFO };
|
||||
- info.semaphoreCount = 1;
|
||||
- info.pSemaphores = &semaphore;
|
||||
- info.pValues = &acquire.FenceValue;
|
||||
+ if (m_fence) {
|
||||
+ VkSemaphore semaphore = m_fence->handle();
|
||||
+ VkSemaphoreWaitInfo info = { VK_STRUCTURE_TYPE_SEMAPHORE_WAIT_INFO };
|
||||
+ info.semaphoreCount = 1;
|
||||
+ info.pSemaphores = &semaphore;
|
||||
+ info.pValues = &acquire.FenceValue;
|
||||
|
||||
- if (m_vkd->vkWaitSemaphores(m_vkd->device(), &info, -1)) {
|
||||
- Logger::warn("DxvkKeyedMutex::AcquireSync: Failed to wait semaphore");
|
||||
- return DXGI_ERROR_INVALID_CALL;
|
||||
+ if (m_vkd->vkWaitSemaphores(m_vkd->device(), &info, -1)) {
|
||||
+ Logger::warn("DxvkKeyedMutex::AcquireSync: Failed to wait semaphore");
|
||||
+ return DXGI_ERROR_INVALID_CALL;
|
||||
+ }
|
||||
}
|
||||
|
||||
m_fenceValue = acquire.FenceValue;
|
||||
m_owned.store(true, std::memory_order_release);
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
|
||||
HRESULT DxvkKeyedMutex::ReleaseSync(UINT64 key) {
|
||||
if (!m_owned.load(std::memory_order_acquire))
|
||||
return DXGI_ERROR_INVALID_CALL;
|
||||
|
||||
- VkSemaphoreSignalInfo info = { VK_STRUCTURE_TYPE_SEMAPHORE_SIGNAL_INFO };
|
||||
- info.semaphore = m_fence->handle();
|
||||
- info.value = m_fenceValue + 1;
|
||||
+ uint64_t fenceValue = m_fenceValue;
|
||||
|
||||
- if (m_vkd->vkSignalSemaphore(m_vkd->device(), &info)) {
|
||||
- Logger::warn("D3D11DXGIKeyedMutex::ReleaseSync: Failed to signal semaphore");
|
||||
- return DXGI_ERROR_INVALID_CALL;
|
||||
+ if (m_fence) {
|
||||
+ VkSemaphoreSignalInfo info = { VK_STRUCTURE_TYPE_SEMAPHORE_SIGNAL_INFO };
|
||||
+ info.semaphore = m_fence->handle();
|
||||
+ info.value = ++fenceValue;
|
||||
+
|
||||
+ if (m_vkd->vkSignalSemaphore(m_vkd->device(), &info)) {
|
||||
+ Logger::warn("D3D11DXGIKeyedMutex::ReleaseSync: Failed to signal semaphore");
|
||||
+ return DXGI_ERROR_INVALID_CALL;
|
||||
+ }
|
||||
}
|
||||
|
||||
D3DKMT_RELEASEKEYEDMUTEX release = { };
|
||||
release.hKeyedMutex = m_kmtLocal;
|
||||
release.Key = key;
|
||||
- release.FenceValue = m_fenceValue + 1;
|
||||
+ release.FenceValue = fenceValue;
|
||||
|
||||
if (D3DKMTReleaseKeyedMutex(&release)) {
|
||||
Logger::warn("D3D11DXGIKeyedMutex::ReleaseSync: Failed to release mutex.");
|
||||
return DXGI_ERROR_INVALID_CALL;
|
||||
}
|
||||
|
||||
m_owned.store(false, std::memory_order_release);
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
|
||||
DxvkImage::DxvkImage(
|
||||
DxvkDevice* device,
|
||||
const DxvkImageCreateInfo& createInfo,
|
||||
DxvkMemoryAllocator& allocator,
|
||||
VkMemoryPropertyFlags memFlags)
|
||||
: DxvkPagedResource(allocator),
|
||||
m_vkd (device->vkd()),
|
||||
m_properties (memFlags),
|
||||
m_shaderStages (util::shaderStages(createInfo.stages)),
|
||||
@@ -1,101 +0,0 @@
|
||||
diff --git a/src/dxvk/dxvk_image.cpp b/src/dxvk/dxvk_image.cpp
|
||||
index 5bcb22a..e98547d 100644
|
||||
--- a/src/dxvk/dxvk_image.cpp
|
||||
+++ b/src/dxvk/dxvk_image.cpp
|
||||
@@ -54,75 +54,81 @@ namespace dxvk {
|
||||
|
||||
HRESULT DxvkKeyedMutex::AcquireSync(UINT64 key, DWORD milliseconds) {
|
||||
if (m_owned.load(std::memory_order_acquire))
|
||||
return DXGI_ERROR_INVALID_CALL;
|
||||
|
||||
LARGE_INTEGER timeout = { };
|
||||
timeout.QuadPart = int64_t(milliseconds) * -10000;
|
||||
|
||||
D3DKMT_ACQUIREKEYEDMUTEX acquire = { };
|
||||
acquire.hKeyedMutex = m_kmtLocal;
|
||||
acquire.Key = key;
|
||||
acquire.pTimeout = milliseconds == INFINITE ? nullptr : &timeout;
|
||||
|
||||
NTSTATUS status = D3DKMTAcquireKeyedMutex(&acquire);
|
||||
|
||||
if (status == STATUS_TIMEOUT)
|
||||
return WAIT_TIMEOUT;
|
||||
if (status)
|
||||
return DXGI_ERROR_INVALID_CALL;
|
||||
|
||||
- VkSemaphore semaphore = m_fence->handle();
|
||||
+ if (m_fence) {
|
||||
+ VkSemaphore semaphore = m_fence->handle();
|
||||
|
||||
- VkSemaphoreWaitInfo info = { VK_STRUCTURE_TYPE_SEMAPHORE_WAIT_INFO };
|
||||
- info.semaphoreCount = 1;
|
||||
- info.pSemaphores = &semaphore;
|
||||
- info.pValues = &acquire.FenceValue;
|
||||
+ VkSemaphoreWaitInfo info = { VK_STRUCTURE_TYPE_SEMAPHORE_WAIT_INFO };
|
||||
+ info.semaphoreCount = 1;
|
||||
+ info.pSemaphores = &semaphore;
|
||||
+ info.pValues = &acquire.FenceValue;
|
||||
|
||||
- if (m_vkd->vkWaitSemaphores(m_vkd->device(), &info, -1)) {
|
||||
- Logger::warn("DxvkKeyedMutex::AcquireSync: Failed to wait semaphore");
|
||||
- return DXGI_ERROR_INVALID_CALL;
|
||||
+ if (m_vkd->vkWaitSemaphores(m_vkd->device(), &info, -1)) {
|
||||
+ Logger::warn("DxvkKeyedMutex::AcquireSync: Failed to wait semaphore");
|
||||
+ return DXGI_ERROR_INVALID_CALL;
|
||||
+ }
|
||||
}
|
||||
|
||||
m_fenceValue = acquire.FenceValue;
|
||||
m_owned.store(true, std::memory_order_release);
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
|
||||
HRESULT DxvkKeyedMutex::ReleaseSync(UINT64 key) {
|
||||
if (!m_owned.load(std::memory_order_acquire))
|
||||
return DXGI_ERROR_INVALID_CALL;
|
||||
|
||||
- VkSemaphoreSignalInfo info = { VK_STRUCTURE_TYPE_SEMAPHORE_SIGNAL_INFO };
|
||||
- info.semaphore = m_fence->handle();
|
||||
- info.value = m_fenceValue + 1;
|
||||
+ uint64_t fenceValue = m_fenceValue;
|
||||
|
||||
- if (m_vkd->vkSignalSemaphore(m_vkd->device(), &info)) {
|
||||
- Logger::warn("D3D11DXGIKeyedMutex::ReleaseSync: Failed to signal semaphore");
|
||||
- return DXGI_ERROR_INVALID_CALL;
|
||||
+ if (m_fence) {
|
||||
+ VkSemaphoreSignalInfo info = { VK_STRUCTURE_TYPE_SEMAPHORE_SIGNAL_INFO };
|
||||
+ info.semaphore = m_fence->handle();
|
||||
+ info.value = ++fenceValue;
|
||||
+
|
||||
+ if (m_vkd->vkSignalSemaphore(m_vkd->device(), &info)) {
|
||||
+ Logger::warn("D3D11DXGIKeyedMutex::ReleaseSync: Failed to signal semaphore");
|
||||
+ return DXGI_ERROR_INVALID_CALL;
|
||||
+ }
|
||||
}
|
||||
|
||||
D3DKMT_RELEASEKEYEDMUTEX release = { };
|
||||
release.hKeyedMutex = m_kmtLocal;
|
||||
release.Key = key;
|
||||
- release.FenceValue = m_fenceValue + 1;
|
||||
+ release.FenceValue = fenceValue;
|
||||
|
||||
if (D3DKMTReleaseKeyedMutex(&release)) {
|
||||
Logger::warn("D3D11DXGIKeyedMutex::ReleaseSync: Failed to release mutex.");
|
||||
return DXGI_ERROR_INVALID_CALL;
|
||||
}
|
||||
|
||||
m_owned.store(false, std::memory_order_release);
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
|
||||
DxvkImage::DxvkImage(
|
||||
DxvkDevice* device,
|
||||
const DxvkImageCreateInfo& createInfo,
|
||||
DxvkMemoryAllocator& allocator,
|
||||
VkMemoryPropertyFlags memFlags)
|
||||
: DxvkPagedResource(allocator),
|
||||
m_vkd (device->vkd()),
|
||||
m_properties (memFlags),
|
||||
m_shaderStages (util::shaderStages(createInfo.stages)),
|
||||
@@ -1,66 +0,0 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
PATCHES = {
|
||||
'pinned component': ROOT / 'tools/dxvk/patches/0005-keyed-mutex-without-fence.patch',
|
||||
'DroidDeck-Proton': ROOT / 'tools/dxvk/proton/keyed-mutex-without-fence.patch',
|
||||
}
|
||||
CHECK = ROOT / 'tools/dxvk/check_keyed_mutex_fence.py'
|
||||
TARGET = 'src/dxvk/dxvk_image.cpp'
|
||||
|
||||
|
||||
def pre_image(patch):
|
||||
lines = []
|
||||
inside = False
|
||||
for line in patch.read_text().splitlines():
|
||||
if line.startswith('@@'):
|
||||
inside = True
|
||||
lines.append('')
|
||||
elif inside and line[:1] in (' ', '-') and not line.startswith('---'):
|
||||
lines.append(line[1:])
|
||||
return '\n'.join(lines) + '\n'
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which(os.environ.get('HOST_CXX', 'c++')), 'needs a native C++ compiler')
|
||||
class KeyedMutexFenceTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
temporary = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(temporary.cleanup)
|
||||
self.tree = Path(temporary.name)
|
||||
|
||||
def run_check(self, path):
|
||||
return subprocess.run(['python3', '-I', str(CHECK), str(path)],
|
||||
capture_output=True, text=True, timeout=120)
|
||||
|
||||
def test_patched_source_passes(self):
|
||||
for name, patch in PATCHES.items():
|
||||
with self.subTest(name):
|
||||
tree = self.tree / patch.stem
|
||||
(tree / 'src/dxvk').mkdir(parents=True)
|
||||
target = tree / TARGET
|
||||
target.write_text(pre_image(patch))
|
||||
subprocess.run(['git', 'apply', '--unsafe-paths', '--directory', str(tree), str(patch)],
|
||||
check=True, cwd=tree)
|
||||
result = self.run_check(target)
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
self.assertIn('PASS', result.stdout)
|
||||
|
||||
def test_unpatched_source_is_rejected(self):
|
||||
for name, patch in PATCHES.items():
|
||||
with self.subTest(name):
|
||||
tree = self.tree / patch.stem
|
||||
(tree / 'src/dxvk').mkdir(parents=True)
|
||||
target = tree / TARGET
|
||||
target.write_text(pre_image(patch))
|
||||
result = self.run_check(target)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn('FAIL', result.stderr)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user