mirror of
https://github.com/tangerineturtle1/NX2navi.git
synced 2026-11-20 23:19:57 -04:00
Import the base tree (MIT, see LICENSE)
This commit is contained in:
21
tools/vendor/macnativegames/LICENSE
vendored
Normal file
21
tools/vendor/macnativegames/LICENSE
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 MacNativeGames contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
14
tools/vendor/macnativegames/README.md
vendored
Normal file
14
tools/vendor/macnativegames/README.md
vendored
Normal file
@@ -0,0 +1,14 @@
|
||||
# MacNativeGames extraction scripts
|
||||
|
||||
Unmodified copies from https://github.com/ly05010419/MacNativeGames at `b75be8cfa704df3701e86130c8ced268e79d6b11`, MIT (see `LICENSE`).
|
||||
|
||||
| File | Upstream path |
|
||||
|---|---|
|
||||
| `extract_exefs.py` | `games/<game>/scripts/extract_exefs.py` |
|
||||
| `extract_romfs.py` | `games/<game>/scripts/extract_romfs.py` |
|
||||
| `extract_update_romfs.py` | `games/<game>/scripts/extract_update_romfs.py` |
|
||||
| `extract_shared_fonts.py` | `games/<game>/scripts/extract_shared_fonts.py` |
|
||||
|
||||
`tools/data/expected-v*.json` come from `games/<game>/assets/` at the same commit.
|
||||
|
||||
Keep these files byte-identical to upstream so they can be updated by copying. Windows-specific behaviour lives in `tools/extract.py` and `tools/extract_fonts.py`.
|
||||
250
tools/vendor/macnativegames/extract_exefs.py
vendored
Normal file
250
tools/vendor/macnativegames/extract_exefs.py
vendored
Normal file
@@ -0,0 +1,250 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Read an XCI or NSP in place; extract and verify its base or explicitly selected update Program ExeFS.
|
||||
|
||||
Supports NCA3, key-area or common-ticket AES-CTR, and hierarchical SHA-256 PFS0.
|
||||
Keys stay in memory. No RomFS extraction, executable launch, or network calls.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import struct
|
||||
import io
|
||||
from pathlib import Path
|
||||
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
|
||||
|
||||
|
||||
def require(condition, message):
|
||||
if not condition:
|
||||
raise ValueError(message)
|
||||
|
||||
|
||||
def decrypt(key, mode, data):
|
||||
ctx = Cipher(algorithms.AES(key), mode).decryptor()
|
||||
return ctx.update(data) + ctx.finalize()
|
||||
|
||||
|
||||
def read_at(f, offset, length):
|
||||
require(0 <= offset and 0 <= length <= 512 * 1024 * 1024, 'Invalid/big read')
|
||||
f.seek(offset)
|
||||
data = f.read(length)
|
||||
require(len(data) == length, 'Truncated input')
|
||||
return data
|
||||
|
||||
|
||||
def hfs(f, offset, bound):
|
||||
return partition_entries(f, offset, bound, b'HFS0', 64)
|
||||
|
||||
|
||||
def partition_entries(f, offset, bound, magic=b'PFS0', stride=24):
|
||||
"""Read a bounded PFS0/HFS0 table without loading its file payloads."""
|
||||
require(bound >= 16, 'Truncated partition header')
|
||||
hdr = read_at(f, offset, 16)
|
||||
require(hdr[:4] == magic, f'Expected {magic.decode()}')
|
||||
count, strings_size = struct.unpack_from('<II', hdr, 4)
|
||||
require(count <= 4096 and strings_size <= 1024 * 1024, 'Invalid partition table')
|
||||
size = 16 + count * stride + strings_size
|
||||
require(size <= bound, 'Partition table out of bounds')
|
||||
raw = read_at(f, offset, size)
|
||||
strings = raw[16 + count * stride:]
|
||||
entries = []
|
||||
names = set()
|
||||
for i in range(count):
|
||||
off, length, nameoff = struct.unpack_from('<QQI', raw, 16 + i * stride)
|
||||
require(nameoff < len(strings), 'Invalid partition filename offset')
|
||||
end = strings.find(b'\0', nameoff)
|
||||
require(end >= 0, 'Unterminated partition filename')
|
||||
name = strings[nameoff:end].decode('utf-8')
|
||||
require(name not in ('', '.', '..') and '/' not in name and '\\' not in name, 'Unsafe partition filename')
|
||||
require(name not in names, 'Duplicate partition filename')
|
||||
names.add(name)
|
||||
require(size + off + length <= bound, 'Partition entry out of bounds')
|
||||
entries.append((name, offset + size + off, length))
|
||||
end = offset + size
|
||||
for _, start, length in sorted(entries, key=lambda e: e[1]):
|
||||
require(start >= end, 'Overlapping partition entries')
|
||||
end = start + length
|
||||
return entries
|
||||
|
||||
|
||||
def container_entries(f, size):
|
||||
if read_at(f, 0, 4) == b'PFS0':
|
||||
return 'nsp', partition_entries(f, 0, size)
|
||||
require(size >= 0x138 and read_at(f, 0x100, 4) == b'HEAD', 'Expected an XCI or NSP (PFS0) game file')
|
||||
root = struct.unpack('<Q', read_at(f, 0x130, 8))[0]
|
||||
partitions = hfs(f, root, size - root)
|
||||
secure = [e for e in partitions if e[0] == 'secure']
|
||||
require(len(secure) == 1, 'Expected one XCI secure partition')
|
||||
return 'xci', hfs(f, secure[0][1], secure[0][2])
|
||||
|
||||
|
||||
def load_keys(path):
|
||||
keys = {}
|
||||
for number, line in enumerate(path.read_text().splitlines(), 1):
|
||||
line = line.split('#', 1)[0].strip()
|
||||
if '=' in line:
|
||||
name, value = line.split('=', 1)
|
||||
try:
|
||||
keys[name.strip().lower()] = bytes.fromhex(value.strip())
|
||||
except ValueError:
|
||||
raise ValueError(f'Invalid key encoding at line {number}') from None
|
||||
return keys
|
||||
|
||||
|
||||
def common_tickets(f, entries):
|
||||
"""Keep encrypted title keys in memory only, as nxnative's NSP importer does.
|
||||
|
||||
Ticket offsets below are relative to the signed body; accept the standard RSA/ECDSA layouts.
|
||||
A personalized ticket cannot provide a common title key and is never treated as one.
|
||||
"""
|
||||
tickets = {}
|
||||
bodies = {0x10000: 0x240, 0x10001: 0x140, 0x10002: 0x80,
|
||||
0x10003: 0x240, 0x10004: 0x140, 0x10005: 0x80}
|
||||
for name, offset, size in entries:
|
||||
if not name.lower().endswith('.tik'):
|
||||
continue
|
||||
require(size >= 4, 'Truncated NSP ticket')
|
||||
# Switch ticket signature type is little-endian: RSA2048/SHA256 = 04 00 01 00.
|
||||
sig = struct.unpack('<I', read_at(f, offset, 4))[0]
|
||||
require(sig in bodies, 'Unsupported NSP ticket signature type')
|
||||
body = bodies[sig]
|
||||
require(size >= body + 0x180, 'Truncated NSP ticket body')
|
||||
data = read_at(f, offset + body, 0x180)
|
||||
require(data[0x141] == 0, 'Personalized NSP tickets are unsupported; a common ticket is required')
|
||||
rights, key = data[0x160:0x170], data[0x40:0x50]
|
||||
require(rights not in tickets or tickets[rights] == key, 'Conflicting NSP tickets')
|
||||
tickets[rights] = key
|
||||
return tickets
|
||||
|
||||
|
||||
def read_nca_header(f, offset, size, keys):
|
||||
require(size >= 0xc00, 'Truncated NCA header')
|
||||
require('header_key' in keys, 'Missing header_key in prod.keys')
|
||||
raw = read_at(f, offset, 0xc00)
|
||||
hdr = b''.join(decrypt(keys['header_key'], modes.XTS(i.to_bytes(16, 'big')),
|
||||
raw[i * 512:(i + 1) * 512]) for i in range(6))
|
||||
require(hdr[0x200:0x204] == b'NCA3', 'Expected NCA3 (check prod.keys and the game file)')
|
||||
require(struct.unpack_from('<Q', hdr, 0x208)[0] == size, 'NCA size does not match container entry')
|
||||
for i in range(4):
|
||||
start, end = struct.unpack_from('<II', hdr, 0x240 + i * 16)
|
||||
require((start == end == 0) or 0xc00 <= start * 512 < end * 512 <= size, 'NCA section out of bounds')
|
||||
return hdr
|
||||
|
||||
|
||||
def nca_ctr_key(hdr, keys, tickets):
|
||||
generation = max(max(hdr[0x206], hdr[0x220]) - 1, 0)
|
||||
rights = hdr[0x230:0x240]
|
||||
if rights != bytes(16):
|
||||
require(rights in tickets, 'Missing common ticket for rights-managed NCA in the NSP')
|
||||
keyname = f'titlekek_{generation:02x}'
|
||||
require(keyname in keys, f'Missing {keyname} in prod.keys')
|
||||
return decrypt(keys[keyname], modes.ECB(), tickets[rights])
|
||||
require(hdr[0x207] < 3, 'Unsupported NCA key area')
|
||||
area = ('application', 'ocean', 'system')[hdr[0x207]]
|
||||
keyname = f'key_area_key_{area}_{generation:02x}'
|
||||
require(keyname in keys, f'Missing {keyname} in prod.keys')
|
||||
return decrypt(keys[keyname], modes.ECB(), hdr[0x300:0x340])[32:48]
|
||||
|
||||
|
||||
def nca_inventory(f, entries, keys):
|
||||
records = []
|
||||
for name, offset, length in entries:
|
||||
if not name.lower().endswith('.nca'):
|
||||
continue
|
||||
hdr = read_nca_header(f, offset, length, keys)
|
||||
record = dict(name=name, nca_offset=offset, size=length, content_type=hdr[0x205],
|
||||
title_id=f'{struct.unpack_from("<Q", hdr, 0x210)[0]:016X}')
|
||||
records.append((record, hdr))
|
||||
return records
|
||||
|
||||
|
||||
def program_nca(records, update=False):
|
||||
if update:
|
||||
programs = [(r, h) for r, h in records if r["content_type"] == 0]
|
||||
require(len(programs) == 1, "Expected one update Program NCA; combined packages are unsupported")
|
||||
record, hdr = programs[0]
|
||||
require(record["title_id"] == "0100F2C0115B6000", "Update belongs to another game")
|
||||
require(any(hdr[0x400 + i*512 + 4] == 4 for i in range(4)), "Expected a BKTR update, not a base game")
|
||||
require(all(r["title_id"] in ("0100F2C0115B6000", "0100F2C0115B6800") for r, _ in records), "Mixed-title update package")
|
||||
return record, hdr
|
||||
# Update Program NCAs can retain the base title ID; their Meta NCA carries the update ID.
|
||||
metadata = [r for r, _ in records if r['content_type'] == 1]
|
||||
require(len(metadata) <= 1 and all(r['title_id'] == '0100F2C0115B6000' for r in metadata),
|
||||
'Expected base game metadata; updates, DLC and combined packages are unsupported')
|
||||
programs = [(r, h) for r, h in records if r['content_type'] == 0]
|
||||
require(len(programs) == 1, 'Expected one base Program NCA; updates, DLC and combined packages are unsupported')
|
||||
record, hdr = programs[0]
|
||||
require(record['title_id'] == '0100F2C0115B6000',
|
||||
'Expected Ocarina of Time base game 1.0.0; updates, DLC and other games are unsupported')
|
||||
return record, hdr
|
||||
|
||||
|
||||
def record_offset(record):
|
||||
# Read manifests produced before NSP support too.
|
||||
return record['nca_offset'] if 'nca_offset' in record else record['xci_offset']
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('game', type=Path, help='base game 1.0.0 (.xci or .nsp)')
|
||||
parser.add_argument('--keys', required=True, type=Path)
|
||||
parser.add_argument('--update', action='store_true', help='extract update code; caller must verify supported version hashes')
|
||||
parser.add_argument('--output', required=True, type=Path)
|
||||
args = parser.parse_args()
|
||||
require(not args.output.exists(), 'Output already exists; choose a new directory')
|
||||
keys = load_keys(args.keys)
|
||||
with args.game.open('rb') as f:
|
||||
kind, entries = container_entries(f, args.game.stat().st_size)
|
||||
tickets = common_tickets(f, entries)
|
||||
records = nca_inventory(f, entries, keys)
|
||||
record, hdr = program_nca(records, update=args.update)
|
||||
ctr_key = nca_ctr_key(hdr, keys, tickets)
|
||||
for i in range(4):
|
||||
start, end = struct.unpack_from('<II', hdr, 0x240 + 16 * i)
|
||||
if not start:
|
||||
continue
|
||||
fs = hdr[0x400 + 512 * i:0x600 + 512 * i]
|
||||
require(hashlib.sha256(fs).digest() == hdr[0x280 + 32 * i:0x2A0 + 32 * i], 'FS header hash mismatch')
|
||||
if fs[2:4] != b'\x01\x02':
|
||||
continue
|
||||
require(fs[4] == 3, 'Only AES-CTR ExeFS is supported')
|
||||
blocksize, levels = struct.unpack_from('<II', fs, 0x28)
|
||||
hashoff, hashsize, pfsoff, pfssize = struct.unpack_from('<QQQQ', fs, 0x30)
|
||||
secstart, secsize = start * 512, (end - start) * 512
|
||||
require(levels == 2 and blocksize > 0 and pfssize <= 512 * 1024 * 1024, 'Unsupported ExeFS hash layout')
|
||||
|
||||
def section_read(relative, size):
|
||||
require(relative >= 0 and relative + size <= secsize, 'Section read out of bounds')
|
||||
absolute = secstart + relative
|
||||
aligned = absolute & ~15
|
||||
iv = fs[0x140:0x148][::-1] + (aligned // 16).to_bytes(8, 'big')
|
||||
data = read_at(f, record_offset(record) + aligned, size + absolute - aligned)
|
||||
return decrypt(ctr_key, modes.CTR(iv), data)[absolute - aligned:]
|
||||
|
||||
hashes = section_read(hashoff, hashsize)
|
||||
require(hashlib.sha256(hashes).digest() == fs[8:40], 'ExeFS hash-table mismatch')
|
||||
pfs = section_read(pfsoff, pfssize)
|
||||
for index, pos in enumerate(range(0, pfssize, blocksize)):
|
||||
expected = hashes[index * 32:(index + 1) * 32]
|
||||
require(hashlib.sha256(pfs[pos:pos + blocksize]).digest() == expected,
|
||||
f'ExeFS block hash mismatch: {index}')
|
||||
files = [(name, pfs[off:off + size]) for name, off, size in
|
||||
partition_entries(io.BytesIO(pfs), 0, len(pfs))]
|
||||
require(any(name == 'main.npdm' for name, _ in files), 'PFS0 is not ExeFS')
|
||||
args.output.mkdir(parents=True)
|
||||
extracted = []
|
||||
for name, data in files:
|
||||
(args.output / name).write_bytes(data)
|
||||
extracted.append({'name': name, 'size': len(data), 'sha256': hashlib.sha256(data).hexdigest()})
|
||||
manifest = {'source': str(args.game.resolve()), 'source_size': args.game.stat().st_size,
|
||||
'source_mtime_ns': args.game.stat().st_mtime_ns, 'container': kind,
|
||||
'nca_inventory': [r for r, _ in records], 'program': record, 'section_index': i,
|
||||
'integrity': 'FS header, ExeFS hash table, and every ExeFS data block verified; RSA signatures not checked',
|
||||
'files': extracted}
|
||||
(args.output.parent / 'extraction-manifest.json').write_text(json.dumps(manifest, indent=2) + '\n')
|
||||
print(json.dumps({'integrity': manifest['integrity'], 'files': extracted}, indent=2))
|
||||
return
|
||||
raise ValueError('No ExeFS section found')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
83
tools/vendor/macnativegames/extract_romfs.py
vendored
Normal file
83
tools/vendor/macnativegames/extract_romfs.py
vendored
Normal file
@@ -0,0 +1,83 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Verify all six IVFC levels, stream a local RomFS image, and index its files."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import struct
|
||||
from pathlib import Path
|
||||
from cryptography.hazmat.primitives.ciphers import modes
|
||||
from extract_exefs import (decrypt, read_at, require, load_keys, container_entries, common_tickets,
|
||||
nca_inventory, program_nca, nca_ctr_key, record_offset)
|
||||
|
||||
def main():
|
||||
parser=argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--keys',type=Path,required=True)
|
||||
parser.add_argument('--manifest',type=Path,default=Path('extracted/v0/extraction-manifest.json'))
|
||||
parser.add_argument('--output',type=Path,default=Path('extracted/v0/romfs'))
|
||||
args=parser.parse_args(); require(not args.output.exists(),'Output already exists')
|
||||
manifest=json.loads(args.manifest.read_text());record=manifest['program'];keys=load_keys(args.keys)
|
||||
source=Path(manifest['source']);require(source.stat().st_size==manifest['source_size'],'Source size changed')
|
||||
with source.open('rb') as f:
|
||||
_,entries=container_entries(f,source.stat().st_size)
|
||||
actual,hdr=program_nca(nca_inventory(f,entries,keys))
|
||||
require(actual['name']==record['name'] and actual['size']==record['size'] and
|
||||
record_offset(actual)==record_offset(record),'Source Program NCA changed; extract ExeFS again')
|
||||
ctr_key=nca_ctr_key(hdr,keys,common_tickets(f,entries))
|
||||
for i in range(4):
|
||||
start,end=struct.unpack_from('<II',hdr,0x240+i*16)
|
||||
if not start:continue
|
||||
fs=hdr[0x400+512*i:0x600+512*i]
|
||||
require(hashlib.sha256(fs).digest()==hdr[0x280+32*i:0x2a0+32*i],'FS header hash')
|
||||
if fs[2:5]!=bytes([0,3,3]):continue
|
||||
require(fs[8:12]==b'IVFC' and struct.unpack_from('<III',fs,12)==(0x20000,32,7),'Unsupported IVFC layout')
|
||||
levels=[struct.unpack_from('<QQII',fs,0x18+j*24) for j in range(6)]
|
||||
def read(relative,size):
|
||||
require(0<=relative<=relative+size<=(end-start)*512,'Section bounds')
|
||||
absolute=start*512+relative;aligned=absolute&~15;skip=absolute-aligned
|
||||
iv=fs[0x140:0x148][::-1]+(aligned//16).to_bytes(8,'big')
|
||||
return decrypt(ctr_key,modes.CTR(iv),read_at(f,record_offset(record)+aligned,size+skip))[skip:]
|
||||
args.output.mkdir(parents=True);image_path=args.output/'romfs.bin';digest=hashlib.sha256();counts=[]
|
||||
parent=fs[0xc8:0xe8]
|
||||
with image_path.open('wb') as image:
|
||||
for level,(offset,size,power,reserved) in enumerate(levels):
|
||||
require(12<=power<=24 and reserved==0,'IVFC block size');block=1<<power
|
||||
require(len(parent)>=(size+block-1)//block*32,'IVFC parent size')
|
||||
captured=bytearray() if level<5 else None
|
||||
index=0
|
||||
for pos in range(0,size,8*1024*1024):
|
||||
chunk=read(offset+pos,min(8*1024*1024,size-pos))
|
||||
for j in range(0,len(chunk),block):
|
||||
payload=chunk[j:j+block]
|
||||
require(hashlib.sha256(payload+bytes(block-len(payload))).digest()==parent[index*32:index*32+32],f'IVFC level {level} block {index} failed')
|
||||
index+=1
|
||||
if captured is not None:captured.extend(chunk)
|
||||
else:image.write(chunk);digest.update(chunk)
|
||||
counts.append(index)
|
||||
if captured is not None:parent=bytes(captured)
|
||||
print(f'IVFC level {level}: {index} blocks verified',flush=True)
|
||||
files=index_romfs(image_path)
|
||||
report=dict(status='pass',source_size=source.stat().st_size,program=record['name'],section=i,ivfc_blocks=counts,romfs_size=levels[-1][1],romfs_sha256=digest.hexdigest(),files=files,integrity='FS header and all six IVFC levels verified; RSA signature not checked')
|
||||
(args.output/'index.json').write_text(json.dumps(report,indent=2)+'\n')
|
||||
print(json.dumps(dict(status='pass',file_count=len(files),size=levels[-1][1],sha256=digest.hexdigest())),flush=True);return
|
||||
raise ValueError('No supported RomFS found')
|
||||
|
||||
def index_romfs(path):
|
||||
with path.open('rb') as f:
|
||||
h=struct.unpack('<10Q',read_at(f,0,80));require(h[0]==80,'RomFS header');length=path.stat().st_size
|
||||
for off,size in [(h[1],h[2]),(h[3],h[4]),(h[5],h[6]),(h[7],h[8])]:require(off+size<=length,'RomFS table bounds')
|
||||
dirs=read_at(f,h[3],h[4]);entries=read_at(f,h[7],h[8]);files=[];seen_dirs=set();seen_files=set();paths=set()
|
||||
def name(table,off,n):
|
||||
require(off+n<=len(table),'Name bounds');s=table[off:off+n].decode('utf-8');require(s not in ['.','..'] and '/' not in s and '\\' not in s and '\0' not in s,'Unsafe path');return s
|
||||
todo=[(0,'')]
|
||||
while todo:
|
||||
off,parent=todo.pop();require(off not in seen_dirs and off+24<=len(dirs),'Invalid/cyclic directory');seen_dirs.add(off)
|
||||
p,sibling,child,file,hash_next,n=struct.unpack_from('<6I',dirs,off);part=name(dirs,off+24,n);prefix=parent+part+'/' if part else parent
|
||||
if sibling!=0xffffffff:todo.append((sibling,parent))
|
||||
if child!=0xffffffff:todo.append((child,prefix))
|
||||
while file!=0xffffffff:
|
||||
require(file not in seen_files and file+32<=len(entries),'Invalid/cyclic file');seen_files.add(file)
|
||||
p,next_file,data,size,hash_next,n=struct.unpack_from('<IIQQII',entries,file);part=name(entries,file+32,n);require(part!='','Empty file name');filename=prefix+part
|
||||
require(filename not in paths and h[9]+data+size<=length,'Duplicate/out-of-bounds file');paths.add(filename)
|
||||
files.append(dict(path=filename,offset=h[9]+data,size=size));file=next_file
|
||||
return sorted(files,key=lambda item:item['path'])
|
||||
if __name__=='__main__':main()
|
||||
202
tools/vendor/macnativegames/extract_shared_fonts.py
vendored
Normal file
202
tools/vendor/macnativegames/extract_shared_fonts.py
vendored
Normal file
@@ -0,0 +1,202 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Extract the system shared fonts (BFTTF) from firmware data NCAs, verifying the NCA FS header,
|
||||
all six IVFC levels and each BFTTF header. Fonts stay in the BFTTF form that hardware places in
|
||||
shared memory; only local copies are written, never printed.
|
||||
|
||||
Sources: --xci <game card image> reads the data NCAs from the card's system update partition (a game card carries the
|
||||
system update it needs, shared fonts included); --firmware reads an unpacked NCA directory. The older --inventory
|
||||
mode lists the NCAs of an installed firmware."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import struct
|
||||
from pathlib import Path
|
||||
from cryptography.hazmat.primitives.ciphers import modes
|
||||
from extract_exefs import decrypt, read_at, require, load_keys, hfs, nca_ctr_key
|
||||
from extract_romfs import index_romfs
|
||||
|
||||
FIRMWARE = Path.home() / 'Library/Application Support/Ryujinx/bis/system/Contents/registered'
|
||||
# nn::pl::SharedFontType -> (system data title, BFTTF file name)
|
||||
FONTS = [
|
||||
(0, 'standard', '0100000000000811', 'nintendo_udsg-r_std_003.bfttf'),
|
||||
(1, 'chinese-simplified', '0100000000000814', 'nintendo_udsg-r_org_zh-cn_003.bfttf'),
|
||||
(2, 'chinese-simplified-extension', '0100000000000814', 'nintendo_udsg-r_ext_zh-cn_003.bfttf'),
|
||||
(3, 'chinese-traditional', '0100000000000813', 'nintendo_udjxh-db_zh-tw_003.bfttf'),
|
||||
(4, 'korean', '0100000000000812', 'nintendo_udsg-r_ko_003.bfttf'),
|
||||
(5, 'nintendo-extension', '0100000000000810', 'nintendo_ext_003.bfttf'),
|
||||
]
|
||||
BFTTF_DECODED_MAGIC = 0x7f9a0218
|
||||
|
||||
|
||||
class Slice:
|
||||
"""A file seen from a base offset: an NCA inside a game card image reads like a standalone NCA file."""
|
||||
def __init__(self, path, base=0):
|
||||
self.f, self.base = path.open('rb'), base
|
||||
|
||||
def seek(self, offset, whence=0):
|
||||
return self.f.seek(self.base + offset if whence == 0 else offset, whence) - self.base
|
||||
|
||||
def read(self, size=-1):
|
||||
return self.f.read(size)
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc):
|
||||
self.f.close()
|
||||
|
||||
|
||||
def hfs0_entries(f, offset):
|
||||
"""(name, absolute offset, size) of each file in the HFS0 partition at offset."""
|
||||
length = f.seek(0, 2)
|
||||
return hfs(f, offset, length - offset)
|
||||
|
||||
|
||||
def nca_header(f, keys):
|
||||
raw = read_at(f, 0, 0xc00)
|
||||
return b''.join(decrypt(keys['header_key'], modes.XTS(i.to_bytes(16, 'big')), raw[i * 512:(i + 1) * 512]) for i in range(6))
|
||||
|
||||
|
||||
def xci_data_ncas(xci, keys):
|
||||
"""title ID -> offset of each data NCA in the card's system update partition."""
|
||||
found = {}
|
||||
with xci.open('rb') as f:
|
||||
require(read_at(f, 0x100, 4) == b'HEAD', 'Not a game card image (XCI)')
|
||||
root = struct.unpack('<Q', read_at(f, 0x130, 8))[0]
|
||||
update = [e for e in hfs0_entries(f, root) if e[0] == 'update']
|
||||
require(update, 'The game card image has no system update partition')
|
||||
for name, offset, size in hfs0_entries(f, update[0][1]):
|
||||
if not name.endswith('.nca') or name.endswith('.cnmt.nca'):
|
||||
continue
|
||||
with Slice(xci, offset) as nca:
|
||||
hdr = nca_header(nca, keys)
|
||||
if hdr[0x200:0x204] == b'NCA3' and hdr[0x205] == 4: # content type 4: data
|
||||
found[f'{struct.unpack_from("<Q", hdr, 0x210)[0]:016x}'] = offset
|
||||
return found
|
||||
|
||||
|
||||
def nca_romfs(source, keys, image_path, tickets=None):
|
||||
"""Write the verified RomFS image of a data NCA (a Path, or a Slice of a game card image) to image_path."""
|
||||
with (source if isinstance(source, Slice) else Slice(source)) as f:
|
||||
raw = read_at(f, 0, 0xc00)
|
||||
hdr = b''.join(decrypt(keys['header_key'], modes.XTS(i.to_bytes(16, 'big')), raw[i * 512:(i + 1) * 512]) for i in range(6))
|
||||
require(hdr[0x200:0x204] == b'NCA3', f'Unsupported NCA at {f.base:#x}')
|
||||
ctr_key = nca_ctr_key(hdr, keys, tickets or {})
|
||||
for i in range(4):
|
||||
start, end = struct.unpack_from('<II', hdr, 0x240 + i * 16)
|
||||
if not start:
|
||||
continue
|
||||
fs = hdr[0x400 + 512 * i:0x600 + 512 * i]
|
||||
require(hashlib.sha256(fs).digest() == hdr[0x280 + 32 * i:0x2a0 + 32 * i], 'FS header hash')
|
||||
if fs[2:5] != bytes([0, 3, 3]):
|
||||
continue
|
||||
require(fs[8:12] == b'IVFC' and struct.unpack_from('<III', fs, 12) == (0x20000, 32, 7), 'Unsupported IVFC layout')
|
||||
levels = [struct.unpack_from('<QQII', fs, 0x18 + j * 24) for j in range(6)]
|
||||
|
||||
def read(relative, size):
|
||||
require(0 <= relative <= relative + size <= (end - start) * 512, 'Section bounds')
|
||||
absolute = start * 512 + relative
|
||||
aligned = absolute & ~15
|
||||
skip = absolute - aligned
|
||||
iv = fs[0x140:0x148][::-1] + (aligned // 16).to_bytes(8, 'big')
|
||||
return decrypt(ctr_key, modes.CTR(iv), read_at(f, aligned, size + skip))[skip:]
|
||||
|
||||
parent = fs[0xc8:0xe8]
|
||||
image = bytearray()
|
||||
for level, (offset, size, power, reserved) in enumerate(levels):
|
||||
require(12 <= power <= 24 and reserved == 0, 'IVFC block size')
|
||||
block = 1 << power
|
||||
data = read(offset, size)
|
||||
for index, j in enumerate(range(0, len(data), block)):
|
||||
payload = data[j:j + block]
|
||||
require(hashlib.sha256(payload + bytes(block - len(payload))).digest() == parent[index * 32:index * 32 + 32], f'IVFC level {level} block {index}')
|
||||
parent = data
|
||||
if level == 5:
|
||||
image = data
|
||||
image_path.write_bytes(image)
|
||||
return
|
||||
raise ValueError(f'No RomFS in the NCA at {f.base:#x}')
|
||||
|
||||
|
||||
def bfttf_size(data):
|
||||
"""BFTTF: big-endian words XORed with key = word0 ^ 0x7f9a0218; word1 = font size; payload follows."""
|
||||
magic, size = struct.unpack_from('>II', data, 0)
|
||||
key = magic ^ BFTTF_DECODED_MAGIC
|
||||
decoded = size ^ key
|
||||
require(decoded + 8 == len(data), 'BFTTF size does not match file')
|
||||
first = struct.unpack_from('>I', data, 8)[0] ^ key
|
||||
require(first in (0x00010000, 0x4f54544f), 'BFTTF payload is not a TrueType/OpenType font')
|
||||
return decoded
|
||||
|
||||
|
||||
def firmware_data_ncas(folder, keys):
|
||||
"""Accept an unpacked firmware directory or an installed registered/ directory."""
|
||||
require(folder.is_dir(), 'Firmware must be a directory containing NCA files')
|
||||
wanted = {title for _, _, title, _ in FONTS}
|
||||
found = {}
|
||||
for path in sorted(folder.iterdir()):
|
||||
if path.is_dir():
|
||||
path = path / '00'
|
||||
if not path.is_file() or (path.name != '00' and path.suffix.lower() != '.nca'):
|
||||
continue
|
||||
with path.open('rb') as f:
|
||||
hdr = nca_header(f, keys)
|
||||
require(hdr[0x200:0x204] == b'NCA3', 'Invalid firmware NCA header (check prod.keys)')
|
||||
title = f'{struct.unpack_from("<Q", hdr, 0x210)[0]:016x}'
|
||||
if hdr[0x205] == 4 and title in wanted:
|
||||
require(title not in found, f'Duplicate shared-font title {title} in firmware')
|
||||
found[title] = path
|
||||
require(wanted <= found.keys(), 'Firmware is missing shared-font data NCAs: ' + ', '.join(sorted(wanted - found.keys())))
|
||||
return found
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--keys', type=Path, required=True)
|
||||
sources = parser.add_mutually_exclusive_group()
|
||||
sources.add_argument('--xci', type=Path, help='game card image: take the fonts from its system update partition')
|
||||
sources.add_argument('--firmware', type=Path, help='unpacked firmware NCA directory (for NSP builds)')
|
||||
parser.add_argument('--inventory', type=Path, default=Path('analysis/firmware-inventory.json'))
|
||||
parser.add_argument('--output', type=Path, default=Path('extracted/firmware/shared-fonts'))
|
||||
args = parser.parse_args()
|
||||
require(not args.output.exists(), 'Output already exists')
|
||||
keys = load_keys(args.keys)
|
||||
if args.xci:
|
||||
card = xci_data_ncas(args.xci, keys)
|
||||
missing = sorted({t for _, _, t, _ in FONTS} - card.keys())
|
||||
require(not missing, f'Shared font data missing from the card update partition: {", ".join(missing)}')
|
||||
source = lambda title: Slice(args.xci, card[title])
|
||||
elif args.firmware:
|
||||
firmware = firmware_data_ncas(args.firmware, keys)
|
||||
source = lambda title: firmware[title]
|
||||
else:
|
||||
rows = json.loads(args.inventory.read_text())['rows']
|
||||
data_nca = {r['title_id']: r['file'] for r in rows if r['content_type'] == 4}
|
||||
source = lambda title: (FIRMWARE / data_nca[title] / '00') if (FIRMWARE / data_nca[title]).is_dir() else FIRMWARE / data_nca[title]
|
||||
args.output.mkdir(parents=True)
|
||||
images = {}
|
||||
report = []
|
||||
for kind, name, title, filename in FONTS:
|
||||
if title not in images:
|
||||
image_path = args.output / f'{title}.romfs'
|
||||
nca_romfs(source(title), keys, image_path)
|
||||
images[title] = (image_path, {e['path']: e for e in index_romfs(image_path)})
|
||||
image_path, entries = images[title]
|
||||
require(filename in entries, f'{filename} missing in {title}')
|
||||
e = entries[filename]
|
||||
with image_path.open('rb') as f:
|
||||
data = read_at(f, e['offset'], e['size'])
|
||||
size = bfttf_size(data)
|
||||
out = args.output / f'{kind}-{name}.bfttf'
|
||||
out.write_bytes(data)
|
||||
report.append(dict(type=kind, name=name, title_id=title, file=filename, bfttf_bytes=len(data), font_bytes=size,
|
||||
sha256=hashlib.sha256(data).hexdigest()))
|
||||
for image_path, _ in images.values():
|
||||
image_path.unlink()
|
||||
manifest = dict(status='pass', integrity='NCA FS header and six IVFC levels verified per NCA; BFTTF header decodes to an sfnt font; RSA not checked', fonts=report)
|
||||
(args.output / 'manifest.json').write_text(json.dumps(manifest, indent=2) + '\n')
|
||||
print(json.dumps(dict(status='pass', fonts=[(r['type'], r['font_bytes']) for r in report])))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
141
tools/vendor/macnativegames/extract_update_romfs.py
vendored
Normal file
141
tools/vendor/macnativegames/extract_update_romfs.py
vendored
Normal file
@@ -0,0 +1,141 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Merge a base XCI/NSP and an update NSP with the pinned hactool BKTR reader.
|
||||
|
||||
Temporary common-ticket keys are private files, never arguments or log output.
|
||||
The caller additionally verifies the resulting image against its known version hash.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
from extract_exefs import (load_keys, container_entries, common_tickets, nca_inventory,
|
||||
program_nca, record_offset, require)
|
||||
from extract_romfs import index_romfs
|
||||
|
||||
# Lockpick_RCM writes these as 17 bytes: the 16-byte source plus a trailing NUL.
|
||||
# hactool exits unless the value is exactly 16 bytes, before any BKTR check.
|
||||
_LOCKPICK_KEK_SOURCE = re.compile(r'(?:mariko_)?master_kek_source_[0-9a-f]{2}\Z')
|
||||
|
||||
|
||||
def copy_range(source, offset, size, target):
|
||||
with source.open('rb') as src, target.open('wb') as dst:
|
||||
src.seek(offset)
|
||||
while size:
|
||||
data = src.read(min(size, 8 << 20))
|
||||
require(bool(data), 'Truncated NCA')
|
||||
dst.write(data)
|
||||
size -= len(data)
|
||||
|
||||
|
||||
def hactool_prod_keys(source, target):
|
||||
"""Copy prod.keys for hactool. The caller's file is left unchanged.
|
||||
|
||||
hactool knows no comments: it reads the rest of a line as the value, so a trailing `# note` makes it exit. The copy
|
||||
keeps only the `name = value` lines, read the way load_keys reads them (comments dropped, spaces trimmed).
|
||||
A Lockpick trailing NUL on master_kek_source / mariko_master_kek_source is dropped. Any other length is rejected
|
||||
without recording the key bytes.
|
||||
"""
|
||||
lines = []
|
||||
for number, line in enumerate(Path(source).read_text().splitlines(), 1):
|
||||
body = line.split('#', 1)[0]
|
||||
if '=' not in body:
|
||||
continue
|
||||
name, value = (part.strip() for part in body.split('=', 1))
|
||||
if _LOCKPICK_KEK_SOURCE.fullmatch(name.lower()) is not None:
|
||||
require(re.fullmatch(r'[0-9a-fA-F]+', value) is not None, f'Invalid key encoding at line {number}')
|
||||
if len(value) == 34 and value[-2:].lower() == '00':
|
||||
value = value[:32]
|
||||
require(len(value) == 32, f'{name.lower()} must be 16 bytes')
|
||||
lines.append(f'{name} = {value}')
|
||||
fd = os.open(target, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
||||
with os.fdopen(fd, 'w') as f:
|
||||
f.write('\n'.join(lines) + ('\n' if lines else ''))
|
||||
|
||||
|
||||
def merge(base, update, keys_path, hactool, output, *, base_romfs=None):
|
||||
require(not output.exists(), 'Output exists')
|
||||
keys = load_keys(keys_path)
|
||||
inputs = []
|
||||
tickets = {}
|
||||
sources = ((update, True),) if base_romfs else ((base, False), (update, True))
|
||||
for source, is_update in sources:
|
||||
with source.open('rb') as f:
|
||||
kind, entries = container_entries(f, source.stat().st_size)
|
||||
require(not is_update or kind == 'nsp', 'Update must be an NSP')
|
||||
found = common_tickets(f, entries)
|
||||
for rights, key in found.items():
|
||||
require(rights not in tickets or tickets[rights] == key, 'Conflicting common tickets')
|
||||
tickets[rights] = key
|
||||
record, header = program_nca(nca_inventory(f, entries, keys), update=is_update)
|
||||
rights = header[0x230:0x240]
|
||||
require(rights == bytes(16) or rights in tickets, 'Missing common ticket')
|
||||
inputs.append((source, record, header))
|
||||
sections = [i for i in range(4) if inputs[-1][2][0x400+i*512+4] == 4]
|
||||
require(len(sections) == 1, 'Expected one BKTR section')
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
require(shutil.disk_usage(output.parent).free > inputs[-1][1]['size'] + 18*(1 << 30),
|
||||
'Need about 19 GiB free for the temporary update NCA and merged image')
|
||||
if base_romfs:
|
||||
require(Path(base_romfs).is_file(), 'Previous-version RomFS is missing')
|
||||
with tempfile.TemporaryDirectory(prefix='update-merge-', dir=output.parent) as tmp:
|
||||
tmp = Path(tmp)
|
||||
keyfile = tmp/'title.keys'
|
||||
fd = os.open(keyfile, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
||||
with os.fdopen(fd, 'w') as f:
|
||||
for rights, key in tickets.items():
|
||||
f.write(f'{rights.hex()} = {key.hex()}\n')
|
||||
source, record, _ = inputs[-1]
|
||||
copy_range(source, record_offset(record), record['size'], tmp/'update.nca')
|
||||
result = tmp/'result'
|
||||
result.mkdir()
|
||||
base_arg = '--baseromfs='+str(Path(base_romfs).resolve()) if base_romfs else '--basenca='+str(base.resolve())
|
||||
environment = dict(os.environ, MNG_TITLE_KEYS=str(keyfile))
|
||||
environment.pop('MNG_BASE_RANGE_OFFSET', None); environment.pop('MNG_BASE_RANGE_SIZE', None)
|
||||
if not base_romfs:
|
||||
environment.update(MNG_BASE_RANGE_OFFSET=str(record_offset(inputs[0][1])),
|
||||
MNG_BASE_RANGE_SIZE=str(inputs[0][1]['size']))
|
||||
hactool_keys = tmp/'hactool.keys'
|
||||
hactool_prod_keys(keys_path, hactool_keys)
|
||||
command = [str(hactool.resolve()), '-x', '-y', '--disablekeywarns', '--suppresskeys',
|
||||
'-k', str(hactool_keys.resolve()), base_arg,
|
||||
f'--section{sections[0]}='+str(result/'romfs.bin'), str(tmp/'update.nca')]
|
||||
with (result/'merge.log').open('w') as log:
|
||||
code = subprocess.run(command, env=environment,
|
||||
stdout=log, stderr=subprocess.STDOUT).returncode
|
||||
log = (result/'merge.log').read_text()
|
||||
# hactool also verifies the NCA's fixed-key and NPDM signatures, which need Nintendo's public keys:
|
||||
# without them it always prints those two lines as (FAIL). They are not data failures; the six IVFC
|
||||
# levels and the image SHA-256 recorded below decide whether the merge worked.
|
||||
unsigned = re.compile(r'\s*(?:Fixed-Key Signature|NPDM Signature) \(FAIL\)')
|
||||
checked = '\n'.join(line for line in log.splitlines() if not unsigned.match(line))
|
||||
if code or re.search(r'\(FAIL\)|\(INVALID\)|Failed to|Error:', checked):
|
||||
# hactool repeats a key it cannot parse ("Key (<value>) must be 32 hex digits!"): keep no long hex in the log
|
||||
(output.parent/(output.name+'-failure.log')).write_text(re.sub(r'[0-9A-Fa-f]{32,}', '<hex removed>', log))
|
||||
require(code == 0 and not re.search(r'\(FAIL\)|\(INVALID\)|Failed to|Error:', checked), 'BKTR verification failed')
|
||||
require(all(re.search(rf'Level {i} \(GOOD\)', log) for i in range(6)), 'Missing verified IVFC levels')
|
||||
image = result/'romfs.bin'
|
||||
with image.open('rb') as f:
|
||||
digest = hashlib.file_digest(f, 'sha256').hexdigest()
|
||||
files = index_romfs(image)
|
||||
report = dict(status='pass', romfs_size=image.stat().st_size, romfs_sha256=digest,
|
||||
files=files, integrity='BKTR merge; all six IVFC levels verified')
|
||||
(result/'index.json').write_text(json.dumps(report, indent=2)+'\n')
|
||||
result.rename(output)
|
||||
print(json.dumps(dict(status='pass', files=len(files), sha256=digest)))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('base', type=Path)
|
||||
parser.add_argument('update', type=Path)
|
||||
parser.add_argument('--keys', required=True, type=Path)
|
||||
parser.add_argument('--hactool', required=True, type=Path)
|
||||
parser.add_argument('--base-romfs', type=Path, help='full decrypted base IVFC section, including hash levels (not a raw RomFS image)')
|
||||
parser.add_argument('--output', required=True, type=Path)
|
||||
args = parser.parse_args()
|
||||
merge(args.base, args.update, args.keys, args.hactool, args.output, base_romfs=args.base_romfs)
|
||||
2
tools/vendor/ryujinx/.gitignore
vendored
Normal file
2
tools/vendor/ryujinx/.gitignore
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
bin/
|
||||
obj/
|
||||
7
tools/vendor/ryujinx/Directory.Build.props
vendored
Normal file
7
tools/vendor/ryujinx/Directory.Build.props
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
<Project>
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<LangVersion>preview</LangVersion>
|
||||
<DebugType Condition="'$(Configuration)'=='Release'">none</DebugType>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
104
tools/vendor/ryujinx/Directory.Packages.props
vendored
Normal file
104
tools/vendor/ryujinx/Directory.Packages.props
vendored
Normal file
@@ -0,0 +1,104 @@
|
||||
<Project>
|
||||
<PropertyGroup>
|
||||
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
|
||||
<!-- Packages included in Ryujinx should be the latest stable releases -->
|
||||
<!-- unless otherwise required for improved functionality or regressions ocurred. -->
|
||||
|
||||
<!-- Packages are listed by module/function first, then alphabetical order. -->
|
||||
|
||||
<!-- UI -->
|
||||
<!-- TODO: Avalonia >= 12.0.0 requires refactoring -->
|
||||
<PackageVersion Include="Avalonia" Version="12.1.1" />
|
||||
<PackageVersion Include="Avalonia.Controls.DataGrid" Version="12.1.2" />
|
||||
<PackageVersion Include="Avalonia.Desktop" Version="12.1.1" />
|
||||
<!-- TODO: Replace Avalonia.Diagnostics (Deprecated). -->
|
||||
<!-- <PackageVersion Include="AvaloniaUI.DiagnosticsSupport" Version="2.2.3" /> -->
|
||||
<PackageVersion Include="AvaloniaUI.DiagnosticsSupport" Version="2.2.3" />
|
||||
<PackageVersion Include="Avalonia.Markup.Xaml.Loader" Version="12.1.1" />
|
||||
|
||||
<PackageVersion Include="FluentAvaloniaUI" Version="3.0.2" />
|
||||
|
||||
<PackageVersion Include="Optris.Icons.Avalonia" Version="12.0.7" />
|
||||
<PackageVersion Include="Optris.Icons.Avalonia.FontAwesome" Version="12.0.7" />
|
||||
<PackageVersion Include="Optris.Icons.Avalonia.MaterialDesign" Version="12.0.7" />
|
||||
|
||||
<!-- TODO: SkiaSharp > 2.88.9 requires refactoring -->
|
||||
<PackageVersion Include="SkiaSharp" Version="3.119.4" />
|
||||
<PackageVersion Include="SkiaSharp.NativeAssets.Win32" Version="3.119.4" />
|
||||
<PackageVersion Include="SkiaSharp.NativeAssets.macOS" Version="3.119.4" />
|
||||
<PackageVersion Include="SkiaSharp.NativeAssets.Linux.NoDependencies" Version="3.119.4" />
|
||||
|
||||
<PackageVersion Include="Svg.Controls.Avalonia" Version="12.0.0.13" />
|
||||
<PackageVersion Include="Svg.Controls.Skia.Avalonia" Version="12.0.0.13" />
|
||||
|
||||
<!-- Building & Packaging -->
|
||||
<PackageVersion Include="CommandLineParser" Version="2.9.1" />
|
||||
<PackageVersion Include="CommunityToolkit.Mvvm" Version="8.4.2" />
|
||||
<PackageVersion Include="DynamicData" Version="9.4.33" />
|
||||
<PackageVersion Include="Gommon" Version="2.8.1.2" />
|
||||
<PackageVersion Include="Humanizer" Version="3.0.10" />
|
||||
|
||||
<!-- TODO: Microsoft.CodeAnalysis.Analyzers > 3.3.4 needs refactoring -->
|
||||
<PackageVersion Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.4" />
|
||||
<PackageVersion Include="Microsoft.CodeAnalysis.CSharp" Version="4.9.2" /> <!-- Must be updated with Analyzers -->
|
||||
|
||||
<PackageVersion Include="Microsoft.Build.Framework" Version="17.11.4" />
|
||||
<PackageVersion Include="Microsoft.Build.Utilities.Core" Version="17.12.50" />
|
||||
<PackageVersion Include="Microsoft.IdentityModel.JsonWebTokens" Version="8.19.1" />
|
||||
<PackageVersion Include="Microsoft.IO.RecyclableMemoryStream" Version="3.0.1" />
|
||||
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.4.1" />
|
||||
|
||||
<PackageVersion Include="MsgPack.Cli" Version="1.0.1" />
|
||||
<PackageVersion Include="NetCoreServer" Version="8.0.7" />
|
||||
<PackageVersion Include="Newtonsoft.Json" Version="13.0.4" />
|
||||
|
||||
<PackageVersion Include="NUnit" Version="3.14.0" />
|
||||
<PackageVersion Include="NUnit3TestAdapter" Version="4.6.0" />
|
||||
|
||||
<PackageVersion Include="securifybv.ShellLink" Version="0.1.0" />
|
||||
<PackageVersion Include="Sep" Version="0.15.0" />
|
||||
|
||||
<PackageVersion Include="SharpCompress" Version="0.50.0" />
|
||||
<PackageVersion Include="SharpZipLib" Version="1.4.2" />
|
||||
|
||||
<PackageVersion Include="System.IO.Hashing" Version="10.0.9" />
|
||||
|
||||
<!--Don't touch this, we're freezing the Unicorn package due to an issue with bindngs.-->
|
||||
<PackageVersion Include="UnicornEngine.Unicorn" Version="2.1.0" />
|
||||
|
||||
<!-- Internal Dependencies -->
|
||||
<!-- Ryujinx.Audio.OpenAL.Dependencies is from the original project, last updated 12/30/20 -->
|
||||
<!--<PackageVersion Include="Ryujinx.Audio.OpenAL.Dependencies" Version="1.21.0.1" />-->
|
||||
<PackageVersion Include="Ryujinx.Audio.OpenAL" Version="1.25.2" />
|
||||
<PackageVersion Include="Ryujinx.Graphics.Nvdec.Dependencies.AllArch" Version="6.1.4-build6" />
|
||||
<PackageVersion Include="Ryujinx.Graphics.Vulkan.MoltenVK" Version="1.4.2-ryujinx.5" />
|
||||
<PackageVersion Include="Ryujinx.LibHac" Version="0.21.0-alpha.133" />
|
||||
<PackageVersion Include="Ryujinx.SDL3-CS" Version="2026.707.0" />
|
||||
<PackageVersion Include="Ryujinx.Systems.Update.Common" Version="2.0.6" />
|
||||
<PackageVersion Include="Ryujinx.UpdateClient" Version="2.0.6" />
|
||||
<PackageVersion Include="SPB" Version="0.0.4-build32" />
|
||||
|
||||
<!-- External Dependencies -->
|
||||
<PackageVersion Include="Concentus" Version="2.2.2" />
|
||||
<PackageVersion Include="DiscordRichPresence" Version="1.6.1.70" />
|
||||
|
||||
<PackageVersion Include="OpenTK.Core" Version="4.9.4" />
|
||||
<PackageVersion Include="OpenTK.Graphics" Version="4.9.4" />
|
||||
<!-- TODO: OpenTk.Audio.OpenAL has moved to OpenTk.Audio -->
|
||||
<!-- OpenTk.Audio.OpenAL > 4.9.4 requires refactoring -->
|
||||
<!--<PackageVersion Include="OpenTK.Audio" Version="5.0.0-pre.16" />-->
|
||||
<PackageVersion Include="OpenTK.Audio.OpenAL" Version="4.9.4" />
|
||||
|
||||
<!-- TODO: Consider replacing with SharpOpenNat. -->
|
||||
<PackageVersion Include="Open.Nat.V2" Version="3.2.1" />
|
||||
|
||||
<PackageVersion Include="Silk.NET.Shaderc" Version="2.23.0" />
|
||||
<PackageVersion Include="Silk.NET.Vulkan" Version="2.23.0" />
|
||||
<PackageVersion Include="Silk.NET.Vulkan.Extensions.EXT" Version="2.23.0" />
|
||||
<PackageVersion Include="Silk.NET.Vulkan.Extensions.KHR" Version="2.23.0" />
|
||||
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
9
tools/vendor/ryujinx/LICENSE.txt
vendored
Normal file
9
tools/vendor/ryujinx/LICENSE.txt
vendored
Normal file
@@ -0,0 +1,9 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) Ryujinx Team and Contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
8
tools/vendor/ryujinx/README.md
vendored
Normal file
8
tools/vendor/ryujinx/README.md
vendored
Normal file
@@ -0,0 +1,8 @@
|
||||
# Ryujinx shader translator (vendored subset)
|
||||
|
||||
Three projects from Ryujinx 1.3.2, unmodified: `Ryujinx.Graphics.Shader`, `Ryujinx.Common` and `Spv.Generator`.
|
||||
The shader translation tool in `dm/gfx/tools/dmsh_xlate` references them to translate the original Switch shaders to SPIR-V.
|
||||
License: MIT, see `LICENSE.txt`. Upstream: <https://github.com/Ryubing>.
|
||||
|
||||
Ryujinx 1.3.2 的三个项目,未做修改:`Ryujinx.Graphics.Shader`、`Ryujinx.Common`、`Spv.Generator`。
|
||||
`dm/gfx/tools/dmsh_xlate` 的着色器翻译工具引用它们,把 Switch 原版着色器翻译成 SPIR-V。许可证 MIT,见 `LICENSE.txt`。
|
||||
102
tools/vendor/ryujinx/src/Ryujinx.Common/AsyncWorkQueue.cs
vendored
Normal file
102
tools/vendor/ryujinx/src/Ryujinx.Common/AsyncWorkQueue.cs
vendored
Normal file
@@ -0,0 +1,102 @@
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Threading;
|
||||
|
||||
namespace Ryujinx.Common
|
||||
{
|
||||
public sealed class AsyncWorkQueue<T> : IDisposable
|
||||
{
|
||||
private readonly Thread _workerThread;
|
||||
private readonly CancellationTokenSource _cts;
|
||||
private readonly Action<T> _workerAction;
|
||||
private readonly BlockingCollection<T> _queue;
|
||||
|
||||
public bool IsCancellationRequested => _cts.IsCancellationRequested;
|
||||
|
||||
public AsyncWorkQueue(Action<T> callback, string name = null) : this(callback, name, new BlockingCollection<T>())
|
||||
{
|
||||
}
|
||||
|
||||
public AsyncWorkQueue(Action<T> callback, string name, BlockingCollection<T> collection)
|
||||
{
|
||||
_cts = new CancellationTokenSource();
|
||||
_queue = collection;
|
||||
_workerAction = callback;
|
||||
_workerThread = new Thread(DoWork)
|
||||
{
|
||||
Name = name,
|
||||
IsBackground = true,
|
||||
};
|
||||
_workerThread.Start();
|
||||
}
|
||||
|
||||
private void DoWork()
|
||||
{
|
||||
try
|
||||
{
|
||||
foreach (T item in _queue.GetConsumingEnumerable(_cts.Token))
|
||||
{
|
||||
_workerAction(item);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
public void Cancel()
|
||||
{
|
||||
_cts.Cancel();
|
||||
}
|
||||
|
||||
public void CancelAfter(int millisecondsDelay)
|
||||
{
|
||||
_cts.CancelAfter(millisecondsDelay);
|
||||
}
|
||||
|
||||
public void CancelAfter(TimeSpan delay)
|
||||
{
|
||||
_cts.CancelAfter(delay);
|
||||
}
|
||||
|
||||
public void Add(T workItem)
|
||||
{
|
||||
_queue.Add(workItem);
|
||||
}
|
||||
|
||||
public void Add(T workItem, CancellationToken cancellationToken)
|
||||
{
|
||||
_queue.Add(workItem, cancellationToken);
|
||||
}
|
||||
|
||||
public bool TryAdd(T workItem)
|
||||
{
|
||||
return _queue.TryAdd(workItem);
|
||||
}
|
||||
|
||||
public bool TryAdd(T workItem, int millisecondsDelay)
|
||||
{
|
||||
return _queue.TryAdd(workItem, millisecondsDelay);
|
||||
}
|
||||
|
||||
public bool TryAdd(T workItem, int millisecondsDelay, CancellationToken cancellationToken)
|
||||
{
|
||||
return _queue.TryAdd(workItem, millisecondsDelay, cancellationToken);
|
||||
}
|
||||
|
||||
public bool TryAdd(T workItem, TimeSpan timeout)
|
||||
{
|
||||
return _queue.TryAdd(workItem, timeout);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_queue.CompleteAdding();
|
||||
_cts.Cancel();
|
||||
_workerThread.Join();
|
||||
|
||||
_queue.Dispose();
|
||||
_cts.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
226
tools/vendor/ryujinx/src/Ryujinx.Common/Collections/BitMap.cs
vendored
Normal file
226
tools/vendor/ryujinx/src/Ryujinx.Common/Collections/BitMap.cs
vendored
Normal file
@@ -0,0 +1,226 @@
|
||||
namespace Ryujinx.Common.Collections
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents a collection that can store 1 bit values.
|
||||
/// </summary>
|
||||
public struct BitMap
|
||||
{
|
||||
/// <summary>
|
||||
/// Size in bits of the integer used internally for the groups of bits.
|
||||
/// </summary>
|
||||
public const int IntSize = 64;
|
||||
|
||||
private const int IntShift = 6;
|
||||
private const int IntMask = IntSize - 1;
|
||||
|
||||
private readonly long[] _masks;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the value of a bit.
|
||||
/// </summary>
|
||||
/// <param name="bit">Bit to access</param>
|
||||
/// <returns>Bit value</returns>
|
||||
public bool this[int bit]
|
||||
{
|
||||
get => IsSet(bit);
|
||||
set
|
||||
{
|
||||
if (value)
|
||||
{
|
||||
Set(bit);
|
||||
}
|
||||
else
|
||||
{
|
||||
Clear(bit);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new bitmap.
|
||||
/// </summary>
|
||||
/// <param name="count">Total number of bits</param>
|
||||
public BitMap(int count)
|
||||
{
|
||||
_masks = new long[(count + IntMask) / IntSize];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if any bit is set.
|
||||
/// </summary>
|
||||
/// <returns>True if any bit is set, false otherwise</returns>
|
||||
public bool AnySet()
|
||||
{
|
||||
for (int i = 0; i < _masks.Length; i++)
|
||||
{
|
||||
if (_masks[i] != 0)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if a specific bit is set.
|
||||
/// </summary>
|
||||
/// <param name="bit">Bit to be checked</param>
|
||||
/// <returns>True if set, false otherwise</returns>
|
||||
public bool IsSet(int bit)
|
||||
{
|
||||
int wordIndex = bit >> IntShift;
|
||||
int wordBit = bit & IntMask;
|
||||
|
||||
long wordMask = 1L << wordBit;
|
||||
|
||||
return (_masks[wordIndex] & wordMask) != 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if any bit inside a given range of bits is set.
|
||||
/// </summary>
|
||||
/// <param name="start">Start bit of the range</param>
|
||||
/// <param name="end">End bit of the range (inclusive)</param>
|
||||
/// <returns>True if any bit is set, false otherwise</returns>
|
||||
public bool IsSet(int start, int end)
|
||||
{
|
||||
if (start == end)
|
||||
{
|
||||
return IsSet(start);
|
||||
}
|
||||
|
||||
int startIndex = start >> IntShift;
|
||||
int startBit = start & IntMask;
|
||||
long startMask = -1L << startBit;
|
||||
|
||||
int endIndex = end >> IntShift;
|
||||
int endBit = end & IntMask;
|
||||
long endMask = (long)(ulong.MaxValue >> (IntMask - endBit));
|
||||
|
||||
if (startIndex == endIndex)
|
||||
{
|
||||
return (_masks[startIndex] & startMask & endMask) != 0;
|
||||
}
|
||||
|
||||
if ((_masks[startIndex] & startMask) != 0)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
for (int i = startIndex + 1; i < endIndex; i++)
|
||||
{
|
||||
if (_masks[i] != 0)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
if ((_masks[endIndex] & endMask) != 0)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the value of a bit to 1.
|
||||
/// </summary>
|
||||
/// <param name="bit">Bit to be set</param>
|
||||
/// <returns>True if the bit was 0 and then changed to 1, false if it was already 1</returns>
|
||||
public bool Set(int bit)
|
||||
{
|
||||
int wordIndex = bit >> IntShift;
|
||||
int wordBit = bit & IntMask;
|
||||
|
||||
long wordMask = 1L << wordBit;
|
||||
|
||||
if ((_masks[wordIndex] & wordMask) != 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
_masks[wordIndex] |= wordMask;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets a given range of bits to 1.
|
||||
/// </summary>
|
||||
/// <param name="start">Start bit of the range</param>
|
||||
/// <param name="end">End bit of the range (inclusive)</param>
|
||||
public void SetRange(int start, int end)
|
||||
{
|
||||
if (start == end)
|
||||
{
|
||||
Set(start);
|
||||
return;
|
||||
}
|
||||
|
||||
int startIndex = start >> IntShift;
|
||||
int startBit = start & IntMask;
|
||||
long startMask = -1L << startBit;
|
||||
|
||||
int endIndex = end >> IntShift;
|
||||
int endBit = end & IntMask;
|
||||
long endMask = (long)(ulong.MaxValue >> (IntMask - endBit));
|
||||
|
||||
if (startIndex == endIndex)
|
||||
{
|
||||
_masks[startIndex] |= startMask & endMask;
|
||||
}
|
||||
else
|
||||
{
|
||||
_masks[startIndex] |= startMask;
|
||||
|
||||
for (int i = startIndex + 1; i < endIndex; i++)
|
||||
{
|
||||
_masks[i] |= -1;
|
||||
}
|
||||
|
||||
_masks[endIndex] |= endMask;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets a given bit to 0.
|
||||
/// </summary>
|
||||
/// <param name="bit">Bit to be cleared</param>
|
||||
public void Clear(int bit)
|
||||
{
|
||||
int wordIndex = bit >> IntShift;
|
||||
int wordBit = bit & IntMask;
|
||||
|
||||
long wordMask = 1L << wordBit;
|
||||
|
||||
_masks[wordIndex] &= ~wordMask;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets all bits to 0.
|
||||
/// </summary>
|
||||
public void Clear()
|
||||
{
|
||||
for (int i = 0; i < _masks.Length; i++)
|
||||
{
|
||||
_masks[i] = 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets one or more groups of bits to 0.
|
||||
/// See <see cref="IntSize"/> for how many bits are inside each group.
|
||||
/// </summary>
|
||||
/// <param name="start">Start index of the group</param>
|
||||
/// <param name="end">End index of the group (inclusive)</param>
|
||||
public void ClearInt(int start, int end)
|
||||
{
|
||||
for (int i = start; i <= end; i++)
|
||||
{
|
||||
_masks[i] = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
507
tools/vendor/ryujinx/src/Ryujinx.Common/Collections/IntervalTree.cs
vendored
Normal file
507
tools/vendor/ryujinx/src/Ryujinx.Common/Collections/IntervalTree.cs
vendored
Normal file
@@ -0,0 +1,507 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
namespace Ryujinx.Common.Collections
|
||||
{
|
||||
/// <summary>
|
||||
/// An Augmented Interval Tree based off of the "TreeDictionary"'s Red-Black Tree. Allows fast overlap checking of ranges.
|
||||
/// </summary>
|
||||
/// <typeparam name="TKey">Key</typeparam>
|
||||
/// <typeparam name="TValue">Value</typeparam>
|
||||
public class IntervalTree<TKey, TValue> : IntrusiveRedBlackTreeImpl<IntervalTreeNode<TKey, TValue>> where TKey : IComparable<TKey>
|
||||
{
|
||||
private const int ArrayGrowthSize = 32;
|
||||
|
||||
#region Public Methods
|
||||
|
||||
/// <summary>
|
||||
/// Gets the values of the interval whose key is <paramref name="key"/>.
|
||||
/// </summary>
|
||||
/// <param name="key">Key of the node value to get</param>
|
||||
/// <param name="overlaps">Overlaps array to place results in</param>
|
||||
/// <returns>Number of values found</returns>
|
||||
/// <exception cref="ArgumentNullException"><paramref name="key"/> is null</exception>
|
||||
public int Get(TKey key, ref TValue[] overlaps)
|
||||
{
|
||||
if (!typeof(TKey).IsValueType)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(key);
|
||||
}
|
||||
|
||||
IntervalTreeNode<TKey, TValue> node = GetNode(key);
|
||||
|
||||
if (node == null)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (node.Values.Count > overlaps.Length)
|
||||
{
|
||||
Array.Resize(ref overlaps, node.Values.Count);
|
||||
}
|
||||
|
||||
int overlapsCount = 0;
|
||||
foreach (RangeNode<TKey, TValue> value in node.Values)
|
||||
{
|
||||
overlaps[overlapsCount++] = value.Value;
|
||||
}
|
||||
|
||||
return overlapsCount;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the values of the intervals whose start and end keys overlap the given range.
|
||||
/// </summary>
|
||||
/// <param name="start">Start of the range</param>
|
||||
/// <param name="end">End of the range</param>
|
||||
/// <param name="overlaps">Overlaps array to place results in</param>
|
||||
/// <param name="overlapCount">Index to start writing results into the array. Defaults to 0</param>
|
||||
/// <returns>Number of values found</returns>
|
||||
/// <exception cref="ArgumentNullException"><paramref name="start"/> or <paramref name="end"/> is null</exception>
|
||||
public int Get(TKey start, TKey end, ref TValue[] overlaps, int overlapCount = 0)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(start);
|
||||
ArgumentNullException.ThrowIfNull(end);
|
||||
|
||||
GetValues(Root, start, end, ref overlaps, ref overlapCount);
|
||||
|
||||
return overlapCount;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a new interval into the tree whose start is <paramref name="start"/>, end is <paramref name="end"/> and value is <paramref name="value"/>.
|
||||
/// </summary>
|
||||
/// <param name="start">Start of the range to add</param>
|
||||
/// <param name="end">End of the range to insert</param>
|
||||
/// <param name="value">Value to add</param>
|
||||
/// <exception cref="ArgumentNullException"><paramref name="start"/>, <paramref name="end"/> or <paramref name="value"/> are null</exception>
|
||||
public void Add(TKey start, TKey end, TValue value)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(start);
|
||||
ArgumentNullException.ThrowIfNull(end);
|
||||
ArgumentNullException.ThrowIfNull(value);
|
||||
|
||||
Insert(start, end, value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the given <paramref name="value"/> from the tree, searching for it with <paramref name="key"/>.
|
||||
/// </summary>
|
||||
/// <param name="key">Key of the node to remove</param>
|
||||
/// <param name="value">Value to remove</param>
|
||||
/// <exception cref="ArgumentNullException"><paramref name="key"/> is null</exception>
|
||||
/// <returns>Number of deleted values</returns>
|
||||
public int Remove(TKey key, TValue value)
|
||||
{
|
||||
if (!typeof(TKey).IsValueType)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(key);
|
||||
}
|
||||
|
||||
int removed = Delete(key, value);
|
||||
|
||||
Count -= removed;
|
||||
|
||||
return removed;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds all the nodes in the dictionary into <paramref name="list"/>.
|
||||
/// </summary>
|
||||
/// <returns>A list of all RangeNodes sorted by Key Order</returns>
|
||||
public List<RangeNode<TKey, TValue>> AsList()
|
||||
{
|
||||
List<RangeNode<TKey, TValue>> list = [];
|
||||
|
||||
AddToList(Root, list);
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Private Methods (BST)
|
||||
|
||||
/// <summary>
|
||||
/// Adds all RangeNodes that are children of or contained within <paramref name="node"/> into <paramref name="list"/>, in Key Order.
|
||||
/// </summary>
|
||||
/// <param name="node">The node to search for RangeNodes within</param>
|
||||
/// <param name="list">The list to add RangeNodes to</param>
|
||||
private static void AddToList(IntervalTreeNode<TKey, TValue> node, List<RangeNode<TKey, TValue>> list)
|
||||
{
|
||||
if (node == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
AddToList(node.Left, list);
|
||||
|
||||
list.AddRange(node.Values);
|
||||
|
||||
AddToList(node.Right, list);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Retrieve the node reference whose key is <paramref name="key"/>, or null if no such node exists.
|
||||
/// </summary>
|
||||
/// <param name="key">Key of the node to get</param>
|
||||
/// <returns>Node reference in the tree</returns>
|
||||
/// <exception cref="ArgumentNullException"><paramref name="key"/> is null</exception>
|
||||
private IntervalTreeNode<TKey, TValue> GetNode(TKey key)
|
||||
{
|
||||
if (!typeof(TKey).IsValueType)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(key);
|
||||
}
|
||||
|
||||
IntervalTreeNode<TKey, TValue> node = Root;
|
||||
while (node != null)
|
||||
{
|
||||
int cmp = key.CompareTo(node.Start);
|
||||
if (cmp < 0)
|
||||
{
|
||||
node = node.Left;
|
||||
}
|
||||
else if (cmp > 0)
|
||||
{
|
||||
node = node.Right;
|
||||
}
|
||||
else
|
||||
{
|
||||
return node;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Retrieve all values that overlap the given start and end keys.
|
||||
/// </summary>
|
||||
/// <param name="start">Start of the range</param>
|
||||
/// <param name="end">End of the range</param>
|
||||
/// <param name="overlaps">Overlaps array to place results in</param>
|
||||
/// <param name="overlapCount">Overlaps count to update</param>
|
||||
private static void GetValues(IntervalTreeNode<TKey, TValue> node, TKey start, TKey end, ref TValue[] overlaps, ref int overlapCount)
|
||||
{
|
||||
if (node == null || start.CompareTo(node.Max) >= 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
GetValues(node.Left, start, end, ref overlaps, ref overlapCount);
|
||||
|
||||
bool endsOnRight = end.CompareTo(node.Start) > 0;
|
||||
if (endsOnRight)
|
||||
{
|
||||
if (start.CompareTo(node.End) < 0)
|
||||
{
|
||||
// Contains this node. Add overlaps to list.
|
||||
foreach (RangeNode<TKey, TValue> overlap in node.Values)
|
||||
{
|
||||
if (start.CompareTo(overlap.End) < 0)
|
||||
{
|
||||
if (overlaps.Length <= overlapCount)
|
||||
{
|
||||
Array.Resize(ref overlaps, overlapCount + ArrayGrowthSize);
|
||||
}
|
||||
|
||||
overlaps[overlapCount++] = overlap.Value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
GetValues(node.Right, start, end, ref overlaps, ref overlapCount);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Inserts a new node into the tree with a given <paramref name="start"/>, <paramref name="end"/> and <paramref name="value"/>.
|
||||
/// </summary>
|
||||
/// <param name="start">Start of the range to insert</param>
|
||||
/// <param name="end">End of the range to insert</param>
|
||||
/// <param name="value">Value to insert</param>
|
||||
private void Insert(TKey start, TKey end, TValue value)
|
||||
{
|
||||
IntervalTreeNode<TKey, TValue> newNode = BSTInsert(start, end, value);
|
||||
RestoreBalanceAfterInsertion(newNode);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Propagate an increase in max value starting at the given node, heading up the tree.
|
||||
/// This should only be called if the max increases - not for rebalancing or removals.
|
||||
/// </summary>
|
||||
/// <param name="node">The node to start propagating from</param>
|
||||
private static void PropagateIncrease(IntervalTreeNode<TKey, TValue> node)
|
||||
{
|
||||
TKey max = node.Max;
|
||||
IntervalTreeNode<TKey, TValue> ptr = node;
|
||||
|
||||
while ((ptr = ptr.Parent) != null)
|
||||
{
|
||||
if (max.CompareTo(ptr.Max) > 0)
|
||||
{
|
||||
ptr.Max = max;
|
||||
}
|
||||
else
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Propagate recalculating max value starting at the given node, heading up the tree.
|
||||
/// This fully recalculates the max value from all children when there is potential for it to decrease.
|
||||
/// </summary>
|
||||
/// <param name="node">The node to start propagating from</param>
|
||||
private static void PropagateFull(IntervalTreeNode<TKey, TValue> node)
|
||||
{
|
||||
IntervalTreeNode<TKey, TValue> ptr = node;
|
||||
|
||||
do
|
||||
{
|
||||
TKey max = ptr.End;
|
||||
|
||||
if (ptr.Left != null && ptr.Left.Max.CompareTo(max) > 0)
|
||||
{
|
||||
max = ptr.Left.Max;
|
||||
}
|
||||
|
||||
if (ptr.Right != null && ptr.Right.Max.CompareTo(max) > 0)
|
||||
{
|
||||
max = ptr.Right.Max;
|
||||
}
|
||||
|
||||
ptr.Max = max;
|
||||
} while ((ptr = ptr.Parent) != null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Insertion Mechanism for the interval tree. Similar to a BST insert, with the start of the range as the key.
|
||||
/// Iterates the tree starting from the root and inserts a new node where all children in the left subtree are less than <paramref name="start"/>, and all children in the right subtree are greater than <paramref name="start"/>.
|
||||
/// Each node can contain multiple values, and has an end address which is the maximum of all those values.
|
||||
/// Post insertion, the "max" value of the node and all parents are updated.
|
||||
/// </summary>
|
||||
/// <param name="start">Start of the range to insert</param>
|
||||
/// <param name="end">End of the range to insert</param>
|
||||
/// <param name="value">Value to insert</param>
|
||||
/// <returns>The inserted Node</returns>
|
||||
private IntervalTreeNode<TKey, TValue> BSTInsert(TKey start, TKey end, TValue value)
|
||||
{
|
||||
IntervalTreeNode<TKey, TValue> parent = null;
|
||||
IntervalTreeNode<TKey, TValue> node = Root;
|
||||
|
||||
while (node != null)
|
||||
{
|
||||
parent = node;
|
||||
int cmp = start.CompareTo(node.Start);
|
||||
if (cmp < 0)
|
||||
{
|
||||
node = node.Left;
|
||||
}
|
||||
else if (cmp > 0)
|
||||
{
|
||||
node = node.Right;
|
||||
}
|
||||
else
|
||||
{
|
||||
node.Values.Add(new RangeNode<TKey, TValue>(start, end, value));
|
||||
|
||||
if (end.CompareTo(node.End) > 0)
|
||||
{
|
||||
node.End = end;
|
||||
if (end.CompareTo(node.Max) > 0)
|
||||
{
|
||||
node.Max = end;
|
||||
PropagateIncrease(node);
|
||||
}
|
||||
}
|
||||
|
||||
Count++;
|
||||
return node;
|
||||
}
|
||||
}
|
||||
|
||||
IntervalTreeNode<TKey, TValue> newNode = new(start, end, value, parent);
|
||||
if (newNode.Parent == null)
|
||||
{
|
||||
Root = newNode;
|
||||
}
|
||||
else if (start.CompareTo(parent.Start) < 0)
|
||||
{
|
||||
parent.Left = newNode;
|
||||
}
|
||||
else
|
||||
{
|
||||
parent.Right = newNode;
|
||||
}
|
||||
|
||||
PropagateIncrease(newNode);
|
||||
Count++;
|
||||
return newNode;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes instances of <paramref name="value"> from the dictionary after searching for it with <paramref name="key">.
|
||||
/// </summary>
|
||||
/// <param name="key">Key to search for</param>
|
||||
/// <param name="value">Value to delete</param>
|
||||
/// <returns>Number of deleted values</returns>
|
||||
private int Delete(TKey key, TValue value)
|
||||
{
|
||||
IntervalTreeNode<TKey, TValue> nodeToDelete = GetNode(key);
|
||||
|
||||
if (nodeToDelete == null)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
int removed = nodeToDelete.Values.RemoveAll(node => node.Value.Equals(value));
|
||||
|
||||
if (nodeToDelete.Values.Count > 0)
|
||||
{
|
||||
if (removed > 0)
|
||||
{
|
||||
nodeToDelete.End = nodeToDelete.Values.Max(node => node.End);
|
||||
|
||||
// Recalculate max from children and new end.
|
||||
PropagateFull(nodeToDelete);
|
||||
}
|
||||
|
||||
return removed;
|
||||
}
|
||||
|
||||
IntervalTreeNode<TKey, TValue> replacementNode;
|
||||
|
||||
if (LeftOf(nodeToDelete) == null || RightOf(nodeToDelete) == null)
|
||||
{
|
||||
replacementNode = nodeToDelete;
|
||||
}
|
||||
else
|
||||
{
|
||||
replacementNode = PredecessorOf(nodeToDelete);
|
||||
}
|
||||
|
||||
IntervalTreeNode<TKey, TValue> tmp = LeftOf(replacementNode) ?? RightOf(replacementNode);
|
||||
|
||||
tmp?.Parent = ParentOf(replacementNode);
|
||||
|
||||
if (ParentOf(replacementNode) == null)
|
||||
{
|
||||
Root = tmp;
|
||||
}
|
||||
else if (replacementNode == LeftOf(ParentOf(replacementNode)))
|
||||
{
|
||||
ParentOf(replacementNode).Left = tmp;
|
||||
}
|
||||
else
|
||||
{
|
||||
ParentOf(replacementNode).Right = tmp;
|
||||
}
|
||||
|
||||
if (replacementNode != nodeToDelete)
|
||||
{
|
||||
nodeToDelete.Start = replacementNode.Start;
|
||||
nodeToDelete.Values = replacementNode.Values;
|
||||
nodeToDelete.End = replacementNode.End;
|
||||
nodeToDelete.Max = replacementNode.Max;
|
||||
}
|
||||
|
||||
PropagateFull(replacementNode);
|
||||
|
||||
if (tmp != null && ColorOf(replacementNode) == Black)
|
||||
{
|
||||
RestoreBalanceAfterRemoval(tmp);
|
||||
}
|
||||
|
||||
return removed;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
protected override void RotateLeft(IntervalTreeNode<TKey, TValue> node)
|
||||
{
|
||||
if (node != null)
|
||||
{
|
||||
base.RotateLeft(node);
|
||||
|
||||
PropagateFull(node);
|
||||
}
|
||||
}
|
||||
|
||||
protected override void RotateRight(IntervalTreeNode<TKey, TValue> node)
|
||||
{
|
||||
if (node != null)
|
||||
{
|
||||
base.RotateRight(node);
|
||||
|
||||
PropagateFull(node);
|
||||
}
|
||||
}
|
||||
|
||||
public bool ContainsKey(TKey key)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(key);
|
||||
|
||||
return GetNode(key) != null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Represents a value and its start and end keys.
|
||||
/// </summary>
|
||||
/// <typeparam name="TKey"></typeparam>
|
||||
/// <typeparam name="TValue"></typeparam>
|
||||
public readonly struct RangeNode<TKey, TValue>
|
||||
{
|
||||
public readonly TKey Start;
|
||||
public readonly TKey End;
|
||||
public readonly TValue Value;
|
||||
|
||||
public RangeNode(TKey start, TKey end, TValue value)
|
||||
{
|
||||
Start = start;
|
||||
End = end;
|
||||
Value = value;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Represents a node in the IntervalTree which contains start and end keys of type K, and a value of generic type V.
|
||||
/// </summary>
|
||||
/// <typeparam name="TKey">Key type of the node</typeparam>
|
||||
/// <typeparam name="TValue">Value type of the node</typeparam>
|
||||
public class IntervalTreeNode<TKey, TValue> : IntrusiveRedBlackTreeNode<IntervalTreeNode<TKey, TValue>>
|
||||
{
|
||||
/// <summary>
|
||||
/// The start of the range.
|
||||
/// </summary>
|
||||
internal TKey Start;
|
||||
|
||||
/// <summary>
|
||||
/// The end of the range - maximum of all in the Values list.
|
||||
/// </summary>
|
||||
internal TKey End;
|
||||
|
||||
/// <summary>
|
||||
/// The maximum end value of this node and all its children.
|
||||
/// </summary>
|
||||
internal TKey Max;
|
||||
|
||||
/// <summary>
|
||||
/// Values contained on the node that shares a common Start value.
|
||||
/// </summary>
|
||||
internal List<RangeNode<TKey, TValue>> Values;
|
||||
|
||||
internal IntervalTreeNode(TKey start, TKey end, TValue value, IntervalTreeNode<TKey, TValue> parent)
|
||||
{
|
||||
Start = start;
|
||||
End = end;
|
||||
Max = end;
|
||||
Values = [new RangeNode<TKey, TValue>(start, end, value)];
|
||||
Parent = parent;
|
||||
}
|
||||
}
|
||||
}
|
||||
353
tools/vendor/ryujinx/src/Ryujinx.Common/Collections/IntrusiveRedBlackTree.cs
vendored
Normal file
353
tools/vendor/ryujinx/src/Ryujinx.Common/Collections/IntrusiveRedBlackTree.cs
vendored
Normal file
@@ -0,0 +1,353 @@
|
||||
using System;
|
||||
|
||||
namespace Ryujinx.Common.Collections
|
||||
{
|
||||
/// <summary>
|
||||
/// Tree that provides the ability for O(logN) lookups for keys that exist in the tree, and O(logN) lookups for keys immediately greater than or less than a specified key.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">Derived node type</typeparam>
|
||||
public class IntrusiveRedBlackTree<T> : IntrusiveRedBlackTreeImpl<T> where T : IntrusiveRedBlackTreeNode<T>, IComparable<T>
|
||||
{
|
||||
#region Public Methods
|
||||
|
||||
/// <summary>
|
||||
/// Adds a new node into the tree.
|
||||
/// </summary>
|
||||
/// <param name="node">Node to be added</param>
|
||||
/// <param name="parent">Node to be added under</param>
|
||||
/// <exception cref="ArgumentNullException"><paramref name="node"/> is null</exception>
|
||||
public void Add(T node, T parent = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(node);
|
||||
|
||||
Insert(node, parent);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes a node from the tree.
|
||||
/// </summary>
|
||||
/// <param name="node">Note to be removed</param>
|
||||
/// <exception cref="ArgumentNullException"><paramref name="node"/> is null</exception>
|
||||
public void Remove(T node)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(node);
|
||||
|
||||
if (Delete(node) != null)
|
||||
{
|
||||
Count--;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Retrieve the node that is considered equal to the specified node by the comparator.
|
||||
/// </summary>
|
||||
/// <param name="searchNode">Node to compare with</param>
|
||||
/// <returns>Node that is equal to <paramref name="searchNode"/></returns>
|
||||
/// <exception cref="ArgumentNullException"><paramref name="searchNode"/> is null</exception>
|
||||
public T GetNode(T searchNode)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(searchNode);
|
||||
|
||||
T node = Root;
|
||||
while (node != null)
|
||||
{
|
||||
int cmp = searchNode.CompareTo(node);
|
||||
if (cmp < 0)
|
||||
{
|
||||
node = node.Left;
|
||||
}
|
||||
else if (cmp > 0)
|
||||
{
|
||||
node = node.Right;
|
||||
}
|
||||
else
|
||||
{
|
||||
return node;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Private Methods (BST)
|
||||
|
||||
/// <summary>
|
||||
/// Inserts a new node into the tree.
|
||||
/// </summary>
|
||||
/// <param name="node">Node to be inserted</param>
|
||||
/// <param name="parent">Node to be inserted under</param>
|
||||
private void Insert(T node, T parent = null)
|
||||
{
|
||||
T newNode = parent != null ? InsertWithParent(node, parent) : BSTInsert(node);
|
||||
|
||||
RestoreBalanceAfterInsertion(newNode);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Insertion Mechanism for a Binary Search Tree (BST).
|
||||
/// <br></br>
|
||||
/// Iterates the tree starting from the root and inserts a new node
|
||||
/// where all children in the left subtree are less than <paramref name="newNode"/>,
|
||||
/// and all children in the right subtree are greater than <paramref name="newNode"/>.
|
||||
/// </summary>
|
||||
/// <param name="newNode">Node to be inserted</param>
|
||||
/// <returns>The inserted Node</returns>
|
||||
private T BSTInsert(T newNode)
|
||||
{
|
||||
T parent = null;
|
||||
T node = Root;
|
||||
|
||||
while (node != null)
|
||||
{
|
||||
parent = node;
|
||||
int cmp = newNode.CompareTo(node);
|
||||
if (cmp < 0)
|
||||
{
|
||||
node = node.Left;
|
||||
}
|
||||
else if (cmp > 0)
|
||||
{
|
||||
node = node.Right;
|
||||
}
|
||||
else
|
||||
{
|
||||
return node;
|
||||
}
|
||||
}
|
||||
|
||||
newNode.Parent = parent;
|
||||
if (parent == null)
|
||||
{
|
||||
Root = newNode;
|
||||
}
|
||||
else if (newNode.CompareTo(parent) < 0)
|
||||
{
|
||||
parent.Left = newNode;
|
||||
|
||||
newNode.Successor = parent;
|
||||
|
||||
if (parent.Predecessor != null)
|
||||
{
|
||||
newNode.Predecessor = parent.Predecessor;
|
||||
newNode.Predecessor.Successor = newNode;
|
||||
}
|
||||
|
||||
parent.Predecessor = newNode;
|
||||
}
|
||||
else
|
||||
{
|
||||
parent.Right = newNode;
|
||||
|
||||
newNode.Predecessor = parent;
|
||||
|
||||
if (parent.Successor != null)
|
||||
{
|
||||
newNode.Successor = parent.Successor;
|
||||
newNode.Successor.Predecessor = newNode;
|
||||
}
|
||||
|
||||
parent.Successor = newNode;
|
||||
}
|
||||
Count++;
|
||||
return newNode;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Insertion Mechanism for a Binary Search Tree (BST).
|
||||
/// <br></br>
|
||||
/// Inserts a new node directly under a parent node
|
||||
/// where all children in the left subtree are less than <paramref name="newNode"/>,
|
||||
/// and all children in the right subtree are greater than <paramref name="newNode"/>.
|
||||
/// </summary>
|
||||
/// <param name="newNode">Node to be inserted</param>
|
||||
/// <param name="parent">Node to be inserted under</param>
|
||||
/// <returns>The inserted Node</returns>
|
||||
private T InsertWithParent(T newNode, T parent)
|
||||
{
|
||||
newNode.Parent = parent;
|
||||
|
||||
if (newNode.CompareTo(parent) < 0)
|
||||
{
|
||||
parent.Left = newNode;
|
||||
|
||||
newNode.Successor = parent;
|
||||
|
||||
if (parent.Predecessor != null)
|
||||
{
|
||||
newNode.Predecessor = parent.Predecessor;
|
||||
parent.Predecessor = newNode;
|
||||
newNode.Predecessor.Successor = newNode;
|
||||
}
|
||||
|
||||
parent.Predecessor = newNode;
|
||||
}
|
||||
else
|
||||
{
|
||||
parent.Right = newNode;
|
||||
|
||||
newNode.Predecessor = parent;
|
||||
|
||||
if (parent.Successor != null)
|
||||
{
|
||||
newNode.Successor = parent.Successor;
|
||||
newNode.Successor.Predecessor = newNode;
|
||||
}
|
||||
|
||||
parent.Successor = newNode;
|
||||
}
|
||||
|
||||
Count++;
|
||||
return newNode;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes <paramref name="nodeToDelete"/> from the tree, if it exists.
|
||||
/// </summary>
|
||||
/// <param name="nodeToDelete">Node to be removed</param>
|
||||
/// <returns>The deleted Node</returns>
|
||||
private T Delete(T nodeToDelete)
|
||||
{
|
||||
if (nodeToDelete == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
T old = nodeToDelete;
|
||||
T child;
|
||||
T parent;
|
||||
bool color;
|
||||
|
||||
if (LeftOf(nodeToDelete) == null)
|
||||
{
|
||||
child = RightOf(nodeToDelete);
|
||||
}
|
||||
else if (RightOf(nodeToDelete) == null)
|
||||
{
|
||||
child = LeftOf(nodeToDelete);
|
||||
}
|
||||
else
|
||||
{
|
||||
T element = nodeToDelete.Successor;
|
||||
|
||||
child = RightOf(element);
|
||||
parent = ParentOf(element);
|
||||
color = ColorOf(element);
|
||||
|
||||
child?.Parent = parent;
|
||||
|
||||
if (parent == null)
|
||||
{
|
||||
Root = child;
|
||||
}
|
||||
else if (element == LeftOf(parent))
|
||||
{
|
||||
parent.Left = child;
|
||||
}
|
||||
else
|
||||
{
|
||||
parent.Right = child;
|
||||
}
|
||||
|
||||
element.Color = old.Color;
|
||||
element.Left = old.Left;
|
||||
element.Right = old.Right;
|
||||
element.Parent = old.Parent;
|
||||
element.Predecessor = old.Predecessor;
|
||||
element.Predecessor?.Successor = element;
|
||||
|
||||
if (ParentOf(old) == null)
|
||||
{
|
||||
Root = element;
|
||||
}
|
||||
else if (old == LeftOf(ParentOf(old)))
|
||||
{
|
||||
ParentOf(old).Left = element;
|
||||
}
|
||||
else
|
||||
{
|
||||
ParentOf(old).Right = element;
|
||||
}
|
||||
|
||||
LeftOf(old).Parent = element;
|
||||
|
||||
if (RightOf(old) != null)
|
||||
{
|
||||
RightOf(old).Parent = element;
|
||||
}
|
||||
|
||||
if (child != null && color == Black)
|
||||
{
|
||||
RestoreBalanceAfterRemoval(child);
|
||||
}
|
||||
|
||||
return old;
|
||||
}
|
||||
|
||||
parent = ParentOf(nodeToDelete);
|
||||
color = ColorOf(nodeToDelete);
|
||||
|
||||
child?.Parent = parent;
|
||||
|
||||
if (parent == null)
|
||||
{
|
||||
Root = child;
|
||||
}
|
||||
else if (nodeToDelete == LeftOf(parent))
|
||||
{
|
||||
parent.Left = child;
|
||||
}
|
||||
else
|
||||
{
|
||||
parent.Right = child;
|
||||
}
|
||||
|
||||
if (child != null && color == Black)
|
||||
{
|
||||
RestoreBalanceAfterRemoval(child);
|
||||
}
|
||||
|
||||
old.Successor?.Predecessor = old.Predecessor;
|
||||
old.Predecessor?.Successor = old.Successor;
|
||||
|
||||
return old;
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
|
||||
public static class IntrusiveRedBlackTreeExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Retrieve the node that is considered equal to the key by the comparator.
|
||||
/// </summary>
|
||||
/// <param name="tree">Tree to search at</param>
|
||||
/// <param name="key">Key of the node to be found</param>
|
||||
/// <returns>Node that is equal to <paramref name="key"/></returns>
|
||||
public static TNode GetNodeByKey<TNode, TKey>(this IntrusiveRedBlackTree<TNode> tree, TKey key)
|
||||
where TNode : IntrusiveRedBlackTreeNode<TNode>, IComparable<TNode>, IComparable<TKey>
|
||||
where TKey : struct
|
||||
{
|
||||
TNode node = tree.RootNode;
|
||||
while (node != null)
|
||||
{
|
||||
int cmp = node.CompareTo(key);
|
||||
if (cmp < 0)
|
||||
{
|
||||
node = node.Right;
|
||||
}
|
||||
else if (cmp > 0)
|
||||
{
|
||||
node = node.Left;
|
||||
}
|
||||
else
|
||||
{
|
||||
return node;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
361
tools/vendor/ryujinx/src/Ryujinx.Common/Collections/IntrusiveRedBlackTreeImpl.cs
vendored
Normal file
361
tools/vendor/ryujinx/src/Ryujinx.Common/Collections/IntrusiveRedBlackTreeImpl.cs
vendored
Normal file
@@ -0,0 +1,361 @@
|
||||
using System;
|
||||
|
||||
namespace Ryujinx.Common.Collections
|
||||
{
|
||||
/// <summary>
|
||||
/// Tree that provides the ability for O(logN) lookups for keys that exist in the tree, and O(logN) lookups for keys immediately greater than or less than a specified key.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">Derived node type</typeparam>
|
||||
public class IntrusiveRedBlackTreeImpl<T> where T : IntrusiveRedBlackTreeNode<T>
|
||||
{
|
||||
protected const bool Black = true;
|
||||
protected const bool Red = false;
|
||||
protected T Root;
|
||||
|
||||
internal T RootNode => Root;
|
||||
|
||||
/// <summary>
|
||||
/// Number of nodes on the tree.
|
||||
/// </summary>
|
||||
public int Count { get; protected set; }
|
||||
|
||||
/// <summary>
|
||||
/// Removes all nodes on the tree.
|
||||
/// </summary>
|
||||
public void Clear()
|
||||
{
|
||||
Root = null;
|
||||
Count = 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Finds the node whose key is immediately greater than <paramref name="node"/>.
|
||||
/// </summary>
|
||||
/// <param name="node">Node to find the successor of</param>
|
||||
/// <returns>Successor of <paramref name="node"/></returns>
|
||||
internal static T SuccessorOf(T node)
|
||||
{
|
||||
if (node.Right != null)
|
||||
{
|
||||
return Minimum(node.Right);
|
||||
}
|
||||
|
||||
T parent = node.Parent;
|
||||
while (parent != null && node == parent.Right)
|
||||
{
|
||||
node = parent;
|
||||
parent = parent.Parent;
|
||||
}
|
||||
|
||||
return parent;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Finds the node whose key is immediately less than <paramref name="node"/>.
|
||||
/// </summary>
|
||||
/// <param name="node">Node to find the predecessor of</param>
|
||||
/// <returns>Predecessor of <paramref name="node"/></returns>
|
||||
internal static T PredecessorOf(T node)
|
||||
{
|
||||
if (node.Left != null)
|
||||
{
|
||||
return Maximum(node.Left);
|
||||
}
|
||||
|
||||
T parent = node.Parent;
|
||||
while (parent != null && node == parent.Left)
|
||||
{
|
||||
node = parent;
|
||||
parent = parent.Parent;
|
||||
}
|
||||
|
||||
return parent;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the node with the largest key where <paramref name="node"/> is considered the root node.
|
||||
/// </summary>
|
||||
/// <param name="node">Root node</param>
|
||||
/// <returns>Node with the maximum key in the tree of <paramref name="node"/></returns>
|
||||
protected static T Maximum(T node)
|
||||
{
|
||||
T tmp = node;
|
||||
while (tmp.Right != null)
|
||||
{
|
||||
tmp = tmp.Right;
|
||||
}
|
||||
|
||||
return tmp;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the node with the smallest key where <paramref name="node"/> is considered the root node.
|
||||
/// </summary>
|
||||
/// <param name="node">Root node</param>
|
||||
/// <returns>Node with the minimum key in the tree of <paramref name="node"/></returns>
|
||||
/// <exception cref="ArgumentNullException"><paramref name="node"/> is null</exception>
|
||||
protected static T Minimum(T node)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(node);
|
||||
|
||||
T tmp = node;
|
||||
while (tmp.Left != null)
|
||||
{
|
||||
tmp = tmp.Left;
|
||||
}
|
||||
|
||||
return tmp;
|
||||
}
|
||||
|
||||
protected void RestoreBalanceAfterRemoval(T balanceNode)
|
||||
{
|
||||
T ptr = balanceNode;
|
||||
|
||||
while (ptr != Root && ColorOf(ptr) == Black)
|
||||
{
|
||||
if (ptr == LeftOf(ParentOf(ptr)))
|
||||
{
|
||||
T sibling = RightOf(ParentOf(ptr));
|
||||
|
||||
if (ColorOf(sibling) == Red)
|
||||
{
|
||||
SetColor(sibling, Black);
|
||||
SetColor(ParentOf(ptr), Red);
|
||||
RotateLeft(ParentOf(ptr));
|
||||
sibling = RightOf(ParentOf(ptr));
|
||||
}
|
||||
|
||||
if (ColorOf(LeftOf(sibling)) == Black && ColorOf(RightOf(sibling)) == Black)
|
||||
{
|
||||
SetColor(sibling, Red);
|
||||
ptr = ParentOf(ptr);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (ColorOf(RightOf(sibling)) == Black)
|
||||
{
|
||||
SetColor(LeftOf(sibling), Black);
|
||||
SetColor(sibling, Red);
|
||||
RotateRight(sibling);
|
||||
sibling = RightOf(ParentOf(ptr));
|
||||
}
|
||||
|
||||
SetColor(sibling, ColorOf(ParentOf(ptr)));
|
||||
SetColor(ParentOf(ptr), Black);
|
||||
SetColor(RightOf(sibling), Black);
|
||||
RotateLeft(ParentOf(ptr));
|
||||
ptr = Root;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
T sibling = LeftOf(ParentOf(ptr));
|
||||
|
||||
if (ColorOf(sibling) == Red)
|
||||
{
|
||||
SetColor(sibling, Black);
|
||||
SetColor(ParentOf(ptr), Red);
|
||||
RotateRight(ParentOf(ptr));
|
||||
sibling = LeftOf(ParentOf(ptr));
|
||||
}
|
||||
|
||||
if (ColorOf(RightOf(sibling)) == Black && ColorOf(LeftOf(sibling)) == Black)
|
||||
{
|
||||
SetColor(sibling, Red);
|
||||
ptr = ParentOf(ptr);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (ColorOf(LeftOf(sibling)) == Black)
|
||||
{
|
||||
SetColor(RightOf(sibling), Black);
|
||||
SetColor(sibling, Red);
|
||||
RotateLeft(sibling);
|
||||
sibling = LeftOf(ParentOf(ptr));
|
||||
}
|
||||
|
||||
SetColor(sibling, ColorOf(ParentOf(ptr)));
|
||||
SetColor(ParentOf(ptr), Black);
|
||||
SetColor(LeftOf(sibling), Black);
|
||||
RotateRight(ParentOf(ptr));
|
||||
ptr = Root;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SetColor(ptr, Black);
|
||||
}
|
||||
|
||||
protected void RestoreBalanceAfterInsertion(T balanceNode)
|
||||
{
|
||||
SetColor(balanceNode, Red);
|
||||
while (balanceNode != null && balanceNode != Root && ColorOf(ParentOf(balanceNode)) == Red)
|
||||
{
|
||||
if (ParentOf(balanceNode) == LeftOf(ParentOf(ParentOf(balanceNode))))
|
||||
{
|
||||
T sibling = RightOf(ParentOf(ParentOf(balanceNode)));
|
||||
|
||||
if (ColorOf(sibling) == Red)
|
||||
{
|
||||
SetColor(ParentOf(balanceNode), Black);
|
||||
SetColor(sibling, Black);
|
||||
SetColor(ParentOf(ParentOf(balanceNode)), Red);
|
||||
balanceNode = ParentOf(ParentOf(balanceNode));
|
||||
}
|
||||
else
|
||||
{
|
||||
if (balanceNode == RightOf(ParentOf(balanceNode)))
|
||||
{
|
||||
balanceNode = ParentOf(balanceNode);
|
||||
RotateLeft(balanceNode);
|
||||
}
|
||||
|
||||
SetColor(ParentOf(balanceNode), Black);
|
||||
SetColor(ParentOf(ParentOf(balanceNode)), Red);
|
||||
RotateRight(ParentOf(ParentOf(balanceNode)));
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
T sibling = LeftOf(ParentOf(ParentOf(balanceNode)));
|
||||
|
||||
if (ColorOf(sibling) == Red)
|
||||
{
|
||||
SetColor(ParentOf(balanceNode), Black);
|
||||
SetColor(sibling, Black);
|
||||
SetColor(ParentOf(ParentOf(balanceNode)), Red);
|
||||
balanceNode = ParentOf(ParentOf(balanceNode));
|
||||
}
|
||||
else
|
||||
{
|
||||
if (balanceNode == LeftOf(ParentOf(balanceNode)))
|
||||
{
|
||||
balanceNode = ParentOf(balanceNode);
|
||||
RotateRight(balanceNode);
|
||||
}
|
||||
|
||||
SetColor(ParentOf(balanceNode), Black);
|
||||
SetColor(ParentOf(ParentOf(balanceNode)), Red);
|
||||
RotateLeft(ParentOf(ParentOf(balanceNode)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SetColor(Root, Black);
|
||||
}
|
||||
|
||||
protected virtual void RotateLeft(T node)
|
||||
{
|
||||
if (node != null)
|
||||
{
|
||||
T right = RightOf(node);
|
||||
node.Right = LeftOf(right);
|
||||
node.Right?.Parent = node;
|
||||
|
||||
T nodeParent = ParentOf(node);
|
||||
right.Parent = nodeParent;
|
||||
if (nodeParent == null)
|
||||
{
|
||||
Root = right;
|
||||
}
|
||||
else if (node == LeftOf(nodeParent))
|
||||
{
|
||||
nodeParent.Left = right;
|
||||
}
|
||||
else
|
||||
{
|
||||
nodeParent.Right = right;
|
||||
}
|
||||
|
||||
right.Left = node;
|
||||
node.Parent = right;
|
||||
}
|
||||
}
|
||||
|
||||
protected virtual void RotateRight(T node)
|
||||
{
|
||||
if (node != null)
|
||||
{
|
||||
T left = LeftOf(node);
|
||||
node.Left = RightOf(left);
|
||||
node.Left?.Parent = node;
|
||||
|
||||
T nodeParent = ParentOf(node);
|
||||
left.Parent = nodeParent;
|
||||
if (nodeParent == null)
|
||||
{
|
||||
Root = left;
|
||||
}
|
||||
else if (node == RightOf(nodeParent))
|
||||
{
|
||||
nodeParent.Right = left;
|
||||
}
|
||||
else
|
||||
{
|
||||
nodeParent.Left = left;
|
||||
}
|
||||
|
||||
left.Right = node;
|
||||
node.Parent = left;
|
||||
}
|
||||
}
|
||||
|
||||
#region Safety-Methods
|
||||
|
||||
// These methods save memory by allowing us to forego sentinel nil nodes, as well as serve as protection against NullReferenceExceptions.
|
||||
|
||||
/// <summary>
|
||||
/// Returns the color of <paramref name="node"/>, or Black if it is null.
|
||||
/// </summary>
|
||||
/// <param name="node">Node</param>
|
||||
/// <returns>The boolean color of <paramref name="node"/>, or black if null</returns>
|
||||
protected static bool ColorOf(T node)
|
||||
{
|
||||
return node == null || node.Color;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the color of <paramref name="node"/> node to <paramref name="color"/>.
|
||||
/// <br></br>
|
||||
/// This method does nothing if <paramref name="node"/> is null.
|
||||
/// </summary>
|
||||
/// <param name="node">Node to set the color of</param>
|
||||
/// <param name="color">Color (Boolean)</param>
|
||||
protected static void SetColor(T node, bool color)
|
||||
{
|
||||
node?.Color = color;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// This method returns the left node of <paramref name="node"/>, or null if <paramref name="node"/> is null.
|
||||
/// </summary>
|
||||
/// <param name="node">Node to retrieve the left child from</param>
|
||||
/// <returns>Left child of <paramref name="node"/></returns>
|
||||
protected static T LeftOf(T node)
|
||||
{
|
||||
return node?.Left;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// This method returns the right node of <paramref name="node"/>, or null if <paramref name="node"/> is null.
|
||||
/// </summary>
|
||||
/// <param name="node">Node to retrieve the right child from</param>
|
||||
/// <returns>Right child of <paramref name="node"/></returns>
|
||||
protected static T RightOf(T node)
|
||||
{
|
||||
return node?.Right;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the parent node of <paramref name="node"/>, or null if <paramref name="node"/> is null.
|
||||
/// </summary>
|
||||
/// <param name="node">Node to retrieve the parent from</param>
|
||||
/// <returns>Parent of <paramref name="node"/></returns>
|
||||
protected static T ParentOf(T node)
|
||||
{
|
||||
return node?.Parent;
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
15
tools/vendor/ryujinx/src/Ryujinx.Common/Collections/IntrusiveRedBlackTreeNode.cs
vendored
Normal file
15
tools/vendor/ryujinx/src/Ryujinx.Common/Collections/IntrusiveRedBlackTreeNode.cs
vendored
Normal file
@@ -0,0 +1,15 @@
|
||||
namespace Ryujinx.Common.Collections
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents a node in the Red-Black Tree.
|
||||
/// </summary>
|
||||
public class IntrusiveRedBlackTreeNode<T> where T : IntrusiveRedBlackTreeNode<T>
|
||||
{
|
||||
public bool Color = true;
|
||||
public T Left;
|
||||
public T Right;
|
||||
public T Parent;
|
||||
public T Predecessor;
|
||||
public T Successor;
|
||||
}
|
||||
}
|
||||
632
tools/vendor/ryujinx/src/Ryujinx.Common/Collections/TreeDictionary.cs
vendored
Normal file
632
tools/vendor/ryujinx/src/Ryujinx.Common/Collections/TreeDictionary.cs
vendored
Normal file
@@ -0,0 +1,632 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
|
||||
namespace Ryujinx.Common.Collections
|
||||
{
|
||||
/// <summary>
|
||||
/// Dictionary that provides the ability for O(logN) Lookups for keys that exist in the Dictionary, and O(logN) lookups for keys immediately greater than or less than a specified key.
|
||||
/// </summary>
|
||||
/// <typeparam name="TKey">Key</typeparam>
|
||||
/// <typeparam name="TValue">Value</typeparam>
|
||||
public class TreeDictionary<TKey, TValue> : IntrusiveRedBlackTreeImpl<Node<TKey, TValue>>, IDictionary<TKey, TValue> where TKey : IComparable<TKey>
|
||||
{
|
||||
#region Public Methods
|
||||
|
||||
/// <summary>
|
||||
/// Returns the value of the node whose key is <paramref name="key"/>, or the default value if no such node exists.
|
||||
/// </summary>
|
||||
/// <param name="key">Key of the node value to get</param>
|
||||
/// <returns>Value associated w/ <paramref name="key"/></returns>
|
||||
/// <exception cref="ArgumentNullException"><paramref name="key"/> is null</exception>
|
||||
public TValue Get(TKey key)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(key);
|
||||
|
||||
Node<TKey, TValue> node = GetNode(key);
|
||||
|
||||
if (node == null)
|
||||
{
|
||||
return default;
|
||||
}
|
||||
|
||||
return node.Value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a new node into the tree whose key is <paramref name="key"/> key and value is <paramref name="value"/>.
|
||||
/// <br></br>
|
||||
/// <b>Note:</b> Adding the same key multiple times will cause the value for that key to be overwritten.
|
||||
/// </summary>
|
||||
/// <param name="key">Key of the node to add</param>
|
||||
/// <param name="value">Value of the node to add</param>
|
||||
/// <exception cref="ArgumentNullException"><paramref name="key"/> or <paramref name="value"/> are null</exception>
|
||||
public void Add(TKey key, TValue value)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(key);
|
||||
ArgumentNullException.ThrowIfNull(value);
|
||||
|
||||
Insert(key, value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the node whose key is <paramref name="key"/> from the tree.
|
||||
/// </summary>
|
||||
/// <param name="key">Key of the node to remove</param>
|
||||
/// <exception cref="ArgumentNullException"><paramref name="key"/> is null</exception>
|
||||
public void Remove(TKey key)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(key);
|
||||
|
||||
if (Delete(key) != null)
|
||||
{
|
||||
Count--;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the value whose key is equal to or immediately less than <paramref name="key"/>.
|
||||
/// </summary>
|
||||
/// <param name="key">Key for which to find the floor value of</param>
|
||||
/// <returns>Key of node immediately less than <paramref name="key"/></returns>
|
||||
/// <exception cref="ArgumentNullException"><paramref name="key"/> is null</exception>
|
||||
public TKey Floor(TKey key)
|
||||
{
|
||||
Node<TKey, TValue> node = FloorNode(key);
|
||||
if (node != null)
|
||||
{
|
||||
return node.Key;
|
||||
}
|
||||
|
||||
return default;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the node whose key is equal to or immediately greater than <paramref name="key"/>.
|
||||
/// </summary>
|
||||
/// <param name="key">Key for which to find the ceiling node of</param>
|
||||
/// <returns>Key of node immediately greater than <paramref name="key"/></returns>
|
||||
/// <exception cref="ArgumentNullException"><paramref name="key"/> is null</exception>
|
||||
public TKey Ceiling(TKey key)
|
||||
{
|
||||
Node<TKey, TValue> node = CeilingNode(key);
|
||||
if (node != null)
|
||||
{
|
||||
return node.Key;
|
||||
}
|
||||
|
||||
return default;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Finds the value whose key is immediately greater than <paramref name="key"/>.
|
||||
/// </summary>
|
||||
/// <param name="key">Key to find the successor of</param>
|
||||
/// <returns>Value</returns>
|
||||
public TKey SuccessorOf(TKey key)
|
||||
{
|
||||
Node<TKey, TValue> node = GetNode(key);
|
||||
if (node != null)
|
||||
{
|
||||
Node<TKey, TValue> successor = node.Successor;
|
||||
|
||||
return successor != null ? successor.Key : default;
|
||||
}
|
||||
|
||||
return default;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Finds the value whose key is immediately less than <paramref name="key"/>.
|
||||
/// </summary>
|
||||
/// <param name="key">Key to find the predecessor of</param>
|
||||
/// <returns>Value</returns>
|
||||
public TKey PredecessorOf(TKey key)
|
||||
{
|
||||
Node<TKey, TValue> node = GetNode(key);
|
||||
if (node != null)
|
||||
{
|
||||
Node<TKey, TValue> predecessor = node.Predecessor;
|
||||
|
||||
return predecessor != null ? predecessor.Key : default;
|
||||
}
|
||||
|
||||
return default;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds all the nodes in the dictionary as key/value pairs into a list.
|
||||
/// <br></br>
|
||||
/// The key/value pairs will be added in Level Order.
|
||||
/// </summary>
|
||||
public List<KeyValuePair<TKey, TValue>> AsLevelOrderList()
|
||||
{
|
||||
List<KeyValuePair<TKey, TValue>> list = [];
|
||||
|
||||
Queue<Node<TKey, TValue>> nodes = new();
|
||||
|
||||
if (this.Root != null)
|
||||
{
|
||||
nodes.Enqueue(this.Root);
|
||||
}
|
||||
|
||||
while (nodes.TryDequeue(out Node<TKey, TValue> node))
|
||||
{
|
||||
list.Add(new KeyValuePair<TKey, TValue>(node.Key, node.Value));
|
||||
if (node.Left != null)
|
||||
{
|
||||
nodes.Enqueue(node.Left);
|
||||
}
|
||||
|
||||
if (node.Right != null)
|
||||
{
|
||||
nodes.Enqueue(node.Right);
|
||||
}
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds all the nodes in the dictionary into a list.
|
||||
/// </summary>
|
||||
/// <returns>A list of all KeyValuePairs sorted by Key Order</returns>
|
||||
public List<KeyValuePair<TKey, TValue>> AsList()
|
||||
{
|
||||
List<KeyValuePair<TKey, TValue>> list = [];
|
||||
|
||||
AddToList(Root, list);
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Private Methods (BST)
|
||||
|
||||
/// <summary>
|
||||
/// Adds all nodes that are children of or contained within <paramref name="node"/> into <paramref name="list"/>, in Key Order.
|
||||
/// </summary>
|
||||
/// <param name="node">The node to search for nodes within</param>
|
||||
/// <param name="list">The list to add node to</param>
|
||||
private static void AddToList(Node<TKey, TValue> node, List<KeyValuePair<TKey, TValue>> list)
|
||||
{
|
||||
if (node == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
AddToList(node.Left, list);
|
||||
|
||||
list.Add(new KeyValuePair<TKey, TValue>(node.Key, node.Value));
|
||||
|
||||
AddToList(node.Right, list);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Retrieve the node reference whose key is <paramref name="key"/>, or null if no such node exists.
|
||||
/// </summary>
|
||||
/// <param name="key">Key of the node to get</param>
|
||||
/// <returns>Node reference in the tree</returns>
|
||||
/// <exception cref="ArgumentNullException"><paramref name="key"/> is null</exception>
|
||||
private Node<TKey, TValue> GetNode(TKey key)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(key);
|
||||
|
||||
Node<TKey, TValue> node = Root;
|
||||
while (node != null)
|
||||
{
|
||||
int cmp = key.CompareTo(node.Key);
|
||||
if (cmp < 0)
|
||||
{
|
||||
node = node.Left;
|
||||
}
|
||||
else if (cmp > 0)
|
||||
{
|
||||
node = node.Right;
|
||||
}
|
||||
else
|
||||
{
|
||||
return node;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Inserts a new node into the tree whose key is <paramref name="key"/> and value is <paramref name="value"/>.
|
||||
/// <br></br>
|
||||
/// Adding the same key multiple times will overwrite the previous value.
|
||||
/// </summary>
|
||||
/// <param name="key">Key of the node to insert</param>
|
||||
/// <param name="value">Value of the node to insert</param>
|
||||
private void Insert(TKey key, TValue value)
|
||||
{
|
||||
Node<TKey, TValue> newNode = BSTInsert(key, value);
|
||||
RestoreBalanceAfterInsertion(newNode);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Insertion Mechanism for a Binary Search Tree (BST).
|
||||
/// <br></br>
|
||||
/// Iterates the tree starting from the root and inserts a new node where all children in the left subtree are less than <paramref name="key"/>, and all children in the right subtree are greater than <paramref name="key"/>.
|
||||
/// <br></br>
|
||||
/// <b>Note: </b> If a node whose key is <paramref name="key"/> already exists, it's value will be overwritten.
|
||||
/// </summary>
|
||||
/// <param name="key">Key of the node to insert</param>
|
||||
/// <param name="value">Value of the node to insert</param>
|
||||
/// <returns>The inserted Node</returns>
|
||||
private Node<TKey, TValue> BSTInsert(TKey key, TValue value)
|
||||
{
|
||||
Node<TKey, TValue> parent = null;
|
||||
Node<TKey, TValue> node = Root;
|
||||
|
||||
while (node != null)
|
||||
{
|
||||
parent = node;
|
||||
int cmp = key.CompareTo(node.Key);
|
||||
if (cmp < 0)
|
||||
{
|
||||
node = node.Left;
|
||||
}
|
||||
else if (cmp > 0)
|
||||
{
|
||||
node = node.Right;
|
||||
}
|
||||
else
|
||||
{
|
||||
node.Value = value;
|
||||
return node;
|
||||
}
|
||||
}
|
||||
|
||||
Node<TKey, TValue> newNode = new(key, value, parent);
|
||||
if (parent == null)
|
||||
{
|
||||
Root = newNode;
|
||||
}
|
||||
else if (key.CompareTo(parent.Key) < 0)
|
||||
{
|
||||
parent.Left = newNode;
|
||||
}
|
||||
else
|
||||
{
|
||||
parent.Right = newNode;
|
||||
}
|
||||
|
||||
Count++;
|
||||
return newNode;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes <paramref name="key"/> from the dictionary, if it exists.
|
||||
/// </summary>
|
||||
/// <param name="key">Key of the node to delete</param>
|
||||
/// <returns>The deleted Node</returns>
|
||||
private Node<TKey, TValue> Delete(TKey key)
|
||||
{
|
||||
// O(1) Retrieval
|
||||
Node<TKey, TValue> nodeToDelete = GetNode(key);
|
||||
|
||||
if (nodeToDelete == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
Node<TKey, TValue> replacementNode;
|
||||
|
||||
if (LeftOf(nodeToDelete) == null || RightOf(nodeToDelete) == null)
|
||||
{
|
||||
replacementNode = nodeToDelete;
|
||||
}
|
||||
else
|
||||
{
|
||||
replacementNode = PredecessorOf(nodeToDelete);
|
||||
}
|
||||
|
||||
Node<TKey, TValue> tmp = LeftOf(replacementNode) ?? RightOf(replacementNode);
|
||||
|
||||
tmp?.Parent = ParentOf(replacementNode);
|
||||
|
||||
if (ParentOf(replacementNode) == null)
|
||||
{
|
||||
Root = tmp;
|
||||
}
|
||||
else if (replacementNode == LeftOf(ParentOf(replacementNode)))
|
||||
{
|
||||
ParentOf(replacementNode).Left = tmp;
|
||||
}
|
||||
else
|
||||
{
|
||||
ParentOf(replacementNode).Right = tmp;
|
||||
}
|
||||
|
||||
if (replacementNode != nodeToDelete)
|
||||
{
|
||||
nodeToDelete.Key = replacementNode.Key;
|
||||
nodeToDelete.Value = replacementNode.Value;
|
||||
}
|
||||
|
||||
if (tmp != null && ColorOf(replacementNode) == Black)
|
||||
{
|
||||
RestoreBalanceAfterRemoval(tmp);
|
||||
}
|
||||
|
||||
return replacementNode;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the node whose key immediately less than or equal to <paramref name="key"/>.
|
||||
/// </summary>
|
||||
/// <param name="key">Key for which to find the floor node of</param>
|
||||
/// <returns>Node whose key is immediately less than or equal to <paramref name="key"/>, or null if no such node is found.</returns>
|
||||
/// <exception cref="ArgumentNullException"><paramref name="key"/> is null</exception>
|
||||
private Node<TKey, TValue> FloorNode(TKey key)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(key);
|
||||
|
||||
Node<TKey, TValue> tmp = Root;
|
||||
|
||||
while (tmp != null)
|
||||
{
|
||||
int cmp = key.CompareTo(tmp.Key);
|
||||
if (cmp > 0)
|
||||
{
|
||||
if (tmp.Right != null)
|
||||
{
|
||||
tmp = tmp.Right;
|
||||
}
|
||||
else
|
||||
{
|
||||
return tmp;
|
||||
}
|
||||
}
|
||||
else if (cmp < 0)
|
||||
{
|
||||
if (tmp.Left != null)
|
||||
{
|
||||
tmp = tmp.Left;
|
||||
}
|
||||
else
|
||||
{
|
||||
Node<TKey, TValue> parent = tmp.Parent;
|
||||
Node<TKey, TValue> ptr = tmp;
|
||||
while (parent != null && ptr == parent.Left)
|
||||
{
|
||||
ptr = parent;
|
||||
parent = parent.Parent;
|
||||
}
|
||||
|
||||
return parent;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
return tmp;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the node whose key is immediately greater than or equal to than <paramref name="key"/>.
|
||||
/// </summary>
|
||||
/// <param name="key">Key for which to find the ceiling node of</param>
|
||||
/// <returns>Node whose key is immediately greater than or equal to <paramref name="key"/>, or null if no such node is found.</returns>
|
||||
/// <exception cref="ArgumentNullException"><paramref name="key"/> is null</exception>
|
||||
private Node<TKey, TValue> CeilingNode(TKey key)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(key);
|
||||
|
||||
Node<TKey, TValue> tmp = Root;
|
||||
|
||||
while (tmp != null)
|
||||
{
|
||||
int cmp = key.CompareTo(tmp.Key);
|
||||
if (cmp < 0)
|
||||
{
|
||||
if (tmp.Left != null)
|
||||
{
|
||||
tmp = tmp.Left;
|
||||
}
|
||||
else
|
||||
{
|
||||
return tmp;
|
||||
}
|
||||
}
|
||||
else if (cmp > 0)
|
||||
{
|
||||
if (tmp.Right != null)
|
||||
{
|
||||
tmp = tmp.Right;
|
||||
}
|
||||
else
|
||||
{
|
||||
Node<TKey, TValue> parent = tmp.Parent;
|
||||
Node<TKey, TValue> ptr = tmp;
|
||||
while (parent != null && ptr == parent.Right)
|
||||
{
|
||||
ptr = parent;
|
||||
parent = parent.Parent;
|
||||
}
|
||||
|
||||
return parent;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
return tmp;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Interface Implementations
|
||||
|
||||
// Method descriptions are not provided as they are already included as part of the interface.
|
||||
public bool ContainsKey(TKey key)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(key);
|
||||
|
||||
return GetNode(key) != null;
|
||||
}
|
||||
|
||||
bool IDictionary<TKey, TValue>.Remove(TKey key)
|
||||
{
|
||||
int count = Count;
|
||||
Remove(key);
|
||||
return count > Count;
|
||||
}
|
||||
|
||||
public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(key);
|
||||
|
||||
Node<TKey, TValue> node = GetNode(key);
|
||||
value = node != null ? node.Value : default;
|
||||
return node != null;
|
||||
}
|
||||
|
||||
public void Add(KeyValuePair<TKey, TValue> item)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(item.Key);
|
||||
|
||||
Add(item.Key, item.Value);
|
||||
}
|
||||
|
||||
public bool Contains(KeyValuePair<TKey, TValue> item)
|
||||
{
|
||||
if (item.Key == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
Node<TKey, TValue> node = GetNode(item.Key);
|
||||
if (node != null)
|
||||
{
|
||||
return node.Key.Equals(item.Key) && node.Value.Equals(item.Value);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
|
||||
{
|
||||
if (arrayIndex < 0 || array.Length - arrayIndex < this.Count)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(arrayIndex));
|
||||
}
|
||||
|
||||
SortedList<TKey, TValue> list = GetKeyValues();
|
||||
|
||||
int offset = 0;
|
||||
|
||||
for (int i = arrayIndex; i < array.Length && offset < list.Count; i++)
|
||||
{
|
||||
array[i] = new KeyValuePair<TKey, TValue>(list.Keys[i], list.Values[i]);
|
||||
offset++;
|
||||
}
|
||||
}
|
||||
|
||||
public bool Remove(KeyValuePair<TKey, TValue> item)
|
||||
{
|
||||
Node<TKey, TValue> node = GetNode(item.Key);
|
||||
|
||||
if (node == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (node.Value.Equals(item.Value))
|
||||
{
|
||||
int count = Count;
|
||||
Remove(item.Key);
|
||||
return count > Count;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
|
||||
{
|
||||
return GetKeyValues().GetEnumerator();
|
||||
}
|
||||
|
||||
IEnumerator IEnumerable.GetEnumerator()
|
||||
{
|
||||
return GetKeyValues().GetEnumerator();
|
||||
}
|
||||
|
||||
public ICollection<TKey> Keys => GetKeyValues().Keys;
|
||||
|
||||
public ICollection<TValue> Values => GetKeyValues().Values;
|
||||
|
||||
public bool IsReadOnly => false;
|
||||
|
||||
public TValue this[TKey key]
|
||||
{
|
||||
get => Get(key);
|
||||
set => Add(key, value);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Private Interface Helper Methods
|
||||
|
||||
/// <summary>
|
||||
/// Returns a sorted list of all the node keys / values in the tree.
|
||||
/// </summary>
|
||||
/// <returns>List of node keys</returns>
|
||||
private SortedList<TKey, TValue> GetKeyValues()
|
||||
{
|
||||
SortedList<TKey, TValue> set = new();
|
||||
Queue<Node<TKey, TValue>> queue = new();
|
||||
if (Root != null)
|
||||
{
|
||||
queue.Enqueue(Root);
|
||||
}
|
||||
|
||||
while (queue.TryDequeue(out Node<TKey, TValue> node))
|
||||
{
|
||||
set.Add(node.Key, node.Value);
|
||||
if (null != node.Left)
|
||||
{
|
||||
queue.Enqueue(node.Left);
|
||||
}
|
||||
|
||||
if (null != node.Right)
|
||||
{
|
||||
queue.Enqueue(node.Right);
|
||||
}
|
||||
}
|
||||
|
||||
return set;
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Represents a node in the TreeDictionary which contains a key and value of generic type K and V, respectively.
|
||||
/// </summary>
|
||||
/// <typeparam name="TKey">Key of the node</typeparam>
|
||||
/// <typeparam name="TValue">Value of the node</typeparam>
|
||||
public class Node<TKey, TValue> : IntrusiveRedBlackTreeNode<Node<TKey, TValue>> where TKey : IComparable<TKey>
|
||||
{
|
||||
internal TKey Key;
|
||||
internal TValue Value;
|
||||
|
||||
internal Node(TKey key, TValue value, Node<TKey, TValue> parent)
|
||||
{
|
||||
Key = key;
|
||||
Value = value;
|
||||
Parent = parent;
|
||||
}
|
||||
}
|
||||
}
|
||||
15
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/AntiAliasing.cs
vendored
Normal file
15
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/AntiAliasing.cs
vendored
Normal file
@@ -0,0 +1,15 @@
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Ryujinx.Common.Configuration
|
||||
{
|
||||
[JsonConverter(typeof(JsonStringEnumConverter<AntiAliasing>))]
|
||||
public enum AntiAliasing
|
||||
{
|
||||
None,
|
||||
Fxaa,
|
||||
SmaaLow,
|
||||
SmaaMedium,
|
||||
SmaaHigh,
|
||||
SmaaUltra,
|
||||
}
|
||||
}
|
||||
328
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/AppDataManager.cs
vendored
Normal file
328
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/AppDataManager.cs
vendored
Normal file
@@ -0,0 +1,328 @@
|
||||
using Ryujinx.Common.Logging;
|
||||
using Ryujinx.Common.Utilities;
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Runtime.Versioning;
|
||||
|
||||
namespace Ryujinx.Common.Configuration
|
||||
{
|
||||
public static class AppDataManager
|
||||
{
|
||||
private const string DefaultBaseDir = "Ryujinx";
|
||||
private const string DefaultPortableDir = "portable";
|
||||
|
||||
// The following 3 are always part of Base Directory
|
||||
private const string GamesDir = "games";
|
||||
private const string ProfilesDir = "profiles";
|
||||
private const string KeysDir = "system";
|
||||
|
||||
public enum LaunchMode
|
||||
{
|
||||
UserProfile,
|
||||
Portable,
|
||||
Custom,
|
||||
}
|
||||
|
||||
public static LaunchMode Mode { get; private set; }
|
||||
|
||||
public static string BaseDirPath { get; private set; }
|
||||
public static string GamesDirPath { get; private set; }
|
||||
public static string ProfilesDirPath { get; private set; }
|
||||
public static string KeysDirPath { get; private set; }
|
||||
public static string KeysDirPathUser { get; }
|
||||
|
||||
public static string LogsDirPath { get; private set; }
|
||||
|
||||
public const string DefaultNandDir = "bis";
|
||||
public const string DefaultSdcardDir = "sdcard";
|
||||
private const string DefaultModsDir = "mods";
|
||||
|
||||
public static string CustomModsPath { get; set; }
|
||||
public static string CustomSdModsPath { get; set; }
|
||||
public static string CustomNandPath { get; set; } // TODO: Actually implement this into VFS
|
||||
public static string CustomSdCardPath { get; set; } // TODO: Actually implement this into VFS
|
||||
|
||||
static AppDataManager()
|
||||
{
|
||||
KeysDirPathUser = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".switch");
|
||||
}
|
||||
|
||||
public static void Initialize(string baseDirPath)
|
||||
{
|
||||
string appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
|
||||
|
||||
if (appDataPath.Length == 0)
|
||||
{
|
||||
appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
|
||||
}
|
||||
|
||||
string userProfilePath = Path.Combine(appDataPath, DefaultBaseDir);
|
||||
string portablePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, DefaultPortableDir);
|
||||
|
||||
// On macOS, check for a portable directory next to the app bundle as well.
|
||||
if (OperatingSystem.IsMacOS() && !Directory.Exists(portablePath))
|
||||
{
|
||||
string bundlePath = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..", ".."));
|
||||
// Make sure we're actually running within an app bundle.
|
||||
if (bundlePath.EndsWith(".app"))
|
||||
{
|
||||
portablePath = Path.GetFullPath(Path.Combine(bundlePath, "..", DefaultPortableDir));
|
||||
}
|
||||
}
|
||||
|
||||
if (Directory.Exists(portablePath))
|
||||
{
|
||||
BaseDirPath = portablePath;
|
||||
Mode = LaunchMode.Portable;
|
||||
}
|
||||
else
|
||||
{
|
||||
BaseDirPath = userProfilePath;
|
||||
Mode = LaunchMode.UserProfile;
|
||||
}
|
||||
|
||||
if (baseDirPath != null && baseDirPath != userProfilePath)
|
||||
{
|
||||
if (!Directory.Exists(baseDirPath))
|
||||
{
|
||||
Logger.Error?.Print(LogClass.Application, $"Custom Data Directory '{baseDirPath}' does not exist. Falling back to {Mode}...");
|
||||
}
|
||||
else
|
||||
{
|
||||
BaseDirPath = baseDirPath;
|
||||
Mode = LaunchMode.Custom;
|
||||
}
|
||||
}
|
||||
|
||||
BaseDirPath = Path.GetFullPath(BaseDirPath); // convert relative paths
|
||||
|
||||
if (IsPathSymlink(BaseDirPath))
|
||||
{
|
||||
Logger.Warning?.Print(LogClass.Application, "Application data directory is a symlink. This may be unintended.");
|
||||
}
|
||||
|
||||
SetupBasePaths();
|
||||
}
|
||||
|
||||
public static string GetOrCreateLogsDir()
|
||||
{
|
||||
if (Directory.Exists(LogsDirPath))
|
||||
{
|
||||
return LogsDirPath;
|
||||
}
|
||||
|
||||
Logger.Notice.Print(LogClass.Application, "Logging directory not found; attempting to create new logging directory.");
|
||||
LogsDirPath = SetUpLogsDir();
|
||||
|
||||
return LogsDirPath;
|
||||
}
|
||||
|
||||
private static string SetUpLogsDir()
|
||||
{
|
||||
string logDir = string.Empty;
|
||||
|
||||
if (Mode == LaunchMode.Portable)
|
||||
{
|
||||
logDir = Path.Combine(BaseDirPath, "Logs");
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(logDir);
|
||||
}
|
||||
catch
|
||||
{
|
||||
Logger.Warning?.Print(LogClass.Application, $"Logging directory could not be created '{logDir}'");
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (OperatingSystem.IsMacOS())
|
||||
{
|
||||
// NOTE: Should evaluate to "~/Library/Logs/Ryujinx/".
|
||||
logDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Library", "Logs", DefaultBaseDir);
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(logDir);
|
||||
}
|
||||
catch
|
||||
{
|
||||
Logger.Warning?.Print(LogClass.Application, $"Logging directory could not be created '{logDir}'");
|
||||
logDir = string.Empty;
|
||||
}
|
||||
|
||||
if (string.IsNullOrEmpty(logDir))
|
||||
{
|
||||
// NOTE: Should evaluate to "~/Library/Application Support/Ryujinx/Logs".
|
||||
logDir = Path.Combine(BaseDirPath, "Logs");
|
||||
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(logDir);
|
||||
}
|
||||
catch
|
||||
{
|
||||
Logger.Warning?.Print(LogClass.Application, $"Logging directory could not be created '{logDir}'");
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (OperatingSystem.IsWindows())
|
||||
{
|
||||
// NOTE: Should evaluate to a "Logs" directory in whatever directory Ryujinx was launched from.
|
||||
logDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Logs");
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(logDir);
|
||||
}
|
||||
catch
|
||||
{
|
||||
Logger.Warning?.Print(LogClass.Application, $"Logging directory could not be created '{logDir}'");
|
||||
logDir = string.Empty;
|
||||
}
|
||||
|
||||
if (string.IsNullOrEmpty(logDir))
|
||||
{
|
||||
// NOTE: Should evaluate to "C:\Users\user\AppData\Roaming\Ryujinx\Logs".
|
||||
logDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), DefaultBaseDir, "Logs");
|
||||
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(logDir);
|
||||
}
|
||||
catch
|
||||
{
|
||||
Logger.Warning?.Print(LogClass.Application, $"Logging directory could not be created '{logDir}'");
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (OperatingSystem.IsLinux())
|
||||
{
|
||||
// NOTE: Should evaluate to "~/.config/Ryujinx/Logs".
|
||||
logDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), DefaultBaseDir, "Logs");
|
||||
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(logDir);
|
||||
}
|
||||
catch
|
||||
{
|
||||
Logger.Warning?.Print(LogClass.Application, $"Logging directory could not be created '{logDir}'");
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return logDir;
|
||||
}
|
||||
|
||||
private static void SetupBasePaths()
|
||||
{
|
||||
Directory.CreateDirectory(BaseDirPath);
|
||||
LogsDirPath = SetUpLogsDir();
|
||||
Directory.CreateDirectory(GamesDirPath = Path.Combine(BaseDirPath, GamesDir));
|
||||
Directory.CreateDirectory(ProfilesDirPath = Path.Combine(BaseDirPath, ProfilesDir));
|
||||
Directory.CreateDirectory(KeysDirPath = Path.Combine(BaseDirPath, KeysDir));
|
||||
}
|
||||
|
||||
// Check if existing old baseDirPath is a symlink, to prevent possible errors.
|
||||
// Should be removed, when the existence of the old directory isn't checked anymore.
|
||||
private static bool IsPathSymlink(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
FileAttributes attributes = File.GetAttributes(path);
|
||||
return (attributes & FileAttributes.ReparsePoint) == FileAttributes.ReparsePoint;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
[SupportedOSPlatform("macos")]
|
||||
public static void FixMacOSConfigurationFolders()
|
||||
{
|
||||
string oldConfigPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),
|
||||
".config", DefaultBaseDir);
|
||||
if (Path.Exists(oldConfigPath) && !IsPathSymlink(oldConfigPath) && !Path.Exists(BaseDirPath))
|
||||
{
|
||||
FileSystemUtils.MoveDirectory(oldConfigPath, BaseDirPath);
|
||||
Directory.CreateSymbolicLink(oldConfigPath, BaseDirPath);
|
||||
}
|
||||
|
||||
string correctApplicationDataDirectoryPath =
|
||||
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), DefaultBaseDir);
|
||||
if (IsPathSymlink(correctApplicationDataDirectoryPath))
|
||||
{
|
||||
//copy the files somewhere temporarily
|
||||
string tempPath = Path.Combine(Path.GetTempPath(), DefaultBaseDir);
|
||||
try
|
||||
{
|
||||
FileSystemUtils.CopyDirectory(correctApplicationDataDirectoryPath, tempPath, true);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
Logger.Error?.Print(LogClass.Application,
|
||||
$"Critical error copying Ryujinx application data into the temp folder. {exception}");
|
||||
try
|
||||
{
|
||||
FileSystemInfo resolvedDirectoryInfo =
|
||||
Directory.ResolveLinkTarget(correctApplicationDataDirectoryPath, true);
|
||||
string resolvedPath = resolvedDirectoryInfo.FullName;
|
||||
Logger.Error?.Print(LogClass.Application, $"Please manually move your Ryujinx data from {resolvedPath} to {correctApplicationDataDirectoryPath}, and remove the symlink.");
|
||||
}
|
||||
catch (Exception symlinkException)
|
||||
{
|
||||
Logger.Error?.Print(LogClass.Application, $"Unable to resolve the symlink for Ryujinx application data: {symlinkException}. Follow the symlink at {correctApplicationDataDirectoryPath} and move your data back to the Application Support folder.");
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
//delete the symlink
|
||||
try
|
||||
{
|
||||
//This will fail if this is an actual directory, so there is no way we can actually delete user data here.
|
||||
File.Delete(correctApplicationDataDirectoryPath);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
Logger.Error?.Print(LogClass.Application,
|
||||
$"Critical error deleting the Ryujinx application data folder symlink at {correctApplicationDataDirectoryPath}. {exception}");
|
||||
try
|
||||
{
|
||||
FileSystemInfo resolvedDirectoryInfo =
|
||||
Directory.ResolveLinkTarget(correctApplicationDataDirectoryPath, true);
|
||||
string resolvedPath = resolvedDirectoryInfo.FullName;
|
||||
Logger.Error?.Print(LogClass.Application, $"Please manually move your Ryujinx data from {resolvedPath} to {correctApplicationDataDirectoryPath}, and remove the symlink.");
|
||||
}
|
||||
catch (Exception symlinkException)
|
||||
{
|
||||
Logger.Error?.Print(LogClass.Application, $"Unable to resolve the symlink for Ryujinx application data: {symlinkException}. Follow the symlink at {correctApplicationDataDirectoryPath} and move your data back to the Application Support folder.");
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
//put the files back
|
||||
try
|
||||
{
|
||||
FileSystemUtils.CopyDirectory(tempPath, correctApplicationDataDirectoryPath, true);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
Logger.Error?.Print(LogClass.Application,
|
||||
$"Critical error copying Ryujinx application data into the correct location. {exception}. Please manually move your application data from {tempPath} to {correctApplicationDataDirectoryPath}.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static string GetModsPath() => CustomModsPath ?? Directory.CreateDirectory(Path.Combine(BaseDirPath, DefaultModsDir)).FullName;
|
||||
public static string GetSdModsPath() => CustomSdModsPath ?? Directory.CreateDirectory(Path.Combine(BaseDirPath, DefaultSdcardDir, "atmosphere")).FullName;
|
||||
}
|
||||
}
|
||||
70
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/AspectRatioExtensions.cs
vendored
Normal file
70
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/AspectRatioExtensions.cs
vendored
Normal file
@@ -0,0 +1,70 @@
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Ryujinx.Common.Configuration
|
||||
{
|
||||
[JsonConverter(typeof(JsonStringEnumConverter<AspectRatio>))]
|
||||
public enum AspectRatio
|
||||
{
|
||||
Fixed4x3,
|
||||
Fixed16x9,
|
||||
Fixed16x10,
|
||||
Fixed21x9,
|
||||
Fixed32x9,
|
||||
Stretched,
|
||||
}
|
||||
|
||||
public static class AspectRatioExtensions
|
||||
{
|
||||
public static float ToFloat(this AspectRatio aspectRatio)
|
||||
{
|
||||
return aspectRatio.ToFloatX() / aspectRatio.ToFloatY();
|
||||
}
|
||||
|
||||
public static float ToFloatX(this AspectRatio aspectRatio)
|
||||
{
|
||||
return aspectRatio switch
|
||||
{
|
||||
#pragma warning disable IDE0055 // Disable formatting
|
||||
AspectRatio.Fixed4x3 => 4.0f,
|
||||
AspectRatio.Fixed16x9 => 16.0f,
|
||||
AspectRatio.Fixed16x10 => 16.0f,
|
||||
AspectRatio.Fixed21x9 => 21.0f,
|
||||
AspectRatio.Fixed32x9 => 32.0f,
|
||||
_ => 16.0f,
|
||||
#pragma warning restore IDE0055
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
|
||||
public static float ToFloatY(this AspectRatio aspectRatio)
|
||||
{
|
||||
return aspectRatio switch
|
||||
{
|
||||
#pragma warning disable IDE0055 // Disable formatting
|
||||
AspectRatio.Fixed4x3 => 3.0f,
|
||||
AspectRatio.Fixed16x9 => 9.0f,
|
||||
AspectRatio.Fixed16x10 => 10.0f,
|
||||
AspectRatio.Fixed21x9 => 9.0f,
|
||||
AspectRatio.Fixed32x9 => 9.0f,
|
||||
_ => 9.0f,
|
||||
#pragma warning restore IDE0055
|
||||
};
|
||||
}
|
||||
|
||||
public static string ToText(this AspectRatio aspectRatio)
|
||||
{
|
||||
return aspectRatio switch
|
||||
{
|
||||
#pragma warning disable IDE0055 // Disable formatting
|
||||
AspectRatio.Fixed4x3 => "4:3",
|
||||
AspectRatio.Fixed16x9 => "16:9",
|
||||
AspectRatio.Fixed16x10 => "16:10",
|
||||
AspectRatio.Fixed21x9 => "21:9",
|
||||
AspectRatio.Fixed32x9 => "32:9",
|
||||
_ => "Stretched",
|
||||
#pragma warning restore IDE0055
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
12
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/BackendThreading.cs
vendored
Normal file
12
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/BackendThreading.cs
vendored
Normal file
@@ -0,0 +1,12 @@
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Ryujinx.Common.Configuration
|
||||
{
|
||||
[JsonConverter(typeof(JsonStringEnumConverter<BackendThreading>))]
|
||||
public enum BackendThreading
|
||||
{
|
||||
Auto,
|
||||
Off,
|
||||
On,
|
||||
}
|
||||
}
|
||||
62
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/DirtyHack.cs
vendored
Normal file
62
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/DirtyHack.cs
vendored
Normal file
@@ -0,0 +1,62 @@
|
||||
using Gommon;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
namespace Ryujinx.Common.Configuration
|
||||
{
|
||||
[Flags]
|
||||
public enum DirtyHack : byte
|
||||
{
|
||||
Xc2MenuSoftlockFix = 1,
|
||||
// ShaderTranslationDelay = 2
|
||||
NifmServiceDisableIsAnyInternetRequestAccepted = 3
|
||||
}
|
||||
|
||||
public readonly struct EnabledDirtyHack(DirtyHack hack, int value)
|
||||
{
|
||||
public DirtyHack Hack => hack;
|
||||
public int Value => value;
|
||||
|
||||
|
||||
|
||||
public ulong Pack() => Raw.PackBitFields(PackedFormat);
|
||||
|
||||
public static EnabledDirtyHack Unpack(ulong packedHack)
|
||||
{
|
||||
uint[] unpackedFields = packedHack.UnpackBitFields(PackedFormat);
|
||||
// ReSharper disable once PatternAlwaysMatches
|
||||
if (unpackedFields is not [uint hack, uint value])
|
||||
throw new Exception("The unpack operation on the integer resulted in an invalid unpacked result.");
|
||||
|
||||
return new EnabledDirtyHack((DirtyHack)hack, (int)value);
|
||||
}
|
||||
|
||||
private uint[] Raw => [(uint)Hack, (uint)Value.CoerceAtLeast(0)];
|
||||
|
||||
public static readonly byte[] PackedFormat = [8, 32];
|
||||
}
|
||||
|
||||
public class DirtyHacks : Dictionary<DirtyHack, int>
|
||||
{
|
||||
public DirtyHacks(IEnumerable<EnabledDirtyHack> hacks)
|
||||
=> hacks.ForEach(edh => Add(edh.Hack, edh.Value));
|
||||
|
||||
public DirtyHacks(ulong[] packedHacks) : this(packedHacks.Select(EnabledDirtyHack.Unpack)) { }
|
||||
|
||||
public ulong[] PackEntries()
|
||||
=> Entries.Select(it => it.Pack()).ToArray();
|
||||
|
||||
public EnabledDirtyHack[] Entries
|
||||
=> this
|
||||
.Select(it => new EnabledDirtyHack(it.Key, it.Value))
|
||||
.ToArray();
|
||||
|
||||
public static implicit operator DirtyHacks(EnabledDirtyHack[] hacks) => new(hacks);
|
||||
public static implicit operator DirtyHacks(ulong[] packedHacks) => new(packedHacks);
|
||||
|
||||
public new int this[DirtyHack hack] => TryGetValue(hack, out int value) ? value : -1;
|
||||
|
||||
public bool IsEnabled(DirtyHack hack) => ContainsKey(hack);
|
||||
}
|
||||
}
|
||||
13
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/DownloadableContentContainer.cs
vendored
Normal file
13
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/DownloadableContentContainer.cs
vendored
Normal file
@@ -0,0 +1,13 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Ryujinx.Common.Configuration
|
||||
{
|
||||
public struct DownloadableContentContainer
|
||||
{
|
||||
[JsonPropertyName("path")]
|
||||
public string ContainerPath { get; set; }
|
||||
[JsonPropertyName("dlc_nca_list")]
|
||||
public List<DownloadableContentNca> DownloadableContentNcaList { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Ryujinx.Common.Configuration
|
||||
{
|
||||
[JsonSourceGenerationOptions(WriteIndented = true)]
|
||||
[JsonSerializable(typeof(List<DownloadableContentContainer>))]
|
||||
public partial class DownloadableContentJsonSerializerContext : JsonSerializerContext
|
||||
{
|
||||
}
|
||||
}
|
||||
14
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/DownloadableContentNca.cs
vendored
Normal file
14
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/DownloadableContentNca.cs
vendored
Normal file
@@ -0,0 +1,14 @@
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Ryujinx.Common.Configuration
|
||||
{
|
||||
public struct DownloadableContentNca
|
||||
{
|
||||
[JsonPropertyName("path")]
|
||||
public string FullPath { get; set; }
|
||||
[JsonPropertyName("title_id")]
|
||||
public ulong TitleId { get; set; }
|
||||
[JsonPropertyName("is_enabled")]
|
||||
public bool Enabled { get; set; }
|
||||
}
|
||||
}
|
||||
11
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/GraphicsBackend.cs
vendored
Normal file
11
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/GraphicsBackend.cs
vendored
Normal file
@@ -0,0 +1,11 @@
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Ryujinx.Common.Configuration
|
||||
{
|
||||
[JsonConverter(typeof(JsonStringEnumConverter<GraphicsBackend>))]
|
||||
public enum GraphicsBackend
|
||||
{
|
||||
Vulkan,
|
||||
OpenGl,
|
||||
}
|
||||
}
|
||||
13
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/GraphicsDebugLevel.cs
vendored
Normal file
13
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/GraphicsDebugLevel.cs
vendored
Normal file
@@ -0,0 +1,13 @@
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Ryujinx.Common.Configuration
|
||||
{
|
||||
[JsonConverter(typeof(JsonStringEnumConverter<GraphicsDebugLevel>))]
|
||||
public enum GraphicsDebugLevel
|
||||
{
|
||||
None,
|
||||
Error,
|
||||
Slowdowns,
|
||||
All,
|
||||
}
|
||||
}
|
||||
11
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/Hid/AssignedInputDevice.cs
vendored
Normal file
11
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/Hid/AssignedInputDevice.cs
vendored
Normal file
@@ -0,0 +1,11 @@
|
||||
namespace Ryujinx.Common.Configuration.Hid
|
||||
{
|
||||
public class AssignedInputDevice
|
||||
{
|
||||
public AssignedInputDeviceType Type { get; set; }
|
||||
|
||||
public string Id { get; set; }
|
||||
|
||||
public string ProfileName { get; set; }
|
||||
}
|
||||
}
|
||||
11
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/Hid/AssignedInputDeviceType.cs
vendored
Normal file
11
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/Hid/AssignedInputDeviceType.cs
vendored
Normal file
@@ -0,0 +1,11 @@
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Ryujinx.Common.Configuration.Hid
|
||||
{
|
||||
[JsonConverter(typeof(JsonStringEnumConverter<AssignedInputDeviceType>))]
|
||||
public enum AssignedInputDeviceType
|
||||
{
|
||||
Keyboard,
|
||||
Controller,
|
||||
}
|
||||
}
|
||||
58
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/Hid/Controller/GamepadInputId.cs
vendored
Normal file
58
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/Hid/Controller/GamepadInputId.cs
vendored
Normal file
@@ -0,0 +1,58 @@
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Ryujinx.Common.Configuration.Hid.Controller
|
||||
{
|
||||
[JsonConverter(typeof(JsonStringEnumConverter<GamepadInputId>))]
|
||||
public enum GamepadInputId : byte
|
||||
{
|
||||
Unbound,
|
||||
A,
|
||||
B,
|
||||
X,
|
||||
Y,
|
||||
LeftStick,
|
||||
RightStick,
|
||||
LeftShoulder,
|
||||
RightShoulder,
|
||||
|
||||
// Likely axis
|
||||
LeftTrigger,
|
||||
// Likely axis
|
||||
RightTrigger,
|
||||
|
||||
DpadUp,
|
||||
DpadDown,
|
||||
DpadLeft,
|
||||
DpadRight,
|
||||
|
||||
// Special buttons
|
||||
|
||||
Minus,
|
||||
Plus,
|
||||
|
||||
Back = Minus,
|
||||
Start = Plus,
|
||||
|
||||
Guide,
|
||||
Misc1,
|
||||
|
||||
// Xbox Elite paddle
|
||||
Paddle1,
|
||||
Paddle2,
|
||||
Paddle3,
|
||||
Paddle4,
|
||||
|
||||
// PS5 touchpad button
|
||||
Touchpad,
|
||||
|
||||
// Virtual buttons for single joycon (left)
|
||||
SingleLeftTrigger0,
|
||||
SingleRightTrigger0,
|
||||
|
||||
// Virtual buttons for single joycon (right)
|
||||
SingleLeftTrigger1,
|
||||
SingleRightTrigger1,
|
||||
|
||||
Count,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
using Ryujinx.Common.Configuration.Hid.Controller.Motion;
|
||||
using System;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Ryujinx.Common.Configuration.Hid.Controller
|
||||
{
|
||||
public class GenericControllerInputConfig<TButton, TStick> : GenericInputConfigurationCommon<TButton> where TButton : unmanaged where TStick : unmanaged
|
||||
{
|
||||
[JsonIgnore]
|
||||
private float _deadzoneLeft;
|
||||
[JsonIgnore]
|
||||
private float _deadzoneRight;
|
||||
[JsonIgnore]
|
||||
private float _triggerThreshold;
|
||||
|
||||
/// <summary>
|
||||
/// Left JoyCon Controller Stick Bindings
|
||||
/// </summary>
|
||||
public JoyconConfigControllerStick<TButton, TStick> LeftJoyconStick { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Right JoyCon Controller Stick Bindings
|
||||
/// </summary>
|
||||
public JoyconConfigControllerStick<TButton, TStick> RightJoyconStick { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Controller Left Analog Stick Deadzone
|
||||
/// </summary>
|
||||
public float DeadzoneLeft
|
||||
{
|
||||
get => _deadzoneLeft; set
|
||||
{
|
||||
_deadzoneLeft = MathF.Round(value, 3);
|
||||
OnPropertyChanged();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Controller Right Analog Stick Deadzone
|
||||
/// </summary>
|
||||
public float DeadzoneRight
|
||||
{
|
||||
get => _deadzoneRight; set
|
||||
{
|
||||
_deadzoneRight = MathF.Round(value, 3);
|
||||
OnPropertyChanged();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Controller Left Analog Stick Range
|
||||
/// </summary>
|
||||
public float RangeLeft { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Controller Right Analog Stick Range
|
||||
/// </summary>
|
||||
public float RangeRight { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Controller Trigger Threshold
|
||||
/// </summary>
|
||||
public float TriggerThreshold
|
||||
{
|
||||
get => _triggerThreshold; set
|
||||
{
|
||||
_triggerThreshold = MathF.Round(value, 3);
|
||||
OnPropertyChanged();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Controller Motion Settings
|
||||
/// </summary>
|
||||
public MotionConfigController Motion { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Controller Rumble Settings
|
||||
/// </summary>
|
||||
public RumbleConfigController Rumble { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Controller LED Settings
|
||||
/// </summary>
|
||||
public LedConfigController Led { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
namespace Ryujinx.Common.Configuration.Hid.Controller
|
||||
{
|
||||
public class JoyconConfigControllerStick<TButton, TStick>
|
||||
where TButton : unmanaged
|
||||
where TStick : unmanaged
|
||||
{
|
||||
public TStick Joystick { get; set; }
|
||||
public bool InvertStickX { get; set; }
|
||||
public bool InvertStickY { get; set; }
|
||||
public bool Rotate90CW { get; set; }
|
||||
public TButton StickButton { get; set; }
|
||||
}
|
||||
}
|
||||
25
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/Hid/Controller/LedConfigController.cs
vendored
Normal file
25
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/Hid/Controller/LedConfigController.cs
vendored
Normal file
@@ -0,0 +1,25 @@
|
||||
namespace Ryujinx.Common.Configuration.Hid.Controller
|
||||
{
|
||||
public class LedConfigController
|
||||
{
|
||||
/// <summary>
|
||||
/// Enable LED color changing by the emulator
|
||||
/// </summary>
|
||||
public bool EnableLed { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Ignores the color and disables the LED entirely.
|
||||
/// </summary>
|
||||
public bool TurnOffLed { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Ignores the color and uses the rainbow color functionality for the LED.
|
||||
/// </summary>
|
||||
public bool UseRainbow { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Packed RGB int of the color
|
||||
/// </summary>
|
||||
public uint LedColor { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
namespace Ryujinx.Common.Configuration.Hid.Controller.Motion
|
||||
{
|
||||
public class CemuHookMotionConfigController : MotionConfigController
|
||||
{
|
||||
/// <summary>
|
||||
/// Motion Controller Slot
|
||||
/// </summary>
|
||||
public int Slot { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Motion Controller Alternative Slot, for RightJoyCon in Pair mode
|
||||
/// </summary>
|
||||
public int AltSlot { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Mirror motion input in Pair mode
|
||||
/// </summary>
|
||||
public bool MirrorInput { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Host address of the DSU Server
|
||||
/// </summary>
|
||||
public string DsuServerHost { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Port of the DSU Server
|
||||
/// </summary>
|
||||
public int DsuServerPort { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
using Ryujinx.Common.Utilities;
|
||||
using System;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Ryujinx.Common.Configuration.Hid.Controller.Motion
|
||||
{
|
||||
class JsonMotionConfigControllerConverter : JsonConverter<MotionConfigController>
|
||||
{
|
||||
private static readonly MotionConfigJsonSerializerContext _serializerContext = new(JsonHelper.GetDefaultSerializerOptions());
|
||||
|
||||
private static MotionInputBackendType GetMotionInputBackendType(ref Utf8JsonReader reader)
|
||||
{
|
||||
// Temporary reader to get the backend type
|
||||
Utf8JsonReader tempReader = reader;
|
||||
|
||||
MotionInputBackendType result = MotionInputBackendType.Invalid;
|
||||
|
||||
while (tempReader.Read())
|
||||
{
|
||||
// NOTE: We scan all properties ignoring the depth entirely on purpose.
|
||||
// The reason behind this is that we cannot track in a reliable way the depth of the object because Utf8JsonReader never emit the first TokenType == StartObject if the json start with an object.
|
||||
// As such, this code will try to parse very field named "motion_backend" to the correct enum.
|
||||
if (tempReader.TokenType == JsonTokenType.PropertyName)
|
||||
{
|
||||
string propertyName = tempReader.GetString();
|
||||
|
||||
if (propertyName.Equals("motion_backend"))
|
||||
{
|
||||
tempReader.Read();
|
||||
|
||||
if (tempReader.TokenType == JsonTokenType.String)
|
||||
{
|
||||
string backendTypeRaw = tempReader.GetString();
|
||||
|
||||
if (!Enum.TryParse(backendTypeRaw, out result))
|
||||
{
|
||||
result = MotionInputBackendType.Invalid;
|
||||
}
|
||||
else
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public override MotionConfigController Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
|
||||
{
|
||||
MotionInputBackendType motionBackendType = GetMotionInputBackendType(ref reader);
|
||||
|
||||
return motionBackendType switch
|
||||
{
|
||||
MotionInputBackendType.GamepadDriver => JsonSerializer.Deserialize(ref reader, _serializerContext.StandardMotionConfigController),
|
||||
MotionInputBackendType.CemuHook => JsonSerializer.Deserialize(ref reader, _serializerContext.CemuHookMotionConfigController),
|
||||
_ => throw new InvalidOperationException($"Unknown backend type {motionBackendType}"),
|
||||
};
|
||||
}
|
||||
|
||||
public override void Write(Utf8JsonWriter writer, MotionConfigController value, JsonSerializerOptions options)
|
||||
{
|
||||
switch (value.MotionBackend)
|
||||
{
|
||||
case MotionInputBackendType.GamepadDriver:
|
||||
JsonSerializer.Serialize(writer, value as StandardMotionConfigController, _serializerContext.StandardMotionConfigController);
|
||||
break;
|
||||
case MotionInputBackendType.CemuHook:
|
||||
JsonSerializer.Serialize(writer, value as CemuHookMotionConfigController, _serializerContext.CemuHookMotionConfigController);
|
||||
break;
|
||||
default:
|
||||
throw new ArgumentException($"Unknown motion backend type {value.MotionBackend}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Ryujinx.Common.Configuration.Hid.Controller.Motion
|
||||
{
|
||||
[JsonConverter(typeof(JsonMotionConfigControllerConverter))]
|
||||
public class MotionConfigController
|
||||
{
|
||||
public MotionInputBackendType MotionBackend { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gyro Sensitivity
|
||||
/// </summary>
|
||||
public int Sensitivity { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gyro Deadzone
|
||||
/// </summary>
|
||||
public double GyroDeadzone { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Enable Motion Controls
|
||||
/// </summary>
|
||||
public bool EnableMotion { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Ryujinx.Common.Configuration.Hid.Controller.Motion
|
||||
{
|
||||
[JsonSourceGenerationOptions(WriteIndented = true)]
|
||||
[JsonSerializable(typeof(MotionConfigController))]
|
||||
[JsonSerializable(typeof(CemuHookMotionConfigController))]
|
||||
[JsonSerializable(typeof(StandardMotionConfigController))]
|
||||
public partial class MotionConfigJsonSerializerContext : JsonSerializerContext
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Ryujinx.Common.Configuration.Hid.Controller.Motion
|
||||
{
|
||||
[JsonConverter(typeof(JsonStringEnumConverter<MotionInputBackendType>))]
|
||||
public enum MotionInputBackendType : byte
|
||||
{
|
||||
Invalid,
|
||||
GamepadDriver,
|
||||
CemuHook,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace Ryujinx.Common.Configuration.Hid.Controller.Motion
|
||||
{
|
||||
public class StandardMotionConfigController : MotionConfigController { }
|
||||
}
|
||||
25
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/Hid/Controller/RumbleConfigController.cs
vendored
Normal file
25
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/Hid/Controller/RumbleConfigController.cs
vendored
Normal file
@@ -0,0 +1,25 @@
|
||||
namespace Ryujinx.Common.Configuration.Hid.Controller
|
||||
{
|
||||
public class RumbleConfigController
|
||||
{
|
||||
/// <summary>
|
||||
/// Controller Strong Rumble Multiplier
|
||||
/// </summary>
|
||||
public float StrongRumble { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Controller Weak Rumble Multiplier
|
||||
/// </summary>
|
||||
public float WeakRumble { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Enable Rumble
|
||||
/// </summary>
|
||||
public bool EnableRumble { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Enable HD Rumble support
|
||||
/// </summary
|
||||
public bool UseHDRumble { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace Ryujinx.Common.Configuration.Hid.Controller
|
||||
{
|
||||
public class StandardControllerInputConfig : GenericControllerInputConfig<GamepadInputId, StickInputId> { }
|
||||
}
|
||||
14
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/Hid/Controller/StickInputId.cs
vendored
Normal file
14
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/Hid/Controller/StickInputId.cs
vendored
Normal file
@@ -0,0 +1,14 @@
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Ryujinx.Common.Configuration.Hid.Controller
|
||||
{
|
||||
[JsonConverter(typeof(JsonStringEnumConverter<StickInputId>))]
|
||||
public enum StickInputId : byte
|
||||
{
|
||||
Unbound,
|
||||
Left,
|
||||
Right,
|
||||
|
||||
Count,
|
||||
}
|
||||
}
|
||||
22
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/Hid/ControllerType.cs
vendored
Normal file
22
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/Hid/ControllerType.cs
vendored
Normal file
@@ -0,0 +1,22 @@
|
||||
using System;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Ryujinx.Common.Configuration.Hid
|
||||
{
|
||||
// This enum was duplicated from Ryujinx.HLE.HOS.Services.Hid.PlayerIndex and should be kept identical
|
||||
[Flags]
|
||||
[JsonConverter(typeof(JsonStringEnumConverter<ControllerType>))]
|
||||
public enum ControllerType
|
||||
{
|
||||
None,
|
||||
ProController = 1 << 0,
|
||||
Handheld = 1 << 1,
|
||||
JoyconPair = 1 << 2,
|
||||
JoyconLeft = 1 << 3,
|
||||
JoyconRight = 1 << 4,
|
||||
Invalid = 1 << 5,
|
||||
Pokeball = 1 << 6,
|
||||
SystemExternal = 1 << 29,
|
||||
System = 1 << 30,
|
||||
}
|
||||
}
|
||||
15
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/Hid/GenericInputConfigurationCommon.cs
vendored
Normal file
15
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/Hid/GenericInputConfigurationCommon.cs
vendored
Normal file
@@ -0,0 +1,15 @@
|
||||
namespace Ryujinx.Common.Configuration.Hid
|
||||
{
|
||||
public class GenericInputConfigurationCommon<TButton> : InputConfig where TButton : unmanaged
|
||||
{
|
||||
/// <summary>
|
||||
/// Left JoyCon Controller Bindings
|
||||
/// </summary>
|
||||
public LeftJoyconCommonConfig<TButton> LeftJoycon { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Right JoyCon Controller Bindings
|
||||
/// </summary>
|
||||
public RightJoyconCommonConfig<TButton> RightJoycon { get; set; }
|
||||
}
|
||||
}
|
||||
13
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/Hid/InputBackendType.cs
vendored
Normal file
13
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/Hid/InputBackendType.cs
vendored
Normal file
@@ -0,0 +1,13 @@
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Ryujinx.Common.Configuration.Hid
|
||||
{
|
||||
[JsonConverter(typeof(JsonStringEnumConverter<InputBackendType>))]
|
||||
public enum InputBackendType
|
||||
{
|
||||
Invalid,
|
||||
WindowKeyboard,
|
||||
GamepadSDL2, //backcompat
|
||||
GamepadSDL3,
|
||||
}
|
||||
}
|
||||
52
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/Hid/InputConfig.cs
vendored
Normal file
52
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/Hid/InputConfig.cs
vendored
Normal file
@@ -0,0 +1,52 @@
|
||||
using System.ComponentModel;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Ryujinx.Common.Configuration.Hid
|
||||
{
|
||||
[JsonConverter(typeof(JsonInputConfigConverter))]
|
||||
public class InputConfig : INotifyPropertyChanged
|
||||
{
|
||||
/// <summary>
|
||||
/// The current version of the input file format
|
||||
/// </summary>
|
||||
public const int CurrentVersion = 1;
|
||||
|
||||
public int Version { get; set; }
|
||||
|
||||
public InputBackendType Backend { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Controller id
|
||||
/// </summary>
|
||||
public string Id { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Controller name
|
||||
/// </summary>
|
||||
public string Name { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Controller's Type
|
||||
/// </summary>
|
||||
public ControllerType ControllerType { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Player's Index for the controller
|
||||
/// </summary>
|
||||
public PlayerIndex PlayerIndex { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Allow a keyboard configuration to temporarily promote to a connected gamepad,
|
||||
/// while preserving the existing keyboard fallback path when that gamepad disappears.
|
||||
/// </summary>
|
||||
public bool EnableDynamicGamepadSwap { get; set; }
|
||||
|
||||
public event PropertyChangedEventHandler PropertyChanged;
|
||||
|
||||
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
|
||||
{
|
||||
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
|
||||
}
|
||||
}
|
||||
}
|
||||
14
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/Hid/InputConfigJsonSerializerContext.cs
vendored
Normal file
14
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/Hid/InputConfigJsonSerializerContext.cs
vendored
Normal file
@@ -0,0 +1,14 @@
|
||||
using Ryujinx.Common.Configuration.Hid.Controller;
|
||||
using Ryujinx.Common.Configuration.Hid.Keyboard;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Ryujinx.Common.Configuration.Hid
|
||||
{
|
||||
[JsonSourceGenerationOptions(WriteIndented = true)]
|
||||
[JsonSerializable(typeof(InputConfig))]
|
||||
[JsonSerializable(typeof(StandardKeyboardInputConfig))]
|
||||
[JsonSerializable(typeof(StandardControllerInputConfig))]
|
||||
public partial class InputConfigJsonSerializerContext : JsonSerializerContext
|
||||
{
|
||||
}
|
||||
}
|
||||
81
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/Hid/JsonInputConfigConverter.cs
vendored
Normal file
81
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/Hid/JsonInputConfigConverter.cs
vendored
Normal file
@@ -0,0 +1,81 @@
|
||||
using Ryujinx.Common.Configuration.Hid.Controller;
|
||||
using Ryujinx.Common.Configuration.Hid.Keyboard;
|
||||
using Ryujinx.Common.Utilities;
|
||||
using System;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Ryujinx.Common.Configuration.Hid
|
||||
{
|
||||
public class JsonInputConfigConverter : JsonConverter<InputConfig>
|
||||
{
|
||||
private static readonly InputConfigJsonSerializerContext _serializerContext = new(JsonHelper.GetDefaultSerializerOptions());
|
||||
|
||||
private static InputBackendType GetInputBackendType(ref Utf8JsonReader reader)
|
||||
{
|
||||
// Temporary reader to get the backend type
|
||||
Utf8JsonReader tempReader = reader;
|
||||
|
||||
InputBackendType result = InputBackendType.Invalid;
|
||||
|
||||
while (tempReader.Read())
|
||||
{
|
||||
// NOTE: We scan all properties ignoring the depth entirely on purpose.
|
||||
// The reason behind this is that we cannot track in a reliable way the depth of the object because Utf8JsonReader never emit the first TokenType == StartObject if the json start with an object.
|
||||
// As such, this code will try to parse very field named "backend" to the correct enum.
|
||||
if (tempReader.TokenType == JsonTokenType.PropertyName)
|
||||
{
|
||||
string propertyName = tempReader.GetString();
|
||||
|
||||
if (propertyName.Equals("backend"))
|
||||
{
|
||||
tempReader.Read();
|
||||
|
||||
if (tempReader.TokenType == JsonTokenType.String)
|
||||
{
|
||||
string backendTypeRaw = tempReader.GetString();
|
||||
|
||||
if (!Enum.TryParse(backendTypeRaw, out result))
|
||||
{
|
||||
result = InputBackendType.Invalid;
|
||||
}
|
||||
else
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public override InputConfig Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
|
||||
{
|
||||
InputBackendType backendType = GetInputBackendType(ref reader);
|
||||
|
||||
return backendType switch
|
||||
{
|
||||
InputBackendType.WindowKeyboard => JsonSerializer.Deserialize(ref reader, _serializerContext.StandardKeyboardInputConfig),
|
||||
InputBackendType.GamepadSDL2 or InputBackendType.GamepadSDL3 => JsonSerializer.Deserialize(ref reader, _serializerContext.StandardControllerInputConfig),
|
||||
_ => throw new InvalidOperationException($"Unknown backend type {backendType}"),
|
||||
};
|
||||
}
|
||||
|
||||
public override void Write(Utf8JsonWriter writer, InputConfig value, JsonSerializerOptions options)
|
||||
{
|
||||
switch (value.Backend)
|
||||
{
|
||||
case InputBackendType.WindowKeyboard:
|
||||
JsonSerializer.Serialize(writer, value as StandardKeyboardInputConfig, _serializerContext.StandardKeyboardInputConfig);
|
||||
break;
|
||||
case InputBackendType.GamepadSDL2 or InputBackendType.GamepadSDL3:
|
||||
JsonSerializer.Serialize(writer, value as StandardControllerInputConfig, _serializerContext.StandardControllerInputConfig);
|
||||
break;
|
||||
default:
|
||||
throw new ArgumentException($"Unknown backend type {value.Backend}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
142
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/Hid/Key.cs
vendored
Normal file
142
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/Hid/Key.cs
vendored
Normal file
@@ -0,0 +1,142 @@
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Ryujinx.Common.Configuration.Hid
|
||||
{
|
||||
[JsonConverter(typeof(JsonStringEnumConverter<Key>))]
|
||||
public enum Key
|
||||
{
|
||||
Unknown,
|
||||
ShiftLeft,
|
||||
ShiftRight,
|
||||
ControlLeft,
|
||||
ControlRight,
|
||||
AltLeft,
|
||||
AltRight,
|
||||
WinLeft,
|
||||
WinRight,
|
||||
Menu,
|
||||
F1,
|
||||
F2,
|
||||
F3,
|
||||
F4,
|
||||
F5,
|
||||
F6,
|
||||
F7,
|
||||
F8,
|
||||
F9,
|
||||
F10,
|
||||
F11,
|
||||
F12,
|
||||
F13,
|
||||
F14,
|
||||
F15,
|
||||
F16,
|
||||
F17,
|
||||
F18,
|
||||
F19,
|
||||
F20,
|
||||
F21,
|
||||
F22,
|
||||
F23,
|
||||
F24,
|
||||
F25,
|
||||
F26,
|
||||
F27,
|
||||
F28,
|
||||
F29,
|
||||
F30,
|
||||
F31,
|
||||
F32,
|
||||
F33,
|
||||
F34,
|
||||
F35,
|
||||
Up,
|
||||
Down,
|
||||
Left,
|
||||
Right,
|
||||
Enter,
|
||||
Escape,
|
||||
Space,
|
||||
Tab,
|
||||
BackSpace,
|
||||
Insert,
|
||||
Delete,
|
||||
PageUp,
|
||||
PageDown,
|
||||
Home,
|
||||
End,
|
||||
CapsLock,
|
||||
ScrollLock,
|
||||
PrintScreen,
|
||||
Pause,
|
||||
NumLock,
|
||||
Clear,
|
||||
Keypad0,
|
||||
Keypad1,
|
||||
Keypad2,
|
||||
Keypad3,
|
||||
Keypad4,
|
||||
Keypad5,
|
||||
Keypad6,
|
||||
Keypad7,
|
||||
Keypad8,
|
||||
Keypad9,
|
||||
KeypadDivide,
|
||||
KeypadMultiply,
|
||||
KeypadSubtract,
|
||||
KeypadAdd,
|
||||
KeypadDecimal,
|
||||
KeypadEnter,
|
||||
A,
|
||||
B,
|
||||
C,
|
||||
D,
|
||||
E,
|
||||
F,
|
||||
G,
|
||||
H,
|
||||
I,
|
||||
J,
|
||||
K,
|
||||
L,
|
||||
M,
|
||||
N,
|
||||
O,
|
||||
P,
|
||||
Q,
|
||||
R,
|
||||
S,
|
||||
T,
|
||||
U,
|
||||
V,
|
||||
W,
|
||||
X,
|
||||
Y,
|
||||
Z,
|
||||
Number0,
|
||||
Number1,
|
||||
Number2,
|
||||
Number3,
|
||||
Number4,
|
||||
Number5,
|
||||
Number6,
|
||||
Number7,
|
||||
Number8,
|
||||
Number9,
|
||||
Tilde,
|
||||
Grave,
|
||||
Minus,
|
||||
Plus,
|
||||
BracketLeft,
|
||||
BracketRight,
|
||||
Semicolon,
|
||||
Quote,
|
||||
Comma,
|
||||
Period,
|
||||
Slash,
|
||||
BackSlash,
|
||||
Unbound,
|
||||
|
||||
Count,
|
||||
}
|
||||
}
|
||||
15
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/Hid/Keyboard/GenericKeyboardInputConfig.cs
vendored
Normal file
15
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/Hid/Keyboard/GenericKeyboardInputConfig.cs
vendored
Normal file
@@ -0,0 +1,15 @@
|
||||
namespace Ryujinx.Common.Configuration.Hid.Keyboard
|
||||
{
|
||||
public class GenericKeyboardInputConfig<TKey> : GenericInputConfigurationCommon<TKey> where TKey : unmanaged
|
||||
{
|
||||
/// <summary>
|
||||
/// Left JoyCon Controller Stick Bindings
|
||||
/// </summary>
|
||||
public JoyconConfigKeyboardStick<TKey> LeftJoyconStick { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Right JoyCon Controller Stick Bindings
|
||||
/// </summary>
|
||||
public JoyconConfigKeyboardStick<TKey> RightJoyconStick { get; set; }
|
||||
}
|
||||
}
|
||||
11
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/Hid/Keyboard/JoyconConfigKeyboardStick.cs
vendored
Normal file
11
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/Hid/Keyboard/JoyconConfigKeyboardStick.cs
vendored
Normal file
@@ -0,0 +1,11 @@
|
||||
namespace Ryujinx.Common.Configuration.Hid.Keyboard
|
||||
{
|
||||
public class JoyconConfigKeyboardStick<TKey> where TKey : unmanaged
|
||||
{
|
||||
public TKey StickUp { get; set; }
|
||||
public TKey StickDown { get; set; }
|
||||
public TKey StickLeft { get; set; }
|
||||
public TKey StickRight { get; set; }
|
||||
public TKey StickButton { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace Ryujinx.Common.Configuration.Hid.Keyboard
|
||||
{
|
||||
public class StandardKeyboardInputConfig : GenericKeyboardInputConfig<PhysicalKey> { }
|
||||
}
|
||||
19
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/Hid/KeyboardHotkeys.cs
vendored
Normal file
19
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/Hid/KeyboardHotkeys.cs
vendored
Normal file
@@ -0,0 +1,19 @@
|
||||
namespace Ryujinx.Common.Configuration.Hid
|
||||
{
|
||||
public class KeyboardHotkeys
|
||||
{
|
||||
public Key ToggleVSyncMode { get; set; }
|
||||
public Key Screenshot { get; set; }
|
||||
public Key ShowUI { get; set; }
|
||||
public Key Pause { get; set; }
|
||||
public Key ToggleMute { get; set; }
|
||||
public Key ResScaleUp { get; set; }
|
||||
public Key ResScaleDown { get; set; }
|
||||
public Key VolumeUp { get; set; }
|
||||
public Key VolumeDown { get; set; }
|
||||
public Key CustomVSyncIntervalIncrement { get; set; }
|
||||
public Key CustomVSyncIntervalDecrement { get; set; }
|
||||
public Key TurboMode { get; set; }
|
||||
public bool TurboModeWhileHeld { get; set; }
|
||||
}
|
||||
}
|
||||
15
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/Hid/LeftJoyconCommonConfig.cs
vendored
Normal file
15
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/Hid/LeftJoyconCommonConfig.cs
vendored
Normal file
@@ -0,0 +1,15 @@
|
||||
namespace Ryujinx.Common.Configuration.Hid
|
||||
{
|
||||
public class LeftJoyconCommonConfig<TButton>
|
||||
{
|
||||
public TButton ButtonMinus { get; set; }
|
||||
public TButton ButtonL { get; set; }
|
||||
public TButton ButtonZl { get; set; }
|
||||
public TButton ButtonSl { get; set; }
|
||||
public TButton ButtonSr { get; set; }
|
||||
public TButton DpadUp { get; set; }
|
||||
public TButton DpadDown { get; set; }
|
||||
public TButton DpadLeft { get; set; }
|
||||
public TButton DpadRight { get; set; }
|
||||
}
|
||||
}
|
||||
142
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/Hid/PhysicalKey.cs
vendored
Normal file
142
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/Hid/PhysicalKey.cs
vendored
Normal file
@@ -0,0 +1,142 @@
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Ryujinx.Common.Configuration.Hid
|
||||
{
|
||||
[JsonConverter(typeof(JsonStringEnumConverter<PhysicalKey>))]
|
||||
public enum PhysicalKey
|
||||
{
|
||||
Unknown,
|
||||
ShiftLeft,
|
||||
ShiftRight,
|
||||
ControlLeft,
|
||||
ControlRight,
|
||||
AltLeft,
|
||||
AltRight,
|
||||
WinLeft,
|
||||
WinRight,
|
||||
Menu,
|
||||
F1,
|
||||
F2,
|
||||
F3,
|
||||
F4,
|
||||
F5,
|
||||
F6,
|
||||
F7,
|
||||
F8,
|
||||
F9,
|
||||
F10,
|
||||
F11,
|
||||
F12,
|
||||
F13,
|
||||
F14,
|
||||
F15,
|
||||
F16,
|
||||
F17,
|
||||
F18,
|
||||
F19,
|
||||
F20,
|
||||
F21,
|
||||
F22,
|
||||
F23,
|
||||
F24,
|
||||
F25,
|
||||
F26,
|
||||
F27,
|
||||
F28,
|
||||
F29,
|
||||
F30,
|
||||
F31,
|
||||
F32,
|
||||
F33,
|
||||
F34,
|
||||
F35,
|
||||
Up,
|
||||
Down,
|
||||
Left,
|
||||
Right,
|
||||
Enter,
|
||||
Escape,
|
||||
Space,
|
||||
Tab,
|
||||
BackSpace,
|
||||
Insert,
|
||||
Delete,
|
||||
PageUp,
|
||||
PageDown,
|
||||
Home,
|
||||
End,
|
||||
CapsLock,
|
||||
ScrollLock,
|
||||
PrintScreen,
|
||||
Pause,
|
||||
NumLock,
|
||||
Clear,
|
||||
Keypad0,
|
||||
Keypad1,
|
||||
Keypad2,
|
||||
Keypad3,
|
||||
Keypad4,
|
||||
Keypad5,
|
||||
Keypad6,
|
||||
Keypad7,
|
||||
Keypad8,
|
||||
Keypad9,
|
||||
KeypadDivide,
|
||||
KeypadMultiply,
|
||||
KeypadSubtract,
|
||||
KeypadAdd,
|
||||
KeypadDecimal,
|
||||
KeypadEnter,
|
||||
A,
|
||||
B,
|
||||
C,
|
||||
D,
|
||||
E,
|
||||
F,
|
||||
G,
|
||||
H,
|
||||
I,
|
||||
J,
|
||||
K,
|
||||
L,
|
||||
M,
|
||||
N,
|
||||
O,
|
||||
P,
|
||||
Q,
|
||||
R,
|
||||
S,
|
||||
T,
|
||||
U,
|
||||
V,
|
||||
W,
|
||||
X,
|
||||
Y,
|
||||
Z,
|
||||
Number0,
|
||||
Number1,
|
||||
Number2,
|
||||
Number3,
|
||||
Number4,
|
||||
Number5,
|
||||
Number6,
|
||||
Number7,
|
||||
Number8,
|
||||
Number9,
|
||||
Tilde,
|
||||
Grave,
|
||||
Minus,
|
||||
Plus,
|
||||
BracketLeft,
|
||||
BracketRight,
|
||||
Semicolon,
|
||||
Quote,
|
||||
Comma,
|
||||
Period,
|
||||
Slash,
|
||||
BackSlash,
|
||||
Unbound,
|
||||
|
||||
Count,
|
||||
}
|
||||
}
|
||||
21
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/Hid/PlayerIndex.cs
vendored
Normal file
21
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/Hid/PlayerIndex.cs
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Ryujinx.Common.Configuration.Hid
|
||||
{
|
||||
// This enum was duplicated from Ryujinx.HLE.HOS.Services.Hid.PlayerIndex and should be kept identical
|
||||
[JsonConverter(typeof(JsonStringEnumConverter<PlayerIndex>))]
|
||||
public enum PlayerIndex
|
||||
{
|
||||
Player1 = 0,
|
||||
Player2 = 1,
|
||||
Player3 = 2,
|
||||
Player4 = 3,
|
||||
Player5 = 4,
|
||||
Player6 = 5,
|
||||
Player7 = 6,
|
||||
Player8 = 7,
|
||||
Handheld = 8,
|
||||
Unknown = 9,
|
||||
Auto = 10, // Shouldn't be used directly
|
||||
}
|
||||
}
|
||||
13
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/Hid/PlayerInputAssignment.cs
vendored
Normal file
13
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/Hid/PlayerInputAssignment.cs
vendored
Normal file
@@ -0,0 +1,13 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace Ryujinx.Common.Configuration.Hid
|
||||
{
|
||||
public class PlayerInputAssignment
|
||||
{
|
||||
public PlayerIndex PlayerIndex { get; set; }
|
||||
|
||||
public bool EnableDynamicInputSwap { get; set; }
|
||||
|
||||
public List<AssignedInputDevice> Devices { get; set; } = [];
|
||||
}
|
||||
}
|
||||
166
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/Hid/PlayerInputAssignmentHelper.cs
vendored
Normal file
166
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/Hid/PlayerInputAssignmentHelper.cs
vendored
Normal file
@@ -0,0 +1,166 @@
|
||||
using Ryujinx.Common.Configuration.Hid.Keyboard;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
namespace Ryujinx.Common.Configuration.Hid
|
||||
{
|
||||
public static class PlayerInputAssignmentHelper
|
||||
{
|
||||
public static AssignedInputDevice CreatePrimaryDevice(InputConfig inputConfig)
|
||||
{
|
||||
if (inputConfig == null || string.IsNullOrWhiteSpace(inputConfig.Id))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return new AssignedInputDevice
|
||||
{
|
||||
Type = inputConfig is StandardKeyboardInputConfig
|
||||
? AssignedInputDeviceType.Keyboard
|
||||
: AssignedInputDeviceType.Controller,
|
||||
Id = inputConfig.Id,
|
||||
};
|
||||
}
|
||||
|
||||
public static PlayerInputAssignment Normalize(PlayerInputAssignment assignment, AssignedInputDevice preferredDevice = null)
|
||||
{
|
||||
if (assignment == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
PlayerInputAssignment normalized = new()
|
||||
{
|
||||
PlayerIndex = assignment.PlayerIndex,
|
||||
EnableDynamicInputSwap = assignment.EnableDynamicInputSwap,
|
||||
};
|
||||
|
||||
List<AssignedInputDevice> distinctDevices = Deduplicate(assignment.Devices);
|
||||
|
||||
if (assignment.EnableDynamicInputSwap)
|
||||
{
|
||||
normalized.Devices.AddRange(distinctDevices.Select(Clone));
|
||||
return normalized;
|
||||
}
|
||||
|
||||
AssignedInputDevice primaryDevice = SelectPrimaryDevice(distinctDevices, preferredDevice) ?? Clone(preferredDevice);
|
||||
|
||||
if (primaryDevice != null)
|
||||
{
|
||||
normalized.Devices.Add(Clone(primaryDevice));
|
||||
}
|
||||
|
||||
return normalized;
|
||||
}
|
||||
|
||||
public static bool AreEquivalent(
|
||||
PlayerInputAssignment left,
|
||||
PlayerInputAssignment right,
|
||||
AssignedInputDevice leftPreferredDevice = null,
|
||||
AssignedInputDevice rightPreferredDevice = null)
|
||||
{
|
||||
if (left == null || right == null)
|
||||
{
|
||||
return left == right;
|
||||
}
|
||||
|
||||
PlayerInputAssignment normalizedLeft = Normalize(left, leftPreferredDevice);
|
||||
PlayerInputAssignment normalizedRight = Normalize(right, rightPreferredDevice);
|
||||
|
||||
if (normalizedLeft.EnableDynamicInputSwap != normalizedRight.EnableDynamicInputSwap)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
List<(AssignedInputDeviceType Type, string Id, string ProfileName)> leftDevices = normalizedLeft.Devices
|
||||
.Select(device => (Type: device.Type, Id: device.Id, ProfileName: device.ProfileName ?? string.Empty))
|
||||
.OrderBy(device => device.Type)
|
||||
.ThenBy(device => device.Id, StringComparer.Ordinal)
|
||||
.ThenBy(device => device.ProfileName, StringComparer.Ordinal)
|
||||
.ToList();
|
||||
|
||||
List<(AssignedInputDeviceType Type, string Id, string ProfileName)> rightDevices = normalizedRight.Devices
|
||||
.Select(device => (Type: device.Type, Id: device.Id, ProfileName: device.ProfileName ?? string.Empty))
|
||||
.OrderBy(device => device.Type)
|
||||
.ThenBy(device => device.Id, StringComparer.Ordinal)
|
||||
.ThenBy(device => device.ProfileName, StringComparer.Ordinal)
|
||||
.ToList();
|
||||
|
||||
return leftDevices.SequenceEqual(rightDevices);
|
||||
}
|
||||
|
||||
private static List<AssignedInputDevice> Deduplicate(IEnumerable<AssignedInputDevice> devices)
|
||||
{
|
||||
List<AssignedInputDevice> result = [];
|
||||
|
||||
if (devices == null)
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
foreach (AssignedInputDevice device in devices)
|
||||
{
|
||||
if (device == null || string.IsNullOrWhiteSpace(device.Id))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
int existingIndex = result.FindIndex(existing =>
|
||||
existing.Type == device.Type &&
|
||||
string.Equals(existing.Id, device.Id, StringComparison.Ordinal));
|
||||
|
||||
if (existingIndex == -1)
|
||||
{
|
||||
result.Add(Clone(device));
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(device.ProfileName) ||
|
||||
string.IsNullOrWhiteSpace(result[existingIndex].ProfileName))
|
||||
{
|
||||
result[existingIndex].ProfileName = device.ProfileName;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private static AssignedInputDevice SelectPrimaryDevice(List<AssignedInputDevice> devices, AssignedInputDevice preferredDevice)
|
||||
{
|
||||
if (devices == null || devices.Count == 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (preferredDevice != null)
|
||||
{
|
||||
AssignedInputDevice matchedDevice = devices.FirstOrDefault(device =>
|
||||
device.Type == preferredDevice.Type &&
|
||||
string.Equals(device.Id, preferredDevice.Id, StringComparison.Ordinal));
|
||||
|
||||
if (matchedDevice != null)
|
||||
{
|
||||
return matchedDevice;
|
||||
}
|
||||
}
|
||||
|
||||
return devices[0];
|
||||
}
|
||||
|
||||
private static AssignedInputDevice Clone(AssignedInputDevice device)
|
||||
{
|
||||
if (device == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return new AssignedInputDevice
|
||||
{
|
||||
Type = device.Type,
|
||||
Id = device.Id,
|
||||
ProfileName = device.ProfileName,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
15
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/Hid/RightJoyconCommonConfig.cs
vendored
Normal file
15
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/Hid/RightJoyconCommonConfig.cs
vendored
Normal file
@@ -0,0 +1,15 @@
|
||||
namespace Ryujinx.Common.Configuration.Hid
|
||||
{
|
||||
public class RightJoyconCommonConfig<TButton>
|
||||
{
|
||||
public TButton ButtonPlus { get; set; }
|
||||
public TButton ButtonR { get; set; }
|
||||
public TButton ButtonZr { get; set; }
|
||||
public TButton ButtonSl { get; set; }
|
||||
public TButton ButtonSr { get; set; }
|
||||
public TButton ButtonX { get; set; }
|
||||
public TButton ButtonB { get; set; }
|
||||
public TButton ButtonY { get; set; }
|
||||
public TButton ButtonA { get; set; }
|
||||
}
|
||||
}
|
||||
9
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/HideCursorMode.cs
vendored
Normal file
9
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/HideCursorMode.cs
vendored
Normal file
@@ -0,0 +1,9 @@
|
||||
namespace Ryujinx.Common.Configuration
|
||||
{
|
||||
public enum HideCursorMode
|
||||
{
|
||||
Never,
|
||||
OnIdle,
|
||||
Always,
|
||||
}
|
||||
}
|
||||
12
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/MemoryManagerMode.cs
vendored
Normal file
12
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/MemoryManagerMode.cs
vendored
Normal file
@@ -0,0 +1,12 @@
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Ryujinx.Common.Configuration
|
||||
{
|
||||
[JsonConverter(typeof(JsonStringEnumConverter<MemoryManagerMode>))]
|
||||
public enum MemoryManagerMode : byte
|
||||
{
|
||||
SoftwarePageTable,
|
||||
HostMapped,
|
||||
HostMappedUnsafe,
|
||||
}
|
||||
}
|
||||
9
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/Mod.cs
vendored
Normal file
9
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/Mod.cs
vendored
Normal file
@@ -0,0 +1,9 @@
|
||||
namespace Ryujinx.Common.Configuration
|
||||
{
|
||||
public class Mod
|
||||
{
|
||||
public string Name { get; set; }
|
||||
public string Path { get; set; }
|
||||
public bool Enabled { get; set; }
|
||||
}
|
||||
}
|
||||
14
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/ModMetadata.cs
vendored
Normal file
14
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/ModMetadata.cs
vendored
Normal file
@@ -0,0 +1,14 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace Ryujinx.Common.Configuration
|
||||
{
|
||||
public struct ModMetadata
|
||||
{
|
||||
public List<Mod> Mods { get; set; }
|
||||
|
||||
public ModMetadata()
|
||||
{
|
||||
Mods = [];
|
||||
}
|
||||
}
|
||||
}
|
||||
10
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/ModMetadataJsonSerializerContext.cs
vendored
Normal file
10
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/ModMetadataJsonSerializerContext.cs
vendored
Normal file
@@ -0,0 +1,10 @@
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Ryujinx.Common.Configuration
|
||||
{
|
||||
[JsonSourceGenerationOptions(WriteIndented = true)]
|
||||
[JsonSerializable(typeof(ModMetadata))]
|
||||
public partial class ModMetadataJsonSerializerContext : JsonSerializerContext
|
||||
{
|
||||
}
|
||||
}
|
||||
9
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/Multiplayer/MultiplayerMode.cs
vendored
Normal file
9
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/Multiplayer/MultiplayerMode.cs
vendored
Normal file
@@ -0,0 +1,9 @@
|
||||
namespace Ryujinx.Common.Configuration.Multiplayer
|
||||
{
|
||||
public enum MultiplayerMode
|
||||
{
|
||||
Disabled,
|
||||
LdnRyu,
|
||||
LdnMitm,
|
||||
}
|
||||
}
|
||||
13
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/ScalingFilter.cs
vendored
Normal file
13
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/ScalingFilter.cs
vendored
Normal file
@@ -0,0 +1,13 @@
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Ryujinx.Common.Configuration
|
||||
{
|
||||
[JsonConverter(typeof(JsonStringEnumConverter<ScalingFilter>))]
|
||||
public enum ScalingFilter
|
||||
{
|
||||
Bilinear,
|
||||
Nearest,
|
||||
Fsr,
|
||||
Area,
|
||||
}
|
||||
}
|
||||
10
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/TitleUpdateMetadata.cs
vendored
Normal file
10
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/TitleUpdateMetadata.cs
vendored
Normal file
@@ -0,0 +1,10 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace Ryujinx.Common.Configuration
|
||||
{
|
||||
public struct TitleUpdateMetadata
|
||||
{
|
||||
public string Selected { get; set; }
|
||||
public List<string> Paths { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Ryujinx.Common.Configuration
|
||||
{
|
||||
[JsonSourceGenerationOptions(WriteIndented = true)]
|
||||
[JsonSerializable(typeof(TitleUpdateMetadata))]
|
||||
public partial class TitleUpdateMetadataJsonSerializerContext : JsonSerializerContext
|
||||
{
|
||||
}
|
||||
}
|
||||
21
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/VSyncMode.cs
vendored
Normal file
21
tools/vendor/ryujinx/src/Ryujinx.Common/Configuration/VSyncMode.cs
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
namespace Ryujinx.Common.Configuration
|
||||
{
|
||||
public enum VSyncMode
|
||||
{
|
||||
Switch,
|
||||
Unbounded,
|
||||
Custom
|
||||
}
|
||||
|
||||
public static class VSyncModeExtensions
|
||||
{
|
||||
public static VSyncMode Next(this VSyncMode vsync, bool customEnabled = false) =>
|
||||
vsync switch
|
||||
{
|
||||
VSyncMode.Switch => customEnabled ? VSyncMode.Custom : VSyncMode.Unbounded,
|
||||
VSyncMode.Unbounded => VSyncMode.Switch,
|
||||
VSyncMode.Custom => VSyncMode.Unbounded,
|
||||
_ => VSyncMode.Switch
|
||||
};
|
||||
}
|
||||
}
|
||||
14
tools/vendor/ryujinx/src/Ryujinx.Common/Extensions/BinaryReaderExtensions.cs
vendored
Normal file
14
tools/vendor/ryujinx/src/Ryujinx.Common/Extensions/BinaryReaderExtensions.cs
vendored
Normal file
@@ -0,0 +1,14 @@
|
||||
using System.IO;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Ryujinx.Common
|
||||
{
|
||||
public static class BinaryReaderExtensions
|
||||
{
|
||||
public static T ReadStruct<T>(this BinaryReader reader) where T : unmanaged
|
||||
{
|
||||
return MemoryMarshal.Cast<byte, T>(reader.ReadBytes(Unsafe.SizeOf<T>()))[0];
|
||||
}
|
||||
}
|
||||
}
|
||||
27
tools/vendor/ryujinx/src/Ryujinx.Common/Extensions/BinaryWriterExtensions.cs
vendored
Normal file
27
tools/vendor/ryujinx/src/Ryujinx.Common/Extensions/BinaryWriterExtensions.cs
vendored
Normal file
@@ -0,0 +1,27 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Ryujinx.Common
|
||||
{
|
||||
public static class BinaryWriterExtensions
|
||||
{
|
||||
public static void WriteStruct<T>(this BinaryWriter writer, T value) where T : unmanaged
|
||||
{
|
||||
ReadOnlySpan<byte> data = MemoryMarshal.Cast<T, byte>(MemoryMarshal.CreateReadOnlySpan(ref value, 1));
|
||||
|
||||
writer.Write(data);
|
||||
}
|
||||
|
||||
public static void Write(this BinaryWriter writer, UInt128 value)
|
||||
{
|
||||
writer.Write((ulong)value);
|
||||
writer.Write((ulong)(value >> 64));
|
||||
}
|
||||
|
||||
public static void Write(this BinaryWriter writer, MemoryStream stream)
|
||||
{
|
||||
stream.CopyTo(writer.BaseStream);
|
||||
}
|
||||
}
|
||||
}
|
||||
182
tools/vendor/ryujinx/src/Ryujinx.Common/Extensions/SequenceReaderExtensions.cs
vendored
Normal file
182
tools/vendor/ryujinx/src/Ryujinx.Common/Extensions/SequenceReaderExtensions.cs
vendored
Normal file
@@ -0,0 +1,182 @@
|
||||
using System;
|
||||
using System.Buffers;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Ryujinx.Common.Extensions
|
||||
{
|
||||
public static class SequenceReaderExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Dumps the entire <see cref="SequenceReader{byte}"/> to a file, restoring its previous location afterward.
|
||||
/// Useful for debugging purposes.
|
||||
/// </summary>
|
||||
/// <param name="reader">The <see cref="SequenceReader{Byte}"/> to write to a file</param>
|
||||
/// <param name="fileFullName">The path and name of the file to create and dump to</param>
|
||||
public static void DumpToFile(this ref SequenceReader<byte> reader, string fileFullName)
|
||||
{
|
||||
long initialConsumed = reader.Consumed;
|
||||
|
||||
reader.Rewind(initialConsumed);
|
||||
|
||||
using (FileStream fileStream = System.IO.File.Create(fileFullName, 4096, System.IO.FileOptions.None))
|
||||
{
|
||||
while (reader.End == false)
|
||||
{
|
||||
ReadOnlySpan<byte> span = reader.CurrentSpan;
|
||||
fileStream.Write(span);
|
||||
reader.Advance(span.Length);
|
||||
}
|
||||
}
|
||||
|
||||
reader.SetConsumed(initialConsumed);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns a reference to the desired value. This ref should always be used. The argument passed in <paramref name="copyDestinationIfRequiredDoNotUse"/> should never be used, as this is only used for storage if the value
|
||||
/// must be copied from multiple <see cref="ReadOnlyMemory{Byte}"/> segments held by the <see cref="SequenceReader{Byte}"/>.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">Type to get</typeparam>
|
||||
/// <param name="reader">The <see cref="SequenceReader{Byte}"/> to read from</param>
|
||||
/// <param name="copyDestinationIfRequiredDoNotUse">A location used as storage if (and only if) the value to be read spans multiple <see cref="ReadOnlyMemory{Byte}"/> segments</param>
|
||||
/// <returns>A reference to the desired value, either directly to memory in the <see cref="SequenceReader{Byte}"/>, or to <paramref name="copyDestinationIfRequiredDoNotUse"/> if it has been used for copying the value in to</returns>
|
||||
/// <remarks>
|
||||
/// DO NOT use <paramref name="copyDestinationIfRequiredDoNotUse"/> after calling this method, as it will only
|
||||
/// contain a value if the value couldn't be referenced directly because it spans multiple <see cref="ReadOnlyMemory{Byte}"/> segments.
|
||||
/// To discourage use, it is recommended to call this method like the following:
|
||||
/// <c>
|
||||
/// ref readonly MyStruct value = ref sequenceReader.GetRefOrRefToCopy{MyStruct}(out _);
|
||||
/// </c>
|
||||
/// </remarks>
|
||||
/// <exception cref="ArgumentOutOfRangeException">The <see cref="SequenceReader{Byte}"/> does not contain enough data to read a value of type <typeparamref name="T"/></exception>
|
||||
public static ref readonly T GetRefOrRefToCopy<T>(this scoped ref SequenceReader<byte> reader, out T copyDestinationIfRequiredDoNotUse) where T : unmanaged
|
||||
{
|
||||
int lengthRequired = Unsafe.SizeOf<T>();
|
||||
|
||||
ReadOnlySpan<byte> span = reader.UnreadSpan;
|
||||
if (lengthRequired <= span.Length)
|
||||
{
|
||||
reader.Advance(lengthRequired);
|
||||
|
||||
copyDestinationIfRequiredDoNotUse = default;
|
||||
|
||||
ReadOnlySpan<T> spanOfT = MemoryMarshal.Cast<byte, T>(span);
|
||||
|
||||
return ref spanOfT[0];
|
||||
}
|
||||
else
|
||||
{
|
||||
copyDestinationIfRequiredDoNotUse = default;
|
||||
|
||||
Span<T> valueSpan = MemoryMarshal.CreateSpan(ref copyDestinationIfRequiredDoNotUse, 1);
|
||||
|
||||
Span<byte> valueBytesSpan = MemoryMarshal.AsBytes(valueSpan);
|
||||
|
||||
if (!reader.TryCopyTo(valueBytesSpan))
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(reader), "The sequence is not long enough to read the desired value.");
|
||||
}
|
||||
|
||||
reader.Advance(lengthRequired);
|
||||
|
||||
return ref valueSpan[0];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads an <see cref="int"/> as little endian.
|
||||
/// </summary>
|
||||
/// <param name="reader">The <see cref="SequenceReader{Byte}"/> to read from</param>
|
||||
/// <param name="value">A location to receive the read value</param>
|
||||
/// <exception cref="ArgumentOutOfRangeException">Thrown if there wasn't enough data for an <see cref="int"/></exception>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static void ReadLittleEndian(this ref SequenceReader<byte> reader, out int value)
|
||||
{
|
||||
if (!reader.TryReadLittleEndian(out value))
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(value), "The sequence is not long enough to read the desired value.");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the desired unmanaged value by copying it to the specified <paramref name="value"/>.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">Type to read</typeparam>
|
||||
/// <param name="reader">The <see cref="SequenceReader{Byte}"/> to read from</param>
|
||||
/// <param name="value">The target that will receive the read value</param>
|
||||
/// <exception cref="ArgumentOutOfRangeException">The <see cref="SequenceReader{Byte}"/> does not contain enough data to read a value of type <typeparamref name="T"/></exception>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static void ReadUnmanaged<T>(this ref SequenceReader<byte> reader, out T value) where T : unmanaged
|
||||
{
|
||||
if (!reader.TryReadUnmanaged(out value))
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(value), "The sequence is not long enough to read the desired value.");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the reader's position as bytes consumed.
|
||||
/// </summary>
|
||||
/// <param name="reader">The <see cref="SequenceReader{Byte}"/> to set the position</param>
|
||||
/// <param name="consumed">The number of bytes consumed</param>
|
||||
public static void SetConsumed(ref this SequenceReader<byte> reader, long consumed)
|
||||
{
|
||||
reader.Rewind(reader.Consumed);
|
||||
reader.Advance(consumed);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Try to read the given type out of the buffer if possible. Warning: this is dangerous to use with arbitrary
|
||||
/// structs - see remarks for full details.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">Type to read</typeparam>
|
||||
/// <remarks>
|
||||
/// IMPORTANT: The read is a straight copy of bits. If a struct depends on specific state of it's members to
|
||||
/// behave correctly this can lead to exceptions, etc. If reading endian specific integers, use the explicit
|
||||
/// overloads such as <see cref="SequenceReader{T}.TryReadLittleEndian"/>
|
||||
/// </remarks>
|
||||
/// <returns>
|
||||
/// True if successful. <paramref name="value"/> will be default if failed (due to lack of space).
|
||||
/// </returns>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static unsafe bool TryReadUnmanaged<T>(ref this SequenceReader<byte> reader, out T value) where T : unmanaged
|
||||
{
|
||||
ReadOnlySpan<byte> span = reader.UnreadSpan;
|
||||
|
||||
if (span.Length < sizeof(T))
|
||||
{
|
||||
return TryReadUnmanagedMultiSegment(ref reader, out value);
|
||||
}
|
||||
|
||||
value = Unsafe.ReadUnaligned<T>(ref MemoryMarshal.GetReference(span));
|
||||
|
||||
reader.Advance(sizeof(T));
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private static unsafe bool TryReadUnmanagedMultiSegment<T>(ref SequenceReader<byte> reader, out T value) where T : unmanaged
|
||||
{
|
||||
Debug.Assert(reader.UnreadSpan.Length < sizeof(T));
|
||||
|
||||
// Not enough data in the current segment, try to peek for the data we need.
|
||||
T buffer = default;
|
||||
|
||||
Span<byte> tempSpan = new(&buffer, sizeof(T));
|
||||
|
||||
if (!reader.TryCopyTo(tempSpan))
|
||||
{
|
||||
value = default;
|
||||
return false;
|
||||
}
|
||||
|
||||
value = Unsafe.ReadUnaligned<T>(ref MemoryMarshal.GetReference(tempSpan));
|
||||
|
||||
reader.Advance(sizeof(T));
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
138
tools/vendor/ryujinx/src/Ryujinx.Common/Extensions/StreamExtensions.cs
vendored
Normal file
138
tools/vendor/ryujinx/src/Ryujinx.Common/Extensions/StreamExtensions.cs
vendored
Normal file
@@ -0,0 +1,138 @@
|
||||
using System;
|
||||
using System.Buffers.Binary;
|
||||
using System.IO;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Ryujinx.Common
|
||||
{
|
||||
public static class StreamExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Writes an int span to this stream.
|
||||
///
|
||||
/// This default implementation converts each buffer value to a stack-allocated
|
||||
/// byte array, then writes it to the Stream using <see cref="Stream.Write(ReadOnlySpan{byte})" />.
|
||||
/// </summary>
|
||||
/// <param name="stream">The stream to be written to</param>
|
||||
/// <param name="buffer">The buffer of values to be written</param>
|
||||
public static void Write(this Stream stream, ReadOnlySpan<int> buffer)
|
||||
{
|
||||
if (buffer.Length == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (BitConverter.IsLittleEndian)
|
||||
{
|
||||
ReadOnlySpan<byte> byteBuffer = MemoryMarshal.Cast<int, byte>(buffer);
|
||||
stream.Write(byteBuffer);
|
||||
}
|
||||
else
|
||||
{
|
||||
Span<byte> byteBuffer = stackalloc byte[sizeof(int)];
|
||||
|
||||
foreach (int value in buffer)
|
||||
{
|
||||
BinaryPrimitives.WriteInt32LittleEndian(byteBuffer, value);
|
||||
stream.Write(byteBuffer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes a four-byte signed integer to this stream. The current position
|
||||
/// of the stream is advanced by four.
|
||||
/// </summary>
|
||||
/// <param name="stream">The stream to be written to</param>
|
||||
/// <param name="value">The value to be written</param>
|
||||
public static void Write(this Stream stream, int value)
|
||||
{
|
||||
Span<byte> buffer = stackalloc byte[sizeof(int)];
|
||||
BinaryPrimitives.WriteInt32LittleEndian(buffer, value);
|
||||
stream.Write(buffer);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes an eight-byte signed integer to this stream. The current position
|
||||
/// of the stream is advanced by eight.
|
||||
/// </summary>
|
||||
/// <param name="stream">The stream to be written to</param>
|
||||
/// <param name="value">The value to be written</param>
|
||||
public static void Write(this Stream stream, long value)
|
||||
{
|
||||
Span<byte> buffer = stackalloc byte[sizeof(long)];
|
||||
BinaryPrimitives.WriteInt64LittleEndian(buffer, value);
|
||||
stream.Write(buffer);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes a four-byte unsigned integer to this stream. The current position
|
||||
/// of the stream is advanced by four.
|
||||
/// </summary>
|
||||
/// <param name="stream">The stream to be written to</param>
|
||||
/// <param name="value">The value to be written</param>
|
||||
public static void Write(this Stream stream, uint value)
|
||||
{
|
||||
Span<byte> buffer = stackalloc byte[sizeof(uint)];
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(buffer, value);
|
||||
stream.Write(buffer);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes an eight-byte unsigned integer to this stream. The current
|
||||
/// position of the stream is advanced by eight.
|
||||
/// </summary>
|
||||
/// <param name="stream">The stream to be written to</param>
|
||||
/// <param name="value">The value to be written</param>
|
||||
public static void Write(this Stream stream, ulong value)
|
||||
{
|
||||
Span<byte> buffer = stackalloc byte[sizeof(ulong)];
|
||||
BinaryPrimitives.WriteUInt64LittleEndian(buffer, value);
|
||||
stream.Write(buffer);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes the contents of source to stream by calling source.CopyTo(stream).
|
||||
/// Provides consistency with other Stream.Write methods.
|
||||
/// </summary>
|
||||
/// <param name="stream">The stream to be written to</param>
|
||||
/// <param name="source">The stream to be read from</param>
|
||||
public static void Write(this Stream stream, Stream source)
|
||||
{
|
||||
source.CopyTo(stream);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes a sequence of bytes to the Stream.
|
||||
/// </summary>
|
||||
/// <param name="stream">The stream to be written to.</param>
|
||||
/// <param name="value">The byte to be written</param>
|
||||
/// <param name="count">The number of times the value should be written</param>
|
||||
public static void WriteByte(this Stream stream, byte value, int count)
|
||||
{
|
||||
if (count <= 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
const int BlockSize = 16;
|
||||
|
||||
int blockCount = count / BlockSize;
|
||||
if (blockCount > 0)
|
||||
{
|
||||
Span<byte> span = stackalloc byte[BlockSize];
|
||||
span.Fill(value);
|
||||
for (int x = 0; x < blockCount; x++)
|
||||
{
|
||||
stream.Write(span);
|
||||
}
|
||||
}
|
||||
|
||||
int nonBlockBytes = count % BlockSize;
|
||||
for (int x = 0; x < nonBlockBytes; x++)
|
||||
{
|
||||
stream.WriteByte(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
42
tools/vendor/ryujinx/src/Ryujinx.Common/GraphicsDriver/DriverUtilities.cs
vendored
Normal file
42
tools/vendor/ryujinx/src/Ryujinx.Common/GraphicsDriver/DriverUtilities.cs
vendored
Normal file
@@ -0,0 +1,42 @@
|
||||
using Ryujinx.Common.Utilities;
|
||||
using System;
|
||||
|
||||
namespace Ryujinx.Common.GraphicsDriver
|
||||
{
|
||||
public static class DriverUtilities
|
||||
{
|
||||
private static void AddMesaFlags(string envVar, string newFlags)
|
||||
{
|
||||
string existingFlags = Environment.GetEnvironmentVariable(envVar);
|
||||
|
||||
string flags = existingFlags == null ? newFlags : $"{existingFlags},{newFlags}";
|
||||
|
||||
OsUtils.SetEnvironmentVariableNoCaching(envVar, flags);
|
||||
}
|
||||
|
||||
public static void InitDriverConfig(bool oglThreading)
|
||||
{
|
||||
if (OperatingSystem.IsLinux())
|
||||
{
|
||||
AddMesaFlags("RADV_DEBUG", "nodcc");
|
||||
}
|
||||
|
||||
ToggleOGLThreading(oglThreading);
|
||||
}
|
||||
|
||||
public static void ToggleOGLThreading(bool enabled)
|
||||
{
|
||||
OsUtils.SetEnvironmentVariableNoCaching("mesa_glthread", enabled.ToString().ToLower());
|
||||
OsUtils.SetEnvironmentVariableNoCaching("__GL_THREADED_OPTIMIZATIONS", enabled ? "1" : "0");
|
||||
|
||||
try
|
||||
{
|
||||
NVThreadedOptimization.SetThreadedOptimization(enabled);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// NVAPI is not available, or couldn't change the application profile.
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
11
tools/vendor/ryujinx/src/Ryujinx.Common/GraphicsDriver/NVAPI/Nvapi.cs
vendored
Normal file
11
tools/vendor/ryujinx/src/Ryujinx.Common/GraphicsDriver/NVAPI/Nvapi.cs
vendored
Normal file
@@ -0,0 +1,11 @@
|
||||
namespace Ryujinx.Common.GraphicsDriver.NVAPI
|
||||
{
|
||||
enum Nvapi : uint
|
||||
{
|
||||
OglThreadControlId = 0x20C1221E,
|
||||
|
||||
OglThreadControlDefault = 0,
|
||||
OglThreadControlEnable = 1,
|
||||
OglThreadControlDisable = 2,
|
||||
}
|
||||
}
|
||||
42
tools/vendor/ryujinx/src/Ryujinx.Common/GraphicsDriver/NVAPI/NvapiUnicodeString.cs
vendored
Normal file
42
tools/vendor/ryujinx/src/Ryujinx.Common/GraphicsDriver/NVAPI/NvapiUnicodeString.cs
vendored
Normal file
@@ -0,0 +1,42 @@
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
|
||||
namespace Ryujinx.Common.GraphicsDriver.NVAPI
|
||||
{
|
||||
[StructLayout(LayoutKind.Sequential, Pack = 4)]
|
||||
public unsafe struct NvapiUnicodeString
|
||||
{
|
||||
private fixed byte _data[4096];
|
||||
|
||||
public NvapiUnicodeString(string text)
|
||||
{
|
||||
Set(text);
|
||||
}
|
||||
|
||||
public readonly string Get()
|
||||
{
|
||||
fixed (byte* data = _data)
|
||||
{
|
||||
string text = Encoding.Unicode.GetString(data, 4096);
|
||||
|
||||
int index = text.IndexOf('\0');
|
||||
if (index > -1)
|
||||
{
|
||||
text = text[..index];
|
||||
}
|
||||
|
||||
return text;
|
||||
}
|
||||
}
|
||||
|
||||
public readonly void Set(string text)
|
||||
{
|
||||
text += '\0';
|
||||
fixed (char* textPtr = text)
|
||||
fixed (byte* data = _data)
|
||||
{
|
||||
int written = Encoding.Unicode.GetBytes(textPtr, text.Length, data, 4096);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
17
tools/vendor/ryujinx/src/Ryujinx.Common/GraphicsDriver/NVAPI/NvdrsApplicationV4.cs
vendored
Normal file
17
tools/vendor/ryujinx/src/Ryujinx.Common/GraphicsDriver/NVAPI/NvdrsApplicationV4.cs
vendored
Normal file
@@ -0,0 +1,17 @@
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Ryujinx.Common.GraphicsDriver.NVAPI
|
||||
{
|
||||
[StructLayout(LayoutKind.Sequential, Pack = 4)]
|
||||
struct NvdrsApplicationV4
|
||||
{
|
||||
public uint Version;
|
||||
public uint IsPredefined;
|
||||
public NvapiUnicodeString AppName;
|
||||
public NvapiUnicodeString UserFriendlyName;
|
||||
public NvapiUnicodeString Launcher;
|
||||
public NvapiUnicodeString FileInFolder;
|
||||
public uint Flags;
|
||||
public NvapiUnicodeString CommandLine;
|
||||
}
|
||||
}
|
||||
15
tools/vendor/ryujinx/src/Ryujinx.Common/GraphicsDriver/NVAPI/NvdrsProfile.cs
vendored
Normal file
15
tools/vendor/ryujinx/src/Ryujinx.Common/GraphicsDriver/NVAPI/NvdrsProfile.cs
vendored
Normal file
@@ -0,0 +1,15 @@
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Ryujinx.Common.GraphicsDriver.NVAPI
|
||||
{
|
||||
[StructLayout(LayoutKind.Sequential, Pack = 1)]
|
||||
struct NvdrsProfile
|
||||
{
|
||||
public uint Version;
|
||||
public NvapiUnicodeString ProfileName;
|
||||
public uint GpuSupport;
|
||||
public uint IsPredefined;
|
||||
public uint NumOfApps;
|
||||
public uint NumOfSettings;
|
||||
}
|
||||
}
|
||||
49
tools/vendor/ryujinx/src/Ryujinx.Common/GraphicsDriver/NVAPI/NvdrsSetting.cs
vendored
Normal file
49
tools/vendor/ryujinx/src/Ryujinx.Common/GraphicsDriver/NVAPI/NvdrsSetting.cs
vendored
Normal file
@@ -0,0 +1,49 @@
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Ryujinx.Common.GraphicsDriver.NVAPI
|
||||
{
|
||||
enum NvdrsSettingType : uint
|
||||
{
|
||||
NvdrsDwordType,
|
||||
NvdrsBinaryType,
|
||||
NvdrsStringType,
|
||||
NvdrsWstringType,
|
||||
}
|
||||
|
||||
enum NvdrsSettingLocation : uint
|
||||
{
|
||||
NvdrsCurrentProfileLocation,
|
||||
NvdrsGlobalProfileLocation,
|
||||
NvdrsBaseProfileLocation,
|
||||
NvdrsDefaultProfileLocation,
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Explicit, Size = 0x3020)]
|
||||
struct NvdrsSetting
|
||||
{
|
||||
[FieldOffset(0x0)]
|
||||
public uint Version;
|
||||
[FieldOffset(0x4)]
|
||||
public NvapiUnicodeString SettingName;
|
||||
[FieldOffset(0x1004)]
|
||||
public Nvapi SettingId;
|
||||
[FieldOffset(0x1008)]
|
||||
public NvdrsSettingType SettingType;
|
||||
[FieldOffset(0x100C)]
|
||||
public NvdrsSettingLocation SettingLocation;
|
||||
[FieldOffset(0x1010)]
|
||||
public uint IsCurrentPredefined;
|
||||
[FieldOffset(0x1014)]
|
||||
public uint IsPredefinedValid;
|
||||
|
||||
[FieldOffset(0x1018)]
|
||||
public uint PredefinedValue;
|
||||
[FieldOffset(0x1018)]
|
||||
public NvapiUnicodeString PredefinedString;
|
||||
|
||||
[FieldOffset(0x201C)]
|
||||
public uint CurrentValue;
|
||||
[FieldOffset(0x201C)]
|
||||
public NvapiUnicodeString CurrentString;
|
||||
}
|
||||
}
|
||||
161
tools/vendor/ryujinx/src/Ryujinx.Common/GraphicsDriver/NVThreadedOptimization.cs
vendored
Normal file
161
tools/vendor/ryujinx/src/Ryujinx.Common/GraphicsDriver/NVThreadedOptimization.cs
vendored
Normal file
@@ -0,0 +1,161 @@
|
||||
using Ryujinx.Common.GraphicsDriver.NVAPI;
|
||||
using System;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
// ReSharper disable InconsistentNaming
|
||||
|
||||
namespace Ryujinx.Common.GraphicsDriver
|
||||
{
|
||||
static partial class NVThreadedOptimization
|
||||
{
|
||||
private const string ProfileName = "Ryujinx Nvidia Profile";
|
||||
|
||||
private const uint NvAPI_Initialize_ID = 0x0150E828;
|
||||
private const uint NvAPI_DRS_CreateSession_ID = 0x0694D52E;
|
||||
private const uint NvAPI_DRS_LoadSettings_ID = 0x375DBD6B;
|
||||
private const uint NvAPI_DRS_FindProfileByName_ID = 0x7E4A9A0B;
|
||||
private const uint NvAPI_DRS_CreateProfile_ID = 0x0CC176068;
|
||||
private const uint NvAPI_DRS_CreateApplication_ID = 0x4347A9DE;
|
||||
private const uint NvAPI_DRS_SetSetting_ID = 0x577DD202;
|
||||
private const uint NvAPI_DRS_SaveSettings_ID = 0xFCBC7E14;
|
||||
private const uint NvAPI_DRS_DestroySession_ID = 0x0DAD9CFF8;
|
||||
|
||||
[LibraryImport("nvapi64")]
|
||||
private static partial nint nvapi_QueryInterface(uint id);
|
||||
|
||||
private delegate int NvAPI_InitializeDelegate();
|
||||
private static NvAPI_InitializeDelegate NvAPI_Initialize;
|
||||
|
||||
private delegate int NvAPI_DRS_CreateSessionDelegate(out nint handle);
|
||||
private static NvAPI_DRS_CreateSessionDelegate NvAPI_DRS_CreateSession;
|
||||
|
||||
private delegate int NvAPI_DRS_LoadSettingsDelegate(nint handle);
|
||||
private static NvAPI_DRS_LoadSettingsDelegate NvAPI_DRS_LoadSettings;
|
||||
|
||||
private delegate int NvAPI_DRS_FindProfileByNameDelegate(nint handle, NvapiUnicodeString profileName, out nint profileHandle);
|
||||
private static NvAPI_DRS_FindProfileByNameDelegate NvAPI_DRS_FindProfileByName;
|
||||
|
||||
private delegate int NvAPI_DRS_CreateProfileDelegate(nint handle, ref NvdrsProfile profileInfo, out nint profileHandle);
|
||||
private static NvAPI_DRS_CreateProfileDelegate NvAPI_DRS_CreateProfile;
|
||||
|
||||
private delegate int NvAPI_DRS_CreateApplicationDelegate(nint handle, nint profileHandle, ref NvdrsApplicationV4 app);
|
||||
private static NvAPI_DRS_CreateApplicationDelegate NvAPI_DRS_CreateApplication;
|
||||
|
||||
private delegate int NvAPI_DRS_SetSettingDelegate(nint handle, nint profileHandle, ref NvdrsSetting setting);
|
||||
private static NvAPI_DRS_SetSettingDelegate NvAPI_DRS_SetSetting;
|
||||
|
||||
private delegate int NvAPI_DRS_SaveSettingsDelegate(nint handle);
|
||||
private static NvAPI_DRS_SaveSettingsDelegate NvAPI_DRS_SaveSettings;
|
||||
|
||||
private delegate int NvAPI_DRS_DestroySessionDelegate(nint handle);
|
||||
private static NvAPI_DRS_DestroySessionDelegate NvAPI_DRS_DestroySession;
|
||||
|
||||
private static bool _initialized;
|
||||
|
||||
private static void Check(int status)
|
||||
{
|
||||
if (status != 0)
|
||||
{
|
||||
throw new Exception($"NVAPI Error: {status}");
|
||||
}
|
||||
}
|
||||
|
||||
private static void Initialize()
|
||||
{
|
||||
if (!_initialized)
|
||||
{
|
||||
NvAPI_Initialize = NvAPI_Delegate<NvAPI_InitializeDelegate>(NvAPI_Initialize_ID);
|
||||
|
||||
Check(NvAPI_Initialize());
|
||||
|
||||
NvAPI_DRS_CreateSession = NvAPI_Delegate<NvAPI_DRS_CreateSessionDelegate>(NvAPI_DRS_CreateSession_ID);
|
||||
NvAPI_DRS_LoadSettings = NvAPI_Delegate<NvAPI_DRS_LoadSettingsDelegate>(NvAPI_DRS_LoadSettings_ID);
|
||||
NvAPI_DRS_FindProfileByName = NvAPI_Delegate<NvAPI_DRS_FindProfileByNameDelegate>(NvAPI_DRS_FindProfileByName_ID);
|
||||
NvAPI_DRS_CreateProfile = NvAPI_Delegate<NvAPI_DRS_CreateProfileDelegate>(NvAPI_DRS_CreateProfile_ID);
|
||||
NvAPI_DRS_CreateApplication = NvAPI_Delegate<NvAPI_DRS_CreateApplicationDelegate>(NvAPI_DRS_CreateApplication_ID);
|
||||
NvAPI_DRS_SetSetting = NvAPI_Delegate<NvAPI_DRS_SetSettingDelegate>(NvAPI_DRS_SetSetting_ID);
|
||||
NvAPI_DRS_SaveSettings = NvAPI_Delegate<NvAPI_DRS_SaveSettingsDelegate>(NvAPI_DRS_SaveSettings_ID);
|
||||
NvAPI_DRS_DestroySession = NvAPI_Delegate<NvAPI_DRS_DestroySessionDelegate>(NvAPI_DRS_DestroySession_ID);
|
||||
|
||||
_initialized = true;
|
||||
}
|
||||
}
|
||||
|
||||
private static uint MakeVersion<T>(uint version) where T : unmanaged
|
||||
{
|
||||
return (uint)Unsafe.SizeOf<T>() | version << 16;
|
||||
}
|
||||
|
||||
public static void SetThreadedOptimization(bool enabled)
|
||||
{
|
||||
Initialize();
|
||||
|
||||
uint targetValue = (uint)(enabled ? Nvapi.OglThreadControlEnable : Nvapi.OglThreadControlDisable);
|
||||
|
||||
Check(NvAPI_Initialize());
|
||||
|
||||
Check(NvAPI_DRS_CreateSession(out nint handle));
|
||||
|
||||
Check(NvAPI_DRS_LoadSettings(handle));
|
||||
|
||||
// Check if the profile already exists.
|
||||
|
||||
int status = NvAPI_DRS_FindProfileByName(handle, new NvapiUnicodeString(ProfileName), out nint profileHandle);
|
||||
|
||||
if (status != 0)
|
||||
{
|
||||
NvdrsProfile profile = new()
|
||||
{
|
||||
Version = MakeVersion<NvdrsProfile>(1),
|
||||
IsPredefined = 0,
|
||||
GpuSupport = uint.MaxValue,
|
||||
};
|
||||
profile.ProfileName.Set(ProfileName);
|
||||
Check(NvAPI_DRS_CreateProfile(handle, ref profile, out profileHandle));
|
||||
|
||||
NvdrsApplicationV4 application = new()
|
||||
{
|
||||
Version = MakeVersion<NvdrsApplicationV4>(4),
|
||||
IsPredefined = 0,
|
||||
Flags = 3, // IsMetro, IsCommandLine
|
||||
};
|
||||
application.AppName.Set("Ryujinx.exe");
|
||||
application.UserFriendlyName.Set("Ryujinx");
|
||||
application.Launcher.Set(string.Empty);
|
||||
application.FileInFolder.Set(string.Empty);
|
||||
|
||||
Check(NvAPI_DRS_CreateApplication(handle, profileHandle, ref application));
|
||||
}
|
||||
|
||||
NvdrsSetting setting = new()
|
||||
{
|
||||
Version = MakeVersion<NvdrsSetting>(1),
|
||||
SettingId = Nvapi.OglThreadControlId,
|
||||
SettingType = NvdrsSettingType.NvdrsDwordType,
|
||||
SettingLocation = NvdrsSettingLocation.NvdrsCurrentProfileLocation,
|
||||
IsCurrentPredefined = 0,
|
||||
IsPredefinedValid = 0,
|
||||
CurrentValue = targetValue,
|
||||
PredefinedValue = targetValue,
|
||||
};
|
||||
|
||||
Check(NvAPI_DRS_SetSetting(handle, profileHandle, ref setting));
|
||||
|
||||
Check(NvAPI_DRS_SaveSettings(handle));
|
||||
|
||||
NvAPI_DRS_DestroySession(handle);
|
||||
}
|
||||
|
||||
private static T NvAPI_Delegate<T>(uint id) where T : class
|
||||
{
|
||||
nint ptr = nvapi_QueryInterface(id);
|
||||
|
||||
if (ptr != nint.Zero)
|
||||
{
|
||||
return Marshal.GetDelegateForFunctionPointer<T>(ptr);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
739
tools/vendor/ryujinx/src/Ryujinx.Common/Hash128.cs
vendored
Normal file
739
tools/vendor/ryujinx/src/Ryujinx.Common/Hash128.cs
vendored
Normal file
@@ -0,0 +1,739 @@
|
||||
using System;
|
||||
using System.Buffers.Binary;
|
||||
using System.Diagnostics;
|
||||
using System.Numerics;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Runtime.Intrinsics;
|
||||
using System.Runtime.Intrinsics.X86;
|
||||
// ReSharper disable InconsistentNaming
|
||||
|
||||
namespace Ryujinx.Common
|
||||
{
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public struct Hash128(ulong low, ulong high) : IEquatable<Hash128>
|
||||
{
|
||||
public ulong Low = low;
|
||||
public ulong High = high;
|
||||
|
||||
public readonly override string ToString() => $"{High:x16}{Low:x16}";
|
||||
|
||||
public static bool operator ==(Hash128 x, Hash128 y) => x.Equals(y);
|
||||
|
||||
public static bool operator !=(Hash128 x, Hash128 y) => !x.Equals(y);
|
||||
|
||||
public readonly override bool Equals(object obj) => obj is Hash128 hash128 && Equals(hash128);
|
||||
|
||||
public readonly bool Equals(Hash128 cmpObj) => Low == cmpObj.Low && High == cmpObj.High;
|
||||
|
||||
public readonly override int GetHashCode() => HashCode.Combine(Low, High);
|
||||
|
||||
public static Hash128 ComputeHash(ReadOnlySpan<byte> input) => Xxh3128bitsInternal(input, Xxh3KSecret, 0UL);
|
||||
|
||||
#region Hash computation
|
||||
|
||||
private const int StripeLen = 64;
|
||||
private const int AccNb = StripeLen / sizeof(ulong);
|
||||
private const int SecretConsumeRate = 8;
|
||||
private const int SecretLastAccStart = 7;
|
||||
private const int SecretMergeAccsStart = 11;
|
||||
private const int SecretSizeMin = 136;
|
||||
private const int MidSizeStartOffset = 3;
|
||||
private const int MidSizeLastOffset = 17;
|
||||
|
||||
private const uint Prime32_1 = 0x9E3779B1U;
|
||||
private const uint Prime32_2 = 0x85EBCA77U;
|
||||
private const uint Prime32_3 = 0xC2B2AE3DU;
|
||||
private const uint Prime32_4 = 0x27D4EB2FU;
|
||||
private const uint Prime32_5 = 0x165667B1U;
|
||||
|
||||
private const ulong Prime64_1 = 0x9E3779B185EBCA87UL;
|
||||
private const ulong Prime64_2 = 0xC2B2AE3D27D4EB4FUL;
|
||||
private const ulong Prime64_3 = 0x165667B19E3779F9UL;
|
||||
private const ulong Prime64_4 = 0x85EBCA77C2B2AE63UL;
|
||||
private const ulong Prime64_5 = 0x27D4EB2F165667C5UL;
|
||||
|
||||
private static readonly ulong[] _xxh3InitAcc =
|
||||
[
|
||||
Prime32_3,
|
||||
Prime64_1,
|
||||
Prime64_2,
|
||||
Prime64_3,
|
||||
Prime64_4,
|
||||
Prime32_2,
|
||||
Prime64_5,
|
||||
Prime32_1
|
||||
];
|
||||
|
||||
private static ReadOnlySpan<byte> Xxh3KSecret =>
|
||||
[
|
||||
0xb8,
|
||||
0xfe,
|
||||
0x6c,
|
||||
0x39,
|
||||
0x23,
|
||||
0xa4,
|
||||
0x4b,
|
||||
0xbe,
|
||||
0x7c,
|
||||
0x01,
|
||||
0x81,
|
||||
0x2c,
|
||||
0xf7,
|
||||
0x21,
|
||||
0xad,
|
||||
0x1c,
|
||||
0xde,
|
||||
0xd4,
|
||||
0x6d,
|
||||
0xe9,
|
||||
0x83,
|
||||
0x90,
|
||||
0x97,
|
||||
0xdb,
|
||||
0x72,
|
||||
0x40,
|
||||
0xa4,
|
||||
0xa4,
|
||||
0xb7,
|
||||
0xb3,
|
||||
0x67,
|
||||
0x1f,
|
||||
0xcb,
|
||||
0x79,
|
||||
0xe6,
|
||||
0x4e,
|
||||
0xcc,
|
||||
0xc0,
|
||||
0xe5,
|
||||
0x78,
|
||||
0x82,
|
||||
0x5a,
|
||||
0xd0,
|
||||
0x7d,
|
||||
0xcc,
|
||||
0xff,
|
||||
0x72,
|
||||
0x21,
|
||||
0xb8,
|
||||
0x08,
|
||||
0x46,
|
||||
0x74,
|
||||
0xf7,
|
||||
0x43,
|
||||
0x24,
|
||||
0x8e,
|
||||
0xe0,
|
||||
0x35,
|
||||
0x90,
|
||||
0xe6,
|
||||
0x81,
|
||||
0x3a,
|
||||
0x26,
|
||||
0x4c,
|
||||
0x3c,
|
||||
0x28,
|
||||
0x52,
|
||||
0xbb,
|
||||
0x91,
|
||||
0xc3,
|
||||
0x00,
|
||||
0xcb,
|
||||
0x88,
|
||||
0xd0,
|
||||
0x65,
|
||||
0x8b,
|
||||
0x1b,
|
||||
0x53,
|
||||
0x2e,
|
||||
0xa3,
|
||||
0x71,
|
||||
0x64,
|
||||
0x48,
|
||||
0x97,
|
||||
0xa2,
|
||||
0x0d,
|
||||
0xf9,
|
||||
0x4e,
|
||||
0x38,
|
||||
0x19,
|
||||
0xef,
|
||||
0x46,
|
||||
0xa9,
|
||||
0xde,
|
||||
0xac,
|
||||
0xd8,
|
||||
0xa8,
|
||||
0xfa,
|
||||
0x76,
|
||||
0x3f,
|
||||
0xe3,
|
||||
0x9c,
|
||||
0x34,
|
||||
0x3f,
|
||||
0xf9,
|
||||
0xdc,
|
||||
0xbb,
|
||||
0xc7,
|
||||
0xc7,
|
||||
0x0b,
|
||||
0x4f,
|
||||
0x1d,
|
||||
0x8a,
|
||||
0x51,
|
||||
0xe0,
|
||||
0x4b,
|
||||
0xcd,
|
||||
0xb4,
|
||||
0x59,
|
||||
0x31,
|
||||
0xc8,
|
||||
0x9f,
|
||||
0x7e,
|
||||
0xc9,
|
||||
0xd9,
|
||||
0x78,
|
||||
0x73,
|
||||
0x64,
|
||||
0xea,
|
||||
0xc5,
|
||||
0xac,
|
||||
0x83,
|
||||
0x34,
|
||||
0xd3,
|
||||
0xeb,
|
||||
0xc3,
|
||||
0xc5,
|
||||
0x81,
|
||||
0xa0,
|
||||
0xff,
|
||||
0xfa,
|
||||
0x13,
|
||||
0x63,
|
||||
0xeb,
|
||||
0x17,
|
||||
0x0d,
|
||||
0xdd,
|
||||
0x51,
|
||||
0xb7,
|
||||
0xf0,
|
||||
0xda,
|
||||
0x49,
|
||||
0xd3,
|
||||
0x16,
|
||||
0x55,
|
||||
0x26,
|
||||
0x29,
|
||||
0xd4,
|
||||
0x68,
|
||||
0x9e,
|
||||
0x2b,
|
||||
0x16,
|
||||
0xbe,
|
||||
0x58,
|
||||
0x7d,
|
||||
0x47,
|
||||
0xa1,
|
||||
0xfc,
|
||||
0x8f,
|
||||
0xf8,
|
||||
0xb8,
|
||||
0xd1,
|
||||
0x7a,
|
||||
0xd0,
|
||||
0x31,
|
||||
0xce,
|
||||
0x45,
|
||||
0xcb,
|
||||
0x3a,
|
||||
0x8f,
|
||||
0x95,
|
||||
0x16,
|
||||
0x04,
|
||||
0x28,
|
||||
0xaf,
|
||||
0xd7,
|
||||
0xfb,
|
||||
0xca,
|
||||
0xbb,
|
||||
0x4b,
|
||||
0x40,
|
||||
0x7e
|
||||
];
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private static ulong Mult32To64(ulong x, ulong y) => (uint)x * (ulong)(uint)y;
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private static Hash128 Mult64To128(ulong lhs, ulong rhs)
|
||||
{
|
||||
ulong high = Math.BigMul(lhs, rhs, out ulong low);
|
||||
|
||||
return new Hash128
|
||||
{
|
||||
Low = low,
|
||||
High = high,
|
||||
};
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private static ulong Mul128Fold64(ulong lhs, ulong rhs)
|
||||
{
|
||||
Hash128 product = Mult64To128(lhs, rhs);
|
||||
|
||||
return product.Low ^ product.High;
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private static ulong XorShift64(ulong v64, int shift)
|
||||
{
|
||||
Debug.Assert(shift is >= 0 and < 64);
|
||||
|
||||
return v64 ^ (v64 >> shift);
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private static ulong Xxh3Avalanche(ulong h64)
|
||||
{
|
||||
h64 = XorShift64(h64, 37);
|
||||
h64 *= 0x165667919E3779F9UL;
|
||||
h64 = XorShift64(h64, 32);
|
||||
|
||||
return h64;
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private static ulong Xxh64Avalanche(ulong h64)
|
||||
{
|
||||
h64 ^= h64 >> 33;
|
||||
h64 *= Prime64_2;
|
||||
h64 ^= h64 >> 29;
|
||||
h64 *= Prime64_3;
|
||||
h64 ^= h64 >> 32;
|
||||
|
||||
return h64;
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private unsafe static void Xxh3Accumulate512(Span<ulong> acc, ReadOnlySpan<byte> input, ReadOnlySpan<byte> secret)
|
||||
{
|
||||
if (Avx2.IsSupported)
|
||||
{
|
||||
fixed (ulong* pAcc = acc)
|
||||
{
|
||||
fixed (byte* pInput = input, pSecret = secret)
|
||||
{
|
||||
Vector256<ulong>* xAcc = (Vector256<ulong>*)pAcc;
|
||||
Vector256<byte>* xInput = (Vector256<byte>*)pInput;
|
||||
Vector256<byte>* xSecret = (Vector256<byte>*)pSecret;
|
||||
|
||||
for (ulong i = 0; i < StripeLen / 32; i++)
|
||||
{
|
||||
Vector256<byte> dataVec = xInput[i];
|
||||
Vector256<byte> keyVec = xSecret[i];
|
||||
Vector256<byte> dataKey = Avx2.Xor(dataVec, keyVec);
|
||||
Vector256<uint> dataKeyLo = Avx2.Shuffle(dataKey.AsUInt32(), 0b00110001);
|
||||
Vector256<ulong> product = Avx2.Multiply(dataKey.AsUInt32(), dataKeyLo);
|
||||
Vector256<uint> dataSwap = Avx2.Shuffle(dataVec.AsUInt32(), 0b01001110);
|
||||
Vector256<ulong> sum = Avx2.Add(xAcc[i], dataSwap.AsUInt64());
|
||||
xAcc[i] = Avx2.Add(product, sum);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (Sse2.IsSupported)
|
||||
{
|
||||
fixed (ulong* pAcc = acc)
|
||||
{
|
||||
fixed (byte* pInput = input, pSecret = secret)
|
||||
{
|
||||
Vector128<ulong>* xAcc = (Vector128<ulong>*)pAcc;
|
||||
Vector128<byte>* xInput = (Vector128<byte>*)pInput;
|
||||
Vector128<byte>* xSecret = (Vector128<byte>*)pSecret;
|
||||
|
||||
for (ulong i = 0; i < StripeLen / 16; i++)
|
||||
{
|
||||
Vector128<byte> dataVec = xInput[i];
|
||||
Vector128<byte> keyVec = xSecret[i];
|
||||
Vector128<byte> dataKey = Sse2.Xor(dataVec, keyVec);
|
||||
Vector128<uint> dataKeyLo = Sse2.Shuffle(dataKey.AsUInt32(), 0b00110001);
|
||||
Vector128<ulong> product = Sse2.Multiply(dataKey.AsUInt32(), dataKeyLo);
|
||||
Vector128<uint> dataSwap = Sse2.Shuffle(dataVec.AsUInt32(), 0b01001110);
|
||||
Vector128<ulong> sum = Sse2.Add(xAcc[i], dataSwap.AsUInt64());
|
||||
xAcc[i] = Sse2.Add(product, sum);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
for (int i = 0; i < AccNb; i++)
|
||||
{
|
||||
ulong dataVal = BinaryPrimitives.ReadUInt64LittleEndian(input[(i * sizeof(ulong))..]);
|
||||
ulong dataKey = dataVal ^ BinaryPrimitives.ReadUInt64LittleEndian(secret[(i * sizeof(ulong))..]);
|
||||
acc[i ^ 1] += dataVal;
|
||||
acc[i] += Mult32To64((uint)dataKey, dataKey >> 32);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private unsafe static void Xxh3ScrambleAcc(Span<ulong> acc, ReadOnlySpan<byte> secret)
|
||||
{
|
||||
if (Avx2.IsSupported)
|
||||
{
|
||||
fixed (ulong* pAcc = acc)
|
||||
{
|
||||
fixed (byte* pSecret = secret)
|
||||
{
|
||||
Vector256<uint> prime32 = Vector256.Create(Prime32_1);
|
||||
Vector256<ulong>* xAcc = (Vector256<ulong>*)pAcc;
|
||||
Vector256<byte>* xSecret = (Vector256<byte>*)pSecret;
|
||||
|
||||
for (ulong i = 0; i < StripeLen / 32; i++)
|
||||
{
|
||||
Vector256<ulong> accVec = xAcc[i];
|
||||
Vector256<ulong> shifted = Avx2.ShiftRightLogical(accVec, 47);
|
||||
Vector256<ulong> dataVec = Avx2.Xor(accVec, shifted);
|
||||
|
||||
Vector256<byte> keyVec = xSecret[i];
|
||||
Vector256<uint> dataKey = Avx2.Xor(dataVec.AsUInt32(), keyVec.AsUInt32());
|
||||
|
||||
Vector256<uint> dataKeyHi = Avx2.Shuffle(dataKey.AsUInt32(), 0b00110001);
|
||||
Vector256<ulong> prodLo = Avx2.Multiply(dataKey, prime32);
|
||||
Vector256<ulong> prodHi = Avx2.Multiply(dataKeyHi, prime32);
|
||||
|
||||
xAcc[i] = Avx2.Add(prodLo, Avx2.ShiftLeftLogical(prodHi, 32));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (Sse2.IsSupported)
|
||||
{
|
||||
fixed (ulong* pAcc = acc)
|
||||
{
|
||||
fixed (byte* pSecret = secret)
|
||||
{
|
||||
Vector128<uint> prime32 = Vector128.Create(Prime32_1);
|
||||
Vector128<ulong>* xAcc = (Vector128<ulong>*)pAcc;
|
||||
Vector128<byte>* xSecret = (Vector128<byte>*)pSecret;
|
||||
|
||||
for (ulong i = 0; i < StripeLen / 16; i++)
|
||||
{
|
||||
Vector128<ulong> accVec = xAcc[i];
|
||||
Vector128<ulong> shifted = Sse2.ShiftRightLogical(accVec, 47);
|
||||
Vector128<ulong> dataVec = Sse2.Xor(accVec, shifted);
|
||||
|
||||
Vector128<byte> keyVec = xSecret[i];
|
||||
Vector128<uint> dataKey = Sse2.Xor(dataVec.AsUInt32(), keyVec.AsUInt32());
|
||||
|
||||
Vector128<uint> dataKeyHi = Sse2.Shuffle(dataKey.AsUInt32(), 0b00110001);
|
||||
Vector128<ulong> prodLo = Sse2.Multiply(dataKey, prime32);
|
||||
Vector128<ulong> prodHi = Sse2.Multiply(dataKeyHi, prime32);
|
||||
|
||||
xAcc[i] = Sse2.Add(prodLo, Sse2.ShiftLeftLogical(prodHi, 32));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
for (int i = 0; i < AccNb; i++)
|
||||
{
|
||||
ulong key64 = BinaryPrimitives.ReadUInt64LittleEndian(secret[(i * sizeof(ulong))..]);
|
||||
ulong acc64 = acc[i];
|
||||
acc64 = XorShift64(acc64, 47);
|
||||
acc64 ^= key64;
|
||||
acc64 *= Prime32_1;
|
||||
acc[i] = acc64;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private static void Xxh3Accumulate(Span<ulong> acc, ReadOnlySpan<byte> input, ReadOnlySpan<byte> secret, int nbStripes)
|
||||
{
|
||||
for (int n = 0; n < nbStripes; n++)
|
||||
{
|
||||
ReadOnlySpan<byte> inData = input[(n * StripeLen)..];
|
||||
Xxh3Accumulate512(acc, inData, secret[(n * SecretConsumeRate)..]);
|
||||
}
|
||||
}
|
||||
|
||||
private static void Xxh3HashLongInternalLoop(Span<ulong> acc, ReadOnlySpan<byte> input, ReadOnlySpan<byte> secret)
|
||||
{
|
||||
int nbStripesPerBlock = (secret.Length - StripeLen) / SecretConsumeRate;
|
||||
int blockLen = StripeLen * nbStripesPerBlock;
|
||||
int nbBlocks = (input.Length - 1) / blockLen;
|
||||
|
||||
Debug.Assert(secret.Length >= SecretSizeMin);
|
||||
|
||||
for (int n = 0; n < nbBlocks; n++)
|
||||
{
|
||||
Xxh3Accumulate(acc, input[(n * blockLen)..], secret, nbStripesPerBlock);
|
||||
Xxh3ScrambleAcc(acc, secret[^StripeLen..]);
|
||||
}
|
||||
|
||||
Debug.Assert(input.Length > StripeLen);
|
||||
|
||||
int nbStripes = (input.Length - 1 - (blockLen * nbBlocks)) / StripeLen;
|
||||
Debug.Assert(nbStripes <= (secret.Length / SecretConsumeRate));
|
||||
Xxh3Accumulate(acc, input[(nbBlocks * blockLen)..], secret, nbStripes);
|
||||
|
||||
ReadOnlySpan<byte> p = input[^StripeLen..];
|
||||
Xxh3Accumulate512(acc, p, secret[(secret.Length - StripeLen - SecretLastAccStart)..]);
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private static ulong Xxh3Mix2Accs(Span<ulong> acc, ReadOnlySpan<byte> secret)
|
||||
{
|
||||
return Mul128Fold64(
|
||||
acc[0] ^ BinaryPrimitives.ReadUInt64LittleEndian(secret),
|
||||
acc[1] ^ BinaryPrimitives.ReadUInt64LittleEndian(secret[8..]));
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private static ulong Xxh3MergeAccs(Span<ulong> acc, ReadOnlySpan<byte> secret, ulong start)
|
||||
{
|
||||
ulong result64 = start;
|
||||
|
||||
for (int i = 0; i < 4; i++)
|
||||
{
|
||||
result64 += Xxh3Mix2Accs(acc[(2 * i)..], secret[(16 * i)..]);
|
||||
}
|
||||
|
||||
return Xxh3Avalanche(result64);
|
||||
}
|
||||
|
||||
[SkipLocalsInit]
|
||||
private static Hash128 Xxh3HashLong128bInternal(ReadOnlySpan<byte> input, ReadOnlySpan<byte> secret)
|
||||
{
|
||||
Span<ulong> acc = stackalloc ulong[AccNb];
|
||||
_xxh3InitAcc.CopyTo(acc);
|
||||
|
||||
Xxh3HashLongInternalLoop(acc, input, secret);
|
||||
|
||||
Debug.Assert(acc.Length == 8);
|
||||
Debug.Assert(secret.Length >= acc.Length * sizeof(ulong) + SecretMergeAccsStart);
|
||||
|
||||
return new Hash128
|
||||
{
|
||||
Low = Xxh3MergeAccs(acc, secret[SecretMergeAccsStart..], (ulong)input.Length * Prime64_1),
|
||||
High = Xxh3MergeAccs(
|
||||
acc,
|
||||
secret[(secret.Length - acc.Length * sizeof(ulong) - SecretMergeAccsStart)..],
|
||||
~((ulong)input.Length * Prime64_2)),
|
||||
};
|
||||
}
|
||||
|
||||
private static Hash128 Xxh3Len1To3128b(ReadOnlySpan<byte> input, ReadOnlySpan<byte> secret, ulong seed)
|
||||
{
|
||||
Debug.Assert(input.Length is >= 1 and <= 3);
|
||||
|
||||
byte c1 = input[0];
|
||||
byte c2 = input[input.Length >> 1];
|
||||
byte c3 = input[^1];
|
||||
|
||||
uint combinedL = ((uint)c1 << 16) | ((uint)c2 << 24) | c3 | ((uint)input.Length << 8);
|
||||
uint combinedH = BitOperations.RotateLeft(BinaryPrimitives.ReverseEndianness(combinedL), 13);
|
||||
ulong bitFlipL = (BinaryPrimitives.ReadUInt32LittleEndian(secret) ^ BinaryPrimitives.ReadUInt32LittleEndian(secret[4..])) + seed;
|
||||
ulong bitFlipH = (BinaryPrimitives.ReadUInt32LittleEndian(secret[8..]) ^ BinaryPrimitives.ReadUInt32LittleEndian(secret[12..])) - seed;
|
||||
ulong keyedLo = combinedL ^ bitFlipL;
|
||||
ulong keyedHi = combinedH ^ bitFlipH;
|
||||
|
||||
return new Hash128
|
||||
{
|
||||
Low = Xxh64Avalanche(keyedLo),
|
||||
High = Xxh64Avalanche(keyedHi),
|
||||
};
|
||||
}
|
||||
|
||||
private static Hash128 Xxh3Len4To8128b(ReadOnlySpan<byte> input, ReadOnlySpan<byte> secret, ulong seed)
|
||||
{
|
||||
Debug.Assert(input.Length is >= 4 and <= 8);
|
||||
|
||||
seed ^= BinaryPrimitives.ReverseEndianness((uint)seed) << 32;
|
||||
|
||||
uint inputLo = BinaryPrimitives.ReadUInt32LittleEndian(input);
|
||||
uint inputHi = BinaryPrimitives.ReadUInt32LittleEndian(input[^4..]);
|
||||
ulong input64 = inputLo + ((ulong)inputHi << 32);
|
||||
ulong bitFlip = (BinaryPrimitives.ReadUInt64LittleEndian(secret[16..]) ^ BinaryPrimitives.ReadUInt64LittleEndian(secret[24..])) + seed;
|
||||
ulong keyed = input64 ^ bitFlip;
|
||||
|
||||
Hash128 m128 = Mult64To128(keyed, Prime64_1 + ((ulong)input.Length << 2));
|
||||
|
||||
m128.High += m128.Low << 1;
|
||||
m128.Low ^= m128.High >> 3;
|
||||
|
||||
m128.Low = XorShift64(m128.Low, 35);
|
||||
m128.Low *= 0x9FB21C651E98DF25UL;
|
||||
m128.Low = XorShift64(m128.Low, 28);
|
||||
m128.High = Xxh3Avalanche(m128.High);
|
||||
|
||||
return m128;
|
||||
}
|
||||
|
||||
private static Hash128 Xxh3Len9To16128b(ReadOnlySpan<byte> input, ReadOnlySpan<byte> secret, ulong seed)
|
||||
{
|
||||
Debug.Assert(input.Length is >= 9 and <= 16);
|
||||
|
||||
ulong bitFlipL = (BinaryPrimitives.ReadUInt64LittleEndian(secret[32..]) ^ BinaryPrimitives.ReadUInt64LittleEndian(secret[40..])) - seed;
|
||||
ulong bitFlipH = (BinaryPrimitives.ReadUInt64LittleEndian(secret[48..]) ^ BinaryPrimitives.ReadUInt64LittleEndian(secret[56..])) + seed;
|
||||
ulong inputLo = BinaryPrimitives.ReadUInt64LittleEndian(input);
|
||||
ulong inputHi = BinaryPrimitives.ReadUInt64LittleEndian(input[^8..]);
|
||||
|
||||
Hash128 m128 = Mult64To128(inputLo ^ inputHi ^ bitFlipL, Prime64_1);
|
||||
m128.Low += ((ulong)input.Length - 1) << 54;
|
||||
inputHi ^= bitFlipH;
|
||||
m128.High += inputHi + Mult32To64((uint)inputHi, Prime32_2 - 1);
|
||||
m128.Low ^= BinaryPrimitives.ReverseEndianness(m128.High);
|
||||
|
||||
Hash128 h128 = Mult64To128(m128.Low, Prime64_2);
|
||||
h128.High += m128.High * Prime64_2;
|
||||
h128.Low = Xxh3Avalanche(h128.Low);
|
||||
h128.High = Xxh3Avalanche(h128.High);
|
||||
|
||||
return h128;
|
||||
}
|
||||
|
||||
private static Hash128 Xxh3Len0To16128b(ReadOnlySpan<byte> input, ReadOnlySpan<byte> secret, ulong seed)
|
||||
{
|
||||
Debug.Assert(input.Length <= 16);
|
||||
|
||||
if (input.Length > 8)
|
||||
{
|
||||
return Xxh3Len9To16128b(input, secret, seed);
|
||||
}
|
||||
|
||||
if (input.Length >= 4)
|
||||
{
|
||||
return Xxh3Len4To8128b(input, secret, seed);
|
||||
}
|
||||
|
||||
if (input.Length != 0)
|
||||
{
|
||||
return Xxh3Len1To3128b(input, secret, seed);
|
||||
}
|
||||
|
||||
Hash128 h128 = new();
|
||||
ulong bitFlipL = BinaryPrimitives.ReadUInt64LittleEndian(secret[64..]) ^ BinaryPrimitives.ReadUInt64LittleEndian(secret[72..]);
|
||||
ulong bitFlipH = BinaryPrimitives.ReadUInt64LittleEndian(secret[80..]) ^ BinaryPrimitives.ReadUInt64LittleEndian(secret[88..]);
|
||||
h128.Low = Xxh64Avalanche(seed ^ bitFlipL);
|
||||
h128.High = Xxh64Avalanche(seed ^ bitFlipH);
|
||||
|
||||
return h128;
|
||||
}
|
||||
|
||||
private static ulong Xxh3Mix16b(ReadOnlySpan<byte> input, ReadOnlySpan<byte> secret, ulong seed)
|
||||
{
|
||||
ulong inputLo = BinaryPrimitives.ReadUInt64LittleEndian(input);
|
||||
ulong inputHi = BinaryPrimitives.ReadUInt64LittleEndian(input[8..]);
|
||||
|
||||
return Mul128Fold64(
|
||||
inputLo ^ (BinaryPrimitives.ReadUInt64LittleEndian(secret) + seed),
|
||||
inputHi ^ (BinaryPrimitives.ReadUInt64LittleEndian(secret[8..]) - seed));
|
||||
}
|
||||
|
||||
private static Hash128 Xxh128Mix32b(Hash128 acc, ReadOnlySpan<byte> input, ReadOnlySpan<byte> input2, ReadOnlySpan<byte> secret, ulong seed)
|
||||
{
|
||||
acc.Low += Xxh3Mix16b(input, secret, seed);
|
||||
acc.Low ^= BinaryPrimitives.ReadUInt64LittleEndian(input2) + BinaryPrimitives.ReadUInt64LittleEndian(input2[8..]);
|
||||
acc.High += Xxh3Mix16b(input2, secret[16..], seed);
|
||||
acc.High ^= BinaryPrimitives.ReadUInt64LittleEndian(input) + BinaryPrimitives.ReadUInt64LittleEndian(input[8..]);
|
||||
|
||||
return acc;
|
||||
}
|
||||
|
||||
private static Hash128 Xxh3Len17To128128b(ReadOnlySpan<byte> input, ReadOnlySpan<byte> secret, ulong seed)
|
||||
{
|
||||
Debug.Assert(secret.Length >= SecretSizeMin);
|
||||
Debug.Assert(input.Length is > 16 and <= 128);
|
||||
|
||||
Hash128 acc = new()
|
||||
{
|
||||
Low = (ulong)input.Length * Prime64_1,
|
||||
High = 0,
|
||||
};
|
||||
|
||||
if (input.Length > 32)
|
||||
{
|
||||
if (input.Length > 64)
|
||||
{
|
||||
if (input.Length > 96)
|
||||
{
|
||||
acc = Xxh128Mix32b(acc, input[48..], input[^64..], secret[96..], seed);
|
||||
}
|
||||
|
||||
acc = Xxh128Mix32b(acc, input[32..], input[^48..], secret[64..], seed);
|
||||
}
|
||||
|
||||
acc = Xxh128Mix32b(acc, input[16..], input[^32..], secret[32..], seed);
|
||||
}
|
||||
|
||||
acc = Xxh128Mix32b(acc, input, input[^16..], secret, seed);
|
||||
|
||||
Hash128 h128 = new()
|
||||
{
|
||||
Low = acc.Low + acc.High,
|
||||
High = acc.Low * Prime64_1 + acc.High * Prime64_4 + ((ulong)input.Length - seed) * Prime64_2,
|
||||
};
|
||||
h128.Low = Xxh3Avalanche(h128.Low);
|
||||
h128.High = 0UL - Xxh3Avalanche(h128.High);
|
||||
|
||||
return h128;
|
||||
}
|
||||
|
||||
private static Hash128 Xxh3Len129To240128b(ReadOnlySpan<byte> input, ReadOnlySpan<byte> secret, ulong seed)
|
||||
{
|
||||
Debug.Assert(secret.Length >= SecretSizeMin);
|
||||
Debug.Assert(input.Length is > 128 and <= 240);
|
||||
|
||||
Hash128 acc = new();
|
||||
|
||||
int nbRounds = input.Length / 32;
|
||||
acc.Low = (ulong)input.Length * Prime64_1;
|
||||
acc.High = 0;
|
||||
|
||||
for (int i = 0; i < 4; i++)
|
||||
{
|
||||
acc = Xxh128Mix32b(acc, input[(32 * i)..], input[(32 * i + 16)..], secret[(32 * i)..], seed);
|
||||
}
|
||||
|
||||
acc.Low = Xxh3Avalanche(acc.Low);
|
||||
acc.High = Xxh3Avalanche(acc.High);
|
||||
Debug.Assert(nbRounds >= 4);
|
||||
|
||||
for (int i = 4; i < nbRounds; i++)
|
||||
{
|
||||
acc = Xxh128Mix32b(acc, input[(32 * i)..], input[(32 * i + 16)..], secret[(MidSizeStartOffset + 32 * (i - 4))..], seed);
|
||||
}
|
||||
|
||||
acc = Xxh128Mix32b(acc, input[^16..], input[^32..], secret[(SecretSizeMin - MidSizeLastOffset - 16)..], 0UL - seed);
|
||||
|
||||
Hash128 h128 = new()
|
||||
{
|
||||
Low = acc.Low + acc.High,
|
||||
High = acc.Low * Prime64_1 + acc.High * Prime64_4 + ((ulong)input.Length - seed) * Prime64_2,
|
||||
};
|
||||
h128.Low = Xxh3Avalanche(h128.Low);
|
||||
h128.High = 0UL - Xxh3Avalanche(h128.High);
|
||||
|
||||
return h128;
|
||||
}
|
||||
|
||||
private static Hash128 Xxh3128bitsInternal(ReadOnlySpan<byte> input, ReadOnlySpan<byte> secret, ulong seed)
|
||||
{
|
||||
Debug.Assert(secret.Length >= SecretSizeMin);
|
||||
|
||||
return input.Length switch
|
||||
{
|
||||
<= 16 => Xxh3Len0To16128b(input, secret, seed),
|
||||
<= 128 => Xxh3Len17To128128b(input, secret, seed),
|
||||
<= 240 => Xxh3Len129To240128b(input, secret, seed),
|
||||
_ => Xxh3HashLong128bInternal(input, secret)
|
||||
};
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
64
tools/vendor/ryujinx/src/Ryujinx.Common/Helpers/ConsoleHelper.cs
vendored
Normal file
64
tools/vendor/ryujinx/src/Ryujinx.Common/Helpers/ConsoleHelper.cs
vendored
Normal file
@@ -0,0 +1,64 @@
|
||||
using Ryujinx.Common.Logging;
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Runtime.Versioning;
|
||||
|
||||
namespace Ryujinx.Common.Helper
|
||||
{
|
||||
public static partial class ConsoleHelper
|
||||
{
|
||||
[SupportedOSPlatform("windows")]
|
||||
[LibraryImport("kernel32")]
|
||||
private static partial nint GetConsoleWindow();
|
||||
|
||||
[SupportedOSPlatform("windows")]
|
||||
[LibraryImport("kernel32", SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
private static partial bool FreeConsole();
|
||||
|
||||
public static bool SetConsoleWindowStateSupported => OperatingSystem.IsWindows();
|
||||
public static bool HasConsoleWindow => OperatingSystem.IsWindows() && GetConsoleWindow() != nint.Zero;
|
||||
|
||||
public static void SetConsoleWindowState(bool show)
|
||||
{
|
||||
if (OperatingSystem.IsWindows())
|
||||
{
|
||||
SetConsoleWindowStateWindows(show);
|
||||
}
|
||||
else if (show == false)
|
||||
{
|
||||
Logger.Warning?.Print(LogClass.Application, "OS doesn't support hiding console window");
|
||||
}
|
||||
}
|
||||
|
||||
[SupportedOSPlatform("windows")]
|
||||
private static void SetConsoleWindowStateWindows(bool show)
|
||||
{
|
||||
if (show)
|
||||
{
|
||||
if (GetConsoleWindow() != nint.Zero)
|
||||
{
|
||||
Logger.SetConsoleTargetEnabled(true);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
Logger.SetConsoleTargetEnabled(false);
|
||||
DetachConsole();
|
||||
}
|
||||
|
||||
[SupportedOSPlatform("windows")]
|
||||
private static void DetachConsole()
|
||||
{
|
||||
if (GetConsoleWindow() == nint.Zero)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (!FreeConsole())
|
||||
{
|
||||
Logger.Warning?.Print(LogClass.Application, "Attempted to detach console window but the operation failed");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
195
tools/vendor/ryujinx/src/Ryujinx.Common/Helpers/FileAssociationHelper.cs
vendored
Normal file
195
tools/vendor/ryujinx/src/Ryujinx.Common/Helpers/FileAssociationHelper.cs
vendored
Normal file
@@ -0,0 +1,195 @@
|
||||
using Microsoft.Win32;
|
||||
using Ryujinx.Common.Logging;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Runtime.Versioning;
|
||||
|
||||
namespace Ryujinx.Common.Helper
|
||||
{
|
||||
public static partial class FileAssociationHelper
|
||||
{
|
||||
private static readonly string[] _fileExtensions = [".nca", ".nro", ".nso", ".nsp", ".xci"];
|
||||
|
||||
[SupportedOSPlatform("linux")]
|
||||
private static readonly string _mimeDbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".local", "share", "mime");
|
||||
|
||||
private const int SHCNE_ASSOCCHANGED = 0x8000000;
|
||||
private const int SHCNF_FLUSH = 0x1000;
|
||||
|
||||
[LibraryImport("shell32.dll", SetLastError = true)]
|
||||
public static partial void SHChangeNotify(uint wEventId, uint uFlags, nint dwItem1, nint dwItem2);
|
||||
|
||||
public static bool IsTypeAssociationSupported => (OperatingSystem.IsLinux() || OperatingSystem.IsWindows());
|
||||
|
||||
// NOTE: On macOS, users have a more robust file association system (via Right-Click > Get Info > "Open with:" > Ryujinx > "Change All...)
|
||||
// Custom file association isn't strictly necessary and will not provide any additional benefit to macOS users.
|
||||
|
||||
public static bool AreMimeTypesRegistered
|
||||
{
|
||||
get
|
||||
{
|
||||
if (OperatingSystem.IsLinux())
|
||||
{
|
||||
return AreMimeTypesRegisteredLinux();
|
||||
}
|
||||
|
||||
if (OperatingSystem.IsWindows())
|
||||
{
|
||||
return AreMimeTypesRegisteredWindows();
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
[SupportedOSPlatform("linux")]
|
||||
private static bool AreMimeTypesRegisteredLinux() => File.Exists(Path.Combine(_mimeDbPath, "packages", "Ryujinx.xml"));
|
||||
|
||||
[SupportedOSPlatform("linux")]
|
||||
private static bool InstallLinuxMimeTypes(bool uninstall = false)
|
||||
{
|
||||
string installKeyword = uninstall ? "uninstall" : "install";
|
||||
|
||||
if ((uninstall && AreMimeTypesRegisteredLinux()) || (!uninstall && !AreMimeTypesRegisteredLinux()))
|
||||
{
|
||||
string mimeTypesFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "mime", "Ryujinx.xml");
|
||||
string additionalArgs = !uninstall ? "--novendor" : string.Empty;
|
||||
|
||||
using Process mimeProcess = new();
|
||||
|
||||
mimeProcess.StartInfo.FileName = "xdg-mime";
|
||||
mimeProcess.StartInfo.Arguments = $"{installKeyword} {additionalArgs} --mode user {mimeTypesFile}";
|
||||
|
||||
mimeProcess.Start();
|
||||
mimeProcess.WaitForExit();
|
||||
|
||||
if (mimeProcess.ExitCode != 0)
|
||||
{
|
||||
Logger.Error?.PrintMsg(LogClass.Application, $"Unable to {installKeyword} mime types. Make sure xdg-utils is installed. Process exited with code: {mimeProcess.ExitCode}");
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
using Process updateMimeProcess = new();
|
||||
|
||||
updateMimeProcess.StartInfo.FileName = "update-mime-database";
|
||||
updateMimeProcess.StartInfo.Arguments = _mimeDbPath;
|
||||
|
||||
updateMimeProcess.Start();
|
||||
updateMimeProcess.WaitForExit();
|
||||
|
||||
if (updateMimeProcess.ExitCode != 0)
|
||||
{
|
||||
Logger.Error?.PrintMsg(LogClass.Application, $"Could not update local mime database. Process exited with code: {updateMimeProcess.ExitCode}");
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
[SupportedOSPlatform("windows")]
|
||||
private static bool AreMimeTypesRegisteredWindows()
|
||||
{
|
||||
return _fileExtensions.Aggregate(false,
|
||||
(current, ext) => current | CheckRegistering(ext)
|
||||
);
|
||||
|
||||
static bool CheckRegistering(string ext)
|
||||
{
|
||||
RegistryKey key = Registry.CurrentUser.OpenSubKey(@$"Software\Classes\{ext}");
|
||||
|
||||
RegistryKey openCmd = key?.OpenSubKey(@"shell\open\command");
|
||||
|
||||
if (openCmd is null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
string keyValue = (string)openCmd.GetValue(string.Empty);
|
||||
|
||||
return keyValue is not null && (keyValue.Contains("Ryujinx") || keyValue.Contains(AppDomain.CurrentDomain.FriendlyName));
|
||||
}
|
||||
}
|
||||
|
||||
[SupportedOSPlatform("windows")]
|
||||
private static bool InstallWindowsMimeTypes(bool uninstall = false)
|
||||
{
|
||||
bool registered = _fileExtensions.Aggregate(false,
|
||||
(current, ext) => current | RegisterExtension(ext, uninstall)
|
||||
);
|
||||
|
||||
// Notify Explorer the file association has been changed.
|
||||
SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_FLUSH, nint.Zero, nint.Zero);
|
||||
|
||||
return registered;
|
||||
|
||||
static bool RegisterExtension(string ext, bool uninstall = false)
|
||||
{
|
||||
string keyString = @$"Software\Classes\{ext}";
|
||||
|
||||
if (uninstall)
|
||||
{
|
||||
// If the types don't already exist, there's nothing to do, and we can call this operation successful.
|
||||
if (!AreMimeTypesRegisteredWindows())
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
Logger.Debug?.Print(LogClass.Application, $"Removing type association {ext}");
|
||||
Registry.CurrentUser.DeleteSubKeyTree(keyString);
|
||||
Logger.Debug?.Print(LogClass.Application, $"Removed type association {ext}");
|
||||
}
|
||||
else
|
||||
{
|
||||
using RegistryKey key = Registry.CurrentUser.CreateSubKey(keyString);
|
||||
|
||||
if (key is null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
Logger.Debug?.Print(LogClass.Application, $"Adding type association {ext}");
|
||||
using RegistryKey openCmd = key.CreateSubKey(@"shell\open\command");
|
||||
openCmd.SetValue(string.Empty, $"\"{Environment.ProcessPath}\" \"%1\"");
|
||||
Logger.Debug?.Print(LogClass.Application, $"Added type association {ext}");
|
||||
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public static bool Install()
|
||||
{
|
||||
if (OperatingSystem.IsLinux())
|
||||
{
|
||||
return InstallLinuxMimeTypes();
|
||||
}
|
||||
|
||||
if (OperatingSystem.IsWindows())
|
||||
{
|
||||
return InstallWindowsMimeTypes();
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public static bool Uninstall()
|
||||
{
|
||||
if (OperatingSystem.IsLinux())
|
||||
{
|
||||
return InstallLinuxMimeTypes(true);
|
||||
}
|
||||
|
||||
if (OperatingSystem.IsWindows())
|
||||
{
|
||||
return InstallWindowsMimeTypes(true);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
62
tools/vendor/ryujinx/src/Ryujinx.Common/Helpers/LinuxHelper.cs
vendored
Normal file
62
tools/vendor/ryujinx/src/Ryujinx.Common/Helpers/LinuxHelper.cs
vendored
Normal file
@@ -0,0 +1,62 @@
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Runtime.Versioning;
|
||||
|
||||
namespace Ryujinx.Common.Helper
|
||||
{
|
||||
[SupportedOSPlatform("linux")]
|
||||
public static class LinuxHelper
|
||||
{
|
||||
// NOTE: This value was determined by manual tests and might need to be increased again.
|
||||
public const int RecommendedVmMaxMapCount = 524288;
|
||||
public const string VmMaxMapCountPath = "/proc/sys/vm/max_map_count";
|
||||
public const string SysCtlConfigPath = "/etc/sysctl.d/99-Ryujinx.conf";
|
||||
public static int VmMaxMapCount => int.Parse(File.ReadAllText(VmMaxMapCountPath));
|
||||
public static string PkExecPath { get; } = GetBinaryPath("pkexec");
|
||||
|
||||
private static string GetBinaryPath(string binary)
|
||||
{
|
||||
string pathVar = Environment.GetEnvironmentVariable("PATH");
|
||||
|
||||
if (pathVar is null || string.IsNullOrEmpty(binary))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
foreach (string searchPath in pathVar.Split(":", StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries))
|
||||
{
|
||||
string binaryPath = Path.Combine(searchPath, binary);
|
||||
|
||||
if (File.Exists(binaryPath))
|
||||
{
|
||||
return binaryPath;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public static int RunPkExec(string command)
|
||||
{
|
||||
if (PkExecPath == null)
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
using Process process = new()
|
||||
{
|
||||
StartInfo =
|
||||
{
|
||||
FileName = PkExecPath,
|
||||
ArgumentList = { "sh", "-c", command },
|
||||
},
|
||||
};
|
||||
|
||||
process.Start();
|
||||
process.WaitForExit();
|
||||
|
||||
return process.ExitCode;
|
||||
}
|
||||
}
|
||||
}
|
||||
159
tools/vendor/ryujinx/src/Ryujinx.Common/Helpers/ObjectiveC.cs
vendored
Normal file
159
tools/vendor/ryujinx/src/Ryujinx.Common/Helpers/ObjectiveC.cs
vendored
Normal file
@@ -0,0 +1,159 @@
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Runtime.Versioning;
|
||||
|
||||
namespace Ryujinx.Common.Helper
|
||||
{
|
||||
[SupportedOSPlatform("macos")]
|
||||
public static partial class ObjectiveC
|
||||
{
|
||||
private const string ObjCRuntime = "/usr/lib/libobjc.A.dylib";
|
||||
|
||||
[LibraryImport(ObjCRuntime, StringMarshalling = StringMarshalling.Utf8)]
|
||||
private static partial nint sel_getUid(string name);
|
||||
|
||||
[LibraryImport(ObjCRuntime, StringMarshalling = StringMarshalling.Utf8)]
|
||||
private static partial nint objc_getClass(string name);
|
||||
|
||||
[LibraryImport(ObjCRuntime)]
|
||||
private static partial void objc_msgSend(nint receiver, Selector selector);
|
||||
|
||||
[LibraryImport(ObjCRuntime)]
|
||||
private static partial void objc_msgSend(nint receiver, Selector selector, byte value);
|
||||
|
||||
[LibraryImport(ObjCRuntime)]
|
||||
private static partial void objc_msgSend(nint receiver, Selector selector, nint value);
|
||||
|
||||
[LibraryImport(ObjCRuntime)]
|
||||
private static partial void objc_msgSend(nint receiver, Selector selector, NSRect point);
|
||||
|
||||
[LibraryImport(ObjCRuntime)]
|
||||
private static partial void objc_msgSend(nint receiver, Selector selector, double value);
|
||||
|
||||
[LibraryImport(ObjCRuntime, EntryPoint = "objc_msgSend")]
|
||||
private static partial nint nint_objc_msgSend(nint receiver, Selector selector);
|
||||
|
||||
[LibraryImport(ObjCRuntime, EntryPoint = "objc_msgSend")]
|
||||
private static partial nint nint_objc_msgSend(nint receiver, Selector selector, nint param);
|
||||
|
||||
[LibraryImport(ObjCRuntime, EntryPoint = "objc_msgSend", StringMarshalling = StringMarshalling.Utf8)]
|
||||
private static partial nint nint_objc_msgSend(nint receiver, Selector selector, string param);
|
||||
|
||||
[LibraryImport(ObjCRuntime, EntryPoint = "objc_msgSend")]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
private static partial bool bool_objc_msgSend(nint receiver, Selector selector, nint param);
|
||||
|
||||
public readonly struct Object
|
||||
{
|
||||
public readonly nint ObjPtr;
|
||||
|
||||
private Object(nint pointer)
|
||||
{
|
||||
ObjPtr = pointer;
|
||||
}
|
||||
|
||||
public Object(string name)
|
||||
{
|
||||
ObjPtr = objc_getClass(name);
|
||||
}
|
||||
|
||||
public void SendMessage(Selector selector)
|
||||
{
|
||||
objc_msgSend(ObjPtr, selector);
|
||||
}
|
||||
|
||||
public void SendMessage(Selector selector, byte value)
|
||||
{
|
||||
objc_msgSend(ObjPtr, selector, value);
|
||||
}
|
||||
|
||||
public void SendMessage(Selector selector, Object obj)
|
||||
{
|
||||
objc_msgSend(ObjPtr, selector, obj.ObjPtr);
|
||||
}
|
||||
|
||||
public void SendMessage(Selector selector, NSRect point)
|
||||
{
|
||||
objc_msgSend(ObjPtr, selector, point);
|
||||
}
|
||||
|
||||
public void SendMessage(Selector selector, double value)
|
||||
{
|
||||
objc_msgSend(ObjPtr, selector, value);
|
||||
}
|
||||
|
||||
public Object GetFromMessage(Selector selector)
|
||||
{
|
||||
return new Object(nint_objc_msgSend(ObjPtr, selector));
|
||||
}
|
||||
|
||||
public Object GetFromMessage(Selector selector, Object obj)
|
||||
{
|
||||
return new Object(nint_objc_msgSend(ObjPtr, selector, obj.ObjPtr));
|
||||
}
|
||||
|
||||
public Object GetFromMessage(Selector selector, NSString nsString)
|
||||
{
|
||||
return new Object(nint_objc_msgSend(ObjPtr, selector, nsString.StrPtr));
|
||||
}
|
||||
|
||||
public Object GetFromMessage(Selector selector, string param)
|
||||
{
|
||||
return new Object(nint_objc_msgSend(ObjPtr, selector, param));
|
||||
}
|
||||
|
||||
public bool GetBoolFromMessage(Selector selector, Object obj)
|
||||
{
|
||||
return bool_objc_msgSend(ObjPtr, selector, obj.ObjPtr);
|
||||
}
|
||||
}
|
||||
|
||||
public readonly struct Selector
|
||||
{
|
||||
public readonly nint SelPtr;
|
||||
|
||||
private Selector(string name)
|
||||
{
|
||||
SelPtr = sel_getUid(name);
|
||||
}
|
||||
|
||||
public static implicit operator Selector(string value) => new(value);
|
||||
}
|
||||
|
||||
public readonly struct NSString
|
||||
{
|
||||
public readonly nint StrPtr;
|
||||
|
||||
public NSString(string aString)
|
||||
{
|
||||
nint nsString = objc_getClass("NSString");
|
||||
StrPtr = nint_objc_msgSend(nsString, "stringWithUTF8String:", aString);
|
||||
}
|
||||
|
||||
public static implicit operator nint(NSString nsString) => nsString.StrPtr;
|
||||
}
|
||||
|
||||
public readonly struct NSPoint
|
||||
{
|
||||
public readonly double X;
|
||||
public readonly double Y;
|
||||
|
||||
public NSPoint(double x, double y)
|
||||
{
|
||||
X = x;
|
||||
Y = y;
|
||||
}
|
||||
}
|
||||
|
||||
public readonly struct NSRect
|
||||
{
|
||||
public readonly NSPoint Pos;
|
||||
public readonly NSPoint Size;
|
||||
|
||||
public NSRect(double x, double y, double width, double height)
|
||||
{
|
||||
Pos = new NSPoint(x, y);
|
||||
Size = new NSPoint(width, height);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
115
tools/vendor/ryujinx/src/Ryujinx.Common/Helpers/OpenHelper.cs
vendored
Normal file
115
tools/vendor/ryujinx/src/Ryujinx.Common/Helpers/OpenHelper.cs
vendored
Normal file
@@ -0,0 +1,115 @@
|
||||
using Gommon;
|
||||
using Ryujinx.Common.Logging;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Ryujinx.Common.Helper
|
||||
{
|
||||
public static partial class OpenHelper
|
||||
{
|
||||
[LibraryImport("shell32.dll", SetLastError = true)]
|
||||
private static partial int SHOpenFolderAndSelectItems(nint pidlFolder, uint cidl, nint apidl, uint dwFlags);
|
||||
|
||||
[LibraryImport("shell32.dll", SetLastError = true)]
|
||||
private static partial void ILFree(nint pidlList);
|
||||
|
||||
[LibraryImport("shell32.dll", SetLastError = true)]
|
||||
private static partial nint ILCreateFromPathW([MarshalAs(UnmanagedType.LPWStr)] string pszPath);
|
||||
|
||||
public static void OpenFolder(string path)
|
||||
{
|
||||
if (Directory.Exists(path))
|
||||
{
|
||||
Process.Start(new ProcessStartInfo
|
||||
{
|
||||
FileName = path,
|
||||
UseShellExecute = true,
|
||||
Verb = "open",
|
||||
});
|
||||
}
|
||||
else
|
||||
{
|
||||
Logger.Notice.Print(LogClass.Application, $"Directory \"{path}\" doesn't exist!");
|
||||
}
|
||||
}
|
||||
|
||||
public static void OpenFolder(FilePath path) => OpenFolder(path.Path);
|
||||
|
||||
public static void LocateFile(string path)
|
||||
{
|
||||
if (File.Exists(path))
|
||||
{
|
||||
if (OperatingSystem.IsWindows())
|
||||
{
|
||||
nint pidlList = ILCreateFromPathW(path);
|
||||
if (pidlList != nint.Zero)
|
||||
{
|
||||
try
|
||||
{
|
||||
Marshal.ThrowExceptionForHR(SHOpenFolderAndSelectItems(pidlList, 0, nint.Zero, 0));
|
||||
}
|
||||
finally
|
||||
{
|
||||
ILFree(pidlList);
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (OperatingSystem.IsMacOS())
|
||||
{
|
||||
ObjectiveC.NSString nsStringPath = new(path);
|
||||
ObjectiveC.Object nsUrl = new("NSURL");
|
||||
ObjectiveC.Object urlPtr = nsUrl.GetFromMessage("fileURLWithPath:", nsStringPath);
|
||||
|
||||
ObjectiveC.Object nsArray = new("NSArray");
|
||||
ObjectiveC.Object urlArray = nsArray.GetFromMessage("arrayWithObject:", urlPtr);
|
||||
|
||||
ObjectiveC.Object nsWorkspace = new("NSWorkspace");
|
||||
ObjectiveC.Object sharedWorkspace = nsWorkspace.GetFromMessage("sharedWorkspace");
|
||||
|
||||
sharedWorkspace.SendMessage("activateFileViewerSelectingURLs:", urlArray);
|
||||
}
|
||||
else if (OperatingSystem.IsLinux())
|
||||
{
|
||||
Process.Start("dbus-send", $"--session --print-reply --dest=org.freedesktop.FileManager1 --type=method_call /org/freedesktop/FileManager1 org.freedesktop.FileManager1.ShowItems array:string:\"file://{path}\" string:\"\"");
|
||||
}
|
||||
else
|
||||
{
|
||||
OpenFolder(Path.GetDirectoryName(path));
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Logger.Notice.Print(LogClass.Application, $"File \"{path}\" doesn't exist!");
|
||||
}
|
||||
}
|
||||
|
||||
public static void OpenUrl(string url)
|
||||
{
|
||||
if (OperatingSystem.IsWindows())
|
||||
{
|
||||
Process.Start(new ProcessStartInfo("cmd", $"/c start {url.Replace("&", "^&")}"));
|
||||
}
|
||||
else if (OperatingSystem.IsLinux())
|
||||
{
|
||||
Process.Start("xdg-open", url);
|
||||
}
|
||||
else if (OperatingSystem.IsMacOS())
|
||||
{
|
||||
ObjectiveC.NSString nsStringPath = new(url);
|
||||
ObjectiveC.Object nsUrl = new("NSURL");
|
||||
ObjectiveC.Object urlPtr = nsUrl.GetFromMessage("URLWithString:", nsStringPath);
|
||||
|
||||
ObjectiveC.Object nsWorkspace = new("NSWorkspace");
|
||||
ObjectiveC.Object sharedWorkspace = nsWorkspace.GetFromMessage("sharedWorkspace");
|
||||
|
||||
sharedWorkspace.GetBoolFromMessage("openURL:", urlPtr);
|
||||
}
|
||||
else
|
||||
{
|
||||
Logger.Notice.Print(LogClass.Application, $"Cannot open url \"{url}\" on this platform!");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
126
tools/vendor/ryujinx/src/Ryujinx.Common/Helpers/Patterns.cs
vendored
Normal file
126
tools/vendor/ryujinx/src/Ryujinx.Common/Helpers/Patterns.cs
vendored
Normal file
@@ -0,0 +1,126 @@
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Ryujinx.Common.Helper
|
||||
{
|
||||
public static partial class Patterns
|
||||
{
|
||||
#region Accessors
|
||||
|
||||
public static readonly Regex Numeric = NumericRegex();
|
||||
|
||||
public static readonly Regex AmdGcn = AmdGcnRegex();
|
||||
public static readonly Regex AmdRdna3 = AmdRdna3Regex();
|
||||
public static readonly Regex NvidiaConsumerClass = NvidiaConsumerClassRegex();
|
||||
public static readonly Regex IntelWindowsDriverVersion = IntelWindowsDriverVersionRegex();
|
||||
|
||||
public static readonly Regex DomainLp1Ns = DomainLp1NsRegex();
|
||||
public static readonly Regex DomainLp1Lp1Npln = DomainLp1Lp1NplnRegex();
|
||||
public static readonly Regex DomainLp1Znc = DomainLp1ZncRegex();
|
||||
public static readonly Regex DomainSbApi = DomainSbApiRegex();
|
||||
public static readonly Regex DomainSbAccounts = DomainSbAccountsRegex();
|
||||
public static readonly Regex DomainAccounts = DomainAccountsRegex();
|
||||
|
||||
public static readonly Regex Module = ModuleRegex();
|
||||
public static readonly Regex FsSdk = FsSdkRegex();
|
||||
public static readonly Regex SdkMw = SdkMwRegex();
|
||||
|
||||
// ReSharper disable once InconsistentNaming
|
||||
public static readonly Regex CJK = CJKRegex();
|
||||
|
||||
public static readonly Regex LdnPassphrase = LdnPassphraseRegex();
|
||||
|
||||
public static readonly Regex CleanText = CleanTextRegex();
|
||||
|
||||
#endregion
|
||||
|
||||
#region Generated pattern stubs
|
||||
|
||||
#region Numeric validation
|
||||
|
||||
[GeneratedRegex("[0-9]|.")]
|
||||
internal static partial Regex NumericRegex();
|
||||
|
||||
#endregion
|
||||
|
||||
#region GPU names
|
||||
|
||||
[GeneratedRegex(
|
||||
"Radeon (((HD|R(5|7|9|X)) )?((M?[2-6]\\d{2}(\\D|$))|([7-8]\\d{3}(\\D|$))|Fury|Nano))|(Pro Duo)")]
|
||||
internal static partial Regex AmdGcnRegex();
|
||||
|
||||
[GeneratedRegex("Radeon ([7-8](\\d{2}\\d?)[MS]|PRO [VW]7(\\d{2}\\d?)|RX 7\\d{3}([MS]?| XTX?| GRE)?)")]
|
||||
public static partial Regex AmdRdna3Regex();
|
||||
|
||||
[GeneratedRegex("NVIDIA GeForce (R|G)?TX? (\\d{3}\\d?)M?")]
|
||||
internal static partial Regex NvidiaConsumerClassRegex();
|
||||
|
||||
[GeneratedRegex(@"^\d+\.\d+\.\d+\.\d+$")]
|
||||
internal static partial Regex IntelWindowsDriverVersionRegex();
|
||||
|
||||
#endregion
|
||||
|
||||
#region DNS blocking
|
||||
|
||||
public static readonly Regex[] BlockedHosts =
|
||||
[
|
||||
DomainLp1Ns,
|
||||
DomainLp1Lp1Npln,
|
||||
DomainLp1Znc,
|
||||
DomainSbApi,
|
||||
DomainSbAccounts,
|
||||
DomainAccounts
|
||||
];
|
||||
|
||||
const RegexOptions DnsRegexOpts =
|
||||
RegexOptions.CultureInvariant | RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture;
|
||||
|
||||
[GeneratedRegex(@"^(.*)\-lp1\.(n|s)\.n\.srv\.nintendo\.net$", DnsRegexOpts)]
|
||||
internal static partial Regex DomainLp1NsRegex();
|
||||
|
||||
[GeneratedRegex(@"^(.*)\-lp1\.lp1\.t\.npln\.srv\.nintendo\.net$", DnsRegexOpts)]
|
||||
internal static partial Regex DomainLp1Lp1NplnRegex();
|
||||
|
||||
[GeneratedRegex(@"^(.*)\-lp1\.(znc|p)\.srv\.nintendo\.net$", DnsRegexOpts)]
|
||||
internal static partial Regex DomainLp1ZncRegex();
|
||||
|
||||
[GeneratedRegex(@"^(.*)\-sb\-api\.accounts\.nintendo\.com$", DnsRegexOpts)]
|
||||
internal static partial Regex DomainSbApiRegex();
|
||||
|
||||
[GeneratedRegex(@"^(.*)\-sb\.accounts\.nintendo\.com$", DnsRegexOpts)]
|
||||
internal static partial Regex DomainSbAccountsRegex();
|
||||
|
||||
[GeneratedRegex(@"^accounts\.nintendo\.com$", DnsRegexOpts)]
|
||||
internal static partial Regex DomainAccountsRegex();
|
||||
|
||||
#endregion
|
||||
|
||||
#region Executable information
|
||||
|
||||
[GeneratedRegex(@"[a-z]:[\\/][ -~]{5,}\.nss", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)]
|
||||
internal static partial Regex ModuleRegex();
|
||||
|
||||
[GeneratedRegex(@"sdk_version: ([0-9.]*)")]
|
||||
internal static partial Regex FsSdkRegex();
|
||||
|
||||
[GeneratedRegex(@"SDK MW[ -~]*")]
|
||||
internal static partial Regex SdkMwRegex();
|
||||
|
||||
#endregion
|
||||
|
||||
#region CJK
|
||||
|
||||
[GeneratedRegex(
|
||||
"\\p{IsHangulJamo}|\\p{IsCJKRadicalsSupplement}|\\p{IsCJKSymbolsandPunctuation}|\\p{IsEnclosedCJKLettersandMonths}|\\p{IsCJKCompatibility}|\\p{IsCJKUnifiedIdeographsExtensionA}|\\p{IsCJKUnifiedIdeographs}|\\p{IsHangulSyllables}|\\p{IsCJKCompatibilityForms}")]
|
||||
private static partial Regex CJKRegex();
|
||||
|
||||
#endregion
|
||||
|
||||
[GeneratedRegex("Ryujinx-[0-9a-f]{8}")]
|
||||
private static partial Regex LdnPassphraseRegex();
|
||||
|
||||
[GeneratedRegex(@"[^\u0000\u0009\u000A\u000D\u0020-\uFFFF]..")]
|
||||
private static partial Regex CleanTextRegex();
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
58
tools/vendor/ryujinx/src/Ryujinx.Common/Helpers/RefEvent.cs
vendored
Normal file
58
tools/vendor/ryujinx/src/Ryujinx.Common/Helpers/RefEvent.cs
vendored
Normal file
@@ -0,0 +1,58 @@
|
||||
using Gommon;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
|
||||
namespace Ryujinx.Common.Helper
|
||||
{
|
||||
public class RefEvent<T>
|
||||
{
|
||||
public delegate void Handler(ref T arg);
|
||||
|
||||
private readonly Lock _subLock = new();
|
||||
private readonly List<Handler> _subscriptions = [];
|
||||
|
||||
public bool HasSubscribers
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_subLock)
|
||||
return _subscriptions.Count != 0;
|
||||
}
|
||||
}
|
||||
|
||||
public IReadOnlyList<Handler> Subscriptions
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_subLock)
|
||||
return _subscriptions;
|
||||
}
|
||||
}
|
||||
|
||||
public void Add(Handler subscriber)
|
||||
{
|
||||
Guard.Require(subscriber, nameof(subscriber));
|
||||
lock (_subLock)
|
||||
_subscriptions.Add(subscriber);
|
||||
}
|
||||
|
||||
public void Remove(Handler subscriber)
|
||||
{
|
||||
Guard.Require(subscriber, nameof(subscriber));
|
||||
lock (_subLock)
|
||||
_subscriptions.Remove(subscriber);
|
||||
}
|
||||
|
||||
public void Clear()
|
||||
{
|
||||
lock (_subLock)
|
||||
_subscriptions.Clear();
|
||||
}
|
||||
|
||||
public void Call(ref T arg)
|
||||
{
|
||||
foreach (Handler subscription in Subscriptions)
|
||||
subscription(ref arg);
|
||||
}
|
||||
}
|
||||
}
|
||||
46
tools/vendor/ryujinx/src/Ryujinx.Common/Helpers/RunningPlatform.cs
vendored
Normal file
46
tools/vendor/ryujinx/src/Ryujinx.Common/Helpers/RunningPlatform.cs
vendored
Normal file
@@ -0,0 +1,46 @@
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
// ReSharper disable MemberCanBePrivate.Global
|
||||
// ReSharper disable InconsistentNaming
|
||||
|
||||
namespace Ryujinx.Common.Helper
|
||||
{
|
||||
public enum OperatingSystemType
|
||||
{
|
||||
MacOS,
|
||||
Linux,
|
||||
Windows
|
||||
}
|
||||
|
||||
public static class RunningPlatform
|
||||
{
|
||||
public static readonly OperatingSystemType CurrentOS
|
||||
= IsMacOS
|
||||
? OperatingSystemType.MacOS
|
||||
: IsWindows
|
||||
? OperatingSystemType.Windows
|
||||
: IsLinux
|
||||
? OperatingSystemType.Linux
|
||||
: throw new PlatformNotSupportedException();
|
||||
|
||||
public static Architecture Architecture => RuntimeInformation.OSArchitecture;
|
||||
public static Architecture CurrentProcessArchitecture => RuntimeInformation.ProcessArchitecture;
|
||||
|
||||
public static bool IsMacOS => OperatingSystem.IsMacOS();
|
||||
public static bool IsWindows => OperatingSystem.IsWindows();
|
||||
public static bool IsLinux => OperatingSystem.IsLinux();
|
||||
|
||||
public static bool IsArm => Architecture is Architecture.Arm64;
|
||||
|
||||
public static bool IsX64 => Architecture is Architecture.X64;
|
||||
|
||||
public static bool IsIntelMac => IsMacOS && IsX64;
|
||||
public static bool IsArmMac => IsMacOS && IsArm;
|
||||
|
||||
public static bool IsX64Windows => IsWindows && IsX64;
|
||||
public static bool IsArmWindows => IsWindows && IsArm;
|
||||
|
||||
public static bool IsX64Linux => IsLinux && IsX64;
|
||||
public static bool IsArmLinux => IsLinux && IsArmMac;
|
||||
}
|
||||
}
|
||||
51
tools/vendor/ryujinx/src/Ryujinx.Common/Logging/Formatters/DefaultLogFormatter.cs
vendored
Normal file
51
tools/vendor/ryujinx/src/Ryujinx.Common/Logging/Formatters/DefaultLogFormatter.cs
vendored
Normal file
@@ -0,0 +1,51 @@
|
||||
using System.Diagnostics;
|
||||
using System.Text;
|
||||
|
||||
namespace Ryujinx.Common.Logging.Formatters
|
||||
{
|
||||
internal class DefaultLogFormatter : ILogFormatter
|
||||
{
|
||||
private static readonly ObjectPool<StringBuilder> _stringBuilderPool = SharedPools.Default<StringBuilder>();
|
||||
|
||||
public string Format(LogEventArgs args)
|
||||
{
|
||||
StringBuilder sb = _stringBuilderPool.Allocate();
|
||||
|
||||
try
|
||||
{
|
||||
sb.Clear();
|
||||
|
||||
sb.Append($@"{args.Time:hh\:mm\:ss\.fff}");
|
||||
sb.Append($" |{args.Level.ToString()[0]}| ");
|
||||
|
||||
if (args.ThreadName != null)
|
||||
{
|
||||
sb.Append(args.ThreadName);
|
||||
sb.Append(' ');
|
||||
}
|
||||
|
||||
sb.Append(args.Message);
|
||||
|
||||
if (args.Data is not null)
|
||||
{
|
||||
if (args.Data is StackTrace trace)
|
||||
{
|
||||
sb.Append('\n');
|
||||
sb.Append(trace);
|
||||
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
sb.Append(' ');
|
||||
DynamicObjectFormatter.Format(sb, args.Data);
|
||||
}
|
||||
|
||||
return sb.ToString();
|
||||
}
|
||||
finally
|
||||
{
|
||||
_stringBuilderPool.Release(sb);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
84
tools/vendor/ryujinx/src/Ryujinx.Common/Logging/Formatters/DynamicObjectFormatter.cs
vendored
Normal file
84
tools/vendor/ryujinx/src/Ryujinx.Common/Logging/Formatters/DynamicObjectFormatter.cs
vendored
Normal file
@@ -0,0 +1,84 @@
|
||||
#nullable enable
|
||||
using System;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
|
||||
namespace Ryujinx.Common.Logging.Formatters
|
||||
{
|
||||
internal static class DynamicObjectFormatter
|
||||
{
|
||||
private static readonly ObjectPool<StringBuilder> _stringBuilderPool = SharedPools.Default<StringBuilder>();
|
||||
|
||||
public static string? Format(object? dynamicObject)
|
||||
{
|
||||
if (dynamicObject is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
StringBuilder sb = _stringBuilderPool.Allocate();
|
||||
|
||||
try
|
||||
{
|
||||
Format(sb, dynamicObject);
|
||||
|
||||
return sb.ToString();
|
||||
}
|
||||
finally
|
||||
{
|
||||
_stringBuilderPool.Release(sb);
|
||||
}
|
||||
}
|
||||
|
||||
public static void Format(StringBuilder sb, object? dynamicObject)
|
||||
{
|
||||
if (dynamicObject is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
PropertyInfo[] props = dynamicObject.GetType().GetProperties();
|
||||
|
||||
sb.Append('{');
|
||||
|
||||
foreach (PropertyInfo prop in props)
|
||||
{
|
||||
sb.Append(prop.Name);
|
||||
sb.Append(": ");
|
||||
|
||||
if (typeof(Array).IsAssignableFrom(prop.PropertyType))
|
||||
{
|
||||
Array? array = (Array?)prop.GetValue(dynamicObject);
|
||||
|
||||
if (array is not null)
|
||||
{
|
||||
foreach (object? item in array)
|
||||
{
|
||||
sb.Append(item);
|
||||
sb.Append(", ");
|
||||
}
|
||||
|
||||
if (array.Length > 0)
|
||||
{
|
||||
sb.Remove(sb.Length - 2, 2);
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
sb.Append(prop.GetValue(dynamicObject));
|
||||
}
|
||||
|
||||
sb.Append(" ; ");
|
||||
}
|
||||
|
||||
// We remove the final ';' from the string
|
||||
if (props.Length > 0)
|
||||
{
|
||||
sb.Remove(sb.Length - 3, 3);
|
||||
}
|
||||
|
||||
sb.Append('}');
|
||||
}
|
||||
}
|
||||
}
|
||||
7
tools/vendor/ryujinx/src/Ryujinx.Common/Logging/Formatters/ILogFormatter.cs
vendored
Normal file
7
tools/vendor/ryujinx/src/Ryujinx.Common/Logging/Formatters/ILogFormatter.cs
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
namespace Ryujinx.Common.Logging.Formatters
|
||||
{
|
||||
interface ILogFormatter
|
||||
{
|
||||
string Format(LogEventArgs args);
|
||||
}
|
||||
}
|
||||
79
tools/vendor/ryujinx/src/Ryujinx.Common/Logging/LogClass.cs
vendored
Normal file
79
tools/vendor/ryujinx/src/Ryujinx.Common/Logging/LogClass.cs
vendored
Normal file
@@ -0,0 +1,79 @@
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Ryujinx.Common.Logging
|
||||
{
|
||||
[JsonConverter(typeof(JsonStringEnumConverter<LogClass>))]
|
||||
public enum LogClass
|
||||
{
|
||||
Application,
|
||||
Audio,
|
||||
AudioRenderer,
|
||||
Configuration,
|
||||
Cpu,
|
||||
Emulation,
|
||||
FFmpeg,
|
||||
GdbStub,
|
||||
Font,
|
||||
Gpu,
|
||||
Hid,
|
||||
Host1x,
|
||||
Kernel,
|
||||
KernelIpc,
|
||||
KernelScheduler,
|
||||
KernelSvc,
|
||||
Loader,
|
||||
ModLoader,
|
||||
Nvdec,
|
||||
Ptc,
|
||||
Service,
|
||||
ServiceAcc,
|
||||
ServiceAm,
|
||||
ServiceApm,
|
||||
ServiceAudio,
|
||||
ServiceBcat,
|
||||
ServiceBsd,
|
||||
ServiceBtm,
|
||||
ServiceCaps,
|
||||
ServiceEctx,
|
||||
ServiceFatal,
|
||||
ServiceFriend,
|
||||
ServiceFs,
|
||||
ServiceHid,
|
||||
ServiceIrs,
|
||||
ServiceLdn,
|
||||
ServiceLdr,
|
||||
ServiceLm,
|
||||
ServiceMii,
|
||||
ServiceMm,
|
||||
ServiceMnpp,
|
||||
ServiceNfc,
|
||||
ServiceNfp,
|
||||
ServiceNgct,
|
||||
ServiceNifm,
|
||||
ServiceNim,
|
||||
ServiceNotification,
|
||||
ServiceNs,
|
||||
ServiceNsd,
|
||||
ServiceNtc,
|
||||
ServiceNv,
|
||||
ServiceOlsc,
|
||||
ServicePctl,
|
||||
ServicePcv,
|
||||
ServicePl,
|
||||
ServicePrepo,
|
||||
ServicePsm,
|
||||
ServicePtm,
|
||||
ServiceSet,
|
||||
ServiceSfdnsres,
|
||||
ServiceSm,
|
||||
ServiceSsl,
|
||||
ServiceSss,
|
||||
ServiceTime,
|
||||
ServiceVi,
|
||||
SurfaceFlinger,
|
||||
TamperMachine,
|
||||
UI,
|
||||
Vic,
|
||||
XCIFileTrimmer
|
||||
}
|
||||
}
|
||||
23
tools/vendor/ryujinx/src/Ryujinx.Common/Logging/LogEventArgs.cs
vendored
Normal file
23
tools/vendor/ryujinx/src/Ryujinx.Common/Logging/LogEventArgs.cs
vendored
Normal file
@@ -0,0 +1,23 @@
|
||||
using System;
|
||||
|
||||
namespace Ryujinx.Common.Logging
|
||||
{
|
||||
public class LogEventArgs : EventArgs
|
||||
{
|
||||
public readonly LogLevel Level;
|
||||
public readonly TimeSpan Time;
|
||||
public readonly string ThreadName;
|
||||
|
||||
public readonly string Message;
|
||||
public readonly object Data;
|
||||
|
||||
public LogEventArgs(LogLevel level, TimeSpan time, string threadName, string message, object data = null)
|
||||
{
|
||||
Level = level;
|
||||
Time = time;
|
||||
ThreadName = threadName;
|
||||
Message = message;
|
||||
Data = data;
|
||||
}
|
||||
}
|
||||
}
|
||||
19
tools/vendor/ryujinx/src/Ryujinx.Common/Logging/LogLevel.cs
vendored
Normal file
19
tools/vendor/ryujinx/src/Ryujinx.Common/Logging/LogLevel.cs
vendored
Normal file
@@ -0,0 +1,19 @@
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Ryujinx.Common.Logging
|
||||
{
|
||||
[JsonConverter(typeof(JsonStringEnumConverter<LogLevel>))]
|
||||
public enum LogLevel
|
||||
{
|
||||
Debug,
|
||||
Stub,
|
||||
Info,
|
||||
Warning,
|
||||
Error,
|
||||
Guest,
|
||||
AccessLog,
|
||||
NetLog,
|
||||
Notice,
|
||||
Trace,
|
||||
}
|
||||
}
|
||||
266
tools/vendor/ryujinx/src/Ryujinx.Common/Logging/Logger.cs
vendored
Normal file
266
tools/vendor/ryujinx/src/Ryujinx.Common/Logging/Logger.cs
vendored
Normal file
@@ -0,0 +1,266 @@
|
||||
using Ryujinx.Common.Logging.Targets;
|
||||
using Ryujinx.Common.SystemInterop;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Threading;
|
||||
|
||||
namespace Ryujinx.Common.Logging
|
||||
{
|
||||
public static class Logger
|
||||
{
|
||||
private static readonly Stopwatch _time;
|
||||
|
||||
private static readonly bool[] _enabledClasses;
|
||||
|
||||
private static readonly List<ILogTarget> _logTargets;
|
||||
|
||||
private static readonly StdErrAdapter _stdErrAdapter;
|
||||
|
||||
public static event EventHandler<LogEventArgs> Updated;
|
||||
|
||||
public readonly struct Log
|
||||
{
|
||||
private static readonly string _homeDir = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
|
||||
private static readonly string _homeDirRedacted = Path.Combine(Directory.GetParent(_homeDir)!.FullName, "[redacted]");
|
||||
|
||||
internal readonly LogLevel Level;
|
||||
|
||||
internal Log(LogLevel level)
|
||||
{
|
||||
Level = level;
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public void PrintMsg(LogClass logClass, string message)
|
||||
{
|
||||
if (_enabledClasses[(int)logClass])
|
||||
{
|
||||
Updated?.Invoke(null, new LogEventArgs(Level, _time.Elapsed, Thread.CurrentThread.Name, FormatMessage(logClass, string.Empty, message)));
|
||||
}
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public void Print(LogClass logClass, string message, [CallerMemberName] string caller = "")
|
||||
{
|
||||
if (_enabledClasses[(int)logClass])
|
||||
{
|
||||
Updated?.Invoke(null, new LogEventArgs(Level, _time.Elapsed, Thread.CurrentThread.Name, FormatMessage(logClass, caller, message)));
|
||||
}
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public void Print(LogClass logClass, string message, object data, [CallerMemberName] string caller = "")
|
||||
{
|
||||
if (_enabledClasses[(int)logClass])
|
||||
{
|
||||
Updated?.Invoke(null, new LogEventArgs(Level, _time.Elapsed, Thread.CurrentThread.Name, FormatMessage(logClass, caller, message), data));
|
||||
}
|
||||
}
|
||||
|
||||
[StackTraceHidden]
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public void PrintStack(LogClass logClass, string message, [CallerMemberName] string caller = "")
|
||||
{
|
||||
if (_enabledClasses[(int)logClass])
|
||||
{
|
||||
Updated?.Invoke(null, new LogEventArgs(Level, _time.Elapsed, Thread.CurrentThread.Name, FormatMessage(logClass, caller, message), new StackTrace(true)));
|
||||
}
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public void PrintStub(LogClass logClass, string message = "", [CallerMemberName] string caller = "")
|
||||
{
|
||||
if (_enabledClasses[(int)logClass])
|
||||
{
|
||||
Updated?.Invoke(null, new LogEventArgs(Level, _time.Elapsed, Thread.CurrentThread.Name, FormatMessage(logClass, caller, "Stubbed. " + message)));
|
||||
}
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public void PrintStub(LogClass logClass, object data, [CallerMemberName] string caller = "")
|
||||
{
|
||||
if (_enabledClasses[(int)logClass])
|
||||
{
|
||||
Updated?.Invoke(null, new LogEventArgs(Level, _time.Elapsed, Thread.CurrentThread.Name, FormatMessage(logClass, caller, "Stubbed."), data));
|
||||
}
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public void PrintStub(LogClass logClass, string message, object data, [CallerMemberName] string caller = "")
|
||||
{
|
||||
if (_enabledClasses[(int)logClass])
|
||||
{
|
||||
Updated?.Invoke(null, new LogEventArgs(Level, _time.Elapsed, Thread.CurrentThread.Name, FormatMessage(logClass, caller, "Stubbed. " + message), data));
|
||||
}
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public void PrintRawMsg(string message)
|
||||
{
|
||||
Updated?.Invoke(null, new LogEventArgs(Level, _time.Elapsed, Thread.CurrentThread.Name, message));
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private static string FormatMessage(LogClass logClass, string caller, string message)
|
||||
{
|
||||
message = message.Replace(_homeDir, _homeDirRedacted);
|
||||
|
||||
return $"{logClass} {caller}: {message}";
|
||||
}
|
||||
}
|
||||
|
||||
public static Log? Debug { get; private set; }
|
||||
public static Log? Info { get; private set; }
|
||||
public static Log? Warning { get; private set; }
|
||||
public static Log? Error { get; private set; }
|
||||
public static Log? Guest { get; private set; }
|
||||
public static Log? AccessLog { get; private set; }
|
||||
public static Log? NetLog { get; private set; }
|
||||
public static Log? Stub { get; private set; }
|
||||
public static Log? Trace { get; private set; }
|
||||
public static Log Notice { get; } // Always enabled
|
||||
|
||||
static Logger()
|
||||
{
|
||||
_enabledClasses = new bool[Enum.GetNames<LogClass>().Length];
|
||||
|
||||
for (int index = 0; index < _enabledClasses.Length; index++)
|
||||
{
|
||||
_enabledClasses[index] = true;
|
||||
}
|
||||
|
||||
_logTargets = [];
|
||||
|
||||
_time = Stopwatch.StartNew();
|
||||
|
||||
SetConsoleTargetEnabled(true);
|
||||
|
||||
Notice = new Log(LogLevel.Notice);
|
||||
|
||||
// Enable important log levels before configuration is loaded
|
||||
Error = new Log(LogLevel.Error);
|
||||
Warning = new Log(LogLevel.Warning);
|
||||
Info = new Log(LogLevel.Info);
|
||||
Trace = new Log(LogLevel.Trace);
|
||||
|
||||
_stdErrAdapter = new StdErrAdapter();
|
||||
}
|
||||
|
||||
public static void RestartTime()
|
||||
{
|
||||
_time.Restart();
|
||||
}
|
||||
|
||||
private static ILogTarget GetTarget(string targetName)
|
||||
=> _logTargets.FirstOrDefault(target => target.Name.Equals(targetName));
|
||||
|
||||
public static void AddTarget(ILogTarget target)
|
||||
{
|
||||
if (_logTargets.Any(t => t.Name == target.Name))
|
||||
{
|
||||
target.Dispose();
|
||||
return;
|
||||
}
|
||||
|
||||
_logTargets.Add(target);
|
||||
|
||||
Updated += target.Log;
|
||||
}
|
||||
|
||||
public static void SetConsoleTargetEnabled(bool enabled)
|
||||
{
|
||||
if (enabled)
|
||||
{
|
||||
AddTarget(new AsyncLogTargetWrapper(
|
||||
new ConsoleLogTarget("console"),
|
||||
1000,
|
||||
AsyncLogTargetOverflowAction.Discard));
|
||||
}
|
||||
else
|
||||
{
|
||||
RemoveTarget("console");
|
||||
}
|
||||
}
|
||||
|
||||
public static void RemoveTarget(string target)
|
||||
{
|
||||
ILogTarget logTarget = GetTarget(target);
|
||||
|
||||
if (logTarget != null)
|
||||
{
|
||||
Updated -= logTarget.Log;
|
||||
|
||||
_logTargets.Remove(logTarget);
|
||||
|
||||
logTarget.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
public static void Flush()
|
||||
{
|
||||
foreach (ILogTarget target in _logTargets)
|
||||
{
|
||||
if (target is AsyncLogTargetWrapper asyncTarget)
|
||||
{
|
||||
asyncTarget.Flush();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void Shutdown()
|
||||
{
|
||||
Updated = null;
|
||||
|
||||
_stdErrAdapter.Dispose();
|
||||
|
||||
foreach (ILogTarget target in _logTargets)
|
||||
{
|
||||
target.Dispose();
|
||||
}
|
||||
|
||||
_logTargets.Clear();
|
||||
}
|
||||
|
||||
public static IReadOnlyCollection<LogLevel> GetEnabledLevels()
|
||||
{
|
||||
Log?[] logs = [Debug, Info, Warning, Error, Guest, AccessLog, Stub, Trace];
|
||||
List<LogLevel> levels = new(logs.Length);
|
||||
foreach (Log? log in logs)
|
||||
{
|
||||
if (log.HasValue)
|
||||
levels.Add(log.Value.Level);
|
||||
}
|
||||
|
||||
return levels;
|
||||
}
|
||||
|
||||
public static void SetEnable(LogLevel logLevel, bool enabled)
|
||||
{
|
||||
switch (logLevel)
|
||||
{
|
||||
#pragma warning disable IDE0055 // Disable formatting
|
||||
case LogLevel.Debug : Debug = enabled ? new Log(LogLevel.Debug) : null; break;
|
||||
case LogLevel.Info : Info = enabled ? new Log(LogLevel.Info) : null; break;
|
||||
case LogLevel.Warning : Warning = enabled ? new Log(LogLevel.Warning) : null; break;
|
||||
case LogLevel.Error : Error = enabled ? new Log(LogLevel.Error) : null; break;
|
||||
case LogLevel.Guest : Guest = enabled ? new Log(LogLevel.Guest) : null; break;
|
||||
case LogLevel.AccessLog : AccessLog = enabled ? new Log(LogLevel.AccessLog) : null; break;
|
||||
case LogLevel.NetLog : NetLog = enabled ? new Log(LogLevel.NetLog) : null; break;
|
||||
case LogLevel.Stub : Stub = enabled ? new Log(LogLevel.Stub) : null; break;
|
||||
case LogLevel.Trace : Trace = enabled ? new Log(LogLevel.Trace) : null; break;
|
||||
case LogLevel.Notice : break;
|
||||
default: throw new ArgumentException("Unknown Log Level", nameof(logLevel));
|
||||
#pragma warning restore IDE0055
|
||||
}
|
||||
}
|
||||
|
||||
public static void SetEnable(LogClass logClass, bool enabled)
|
||||
{
|
||||
_enabledClasses[(int)logClass] = enabled;
|
||||
}
|
||||
}
|
||||
}
|
||||
117
tools/vendor/ryujinx/src/Ryujinx.Common/Logging/Targets/AsyncLogTargetWrapper.cs
vendored
Normal file
117
tools/vendor/ryujinx/src/Ryujinx.Common/Logging/Targets/AsyncLogTargetWrapper.cs
vendored
Normal file
@@ -0,0 +1,117 @@
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Threading;
|
||||
|
||||
namespace Ryujinx.Common.Logging.Targets
|
||||
{
|
||||
public enum AsyncLogTargetOverflowAction
|
||||
{
|
||||
/// <summary>
|
||||
/// Block until there's more room in the queue
|
||||
/// </summary>
|
||||
Block = 0,
|
||||
|
||||
/// <summary>
|
||||
/// Discard the overflowing item
|
||||
/// </summary>
|
||||
Discard = 1,
|
||||
}
|
||||
|
||||
public class AsyncLogTargetWrapper : ILogTarget
|
||||
{
|
||||
private readonly ILogTarget _target;
|
||||
|
||||
private readonly Thread _messageThread;
|
||||
|
||||
private readonly BlockingCollection<LogEventArgs> _messageQueue;
|
||||
|
||||
private readonly int _overflowTimeout;
|
||||
|
||||
private sealed class FlushEventArgs : LogEventArgs
|
||||
{
|
||||
public readonly ManualResetEventSlim SignalEvent;
|
||||
|
||||
public FlushEventArgs(ManualResetEventSlim signalEvent)
|
||||
: base(LogLevel.Notice, TimeSpan.Zero, string.Empty, string.Empty)
|
||||
{
|
||||
SignalEvent = signalEvent;
|
||||
}
|
||||
}
|
||||
|
||||
string ILogTarget.Name => _target.Name;
|
||||
|
||||
public AsyncLogTargetWrapper(ILogTarget target, int queueLimit = -1, AsyncLogTargetOverflowAction overflowAction = AsyncLogTargetOverflowAction.Block)
|
||||
{
|
||||
_target = target;
|
||||
_messageQueue = new BlockingCollection<LogEventArgs>(queueLimit);
|
||||
_overflowTimeout = overflowAction == AsyncLogTargetOverflowAction.Block ? -1 : 0;
|
||||
|
||||
_messageThread = new Thread(() =>
|
||||
{
|
||||
while (!_messageQueue.IsCompleted)
|
||||
{
|
||||
try
|
||||
{
|
||||
LogEventArgs item = _messageQueue.Take();
|
||||
|
||||
if (item is FlushEventArgs flush)
|
||||
{
|
||||
flush.SignalEvent.Set();
|
||||
continue;
|
||||
}
|
||||
|
||||
_target.Log(this, item);
|
||||
}
|
||||
catch (InvalidOperationException)
|
||||
{
|
||||
// IOE means that Take() was called on a completed collection.
|
||||
// Some other thread can call CompleteAdding after we pass the
|
||||
// IsCompleted check but before we call Take.
|
||||
// We can simply catch the exception since the loop will break
|
||||
// on the next iteration.
|
||||
}
|
||||
}
|
||||
})
|
||||
{
|
||||
Name = "Logger.MessageThread",
|
||||
IsBackground = true,
|
||||
};
|
||||
_messageThread.Start();
|
||||
}
|
||||
|
||||
public void Log(object sender, LogEventArgs e)
|
||||
{
|
||||
if (!_messageQueue.IsAddingCompleted)
|
||||
{
|
||||
_messageQueue.TryAdd(e, _overflowTimeout);
|
||||
}
|
||||
}
|
||||
|
||||
public void Flush()
|
||||
{
|
||||
if (_messageQueue.Count == 0 || _messageQueue.IsAddingCompleted)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
using ManualResetEventSlim signal = new ManualResetEventSlim(false);
|
||||
try
|
||||
{
|
||||
_messageQueue.Add(new FlushEventArgs(signal));
|
||||
}
|
||||
catch (InvalidOperationException)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
signal.Wait();
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
GC.SuppressFinalize(this);
|
||||
_messageQueue.CompleteAdding();
|
||||
_messageThread.Join();
|
||||
}
|
||||
}
|
||||
}
|
||||
44
tools/vendor/ryujinx/src/Ryujinx.Common/Logging/Targets/ConsoleLogTarget.cs
vendored
Normal file
44
tools/vendor/ryujinx/src/Ryujinx.Common/Logging/Targets/ConsoleLogTarget.cs
vendored
Normal file
@@ -0,0 +1,44 @@
|
||||
using Ryujinx.Common.Logging.Formatters;
|
||||
using System;
|
||||
|
||||
namespace Ryujinx.Common.Logging.Targets
|
||||
{
|
||||
public class ConsoleLogTarget : ILogTarget
|
||||
{
|
||||
private readonly DefaultLogFormatter _formatter;
|
||||
|
||||
private readonly string _name;
|
||||
|
||||
string ILogTarget.Name { get => _name; }
|
||||
|
||||
private static ConsoleColor GetLogColor(LogLevel level) => level switch
|
||||
{
|
||||
LogLevel.Info => ConsoleColor.White,
|
||||
LogLevel.Warning => ConsoleColor.Yellow,
|
||||
LogLevel.Error => ConsoleColor.Red,
|
||||
LogLevel.Stub => ConsoleColor.DarkGray,
|
||||
LogLevel.Notice => ConsoleColor.Cyan,
|
||||
LogLevel.Trace => ConsoleColor.DarkCyan,
|
||||
_ => ConsoleColor.Gray,
|
||||
};
|
||||
|
||||
public ConsoleLogTarget(string name)
|
||||
{
|
||||
_formatter = new DefaultLogFormatter();
|
||||
_name = name;
|
||||
}
|
||||
|
||||
public void Log(object sender, LogEventArgs args)
|
||||
{
|
||||
Console.ForegroundColor = GetLogColor(args.Level);
|
||||
Console.WriteLine(_formatter.Format(args));
|
||||
Console.ResetColor();
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
GC.SuppressFinalize(this);
|
||||
Console.ResetColor();
|
||||
}
|
||||
}
|
||||
}
|
||||
109
tools/vendor/ryujinx/src/Ryujinx.Common/Logging/Targets/FileLogTarget.cs
vendored
Normal file
109
tools/vendor/ryujinx/src/Ryujinx.Common/Logging/Targets/FileLogTarget.cs
vendored
Normal file
@@ -0,0 +1,109 @@
|
||||
using Ryujinx.Common.Logging.Formatters;
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
|
||||
namespace Ryujinx.Common.Logging.Targets
|
||||
{
|
||||
public class FileLogTarget : ILogTarget
|
||||
{
|
||||
private readonly StreamWriter _logWriter;
|
||||
private readonly DefaultLogFormatter _formatter;
|
||||
private readonly string _name;
|
||||
|
||||
string ILogTarget.Name { get => _name; }
|
||||
|
||||
public FileLogTarget(string name, FileStream fileStream)
|
||||
{
|
||||
_name = name;
|
||||
_logWriter = new StreamWriter(fileStream);
|
||||
_formatter = new DefaultLogFormatter();
|
||||
}
|
||||
|
||||
public static FileStream PrepareLogFile(string path)
|
||||
{
|
||||
// Ensure directory is present
|
||||
DirectoryInfo logDir;
|
||||
try
|
||||
{
|
||||
logDir = new DirectoryInfo(path);
|
||||
}
|
||||
catch (ArgumentException exception)
|
||||
{
|
||||
Logger.Warning?.Print(LogClass.Application, $"Logging directory path ('{path}') was invalid: {exception}");
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
logDir.Create();
|
||||
}
|
||||
catch (IOException exception)
|
||||
{
|
||||
Logger.Warning?.Print(LogClass.Application, $"Logging directory could not be created '{logDir}': {exception}");
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
// Clean up old logs, should only keep 3
|
||||
FileInfo[] files = logDir.GetFiles("*.log").OrderBy(info => info.CreationTime).ToArray();
|
||||
for (int i = 0; i < files.Length - 2; i++)
|
||||
{
|
||||
try
|
||||
{
|
||||
files[i].Delete();
|
||||
}
|
||||
catch (UnauthorizedAccessException exception)
|
||||
{
|
||||
Logger.Warning?.Print(LogClass.Application, $"Old log file could not be deleted '{files[i].FullName}': {exception}");
|
||||
|
||||
return null;
|
||||
}
|
||||
catch (IOException exception)
|
||||
{
|
||||
Logger.Warning?.Print(LogClass.Application, $"Old log file could not be deleted '{files[i].FullName}': {exception}");
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
string version = ReleaseInformation.Version;
|
||||
string appName = ReleaseInformation.IsCanaryBuild ? "Ryujinx_Canary" : "Ryujinx";
|
||||
|
||||
// Get path for the current time
|
||||
path = Path.Combine(logDir.FullName, $"{appName}_{version}_{DateTime.Now:yyyy-MM-dd_HH-mm-ss}.log");
|
||||
|
||||
try
|
||||
{
|
||||
return File.Open(path, FileMode.Append, FileAccess.Write, FileShare.Read);
|
||||
}
|
||||
catch (UnauthorizedAccessException exception)
|
||||
{
|
||||
Logger.Warning?.Print(LogClass.Application, $"Log file could not be created '{path}': {exception}");
|
||||
|
||||
return null;
|
||||
}
|
||||
catch (IOException exception)
|
||||
{
|
||||
Logger.Warning?.Print(LogClass.Application, $"Log file could not be created '{path}': {exception}");
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public void Log(object sender, LogEventArgs args)
|
||||
{
|
||||
_logWriter.WriteLine(_formatter.Format(args));
|
||||
_logWriter.Flush();
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
GC.SuppressFinalize(this);
|
||||
_logWriter.WriteLine("---- End of Log ----");
|
||||
_logWriter.Flush();
|
||||
_logWriter.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user