id
int64 0
755k
| file_name
stringlengths 3
109
| file_path
stringlengths 13
185
| content
stringlengths 31
9.38M
| size
int64 31
9.38M
| language
stringclasses 1
value | extension
stringclasses 11
values | total_lines
int64 1
340k
| avg_line_length
float64 2.18
149k
| max_line_length
int64 7
2.22M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 6
65
| repo_stars
int64 100
47.3k
| repo_forks
int64 0
12k
| repo_open_issues
int64 0
3.4k
| repo_license
stringclasses 9
values | repo_extraction_date
stringclasses 92
values | exact_duplicates_redpajama
bool 2
classes | near_duplicates_redpajama
bool 2
classes | exact_duplicates_githubcode
bool 2
classes | exact_duplicates_stackv2
bool 1
class | exact_duplicates_stackv1
bool 2
classes | near_duplicates_githubcode
bool 2
classes | near_duplicates_stackv1
bool 2
classes | near_duplicates_stackv2
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
23,323
|
ZpIRBuilder.h
|
cemu-project_Cemu/src/util/Zir/Core/ZpIRBuilder.h
|
#pragma once
#include "util/Zir/Core/IR.h"
namespace ZpIR
{
// helper class for building a single basic block
class BasicBlockBuilder
{
public:
BasicBlockBuilder(ZpIRBasicBlock* basicBlock) : m_basicBlock(basicBlock) {};
IRReg createReg(DataType type, uint8 elementCount = 1)
{
return m_basicBlock->createRegister(type, elementCount);
}
IRReg createReg(IRReg& r, DataType type, uint8 elementCount = 1)
{
r = m_basicBlock->createRegister(type, elementCount);
return r;
}
// append a single instruction at the end
void append(IR::__InsBase* ins)
{
assert_dbg();
}
void emit_EXPORT(LocationSymbolName exportSymbolName, IRReg r0)
{
m_basicBlock->appendInstruction(new IR::InsEXPORT(exportSymbolName, r0));
}
void emit_EXPORT(LocationSymbolName exportSymbolName, std::span<IRReg> regs)
{
m_basicBlock->appendInstruction(new IR::InsEXPORT(exportSymbolName, regs));
}
void emit_IMPORT(LocationSymbolName importSymbolName, IRReg r0)
{
m_basicBlock->appendInstruction(new IR::InsIMPORT(importSymbolName, r0));
}
// result is rA, operand is rB
// for some opcodes both can be operands
void emit_RR(IR::OpCode opcode, IRReg rA, IRReg rB)
{
m_basicBlock->appendInstruction(new IR::InsRR(opcode, rA, rB));
}
IRReg emit_RR(IR::OpCode opcode, DataType resultType, IRReg rB)
{
IRReg resultReg = m_basicBlock->createRegister(resultType);
emit_RR(opcode, resultReg, rB);
return resultReg;
}
// result is rA, operands are rB and rC
// for some opcodes all three can be operands
void emit_RRR(IR::OpCode opcode, IRReg rA, IRReg rB, IRReg rC)
{
m_basicBlock->appendInstruction(new IR::InsRRR(opcode, rA, rB, rC));
}
IRReg emit_RRR(IR::OpCode opcode, DataType resultType, IRReg rB, IRReg rC)
{
IRReg resultReg = m_basicBlock->createRegister(resultType);
m_basicBlock->appendInstruction(new IR::InsRRR(opcode, resultReg, rB, rC));
return resultReg;
}
void emit(IR::__InsBase* ins)
{
m_basicBlock->appendInstruction(ins);
}
// constant var creation
IRReg createConstU32(uint32 v)
{
return m_basicBlock->createConstantU32(v);
}
IRReg createTypedConst(uint32 v, DataType type)
{
return m_basicBlock->createTypedConstant(v, type);
}
IRReg createConstS32(uint32 v)
{
return m_basicBlock->createConstantS32(v);
}
IRReg createConstF32(f32 v)
{
return m_basicBlock->createConstantF32(v);
}
IRReg createConstPointer(void* v)
{
return m_basicBlock->createConstantPointer(v);
}
// use templates to compact other types?
DataType getRegType(IRReg reg)
{
return m_basicBlock->getRegType(reg);
}
void addImport(IRReg reg, LocationSymbolName importSymbolName)
{
m_basicBlock->addImport(reg, importSymbolName);
}
private:
ZpIRBasicBlock* m_basicBlock;
};
// helper class for constructing multiple basic blocks with control flow
class ZpIRBuilder
{
public:
typedef uint64 BlockBranchTarget;
static const inline BlockBranchTarget INVALID_BLOCK_NAME = 0xFFFFFFFFFFFFFFFFull;
struct BasicBlockWorkbuffer
{
BlockBranchTarget name{ INVALID_BLOCK_NAME };
BlockBranchTarget targetBranchNotTaken{ INVALID_BLOCK_NAME };
BlockBranchTarget targetBranchTaken{ INVALID_BLOCK_NAME };
};
void beginBlock(BlockBranchTarget name)
{
m_currentBasicBlock = new ZpIRBasicBlock();
BasicBlockWorkbuffer* wb = new BasicBlockWorkbuffer();
m_currentBasicBlock->setWorkbuffer(wb);
wb->name = name;
m_blocks.emplace_back(m_currentBasicBlock);
m_blocksByName.emplace(name, m_currentBasicBlock);
}
ZpIRBasicBlock* endBlock()
{
ZpIRBasicBlock* block = m_currentBasicBlock;
m_currentBasicBlock = nullptr;
BasicBlockWorkbuffer* wb = (BasicBlockWorkbuffer*)block->getWorkbuffer();
wb->targetBranchNotTaken = m_targetBranchNotTaken;
wb->targetBranchTaken = m_targetBranchTaken;
m_targetBranchNotTaken = INVALID_BLOCK_NAME;
m_targetBranchTaken = INVALID_BLOCK_NAME;
return block;
}
ZpIRFunction* finish()
{
if (m_currentBasicBlock)
assert_dbg();
// create function
ZpIRFunction* func = new ZpIRFunction();
// link all blocks
// and also collect a list of entry and exit nodes
for (auto& itr : m_blocks)
{
BasicBlockWorkbuffer* wb = (BasicBlockWorkbuffer*)itr->getWorkbuffer();
if (wb->targetBranchNotTaken != INVALID_BLOCK_NAME)
{
auto target = m_blocksByName.find(wb->targetBranchNotTaken);
if (target == m_blocksByName.end())
{
assert_dbg();
}
itr->m_branchNotTaken = target->second;
}
if (wb->targetBranchTaken != INVALID_BLOCK_NAME)
{
auto target = m_blocksByName.find(wb->targetBranchTaken);
if (target == m_blocksByName.end())
{
assert_dbg();
}
itr->m_branchTaken = target->second;
}
delete wb;
itr->setWorkbuffer(nullptr);
func->m_basicBlocks.emplace_back(itr);
// todo - track entry and exit blocks (set block flags for entry/exit during block gen)
}
return func;
}
IRReg createBlockRegister(DataType type, uint8 elementCount = 1)
{
return m_currentBasicBlock->createRegister(type, elementCount);
}
IRReg createConstU32(uint32 v)
{
return m_currentBasicBlock->createConstantU32(v);
}
IRReg createConstPointer(void* v)
{
return m_currentBasicBlock->createConstantPointer(v);
}
IRReg createConstPointerV(size_t v)
{
return m_currentBasicBlock->createConstantPointer((void*)v);
}
void addImport(IRReg reg, LocationSymbolName importName)
{
m_currentBasicBlock->addImport(reg, importName);
}
void addExport(IRReg reg, LocationSymbolName importName)
{
m_currentBasicBlock->addExport(reg, importName);
}
void setBlockTargetBranchTaken(BlockBranchTarget target)
{
if (m_targetBranchTaken != INVALID_BLOCK_NAME)
assert_dbg();
m_targetBranchTaken = target;
}
void setBlockTargetBranchNotTaken(BlockBranchTarget target)
{
if (m_targetBranchNotTaken != INVALID_BLOCK_NAME)
assert_dbg();
m_targetBranchNotTaken = target;
}
private:
ZpIRBasicBlock* m_currentBasicBlock{};
std::vector<ZpIRBasicBlock*> m_blocks;
std::unordered_map<BlockBranchTarget, ZpIRBasicBlock*> m_blocksByName;
BlockBranchTarget m_targetBranchNotTaken{ INVALID_BLOCK_NAME };
BlockBranchTarget m_targetBranchTaken{ INVALID_BLOCK_NAME };
};
}
| 6,392
|
C++
|
.h
| 208
| 27.024038
| 91
| 0.739577
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,324
|
ZirUtility.h
|
cemu-project_Cemu/src/util/Zir/Core/ZirUtility.h
|
#pragma once
#include "util/Zir/Core/IR.h"
namespace ZpIR
{
struct ZpIRCmdUtil
{
template<typename TFuncRegRead, typename TFuncRegWrite>
static void forEachAccessedReg(ZpIRBasicBlock& block, IR::__InsBase* instruction, TFuncRegRead funcRegRead, TFuncRegWrite funcRegWrite)
{
if (auto ins = IR::InsRR::getIfForm(instruction))
{
switch (ins->opcode)
{
case ZpIR::IR::OpCode::MOV:
case ZpIR::IR::OpCode::BITCAST:
case ZpIR::IR::OpCode::SWAP_ENDIAN:
case ZpIR::IR::OpCode::CONVERT_FLOAT_TO_INT:
case ZpIR::IR::OpCode::CONVERT_INT_TO_FLOAT:
if (isRegVar(ins->rB))
funcRegRead(ins->rB);
cemu_assert_debug(isRegVar(ins->rA));
funcRegWrite(ins->rA);
break;
default:
cemu_assert_unimplemented();
}
}
else if (auto ins = IR::InsRRR::getIfForm(instruction))
{
switch (ins->opcode)
{
case ZpIR::IR::OpCode::ADD:
case ZpIR::IR::OpCode::SUB:
case ZpIR::IR::OpCode::MUL:
case ZpIR::IR::OpCode::DIV:
if (isRegVar(ins->rB))
funcRegRead(ins->rB);
if (isRegVar(ins->rC))
funcRegRead(ins->rC);
cemu_assert_debug(isRegVar(ins->rA));
funcRegWrite(ins->rA);
break;
default:
cemu_assert_unimplemented();
}
}
else if (auto ins = IR::InsIMPORT::getIfForm(instruction))
{
for (uint16 i = 0; i < ins->count; i++)
{
cemu_assert_debug(isRegVar(ins->regArray[i]));
funcRegWrite(ins->regArray[i]);
}
}
else if (auto ins = IR::InsEXPORT::getIfForm(instruction))
{
for (uint16 i = 0; i < ins->count; i++)
{
if (isRegVar(ins->regArray[i]))
funcRegRead(ins->regArray[i]);
}
}
else
{
cemu_assert_unimplemented();
}
}
static void replaceRegisters(IR::__InsBase& ins, std::unordered_map<IRReg, IRReg>& translationTable)
{
cemu_assert_unimplemented();
}
};
}
| 1,876
|
C++
|
.h
| 73
| 21.178082
| 137
| 0.642976
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,325
|
IR.h
|
cemu-project_Cemu/src/util/Zir/Core/IR.h
|
#pragma once
#include <optional>
using f32 = float;
using f64 = double;
inline void zpir_debug_assert(bool _cond)
{
if(!_cond)
assert_dbg();
}
namespace ZpIR
{
//enum class ZpIRCmdForm : uint8
//{
// FORM_VOID, // no-op
// FORM_ZERO, // opcode without operands
// FORM_1OP, // op0
// FORM_2OP, // op0, op1
// FORM_3OP, // op0, op1, op2
// FORM_4OP, // op0, op1, op2, op3
// // todo - memory read + memory store
// FORM_MEM, // op0, opEA, offset, type
// // todo - function calls
//};
//enum class ZpIROpcodeDepr : uint8
//{
// OP_VOID,
// // FORM_1OP
// OP_CALL,
// // FORM_2OP
// OP_ASSIGN, // copy/assignment
// OP_CAST_ZEROEXT, // cast type to another. If broadening then zero-extend (unsigned cast)
// OP_CAST_SIGNEXT, // cast type to another. If broadening then sign-extend (signed cast)
// // FORM_3OP
// OP_ADD, // op0 = op1 + op2
// OP_SUB, // op0 = op1 - op2
// OP_MUL, // op0 = op1 * op2
// OP_DIV, // op0 = op1 / op2
// // memory
// OP_MEM_READ,
// OP_MEM_WRITE,
//};
enum class DataType : uint8
{
NONE = 0x00,
// integer
U8 = 1,
S8 = 2,
U16 = 3,
S16 = 4,
U32 = 5,
S32 = 6,
U64 = 7,
S64 = 8,
// floating-point
F32 = 0x10 + 0,
F64 = 0x10 + 1,
// special
POINTER = 0x20, // dynamic width based on pointer width of target architecture
// boolean
BOOL = 0x30, // can hold false/true. Size depends on target architecture
};
typedef uint16 IRReg;
typedef uint64 LocationSymbolName;
typedef uint32 ZpIRPhysicalReg;
inline bool isRegVar(IRReg r) { return r < 0x8000; };
inline bool isConstVar(IRReg r) { return r >= 0x8000; };
inline uint16 getRegIndex(IRReg r) { return (uint16)r & 0x7FFF; };
namespace IR
{
enum class OpCode : uint8
{
UNDEF = 0, // undefined
// basic opcodes
MOV,
// basic arithmetic opcodes
ADD, // addition
SUB, // subtraction
MUL, // multiplication
DIV, // division
// conversion
BITCAST, // like MOV, but allows registers of different types. No value conversion happens, raw bit copy
SWAP_ENDIAN, // swap endianness
CONVERT_INT_TO_FLOAT,
CONVERT_FLOAT_TO_INT,
// misc
IMPORT_SINGLE, // import into a single IRReg. Depr: Make this like EXPORT where there is a 1-4 regs variant and one for more
IMPORT, // import from external/custom resource into 1-4 IRReg
EXPORT, // export 1-4 registers to external/custom resource
// EXPORT_MANY // for when more than 4 registers are needed
// vector
EXTRACT_ELEMENT, // extract a scalar type from a vector type
// some notes: We need this for texture read instructions. Where the result is a vec4 (f32x4) and this is how we can extract individual registers from that
// update -> We may also instead just let the texture sample instruction specify 4 output registers
};
enum class OpForm : uint8
{
NONE = 0,
RR = 1,
RRR = 2,
IMPORT_SINGLE = 3, // deprecated
IMPORT = 4,
EXPORT = 5,
};
// instruction base class
class __InsBase
{
public:
OpCode opcode;
OpForm opform;
__InsBase* next;
protected:
__InsBase(OpCode opcode, OpForm opform) : opcode(opcode), opform(opform) { };
};
// adapted base class, instruction forms inherit from this
template<typename TInstr, OpForm TOpForm>
class __InsBaseWithForm : public __InsBase
{
public:
//OpCode opcode;
//OpForm opform;
//__InsBase* next;
static const OpForm getForm()
{
return TOpForm;
}
static TInstr* getIfForm(__InsBase* instructionBase)
{
if (instructionBase->opform != TOpForm)
return nullptr;
return (TInstr*)instructionBase;
}
protected:
__InsBaseWithForm(OpCode opcode) : __InsBase(opcode, TOpForm) { };
};
class InsRR : public __InsBaseWithForm<InsRR, OpForm::RR>
{
public:
InsRR(OpCode opcode, IRReg rA, IRReg rB) : __InsBaseWithForm(opcode), rA(rA), rB(rB) {};
IRReg rA;
IRReg rB;
};
class InsRRR : public __InsBaseWithForm<InsRRR, OpForm::RRR>
{
public:
InsRRR(OpCode opcode, IRReg rA, IRReg rB, IRReg rC) : __InsBaseWithForm(opcode), rA(rA), rB(rB), rC(rC) {};
IRReg rA;
IRReg rB;
IRReg rC;
};
// should we support RRI format with 32bit signed integer as a way to avoid having to generate dozens of IR const regs for stuff like shift and other logical instructions with constant rhs?
// and if we do, should it be a 32bit signed integer or should the type match the instruction type?
class InsEXPORT : public __InsBaseWithForm<InsEXPORT, OpForm::EXPORT>
{
public:
InsEXPORT(LocationSymbolName exportSymbol, IRReg r) : __InsBaseWithForm(OpCode::EXPORT), exportSymbol(exportSymbol)
{
regArray[0] = r;
count = 1;
};
InsEXPORT(LocationSymbolName exportSymbol, IRReg r0, IRReg r1) : __InsBaseWithForm(OpCode::EXPORT), exportSymbol(exportSymbol)
{
regArray[0] = r0; regArray[1] = r1;
count = 2;
};
InsEXPORT(LocationSymbolName exportSymbol, IRReg r0, IRReg r1, IRReg r2) : __InsBaseWithForm(OpCode::EXPORT), exportSymbol(exportSymbol)
{
regArray[0] = r0; regArray[1] = r1; regArray[2] = r2;
count = 3;
};
InsEXPORT(LocationSymbolName exportSymbol, IRReg r0, IRReg r1, IRReg r2, IRReg r3) : __InsBaseWithForm(OpCode::EXPORT), exportSymbol(exportSymbol)
{
regArray[0] = r0;
regArray[1] = r1;
regArray[2] = r2;
regArray[3] = r3;
count = 4;
};
InsEXPORT(LocationSymbolName exportSymbol, std::span<IRReg> regs) : __InsBaseWithForm(OpCode::EXPORT), exportSymbol(exportSymbol)
{
zpir_debug_assert(regs.size() <= 4);
for(size_t i=0; i<regs.size(); i++)
regArray[i] = regs[i];
count = (uint16)regs.size();
};
uint16 count;
IRReg regArray[4]; // up to 4 registers
LocationSymbolName exportSymbol;
};
class InsIMPORT : public __InsBaseWithForm<InsIMPORT, OpForm::IMPORT>
{
public:
InsIMPORT(LocationSymbolName importSymbol, IRReg r) : __InsBaseWithForm(OpCode::IMPORT), importSymbol(importSymbol)
{
regArray[0] = r;
count = 1;
};
InsIMPORT(LocationSymbolName importSymbol, IRReg r0, IRReg r1) : __InsBaseWithForm(OpCode::IMPORT), importSymbol(importSymbol)
{
regArray[0] = r0; regArray[1] = r1;
count = 2;
};
InsIMPORT(LocationSymbolName importSymbol, IRReg r0, IRReg r1, IRReg r2) : __InsBaseWithForm(OpCode::IMPORT), importSymbol(importSymbol)
{
regArray[0] = r0; regArray[1] = r1; regArray[2] = r2;
count = 3;
};
InsIMPORT(LocationSymbolName importSymbol, IRReg r0, IRReg r1, IRReg r2, IRReg r3) : __InsBaseWithForm(OpCode::IMPORT), importSymbol(importSymbol)
{
regArray[0] = r0;
regArray[1] = r1;
regArray[2] = r2;
regArray[3] = r3;
count = 4;
};
InsIMPORT(LocationSymbolName importSymbol, std::span<IRReg> regs) : __InsBaseWithForm(OpCode::IMPORT), importSymbol(importSymbol)
{
zpir_debug_assert(regs.size() <= 4);
for (size_t i = 0; i < regs.size(); i++)
regArray[i] = regs[i];
count = (uint16)regs.size();
};
uint16 count;
IRReg regArray[4]; // up to 4 registers
LocationSymbolName importSymbol;
};
};
// IR register definition stored in basic block
struct IRRegDef
{
IRRegDef(DataType type, uint8 elementCount) : type(type), elementCount(elementCount) {};
DataType type;
uint8 elementCount; // 1 = scalar
ZpIRPhysicalReg physicalRegister{ std::numeric_limits<ZpIRPhysicalReg>::max()};
// todo - information about spilling location? (it depends on the architecture so we should keep this out of the core IR)
bool hasAssignedPhysicalRegister() const
{
return physicalRegister != std::numeric_limits<ZpIRPhysicalReg>::max();
}
void assignPhysicalRegister(ZpIRPhysicalReg physReg)
{
physicalRegister = physReg;
}
};
// IR register constant definition stored in basic block
struct IRRegConstDef
{
IRRegConstDef() = default;
// todo - support for constants with more than one element?
IRRegConstDef& setU32(uint32 v) { value_u32 = v; type = DataType::U32; return *this; };
IRRegConstDef& setS32(sint32 v) { value_s32 = v; type = DataType::S32; return *this; };
IRRegConstDef& setF32(f32 v) { value_f32 = v; type = DataType::F32; return *this; };
IRRegConstDef& setPtr(void* v) { value_ptr = v; type = DataType::POINTER; return *this; };
IRRegConstDef& setRaw(uint32 v, DataType regType) { value_u32 = v; type = regType; return *this; };
DataType type{ DataType::NONE };
union
{
uint32 value_u32;
sint32 value_s32;
sint64 value_s64;
uint64 value_u64;
void* value_ptr;
f32 value_f32;
f64 value_f64;
};
};
struct ZpIRBasicBlock
{
friend class ZpIRBuilder;
struct IRBBImport
{
IRBBImport(IRReg reg, LocationSymbolName name) : reg(reg), name(name) {};
IRReg reg;
LocationSymbolName name;
};
struct IRBBExport
{
IRBBExport(IRReg reg, LocationSymbolName name) : reg(reg), name(name) {};
IRReg reg;
LocationSymbolName name;
};
IR::__InsBase* m_instructionFirst{};
IR::__InsBase* m_instructionLast{};
std::vector<IRRegDef> m_regs;
std::vector<IRRegConstDef> m_consts;
std::vector<IRBBImport> m_imports;
std::vector<IRBBExport> m_exports;
ZpIRBasicBlock* m_branchNotTaken{ nullptr }; // next block if branch not taken or no branch present
ZpIRBasicBlock* m_branchTaken{ nullptr }; // next block if branch is taken
void* m_workbuffer{}; // can be used as temporary storage for information
void appendInstruction(IR::__InsBase* ins)
{
if (m_instructionFirst == nullptr)
{
m_instructionFirst = ins;
m_instructionLast = ins;
ins->next = nullptr;
return;
}
m_instructionLast->next = ins;
m_instructionLast = ins;
ins->next = nullptr;
}
IRReg createRegister(DataType type, uint8 elementCount = 1)
{
uint32 index = (uint32)m_regs.size();
cemu_assert_debug(index < 0x8000);
m_regs.emplace_back(type, elementCount);
return (IRReg)index;
}
IRReg createConstantU32(uint32 value)
{
uint32 index = (uint32)m_consts.size();
cemu_assert_debug(index < 0x8000);
m_consts.emplace_back().setU32(value);
return (IRReg)((uint16)index + 0x8000);
}
IRReg createTypedConstant(uint32 value, DataType type)
{
uint32 index = (uint32)m_consts.size();
cemu_assert_debug(index < 0x8000);
m_consts.emplace_back().setRaw(value, type);
return (IRReg)((uint16)index + 0x8000);
}
IRReg createConstantS32(uint32 value)
{
uint32 index = (uint32)m_consts.size();
cemu_assert_debug(index < 0x8000);
m_consts.emplace_back().setS32(value);
return (IRReg)((uint16)index + 0x8000);
}
IRReg createConstantF32(f32 value)
{
uint32 index = (uint32)m_consts.size();
cemu_assert_debug(index < 0x8000);
m_consts.emplace_back().setF32(value);
return (IRReg)((uint16)index + 0x8000);
}
IRReg createConstantPointer(void* value)
{
uint32 index = (uint32)m_consts.size();
cemu_assert_debug(index < 0x8000);
m_consts.emplace_back().setPtr(value);
return (IRReg)((uint16)index + 0x8000);
}
void addImport(IRReg reg, LocationSymbolName importName)
{
m_imports.emplace_back(reg, importName);
}
void addExport(IRReg reg, LocationSymbolName importName)
{
m_exports.emplace_back(reg, importName);
}
void setWorkbuffer(void* buffer)
{
if (buffer != nullptr)
{
if (m_workbuffer)
assert_dbg();
}
m_workbuffer = buffer;
}
void* getWorkbuffer()
{
return m_workbuffer;
}
DataType getRegType(IRReg reg)
{
uint32 index = (uint32)reg;
if (index >= 0x8000)
{
index -= 0x8000;
cemu_assert_debug(index < m_consts.size());
return m_consts[index].type;
}
return m_regs[index].type;
}
IRRegConstDef* getConstant(IRReg reg)
{
uint32 index = (uint32)reg;
if (index < 0x8000)
return nullptr;
index -= 0x8000;
if (index >= m_consts.size())
return nullptr;
return m_consts.data() + index;
}
std::optional<sint32> getConstantS32(IRReg reg)
{
uint32 index = (uint32)reg;
if (index < 0x8000)
return std::nullopt;
index -= 0x8000;
if (index >= m_consts.size())
return std::nullopt;
if (m_consts[index].type == DataType::U32)
return (sint32)m_consts[index].value_u32;
else if (m_consts[index].type == DataType::POINTER)
assert_dbg();
else if (m_consts[index].type == DataType::U64)
{
if (m_consts[index].value_u64 >= 0x80000000ull)
assert_dbg();
return (sint32)m_consts[index].value_u64;
}
else
assert_dbg();
return std::nullopt;
}
std::optional<uint64> getConstantU64(IRReg reg)
{
auto constReg = getConstant(reg);
if (!constReg)
return std::nullopt;
if (constReg->type == DataType::U64)
return constReg->value_u64;
else
assert_dbg();
return std::nullopt;
}
};
struct ZpIRFunction
{
std::vector<ZpIRBasicBlock*> m_basicBlocks;
std::vector<ZpIRBasicBlock*> m_entryBlocks;
std::vector<ZpIRBasicBlock*> m_exitBlocks;
struct
{
bool registersAllocated{false};
}state;
};
// helpers for shader code
namespace ShaderSubset
{
class ShaderImportLocation
{
enum LOC_TYPE : uint8
{
LOC_TYPE_UNIFORM_REGISTER = 1,
LOC_TYPE_UNIFORM_BUFFER = 2,
LOC_TYPE_ATTRIBUTE = 3,
};
public:
ShaderImportLocation() = default;
ShaderImportLocation(LocationSymbolName loc)
{
uint64 v = (uint64)loc;
m_locType = (LOC_TYPE)(v >> 56);
m_indexA = (uint16)(v >> 0);
m_indexB = (uint16)(v >> 16);
}
ShaderImportLocation& SetUniformRegister(uint16 index)
{
m_locType = LOC_TYPE_UNIFORM_REGISTER;
m_indexA = index;
m_indexB = 0;
return *this;
}
ShaderImportLocation& SetVertexAttribute(uint16 attributeIndex, uint16 channelIndex)
{
m_locType = LOC_TYPE_ATTRIBUTE;
m_indexA = attributeIndex;
m_indexB = channelIndex;
return *this;
}
bool IsUniformRegister() const
{
return m_locType == LOC_TYPE_UNIFORM_REGISTER;
}
bool IsVertexAttribute() const
{
return m_locType == LOC_TYPE_ATTRIBUTE;
}
void GetUniformRegister(uint16& index)
{
index = m_indexA;
}
void GetVertexAttribute(uint16& attributeIndex, uint16& channelIndex) const
{
attributeIndex = m_indexA;
channelIndex = m_indexB;
}
operator LocationSymbolName() const
{
uint64 v = 0;
v |= ((uint64)m_locType << 56);
v |= ((uint64)m_indexA << 0);
v |= ((uint64)m_indexB << 16);
return (LocationSymbolName)v;
}
std::string GetDebugName()
{
const char elementTable[] = { 'x' , 'y', 'z', 'w' };
if (m_locType == LOC_TYPE_UNIFORM_REGISTER)
return fmt::format("UniformReg[{0}].{1}", m_indexA >> 2, elementTable[m_indexA & 3]);
if (m_locType == LOC_TYPE_ATTRIBUTE)
return fmt::format("VertexAttribute[{0}].{1}", m_indexA, elementTable[m_indexB]);
return "Unknown";
}
private:
LOC_TYPE m_locType{};
uint16 m_indexA{};
uint16 m_indexB{};
//LocationSymbolName m_symbolName{};
static_assert(sizeof(LocationSymbolName) == 8);
};
class ShaderExportLocation
{
enum LOC_TYPE : uint8
{
LOC_TYPE_POSITION = 1,
LOC_TYPE_OUTPUT = 2,
};
public:
ShaderExportLocation() = default;
ShaderExportLocation(LocationSymbolName loc)
{
uint64 v = (uint64)loc;
m_locType = (LOC_TYPE)(v >> 56);
m_indexA = (uint16)(v >> 0);
m_indexB = (uint16)(v >> 16);
}
ShaderExportLocation& SetPosition()
{
m_locType = LOC_TYPE_POSITION;
m_indexA = 0;
m_indexB = 0;
return *this;
}
ShaderExportLocation& SetOutputAttribute(uint16 attributeIndex) // todo - channel mask?
{
m_locType = LOC_TYPE_OUTPUT;
m_indexA = attributeIndex;
m_indexB = 0;
return *this;
}
bool IsPosition() const
{
return m_locType == LOC_TYPE_POSITION;
}
bool IsOutputAttribute() const
{
return m_locType == LOC_TYPE_OUTPUT;
}
void GetOutputAttribute(uint16& attributeIndex) const
{
attributeIndex = m_indexA;
}
operator LocationSymbolName() const
{
uint64 v = 0;
v |= ((uint64)m_locType << 56);
v |= ((uint64)m_indexA << 0);
v |= ((uint64)m_indexB << 16);
return (LocationSymbolName)v;
}
std::string GetDebugName()
{
const char elementTable[] = { 'x' , 'y', 'z', 'w' };
//if (m_locType == LOC_TYPE_UNIFORM_REGISTER)
// return fmt::format("UniformReg[{0}].{1}", m_indexA >> 2, elementTable[m_indexA & 3]);
//if (m_locType == LOC_TYPE_ATTRIBUTE)
// return fmt::format("VertexAttribute[{0}].{1}", m_indexA, elementTable[m_indexB]);
return "Unknown";
}
private:
LOC_TYPE m_locType{};
uint16 m_indexA{};
uint16 m_indexB{};
static_assert(sizeof(LocationSymbolName) == 8);
};
};
}
| 16,782
|
C++
|
.h
| 572
| 25.461538
| 191
| 0.674677
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,326
|
ZpIRPasses.h
|
cemu-project_Cemu/src/util/Zir/Core/ZpIRPasses.h
|
#pragma once
#include "util/Zir/Core/IR.h"
namespace ZirPass
{
class ZpIRPass
{
public:
ZpIRPass(ZpIR::ZpIRFunction* irFunction) : m_irFunction(irFunction) { };
virtual void applyPass() = 0;
protected:
ZpIR::ZpIRFunction* m_irFunction;
};
struct RALivenessRange_t
{
RALivenessRange_t(struct RABlock_t* block, ZpIR::IRReg irReg, sint32 start, sint32 end, ZpIR::DataType irDataType);
~RALivenessRange_t();
enum class SOURCE
{
NONE,
INSTRUCTION, // instruction initializes value
PREVIOUS_BLOCK, // imported from previous block(s)
PREVIOUS_RANGE, // from previous range within same block
};
enum class LOCATION
{
UNASSIGNED,
PHYSICAL_REGISTER,
SPILLED,
};
void setStart(sint32 startIndex);
void setEnd(sint32 endIndex);
void addSourceFromPreviousBlock(RALivenessRange_t* source)
{
if (m_source != SOURCE::NONE && m_source != SOURCE::PREVIOUS_BLOCK)
assert_dbg();
m_source = SOURCE::PREVIOUS_BLOCK;
m_sourceRanges.emplace_back(source);
source->m_destinationRanges.emplace_back(this);
}
void addSourceFromSameBlock(RALivenessRange_t* source)
{
if (m_source != SOURCE::NONE)
assert_dbg();
m_source = SOURCE::PREVIOUS_RANGE;
m_sourceRanges.emplace_back(source);
source->m_destinationRanges.emplace_back(this);
}
bool isOverlapping(sint32 start, sint32 end) const
{
return m_startIndex < end && m_endIndex >= start;
}
bool isOverlapping(RALivenessRange_t* range) const
{
return isOverlapping(range->m_startIndex, range->m_endIndex);
}
void assignPhysicalRegister(ZpIR::ZpIRPhysicalReg physReg);
RABlock_t* m_block;
ZpIR::IRReg m_irReg;
ZpIR::DataType m_irDataType;
sint32 m_startIndex{ -1 };
sint32 m_endIndex{ -1 }; // inclusive
//std::vector<bool> m_reservedPhysRegisters; // unavailable physical registers
std::vector<RALivenessRange_t*> m_overlappingRanges;
// state / assigned location
LOCATION m_location{ LOCATION::UNASSIGNED };
sint32 m_physicalRegister;
// source
SOURCE m_source{ SOURCE::NONE };
std::vector<RALivenessRange_t*> m_sourceRanges;
// destination
//RALivenessRange_t* m_destinationRange{ nullptr };
std::vector<RALivenessRange_t*> m_destinationRanges;
};
struct RABlock_t
{
std::unordered_map<ZpIR::IRReg, RALivenessRange_t*> livenessRanges;
struct Compare
{
bool operator()(const RALivenessRange_t* lhs, const RALivenessRange_t* rhs) const /* noexcept */
{
// order for unassignedRanges
// aka order in which ranges should be assigned physical registers
return lhs->m_startIndex < rhs->m_startIndex;
}
};
public:
std::multiset<RALivenessRange_t*, Compare> unassignedRanges;
};
class RARegular : public ZpIRPass
{
public:
RARegular(ZpIR::ZpIRFunction* irFunction) : ZpIRPass(irFunction) {};
void applyPass()
{
prepareRABlocks();
generateLivenessRanges();
assignPhysicalRegisters();
assert_dbg(); // todo -> rewrite doesnt need to be separate any longer since we store a separate physical register index now (in IRReg)
rewrite();
m_irFunction->state.registersAllocated = true;
}
private:
void prepareRABlocks();
void generateLivenessRanges();
void assignPhysicalRegisters();
void rewrite();
void assignPhysicalRegistersForBlock(RABlock_t& raBlock);
void rewriteBlock(ZpIR::ZpIRBasicBlock& basicBlock, RABlock_t& raBlock);
std::span<sint32> extGetSuitablePhysicalRegisters(ZpIR::DataType dataType)
{
const sint32 OFFSET_U64 = 0;
const sint32 OFFSET_U32 = 16;
static sint32 _regCandidatesU64[] = { OFFSET_U64 + 0, OFFSET_U64 + 1, OFFSET_U64 + 2, OFFSET_U64 + 3, OFFSET_U64 + 4, OFFSET_U64 + 5, OFFSET_U64 + 6, OFFSET_U64 + 7, OFFSET_U64 + 8, OFFSET_U64 + 9, OFFSET_U64 + 10, OFFSET_U64 + 11, OFFSET_U64 + 12, OFFSET_U64 + 13, OFFSET_U64 + 14, OFFSET_U64 + 15 };
static sint32 _regCandidatesU32[] = { OFFSET_U32 + 0, OFFSET_U32 + 1, OFFSET_U32 + 2, OFFSET_U32 + 3, OFFSET_U32 + 4, OFFSET_U32 + 5, OFFSET_U32 + 6, OFFSET_U32 + 7, OFFSET_U32 + 8, OFFSET_U32 + 9, OFFSET_U32 + 10, OFFSET_U32 + 11, OFFSET_U32 + 12, OFFSET_U32 + 13, OFFSET_U32 + 14, OFFSET_U32 + 15 };
if (dataType == ZpIR::DataType::POINTER || dataType == ZpIR::DataType::U64)
return _regCandidatesU64;
if (dataType == ZpIR::DataType::U32)
return _regCandidatesU32;
//if (dataType != ZpIRDataType::POINTER)
//{
//}
assert_dbg();
return _regCandidatesU32;
}
void extFilterPhysicalRegisters(std::vector<sint32>& physRegCandidates, ZpIR::ZpIRPhysicalReg registerToFilter)
{
// todo - this is quite complex on x86 where registers overlap (e.g. RAX and EAX/AL/AH/AX)
// so registerToFilter can translate to multiple filtered values
// but for now we use a simplified placeholder implementation
if (registerToFilter >= 0 && registerToFilter < 16)
{
physRegCandidates.erase(std::remove(physRegCandidates.begin(), physRegCandidates.end(), (sint32)registerToFilter), physRegCandidates.end());
physRegCandidates.erase(std::remove(physRegCandidates.begin(), physRegCandidates.end(), (sint32)registerToFilter + 16), physRegCandidates.end());
}
else if (registerToFilter >= 16 && registerToFilter < 32)
{
physRegCandidates.erase(std::remove(physRegCandidates.begin(), physRegCandidates.end(), (sint32)registerToFilter), physRegCandidates.end());
physRegCandidates.erase(std::remove(physRegCandidates.begin(), physRegCandidates.end(), (sint32)registerToFilter - 16), physRegCandidates.end());
}
else
assert_dbg();
}
ZpIR::ZpIRPhysicalReg extPickPreferredRegister(std::vector<sint32>& physRegCandidates)
{
if (physRegCandidates.empty())
assert_dbg();
return physRegCandidates[0];
}
void debugPrint(RABlock_t& raBlock)
{
std::multiset<RALivenessRange_t*, RABlock_t::Compare> sortedRanges;
for (auto& itr : raBlock.livenessRanges)
sortedRanges.emplace(itr.second);
for (auto& itr : sortedRanges)
{
printf("%04x - %04x reg %04d: ", (uint32)(uint16)itr->m_startIndex, (uint32)(uint16)itr->m_endIndex, (uint32)itr->m_irReg);
if (itr->m_location == RALivenessRange_t::LOCATION::PHYSICAL_REGISTER)
printf("PHYS_REG %d", (int)itr->m_physicalRegister);
else if (itr->m_location == RALivenessRange_t::LOCATION::UNASSIGNED)
printf("UNASSIGNED");
else
assert_dbg();
printf("\n");
}
}
// remove all physical registers from physRegCandidates which are already reserved by any of the overlapping ranges
void filterCandidates(std::vector<sint32>& physRegCandidates, RALivenessRange_t* range)
{
for (auto& itr : range->m_overlappingRanges)
{
if (itr->m_location != RALivenessRange_t::LOCATION::PHYSICAL_REGISTER)
continue;
extFilterPhysicalRegisters(physRegCandidates, itr->m_physicalRegister);
}
}
std::vector<RABlock_t> m_raBlockArray;
};
class RegisterAllocatorForGLSL : public ZpIRPass
{
enum class PHYS_REG_TYPE : uint8
{
U32 = 0,
S32 = 1,
F32 = 2
};
public:
RegisterAllocatorForGLSL(ZpIR::ZpIRFunction* irFunction) : ZpIRPass(irFunction) {};
void applyPass()
{
assignPhysicalRegisters();
m_irFunction->state.registersAllocated = true;
}
static bool IsPhysRegTypeU32(ZpIR::ZpIRPhysicalReg physReg)
{
return ((uint32)physReg >> 30) == (uint32)PHYS_REG_TYPE::U32;
}
static bool IsPhysRegTypeS32(ZpIR::ZpIRPhysicalReg physReg)
{
return ((uint32)physReg >> 30) == (uint32)PHYS_REG_TYPE::S32;
}
static bool IsPhysRegTypeF32(ZpIR::ZpIRPhysicalReg physReg)
{
return ((uint32)physReg >> 30) == (uint32)PHYS_REG_TYPE::F32;
}
static uint32 GetPhysRegIndex(ZpIR::ZpIRPhysicalReg physReg)
{
return (uint32)physReg & 0x3FFFFFFF;
}
static std::string DebugPrintHelper_getPhysRegisterName(ZpIR::ZpIRBasicBlock* block, ZpIR::ZpIRPhysicalReg r);
private:
void assignPhysicalRegisters();
void assignPhysicalRegistersForBlock(ZpIR::ZpIRBasicBlock* basicBlock);
uint32 m_physicalRegisterCounterU32{};
uint32 m_physicalRegisterCounterS32{};
uint32 m_physicalRegisterCounterF32{};
ZpIR::ZpIRPhysicalReg MakePhysReg(PHYS_REG_TYPE regType, uint32 index)
{
uint32 v = (uint32)regType << 30;
v |= index;
return (ZpIR::ZpIRPhysicalReg)v;
}
};
};
| 8,263
|
C++
|
.h
| 223
| 33.372197
| 304
| 0.729039
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,327
|
VirtualHeap.h
|
cemu-project_Cemu/src/util/VirtualHeap/VirtualHeap.h
|
#pragma once
// virtual heap
struct VirtualBufferHeapEntry_t
{
uint32 startOffset;
uint32 endOffset;
VirtualBufferHeapEntry_t* next;
VirtualBufferHeapEntry_t* previous;
};
struct VirtualBufferHeap_t
{
uint32 virtualSize;
void* baseAddress; // base address for _allocateAddr and _freeAddr
VirtualBufferHeapEntry_t* firstEntry;
// unused entries
VirtualBufferHeapEntry_t* firstUnusedEntry;
// update tracking
uint32 updateTrackIndex;
// stats
struct
{
uint32 numActiveAllocs;
uint32 allocatedMemory;
}stats;
};
VirtualBufferHeap_t* virtualBufferHeap_create(uint32 virtualHeapSize, void* baseAddr = nullptr);
VirtualBufferHeapEntry_t* virtualBufferHeap_allocate(VirtualBufferHeap_t* bufferHeap, uint32 size);
void virtualBufferHeap_free(VirtualBufferHeap_t* bufferHeap, VirtualBufferHeapEntry_t* entry);
void* virtualBufferHeap_allocateAddr(VirtualBufferHeap_t* bufferHeap, uint32 size);
void virtualBufferHeap_freeAddr(VirtualBufferHeap_t* bufferHeap, void* addr);
| 988
|
C++
|
.h
| 30
| 31.1
| 99
| 0.834382
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,328
|
DXGIWrapper.h
|
cemu-project_Cemu/src/util/DXGIWrapper/DXGIWrapper.h
|
#pragma once
#include <dxgi1_4.h>
//#include <atlbase.h>
class DXGIWrapper
{
public:
DXGIWrapper()
: DXGIWrapper(nullptr)
{}
DXGIWrapper(uint8* deviceLUID)
{
m_moduleHandle = LoadLibraryA("dxgi.dll");
if (!m_moduleHandle)
throw std::runtime_error("can't load dxgi module");
const auto pCreateDXGIFactory1 = (decltype(&CreateDXGIFactory1))GetProcAddress(m_moduleHandle, "CreateDXGIFactory1");
if (!pCreateDXGIFactory1)
{
FreeLibrary(m_moduleHandle);
throw std::runtime_error("can't find CreateDXGIFactory1 in dxgi module");
}
IDXGIFactory1* dxgiFactory = nullptr;
pCreateDXGIFactory1(IID_PPV_ARGS(&dxgiFactory));
IDXGIAdapter1* tmpDxgiAdapter = nullptr;
UINT adapterIndex = 0;
while (dxgiFactory->EnumAdapters1(adapterIndex, &tmpDxgiAdapter) != DXGI_ERROR_NOT_FOUND)
{
DXGI_ADAPTER_DESC1 desc;
tmpDxgiAdapter->GetDesc1(&desc);
if (deviceLUID == nullptr || memcmp(&desc.AdapterLuid, deviceLUID, sizeof(LUID)) == 0)
{
tmpDxgiAdapter->QueryInterface(IID_PPV_ARGS(&m_dxgiAdapter));
tmpDxgiAdapter->Release();
break;
}
tmpDxgiAdapter->Release();
++adapterIndex;
}
dxgiFactory->Release();
if (!m_dxgiAdapter)
{
Cleanup();
throw std::runtime_error("can't create dxgi adapter");
}
}
~DXGIWrapper()
{
Cleanup();
}
bool QueryVideoMemoryInfo(DXGI_QUERY_VIDEO_MEMORY_INFO& info) const
{
return m_dxgiAdapter->QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &info) == S_OK;
}
private:
HMODULE m_moduleHandle = nullptr;
IDXGIAdapter3* m_dxgiAdapter = nullptr;
void Cleanup()
{
if (m_dxgiAdapter)
{
m_dxgiAdapter->Release();
m_dxgiAdapter = nullptr;
}
if (m_moduleHandle)
{
FreeLibrary(m_moduleHandle);
m_moduleHandle = nullptr;
}
}
};
| 1,772
|
C++
|
.h
| 69
| 22.608696
| 119
| 0.728081
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,329
|
ChunkedHeap.h
|
cemu-project_Cemu/src/util/ChunkedHeap/ChunkedHeap.h
|
#pragma once
struct CHAddr
{
uint32 offset;
uint32 chunkIndex;
CHAddr(uint32 _offset, uint32 _chunkIndex) : offset(_offset), chunkIndex(_chunkIndex) {};
CHAddr() : offset(0xFFFFFFFF), chunkIndex(0xFFFFFFFF) {};
bool isValid() { return chunkIndex != 0xFFFFFFFF; };
static CHAddr getInvalid() { return CHAddr(0xFFFFFFFF, 0xFFFFFFFF); };
};
class ChunkedHeap
{
struct allocRange_t
{
allocRange_t* nextFree{};
allocRange_t* prevFree{};
allocRange_t* prevOrdered{};
allocRange_t* nextOrdered{};
uint32 offset;
uint32 chunkIndex;
uint32 size;
bool isFree;
allocRange_t(uint32 _offset, uint32 _chunkIndex, uint32 _size, bool _isFree) : offset(_offset), chunkIndex(_chunkIndex), size(_size), isFree(_isFree), nextFree(nullptr) {};
};
struct chunk_t
{
std::unordered_map<uint32, allocRange_t*> map_allocatedRange;
};
public:
ChunkedHeap()
{
}
CHAddr alloc(uint32 size, uint32 alignment = 4)
{
return _alloc(size, alignment);
}
void free(CHAddr addr)
{
_free(addr);
}
virtual uint32 allocateNewChunk(uint32 chunkIndex, uint32 minimumAllocationSize)
{
return 0;
}
private:
unsigned ulog2(uint32 v)
{
static const unsigned MUL_DE_BRUIJN_BIT[] =
{
0, 9, 1, 10, 13, 21, 2, 29, 11, 14, 16, 18, 22, 25, 3, 30,
8, 12, 20, 28, 15, 17, 24, 7, 19, 27, 23, 6, 26, 5, 4, 31
};
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
return MUL_DE_BRUIJN_BIT[(v * 0x07C4ACDDu) >> 27];
}
void trackFreeRange(allocRange_t* range)
{
// get index of msb
cemu_assert_debug(range->size != 0); // size of zero is not allowed
uint32 bucketIndex = ulog2(range->size);
range->nextFree = bucketFreeRange[bucketIndex];
if (bucketFreeRange[bucketIndex])
bucketFreeRange[bucketIndex]->prevFree = range;
range->prevFree = nullptr;
bucketFreeRange[bucketIndex] = range;
}
void forgetFreeRange(allocRange_t* range, uint32 bucketIndex)
{
allocRange_t* prevRange = range->prevFree;
allocRange_t* nextRange = range->nextFree;
if (prevRange)
{
prevRange->nextFree = nextRange;
if (nextRange)
nextRange->prevFree = prevRange;
}
else
{
if (bucketFreeRange[bucketIndex] != range)
assert_dbg();
bucketFreeRange[bucketIndex] = nextRange;
if (nextRange)
nextRange->prevFree = nullptr;
}
}
bool allocateChunk(uint32 minimumAllocationSize)
{
uint32 chunkIndex = (uint32)list_chunks.size();
list_chunks.emplace_back(new chunk_t());
uint32 chunkSize = allocateNewChunk(chunkIndex, minimumAllocationSize);
if (chunkSize == 0)
return false;
allocRange_t* range = new allocRange_t(0, chunkIndex, chunkSize, true);
trackFreeRange(range);
numHeapBytes += chunkSize;
return true;
}
void _allocFrom(allocRange_t* range, uint32 bucketIndex, uint32 allocOffset, uint32 allocSize)
{
// remove the range from the chain of free ranges
forgetFreeRange(range, bucketIndex);
// split head, allocation and tail into separate ranges
if (allocOffset > range->offset)
{
// alignment padding -> create free range
allocRange_t* head = new allocRange_t(range->offset, range->chunkIndex, allocOffset - range->offset, true);
trackFreeRange(head);
if (range->prevOrdered)
range->prevOrdered->nextOrdered = head;
head->prevOrdered = range->prevOrdered;
head->nextOrdered = range;
range->prevOrdered = head;
}
if ((allocOffset + allocSize) < (range->offset + range->size)) // todo - create only if it's more than a couple of bytes?
{
// tail -> create free range
allocRange_t* tail = new allocRange_t((allocOffset + allocSize), range->chunkIndex, (range->offset + range->size) - (allocOffset + allocSize), true);
trackFreeRange(tail);
if (range->nextOrdered)
range->nextOrdered->prevOrdered = tail;
tail->prevOrdered = range;
tail->nextOrdered = range->nextOrdered;
range->nextOrdered = tail;
}
range->offset = allocOffset;
range->size = allocSize;
range->isFree = false;
}
CHAddr _alloc(uint32 size, uint32 alignment)
{
// find smallest bucket to scan
uint32 alignmentM1 = alignment - 1;
uint32 bucketIndex = ulog2(size);
while (bucketIndex < 32)
{
allocRange_t* range = bucketFreeRange[bucketIndex];
while (range)
{
if (range->size >= size)
{
// verify if aligned allocation fits
uint32 alignedOffset = (range->offset + alignmentM1) & ~alignmentM1;
uint32 alignmentLoss = alignedOffset - range->offset;
if (alignmentLoss < range->size && (range->size - alignmentLoss) >= size)
{
_allocFrom(range, bucketIndex, alignedOffset, size);
list_chunks[range->chunkIndex]->map_allocatedRange.emplace(alignedOffset, range);
numAllocatedBytes += size;
return CHAddr(alignedOffset, range->chunkIndex);
}
}
range = range->nextFree;
}
bucketIndex++; // try higher bucket
}
if(allocationLimitReached)
return CHAddr(0xFFFFFFFF, 0xFFFFFFFF);
if (!allocateChunk(size))
{
allocationLimitReached = true;
return CHAddr(0xFFFFFFFF, 0xFFFFFFFF);
}
return _alloc(size, alignment);
}
void _free(CHAddr addr)
{
auto it = list_chunks[addr.chunkIndex]->map_allocatedRange.find(addr.offset);
if (it == list_chunks[addr.chunkIndex]->map_allocatedRange.end())
{
cemuLog_log(LogType::Force, "Internal heap error. {:08x} {:08x}", addr.chunkIndex, addr.offset);
cemuLog_log(LogType::Force, "Debug info:");
for (auto& rangeItr : list_chunks[addr.chunkIndex]->map_allocatedRange)
{
cemuLog_log(LogType::Force, "{:08x} {:08x}", rangeItr.second->offset, rangeItr.second->size);
}
return;
}
allocRange_t* range = it->second;
numAllocatedBytes -= it->second->size;
list_chunks[range->chunkIndex]->map_allocatedRange.erase(it);
// try merge left or right
allocRange_t* prevRange = range->prevOrdered;
allocRange_t* nextRange = range->nextOrdered;
if (prevRange && prevRange->isFree)
{
if (nextRange && nextRange->isFree)
{
forgetFreeRange(nextRange, ulog2(nextRange->size));
uint32 newSize = (nextRange->offset + nextRange->size) - prevRange->offset;
prevRange->nextOrdered = nextRange->nextOrdered;
if (nextRange->nextOrdered)
nextRange->nextOrdered->prevOrdered = prevRange;
forgetFreeRange(prevRange, ulog2(prevRange->size));
prevRange->size = newSize;
trackFreeRange(prevRange);
delete range;
delete nextRange;
}
else
{
uint32 newSize = (range->offset + range->size) - prevRange->offset;
prevRange->nextOrdered = nextRange;
if (nextRange)
nextRange->prevOrdered = prevRange;
forgetFreeRange(prevRange, ulog2(prevRange->size));
prevRange->size = newSize;
trackFreeRange(prevRange);
delete range;
}
}
else if (nextRange && nextRange->isFree)
{
uint32 newOffset = range->offset;
uint32 newSize = (nextRange->offset + nextRange->size) - newOffset;
forgetFreeRange(nextRange, ulog2(nextRange->size));
nextRange->offset = newOffset;
nextRange->size = newSize;
if (range->prevOrdered)
range->prevOrdered->nextOrdered = nextRange;
nextRange->prevOrdered = range->prevOrdered;
trackFreeRange(nextRange);
delete range;
}
else
{
range->isFree = true;
trackFreeRange(range);
}
}
void verifyHeap()
{
// check for collisions within bucketFreeRange
struct availableRange_t
{
uint32 chunkIndex;
uint32 offset;
uint32 size;
};
std::vector<availableRange_t> availRanges;
for (uint32 i = 0; i < 32; i++)
{
allocRange_t* ar = bucketFreeRange[i];
while (ar)
{
availableRange_t dbgRange;
dbgRange.chunkIndex = ar->chunkIndex;
dbgRange.offset = ar->offset;
dbgRange.size = ar->size;
for (auto& itr : availRanges)
{
if (itr.chunkIndex != dbgRange.chunkIndex)
continue;
if (itr.offset < (dbgRange.offset + dbgRange.size) && (itr.offset + itr.size) >(dbgRange.offset))
assert_dbg();
}
availRanges.emplace_back(dbgRange);
ar = ar->nextFree;
}
}
}
private:
std::vector<chunk_t*> list_chunks;
allocRange_t* bucketFreeRange[32]{};
bool allocationLimitReached = false;
public:
// statistics
uint32 numHeapBytes{}; // total size of the heap
uint32 numAllocatedBytes{};
};
class VGenericHeap
{
public:
virtual void* alloc(uint32 size, uint32 alignment) = 0;
virtual void free(void* addr) = 0;
};
class VHeap : public VGenericHeap
{
struct allocRange_t
{
allocRange_t* nextFree{};
allocRange_t* prevFree{};
allocRange_t* prevOrdered{};
allocRange_t* nextOrdered{};
uint32 offset;
uint32 size;
bool isFree;
allocRange_t(uint32 _offset, uint32 _size, bool _isFree) : offset(_offset), size(_size), isFree(_isFree), nextFree(nullptr) {};
};
struct chunk_t
{
std::unordered_map<uint32, allocRange_t*> map_allocatedRange;
};
public:
VHeap(void* heapBase, uint32 heapSize) : m_heapBase((uint8*)heapBase), m_heapSize(heapSize)
{
allocRange_t* range = new allocRange_t(0, heapSize, true);
trackFreeRange(range);
}
~VHeap()
{
for (auto freeRange : bucketFreeRange)
{
while (freeRange)
{
auto temp = freeRange;
freeRange = freeRange->nextFree;
delete temp;
}
}
}
void setHeapBase(void* heapBase)
{
cemu_assert_debug(map_allocatedRange.empty()); // heap base can only be changed when there are no active allocations
m_heapBase = (uint8*)heapBase;
}
void* alloc(uint32 size, uint32 alignment = 4) override
{
cemu_assert_debug(m_heapBase != nullptr); // if this is null, we cant use alloc() == nullptr to determine if an allocation failed
uint32 allocOffset = 0;
bool r = _alloc(size, alignment, allocOffset);
if (!r)
return nullptr;
return m_heapBase + allocOffset;
}
void free(void* addr) override
{
_free((uint32)((uint8*)addr - (uint8*)m_heapBase));
}
bool allocOffset(uint32 size, uint32 alignment, uint32& offsetOut)
{
uint32 allocOffset = 0;
bool r = _alloc(size, alignment, allocOffset);
if (!r)
return false;
offsetOut = allocOffset;
return true;
}
void freeOffset(uint32 offset)
{
_free((uint32)offset);
}
uint32 getAllocationSizeFromAddr(void* addr)
{
uint32 addrOffset = (uint32)((uint8*)addr - m_heapBase);
auto it = map_allocatedRange.find(addrOffset);
if (it == map_allocatedRange.end())
assert_dbg();
return it->second->size;
}
bool hasAllocations()
{
return !map_allocatedRange.empty();
}
void getStats(uint32& heapSize, uint32& allocationSize, uint32& allocNum)
{
heapSize = m_heapSize;
allocationSize = m_statsMemAllocated;
allocNum = (uint32)map_allocatedRange.size();
}
private:
unsigned ulog2(uint32 v)
{
static const unsigned MUL_DE_BRUIJN_BIT[] =
{
0, 9, 1, 10, 13, 21, 2, 29, 11, 14, 16, 18, 22, 25, 3, 30,
8, 12, 20, 28, 15, 17, 24, 7, 19, 27, 23, 6, 26, 5, 4, 31
};
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
return MUL_DE_BRUIJN_BIT[(v * 0x07C4ACDDu) >> 27];
}
void trackFreeRange(allocRange_t* range)
{
// get index of msb
if (range->size == 0)
assert_dbg(); // not allowed
uint32 bucketIndex = ulog2(range->size);
range->nextFree = bucketFreeRange[bucketIndex];
if (bucketFreeRange[bucketIndex])
bucketFreeRange[bucketIndex]->prevFree = range;
range->prevFree = nullptr;
bucketFreeRange[bucketIndex] = range;
}
void forgetFreeRange(allocRange_t* range, uint32 bucketIndex)
{
allocRange_t* prevRange = range->prevFree;
allocRange_t* nextRange = range->nextFree;
if (prevRange)
{
prevRange->nextFree = nextRange;
if (nextRange)
nextRange->prevFree = prevRange;
}
else
{
if (bucketFreeRange[bucketIndex] != range)
assert_dbg();
bucketFreeRange[bucketIndex] = nextRange;
if (nextRange)
nextRange->prevFree = nullptr;
}
}
void _allocFrom(allocRange_t* range, uint32 bucketIndex, uint32 allocOffset, uint32 allocSize)
{
// remove the range from the chain of free ranges
forgetFreeRange(range, bucketIndex);
// split head, allocation and tail into separate ranges
if (allocOffset > range->offset)
{
// alignment padding -> create free range
allocRange_t* head = new allocRange_t(range->offset, allocOffset - range->offset, true);
trackFreeRange(head);
if (range->prevOrdered)
range->prevOrdered->nextOrdered = head;
head->prevOrdered = range->prevOrdered;
head->nextOrdered = range;
range->prevOrdered = head;
}
if ((allocOffset + allocSize) < (range->offset + range->size)) // todo - create only if it's more than a couple of bytes?
{
// tail -> create free range
allocRange_t* tail = new allocRange_t((allocOffset + allocSize), (range->offset + range->size) - (allocOffset + allocSize), true);
trackFreeRange(tail);
if (range->nextOrdered)
range->nextOrdered->prevOrdered = tail;
tail->prevOrdered = range;
tail->nextOrdered = range->nextOrdered;
range->nextOrdered = tail;
}
range->offset = allocOffset;
range->size = allocSize;
range->isFree = false;
m_statsMemAllocated += allocSize;
}
bool _alloc(uint32 size, uint32 alignment, uint32& allocOffsetOut)
{
if(size == 0)
{
size = 1; // zero-sized allocations are not supported
cemu_assert_suspicious();
}
// find smallest bucket to scan
uint32 alignmentM1 = alignment - 1;
uint32 bucketIndex = ulog2(size);
while (bucketIndex < 32)
{
allocRange_t* range = bucketFreeRange[bucketIndex];
while (range)
{
if (range->size >= size)
{
// verify if aligned allocation fits
uint32 alignedOffset = (range->offset + alignmentM1) & ~alignmentM1;
uint32 alignmentLoss = alignedOffset - range->offset;
if (alignmentLoss < range->size && (range->size - alignmentLoss) >= size)
{
_allocFrom(range, bucketIndex, alignedOffset, size);
map_allocatedRange.emplace(alignedOffset, range);
allocOffsetOut = alignedOffset;
return true;
}
}
range = range->nextFree;
}
bucketIndex++; // try higher bucket
}
return false;
}
void _free(uint32 addrOffset)
{
auto it = map_allocatedRange.find(addrOffset);
if (it == map_allocatedRange.end())
{
cemuLog_log(LogType::Force, "VHeap internal error");
cemu_assert(false);
}
allocRange_t* range = it->second;
map_allocatedRange.erase(it);
m_statsMemAllocated -= range->size;
// try merge left or right
allocRange_t* prevRange = range->prevOrdered;
allocRange_t* nextRange = range->nextOrdered;
if (prevRange && prevRange->isFree)
{
if (nextRange && nextRange->isFree)
{
forgetFreeRange(nextRange, ulog2(nextRange->size));
uint32 newSize = (nextRange->offset + nextRange->size) - prevRange->offset;
prevRange->nextOrdered = nextRange->nextOrdered;
if (nextRange->nextOrdered)
nextRange->nextOrdered->prevOrdered = prevRange;
forgetFreeRange(prevRange, ulog2(prevRange->size));
prevRange->size = newSize;
trackFreeRange(prevRange);
delete range;
delete nextRange;
}
else
{
uint32 newSize = (range->offset + range->size) - prevRange->offset;
prevRange->nextOrdered = nextRange;
if (nextRange)
nextRange->prevOrdered = prevRange;
forgetFreeRange(prevRange, ulog2(prevRange->size));
prevRange->size = newSize;
trackFreeRange(prevRange);
delete range;
}
}
else if (nextRange && nextRange->isFree)
{
uint32 newOffset = range->offset;
uint32 newSize = (nextRange->offset + nextRange->size) - newOffset;
forgetFreeRange(nextRange, ulog2(nextRange->size));
nextRange->offset = newOffset;
nextRange->size = newSize;
if (range->prevOrdered)
range->prevOrdered->nextOrdered = nextRange;
nextRange->prevOrdered = range->prevOrdered;
trackFreeRange(nextRange);
delete range;
}
else
{
range->isFree = true;
trackFreeRange(range);
}
}
private:
allocRange_t* bucketFreeRange[32]{};
std::unordered_map<uint32, allocRange_t*> map_allocatedRange;
uint8* m_heapBase;
const uint32 m_heapSize;
uint32 m_statsMemAllocated{ 0 };
};
template<uint32 TChunkSize>
class ChunkedFlatAllocator
{
public:
void setBaseAllocator(VGenericHeap* baseHeap)
{
m_currentBaseAllocator = baseHeap;
}
void* alloc(uint32 size, uint32 alignment = 4)
{
if (m_currentBlockPtr)
{
m_currentBlockOffset = (m_currentBlockOffset + alignment - 1) & ~(alignment - 1);
if ((m_currentBlockOffset+size) <= TChunkSize)
{
void* allocPtr = m_currentBlockPtr + m_currentBlockOffset;
m_currentBlockOffset += size;
return allocPtr;
}
}
allocateAdditionalChunk();
return alloc(size, alignment);
}
void releaseAll()
{
for (auto it : m_allocatedBlocks)
m_currentBaseAllocator->free(it);
m_allocatedBlocks.clear();
m_currentBlockPtr = nullptr;
m_currentBlockOffset = 0;
}
void forEachBlock(void(*funcCb)(void* mem, uint32 size))
{
for (auto it : m_allocatedBlocks)
funcCb(it, TChunkSize);
}
uint32 getCurrentBlockOffset() const { return m_currentBlockOffset; }
uint8* getCurrentBlockPtr() const { return m_currentBlockPtr; }
private:
void allocateAdditionalChunk()
{
m_currentBlockPtr = (uint8*)m_currentBaseAllocator->alloc(TChunkSize, 256);
m_currentBlockOffset = 0;
m_allocatedBlocks.emplace_back(m_currentBlockPtr);
}
VGenericHeap* m_currentBaseAllocator{};
uint8* m_currentBlockPtr{};
uint32 m_currentBlockOffset{};
std::vector<void*> m_allocatedBlocks;
};
| 17,381
|
C++
|
.h
| 592
| 25.974662
| 174
| 0.704979
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,330
|
bmp.h
|
cemu-project_Cemu/src/util/ImageWriter/bmp.h
|
#include "Common/FileStream.h"
static void _bmp_write(FileStream* fs, sint32 width, sint32 height, uint32 bits, void* pixelData)
{
BITMAPFILEHEADER bmp_fh;
BITMAPINFOHEADER bmp_ih;
bmp_fh.bfType = 0x4d42;
bmp_fh.bfSize = 0;
bmp_fh.bfReserved1 = 0;
bmp_fh.bfReserved2 = 0;
bmp_fh.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
bmp_ih.biSize = sizeof(bmp_ih);
bmp_ih.biWidth = width;
bmp_ih.biHeight = height;
bmp_ih.biPlanes = 1;
bmp_ih.biBitCount = bits;
bmp_ih.biCompression = 0;
bmp_ih.biSizeImage = 0;
bmp_ih.biXPelsPerMeter = 0;
bmp_ih.biYPelsPerMeter = 0;
bmp_ih.biClrUsed = 0;
bmp_ih.biClrImportant = 0;
sint32 rowPitch = (width * bits / 8);
rowPitch = (rowPitch + 3)&~3;
uint8 padding[4] = { 0 };
sint32 paddingLength = rowPitch - (width * bits / 8);
bmp_ih.biSize = sizeof(BITMAPINFOHEADER);
bmp_fh.bfSize = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + rowPitch * height;
fs->writeData(&bmp_fh, sizeof(BITMAPFILEHEADER));
fs->writeData(&bmp_ih, sizeof(BITMAPINFOHEADER));
if (bits == 24 || bits == 32)
{
for (sint32 y = 0; y < height; y++)
{
void* rowInput = ((uint8*)pixelData) + rowPitch * (height - y - 1);
fs->writeData(rowInput, width*bits/8);
// write padding
if(paddingLength > 0)
fs->writeData(padding, paddingLength);
}
}
}
static bool bmp_store8BitAs24(wchar_t* path, sint32 width, sint32 height, sint32 bytesPerRow, void* pixelData)
{
FileStream* fs = FileStream::createFile(path);
if (fs == nullptr)
return false;
uint8* pixelI = (uint8*)pixelData;
uint8* pixelRGB = (uint8*)malloc(width * height * 3);
for (sint32 y = 0; y < height; y++)
{
sint32 srcIdx = y * bytesPerRow;
for (sint32 x = 0; x < width; x++)
{
sint32 dstIdx = x + y * width;
pixelRGB[dstIdx * 3 + 0] = pixelI[srcIdx];
pixelRGB[dstIdx * 3 + 1] = pixelI[srcIdx];
pixelRGB[dstIdx * 3 + 2] = pixelI[srcIdx];
srcIdx++;
}
}
_bmp_write(fs, width, height, 24, pixelRGB);
free(pixelRGB);
delete fs;
return true;
}
static bool bmp_store16BitAs24(wchar_t* path, sint32 width, sint32 height, sint32 bytesPerRow, void* pixelData)
{
FileStream* fs = FileStream::createFile(path);
if (fs == nullptr)
return false;
uint8* pixelI = (uint8*)pixelData;
uint8* pixelRGB = (uint8*)malloc(width * height * 3);
for (sint32 y = 0; y < height; y++)
{
sint32 srcIdx = y * bytesPerRow;
for (sint32 x = 0; x < width; x++)
{
sint32 dstIdx = x + y * width;
pixelRGB[dstIdx * 3 + 0] = pixelI[srcIdx + 0];
pixelRGB[dstIdx * 3 + 1] = pixelI[srcIdx + 1];
pixelRGB[dstIdx * 3 + 2] = 0;
srcIdx += 2;
}
}
_bmp_write(fs, width, height, 24, pixelRGB);
free(pixelRGB);
delete fs;
return true;
}
static bool bmp_store24BitAs24(wchar_t* path, sint32 width, sint32 height, sint32 bytesPerRow, void* pixelData)
{
FileStream* fs = FileStream::createFile(path);
if (fs == nullptr)
return false;
uint8* pixelI = (uint8*)pixelData;
uint8* pixelRGB = (uint8*)malloc(width * height * 3);
for (sint32 y = 0; y < height; y++)
{
sint32 srcIdx = y * bytesPerRow;
for (sint32 x = 0; x < width; x++)
{
sint32 dstIdx = x + y * width;
pixelRGB[dstIdx * 3 + 0] = pixelI[srcIdx + 0];
pixelRGB[dstIdx * 3 + 1] = pixelI[srcIdx + 1];
pixelRGB[dstIdx * 3 + 2] = pixelI[srcIdx + 2];
srcIdx += 3;
}
}
_bmp_write(fs, width, height, 24, pixelRGB);
free(pixelRGB);
delete fs;
return true;
}
| 3,409
|
C++
|
.h
| 113
| 27.637168
| 111
| 0.674992
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,331
|
tga.h
|
cemu-project_Cemu/src/util/ImageWriter/tga.h
|
#include "Common/FileStream.h"
#include <vector>
static bool tga_write_rgba(wchar_t* path, sint32 width, sint32 height, uint8* pixelData)
{
FileStream* fs = FileStream::createFile(path);
if (fs == nullptr)
return false;
uint8_t header[18] = {0,0,2,0,0,0,0,0,0,0,0,0, (uint8)(width % 256), (uint8)(width / 256), (uint8)(height % 256), (uint8)(height / 256), 32, 0x20};
fs->writeData(&header, sizeof(header));
std::vector<uint8> tempPixelData;
tempPixelData.resize(width * height * 4);
// write one row at a time
uint8* pOut = tempPixelData.data();
for (sint32 y = 0; y < height; y++)
{
const uint8* rowIn = pixelData + y * width*4;
for (sint32 x = 0; x < width; x++)
{
pOut[0] = rowIn[2];
pOut[1] = rowIn[1];
pOut[2] = rowIn[0];
pOut[3] = rowIn[3];
pOut += 4;
rowIn += 4;
}
}
fs->writeData(tempPixelData.data(), width * height * 4);
delete fs;
return true;
}
| 905
|
C++
|
.h
| 30
| 27.6
| 148
| 0.645235
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,332
|
ScreenSaver.h
|
cemu-project_Cemu/src/util/ScreenSaver/ScreenSaver.h
|
#include "Cemu/Logging/CemuLogging.h"
#include <SDL2/SDL.h>
class ScreenSaver
{
public:
static void SetInhibit(bool inhibit)
{
// temporary workaround because feature crashes on macOS
#if BOOST_OS_MACOS
return;
#endif
// Initialize video subsystem if necessary
if (SDL_WasInit(SDL_INIT_VIDEO) == 0)
{
int initErr = SDL_InitSubSystem(SDL_INIT_VIDEO);
if (initErr)
{
cemuLog_log(LogType::Force, "Could not disable screen saver (SDL video subsystem initialization error)");
}
}
// Toggle SDL's screen saver inhibition
if (inhibit)
{
SDL_DisableScreenSaver();
if (SDL_IsScreenSaverEnabled() == SDL_TRUE)
{
cemuLog_log(LogType::Force, "Could not verify if screen saver was disabled (`SDL_IsScreenSaverEnabled()` returned SDL_TRUE)");
}
}
else
{
SDL_EnableScreenSaver();
if (SDL_IsScreenSaverEnabled() == SDL_FALSE)
{
cemuLog_log(LogType::Force, "Could not verify if screen saver was re-enabled (`SDL_IsScreenSaverEnabled()` returned SDL_FALSE)");
}
}
};
};
| 1,105
|
C++
|
.h
| 39
| 23.410256
| 137
| 0.665728
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,333
|
MemoryPool.h
|
cemu-project_Cemu/src/util/helpers/MemoryPool.h
|
#pragma once
template<typename T>
class MemoryPool
{
static_assert(sizeof(T) >= sizeof(void*)); // object must be large enough to store a single pointer
public:
MemoryPool(int allocationGranularity)
: m_numObjectsAllocated(0)
{
m_allocationGranularity = allocationGranularity;
m_nextFreeObject = nullptr;
}
template <typename... Ts>
T* allocObj(Ts&&... args)
{
if (m_nextFreeObject)
{
T* allocatedObj = m_nextFreeObject;
m_nextFreeObject = *(T**)allocatedObj;
new (allocatedObj) T(std::forward<Ts>(args)...);
return allocatedObj;
}
// enlarge pool
increasePoolSize();
T* allocatedObj = m_nextFreeObject;
m_nextFreeObject = *(T**)allocatedObj;
new (allocatedObj) T(std::forward<Ts>(args)...);
return allocatedObj;
}
void freeObj(T* obj)
{
obj->~T();
pushElementOnFreeStack(obj);
}
private:
void pushElementOnFreeStack(T* obj)
{
*(T**)obj = m_nextFreeObject;
m_nextFreeObject = obj;
}
void increasePoolSize()
{
T* newElements = static_cast<T*>(::operator new(m_allocationGranularity * sizeof(T), std::nothrow));
m_numObjectsAllocated += m_allocationGranularity;
for (int i = 0; i < m_allocationGranularity; i++)
{
pushElementOnFreeStack(newElements);
newElements++;
}
}
private:
T* m_nextFreeObject;
int m_allocationGranularity;
int m_numObjectsAllocated;
};
// this memory pool calls the default constructor when the internal pool is allocated
// no constructor/destructor will be called on acquire/release
template<typename T>
class MemoryPoolPermanentObjects
{
struct internalObject_t
{
T v;
internalObject_t* next;
};
public:
MemoryPoolPermanentObjects(int allocationGranularity)
: m_numObjectsAllocated(0)
{
m_allocationGranularity = allocationGranularity;
m_nextFreeObject = nullptr;
}
template <typename... Ts>
T* acquireObj(Ts&&... args)
{
if (m_nextFreeObject)
{
internalObject_t* allocatedObject = m_nextFreeObject;
m_nextFreeObject = allocatedObject->next;
return &allocatedObject->v;
}
// enlarge pool
increasePoolSize();
internalObject_t* allocatedObject = m_nextFreeObject;
m_nextFreeObject = allocatedObject->next;
return &allocatedObject->v;
}
void releaseObj(T* obj)
{
internalObject_t* internalObj = (internalObject_t*)((uint8*)obj - offsetof(internalObject_t, v));
pushElementOnFreeStack(internalObj);
}
private:
void pushElementOnFreeStack(internalObject_t* obj)
{
obj->next = m_nextFreeObject;
m_nextFreeObject = obj;
}
void increasePoolSize()
{
internalObject_t* newElements = static_cast<internalObject_t*>(::operator new(m_allocationGranularity * sizeof(internalObject_t), std::nothrow));
m_numObjectsAllocated += m_allocationGranularity;
for (int i = 0; i < m_allocationGranularity; i++)
{
new (&newElements->v) T();
pushElementOnFreeStack(newElements);
newElements++;
}
}
private:
internalObject_t* m_nextFreeObject;
int m_allocationGranularity;
int m_numObjectsAllocated;
};
| 2,977
|
C++
|
.h
| 114
| 23.561404
| 147
| 0.748421
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,334
|
Singleton.h
|
cemu-project_Cemu/src/util/helpers/Singleton.h
|
#pragma once
template<typename TType>
class Singleton
{
protected:
Singleton() = default;
Singleton(const Singleton&) = delete;
Singleton(Singleton&&) noexcept = delete;
public:
static TType& instance() noexcept
{
static TType s_instance;
return s_instance;
}
};
| 275
|
C++
|
.h
| 15
| 16.533333
| 42
| 0.771318
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,335
|
ConcurrentQueue.h
|
cemu-project_Cemu/src/util/helpers/ConcurrentQueue.h
|
#pragma once
#include <mutex>
#include <condition_variable>
#include <queue>
template <typename T>
class ConcurrentQueue
{
public:
ConcurrentQueue() = default;
ConcurrentQueue(const ConcurrentQueue&) = delete;
ConcurrentQueue& operator=(const ConcurrentQueue&) = delete;
size_t push(const T& item)
{
std::unique_lock<std::mutex> mlock(m_mutex);
m_queue.push(item);
const size_t result = m_queue.size();
mlock.unlock();
m_condVar.notify_one();
return result;
}
template<typename ... Args>
size_t push(Args&& ... args)
{
std::unique_lock<std::mutex> mlock(m_mutex);
m_queue.emplace(std::forward<Args>(args)...);
const size_t result = m_queue.size();
mlock.unlock();
m_condVar.notify_one();
return result;
}
T peek()
{
std::unique_lock<std::mutex> mlock(m_mutex);
while (m_queue.empty())
{
m_condVar.wait(mlock);
}
return m_queue.front();
}
bool peek2(T& item)
{
std::unique_lock<std::mutex> mlock(m_mutex);
if (m_queue.empty())
return false;
item = m_queue.front();
m_queue.pop();
return true;
}
T pop()
{
std::unique_lock<std::mutex> mlock(m_mutex);
while (m_queue.empty())
{
m_condVar.wait(mlock);
}
auto val = m_queue.front();
m_queue.pop();
return val;
}
void pop(T& item)
{
std::unique_lock<std::mutex> mlock(m_mutex);
while (m_queue.empty())
{
m_condVar.wait(mlock);
}
item = m_queue.front();
m_queue.pop();
}
void clear()
{
std::unique_lock<std::mutex> mlock(m_mutex);
while (!m_queue.empty())
m_queue.pop();
}
size_t size()
{
std::unique_lock<std::mutex> mlock(m_mutex);
return m_queue.size();
}
bool empty()
{
std::unique_lock<std::mutex> mlock(m_mutex);
return m_queue.empty();
}
private:
std::mutex m_mutex;
std::condition_variable m_condVar;
std::queue<T> m_queue;
};
| 1,825
|
C++
|
.h
| 90
| 17.644444
| 61
| 0.669767
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,336
|
Serializer.h
|
cemu-project_Cemu/src/util/helpers/Serializer.h
|
#pragma once
class MemStreamReader
{
public:
MemStreamReader(const uint8* data, sint32 size) : m_data(data), m_size(size)
{
m_cursorPos = 0;
}
template<typename T> T readBE();
template<typename T> T readLE();
template<typename T>
std::vector<T> readPODVector()
{
uint32 numElements = readBE<uint32>();
if (hasError())
{
return std::vector<T>();
}
std::vector<T> v;
v.reserve(numElements);
v.resize(numElements);
readData(v.data(), v.size() * sizeof(T));
return v;
}
// read string terminated by newline character (or end of stream)
// will also trim off any carriage return
std::string_view readLine()
{
size_t length = 0;
if (m_cursorPos >= m_size)
{
m_hasError = true;
return std::basic_string_view((const char*)nullptr, 0);
}
// end of line is determined by '\n'
const char* lineStrBegin = (const char*)(m_data + m_cursorPos);
const char* lineStrEnd = nullptr;
while (m_cursorPos < m_size)
{
if (m_data[m_cursorPos] == '\n')
{
lineStrEnd = (const char*)(m_data + m_cursorPos);
m_cursorPos++; // skip the newline character
break;
}
m_cursorPos++;
}
if(lineStrEnd == nullptr)
lineStrEnd = (const char*)(m_data + m_cursorPos);
// truncate any '\r' at the beginning and end
while (lineStrBegin < lineStrEnd)
{
if (lineStrBegin[0] != '\r')
break;
lineStrBegin++;
}
while (lineStrEnd > lineStrBegin)
{
if (lineStrEnd[-1] != '\r')
break;
lineStrEnd--;
}
length = (lineStrEnd - lineStrBegin);
return std::basic_string_view((const char*)lineStrBegin, length);
}
bool readData(void* ptr, size_t size)
{
if (m_cursorPos + size > m_size)
{
m_cursorPos = m_size;
m_hasError = true;
return false;
}
memcpy(ptr, m_data + m_cursorPos, size);
m_cursorPos += (sint32)size;
return true;
}
std::span<uint8> readDataNoCopy(size_t size)
{
if (m_cursorPos + size > m_size)
{
m_cursorPos = m_size;
m_hasError = true;
return std::span<uint8>();
}
auto r = std::span<uint8>((uint8*)m_data + m_cursorPos, size);
m_cursorPos += (sint32)size;
return r;
}
// returns true if any of the reads was out of bounds
bool hasError() const
{
return m_hasError;
}
bool isEndOfStream() const
{
return m_cursorPos == m_size;
}
private:
bool reserveReadLength(size_t length)
{
if (m_cursorPos + length > m_size)
{
m_cursorPos = m_size;
m_hasError = true;
return false;
}
return true;
}
void skipCRLF()
{
while (m_cursorPos < m_size)
{
if (m_data[m_cursorPos] != '\r' && m_data[m_cursorPos] != '\n')
break;
m_cursorPos++;
}
}
const uint8* m_data;
sint32 m_size;
sint32 m_cursorPos;
bool m_hasError{ false };
};
class MemStreamWriter
{
public:
MemStreamWriter(size_t reservedSize)
{
if (reservedSize > 0)
m_buffer.reserve(reservedSize);
else
m_buffer.reserve(128);
}
void writeData(const void* ptr, size_t size)
{
m_buffer.resize(m_buffer.size() + size);
uint8* p = m_buffer.data() + m_buffer.size() - size;
memcpy(p, ptr, size);
}
template<typename T> void writeBE(const T& v);
template<typename T> void writeLE(const T& v);
template<typename T>
void writePODVector(const std::vector<T>& v)
{
writeBE<uint32>(v.size());
writeData(v.data(), v.size() * sizeof(T));
}
// get result buffer without copy
// resets internal state
void getResultAndReset(std::vector<uint8>& data)
{
std::swap(m_buffer, data);
m_buffer.clear();
}
std::span<uint8> getResult()
{
return std::span<uint8>(m_buffer.data(), m_buffer.size());
}
private:
std::vector<uint8> m_buffer;
};
class SerializerHelper
{
public:
bool serialize(std::vector<uint8>& data)
{
MemStreamWriter streamWriter(0);
bool r = serializeImpl(streamWriter);
if (!r)
return false;
streamWriter.getResultAndReset(data);
return true;
}
bool deserialize(std::vector<uint8>& data)
{
MemStreamReader memStreamReader(data.data(), (sint32)data.size());
return deserializeImpl(memStreamReader);
}
protected:
virtual bool serializeImpl(MemStreamWriter& streamWriter) = 0;
virtual bool deserializeImpl(MemStreamReader& streamReader) = 0;
};
| 4,159
|
C++
|
.h
| 182
| 20.065934
| 77
| 0.681577
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,337
|
StringBuf.h
|
cemu-project_Cemu/src/util/helpers/StringBuf.h
|
#pragma once
class StringBuf
{
public:
StringBuf(uint32 bufferSize)
{
this->str = (uint8*)malloc(bufferSize + 4);
this->allocated = true;
this->length = 0;
this->limit = bufferSize;
}
~StringBuf()
{
if (this->allocated)
free(this->str);
}
template<typename TFmt, typename ... TArgs>
void addFmt(const TFmt& format, TArgs&&... args)
{
auto r = fmt::vformat_to_n((char*)(this->str + this->length), (size_t)(this->limit - this->length), fmt::detail::to_string_view(format), fmt::make_format_args(args...));
this->length += (uint32)r.size;
}
void add(const char* appendedStr)
{
const char* outputStart = (char*)(this->str + this->length);
char* output = (char*)outputStart;
const char* outputEnd = (char*)(this->str + this->limit - 1);
while (output < outputEnd)
{
char c = *appendedStr;
if (c == '\0')
break;
*output = c;
appendedStr++;
output++;
}
this->length += (uint32)(output - outputStart);
*output = '\0';
}
void add(std::string_view appendedStr)
{
size_t remainingLen = this->limit - this->length;
size_t copyLen = appendedStr.size();
if (remainingLen < copyLen)
copyLen = remainingLen;
char* outputStart = (char*)(this->str + this->length);
std::copy(appendedStr.data(), appendedStr.data() + copyLen, outputStart);
length += copyLen;
outputStart[copyLen] = '\0';
}
void reset()
{
length = 0;
}
uint32 getLen() const
{
return length;
}
const char* c_str() const
{
str[length] = '\0';
return (const char*)str;
}
void shrink_to_fit()
{
if (!this->allocated)
return;
uint32 newLimit = this->length;
this->str = (uint8*)realloc(this->str, newLimit + 4);
this->limit = newLimit;
}
private:
uint8* str;
uint32 length; /* in bytes */
uint32 limit; /* in bytes */
bool allocated;
};
| 1,809
|
C++
|
.h
| 77
| 20.818182
| 171
| 0.656413
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,338
|
ringbuffer.h
|
cemu-project_Cemu/src/util/helpers/ringbuffer.h
|
#pragma once
#include <mutex>
template<typename T, uint32 elements, typename P = uint32>
class RingBuffer
{
public:
RingBuffer();
bool Push(const T& v);
template<class Q = T>
typename std::enable_if< !std::is_array<T>::value, Q >::type
Pop()
{
std::unique_lock<std::mutex> lock(m_mutex);
if (m_readPointer == m_writePointer)
{
return T();
}
const T& tmp = m_data[m_readPointer];
m_readPointer = (m_readPointer + 1) % elements;
return tmp;
}
T& GetSlot();
T& GetSlotAndAdvance();
void Advance();
void Clear();
P GetReadPointer();
P GetWritePointer();
bool HasData();
private:
T m_data[elements];
P m_readPointer;
P m_writePointer;
std::mutex m_mutex;
};
template <typename T, uint32 elements, typename P>
RingBuffer<T, elements, P>::RingBuffer()
: m_readPointer(0), m_writePointer(0)
{
}
template <typename T, uint32 elements, typename P>
bool RingBuffer<T, elements, P>::Push(const T& v)
{
std::unique_lock<std::mutex> lock(m_mutex);
if (m_readPointer == ((m_writePointer + 1) % elements))
{
debugBreakpoint(); // buffer is full
return false;
}
m_data[m_writePointer] = v;
m_writePointer = (m_writePointer + 1) % elements;
return true;
}
template <typename T, uint32 elements, typename P>
T& RingBuffer<T, elements, P>::GetSlot()
{
std::unique_lock<std::mutex> lock(m_mutex);
T& result = m_data[m_writePointer];
m_writePointer = (m_writePointer + 1) % elements;
return result;
}
template <typename T, uint32 elements, typename P>
T& RingBuffer<T, elements, P>::GetSlotAndAdvance()
{
std::unique_lock<std::mutex> lock(m_mutex);
T& result = m_data[m_writePointer];
m_writePointer = (m_writePointer + 1) % elements;
m_readPointer = (m_readPointer + 1) % elements;
return result;
}
template <typename T, uint32 elements, typename P>
void RingBuffer<T, elements, P>::Advance()
{
std::unique_lock<std::mutex> lock(m_mutex);
if (m_readPointer != m_writePointer)
{
m_readPointer = (m_readPointer + 1) % elements;
}
}
template <typename T, uint32 elements, typename P>
void RingBuffer<T, elements, P>::Clear()
{
std::unique_lock<std::mutex> lock(m_mutex);
m_readPointer = 0;
m_writePointer = 0;
}
template <typename T, uint32 elements, typename P>
P RingBuffer<T, elements, P>::GetReadPointer()
{
std::unique_lock<std::mutex> lock(m_mutex);
P tmp = m_readPointer;
return tmp;
}
template <typename T, uint32 elements, typename P>
P RingBuffer<T, elements, P>::GetWritePointer()
{
std::unique_lock<std::mutex> lock(m_mutex);
P tmp = m_writePointer;
return tmp;
}
template <typename T, uint32 elements, typename P>
bool RingBuffer<T, elements, P>::HasData()
{
std::unique_lock<std::mutex> lock(m_mutex);
return m_readPointer != m_writePointer;
}
| 2,730
|
C++
|
.h
| 105
| 24.085714
| 61
| 0.717525
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,339
|
enum_array.hpp
|
cemu-project_Cemu/src/util/helpers/enum_array.hpp
|
#pragma once
// expects the enum class (T) to have a value called ENUM_COUNT which is the maximum value + 1
template<typename E, class T>
class enum_array : public std::array<T, static_cast<size_t>(E::ENUM_COUNT)> {
public:
T& operator[] (E e) {
return std::array<T, static_cast<size_t>(E::ENUM_COUNT)>::operator[]((std::size_t)e);
}
const T& operator[] (E e) const {
return std::array<T, static_cast<size_t>(E::ENUM_COUNT)>::operator[]((std::size_t)e);
}
};
| 469
|
C++
|
.h
| 12
| 37.25
| 94
| 0.679121
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,340
|
fixedSizeList.h
|
cemu-project_Cemu/src/util/helpers/fixedSizeList.h
|
#pragma once
#include<array>
template<typename T, uint32 maxElements, bool checkMaxSize = true>
class FixedSizeList
{
public:
std::array<T, maxElements> m_elementArray;
int count = 0;
void add(T n)
{
if (checkMaxSize && count >= maxElements)
return;
m_elementArray[count] = n;
count++;
}
void addUnique(T n)
{
if (checkMaxSize && count >= maxElements)
return;
for (int i = 0; i < count; i++)
{
if (m_elementArray[i] == n)
return;
}
m_elementArray[count] = n;
count++;
}
void remove(T n)
{
for (int i = 0; i < count; i++)
{
if (m_elementArray[i] == n)
{
m_elementArray[i] = m_elementArray[count - 1];
count--;
return;
}
}
}
bool containsAndRemove(T n)
{
for (int i = 0; i < count; i++)
{
if (m_elementArray[i] == n)
{
m_elementArray[i] = m_elementArray[count - 1];
count--;
return true;
}
}
return false;
}
sint32 find(T n)
{
for (int i = 0; i < count; i++)
{
if (m_elementArray[i] == n)
{
return i;
}
}
return -1;
}
private:
};
| 1,062
|
C++
|
.h
| 65
| 13.276923
| 66
| 0.598178
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,341
|
Semaphore.h
|
cemu-project_Cemu/src/util/helpers/Semaphore.h
|
#pragma once
#include <mutex>
#include <condition_variable>
class Semaphore
{
public:
void notify()
{
std::lock_guard lock(m_mutex);
++m_count;
m_condition.notify_one();
}
void wait()
{
std::unique_lock lock(m_mutex);
while (m_count == 0)
{
m_condition.wait(lock);
}
--m_count;
}
bool try_wait()
{
std::lock_guard lock(m_mutex);
if (m_count == 0)
return false;
--m_count;
return true;
}
void reset()
{
std::lock_guard lock(m_mutex);
m_count = 0;
}
private:
std::mutex m_mutex;
std::condition_variable m_condition;
uint64 m_count = 0;
};
class CounterSemaphore
{
public:
void reset()
{
std::lock_guard lock(m_mutex);
m_count = 0;
}
void increment()
{
std::lock_guard lock(m_mutex);
++m_count;
if (m_count == 1)
m_condition.notify_all();
}
void decrement()
{
std::lock_guard lock(m_mutex);
--m_count;
cemu_assert_debug(m_count >= 0);
if (m_count == 0)
m_condition.notify_all();
}
// decrement only if non-zero
// otherwise wait
void decrementWithWait()
{
std::unique_lock lock(m_mutex);
while (m_count == 0)
m_condition.wait(lock);
m_count--;
}
// decrement only if non-zero
// otherwise wait
// may wake up spuriously
bool decrementWithWaitAndTimeout(uint32 ms)
{
std::unique_lock lock(m_mutex);
if (m_count == 0)
{
m_condition.wait_for(lock, std::chrono::milliseconds(ms));
}
if (m_count == 0)
return false;
m_count--;
return true;
}
void waitUntilZero()
{
std::unique_lock lock(m_mutex);
while (m_count != 0)
m_condition.wait(lock);
}
void waitUntilNonZero()
{
std::unique_lock lock(m_mutex);
while (m_count == 0)
m_condition.wait(lock);
}
bool isZero() const
{
return m_count == 0;
}
private:
std::mutex m_mutex;
std::condition_variable m_condition;
sint64 m_count = 0;
};
template<typename T>
class StateSemaphore
{
public:
StateSemaphore(T initialState) : m_state(initialState) {};
T getValue()
{
std::unique_lock lock(m_mutex);
return m_state;
}
bool hasState(T state)
{
std::unique_lock lock(m_mutex);
return m_state == state;
}
void setValue(T newState)
{
std::unique_lock lock(m_mutex);
m_state = newState;
m_condition.notify_all();
}
void setValue(T newState, T expectedValue)
{
std::unique_lock lock(m_mutex);
while (m_state != expectedValue)
m_condition.wait(lock);
m_state = newState;
m_condition.notify_all();
}
void waitUntilValue(T state)
{
std::unique_lock lock(m_mutex);
while (m_state != state)
m_condition.wait(lock);
}
private:
std::mutex m_mutex;
std::condition_variable m_condition;
T m_state;
};
| 2,646
|
C++
|
.h
| 147
| 15.455782
| 61
| 0.67811
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,342
|
TempState.h
|
cemu-project_Cemu/src/util/helpers/TempState.h
|
#pragma once
template<typename TCtor, typename TDtor>
class TempState
{
public:
TempState(TCtor ctor, TDtor dtor)
: m_dtor(std::move(dtor))
{
ctor();
}
~TempState()
{
m_dtor();
}
private:
TDtor m_dtor;
};
| 221
|
C++
|
.h
| 17
| 11.058824
| 40
| 0.706468
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,343
|
helpers.h
|
cemu-project_Cemu/src/util/helpers/helpers.h
|
#pragma once
#include <charconv>
#include <filesystem>
#include <string_view>
#include "util/math/vector2.h"
#include "util/math/vector3.h"
#ifdef __clang__
#include "Common/unix/fast_float.h"
#endif
template <typename TType>
constexpr auto to_underlying(TType v) noexcept
{
return static_cast<std::underlying_type_t<TType>>(v);
}
// wrapper to allow reverse iteration with range-based loops before C++20
template<typename T>
class reverse_itr {
private:
T& iterable_;
public:
explicit reverse_itr(T& iterable) : iterable_{ iterable } {}
auto begin() const { return std::rbegin(iterable_); }
auto end() const { return std::rend(iterable_); }
};
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
template<typename T>
T deg2rad(T v) { return v * static_cast<T>(M_PI) / static_cast<T>(180); }
template<typename T>
T rad2deg(T v) { return v * static_cast<T>(180) / static_cast<T>(M_PI); }
template<typename T>
Vector3<T> deg2rad(const Vector3<T>& v) { return { deg2rad(v.x), deg2rad(v.y), deg2rad(v.z) }; }
template<typename T>
Vector3<T> rad2deg(const Vector3<T>& v) { return { rad2deg(v.x), rad2deg(v.y), rad2deg(v.z) }; }
template<typename T>
Vector2<T> deg2rad(const Vector2<T>& v) { return { deg2rad(v.x), deg2rad(v.y) }; }
template<typename T>
Vector2<T> rad2deg(const Vector2<T>& v) { return { rad2deg(v.x), rad2deg(v.y) }; }
uint32_t GetPhysicalCoreCount();
// Creates a temporary file to test for write access
bool TestWriteAccess(const fs::path& p);
fs::path MakeRelativePath(const fs::path& base, const fs::path& path);
#ifdef HAS_DIRECTINPUT
bool GUIDFromString(const char* string, GUID& guid);
std::string StringFromGUID(const GUID& guid);
std::wstring WStringFromGUID(const GUID& guid);
#endif
std::vector<std::string_view> TokenizeView(std::string_view string, char delimiter);
std::vector<std::string> Tokenize(std::string_view string, char delimiter);
std::string ltrim_copy(const std::string& s);
std::string rtrim_copy(const std::string& s);
std::string& ltrim(std::string& str, const std::string& chars = "\t\n\v\f\r ");
std::string& rtrim(std::string& str, const std::string& chars = "\t\n\v\f\r ");
std::string& trim(std::string& str, const std::string& chars = "\t\n\v\f\r ");
std::string_view& ltrim(std::string_view& str, const std::string& chars = "\t\n\v\f\r ");
std::string_view& rtrim(std::string_view& str, const std::string& chars = "\t\n\v\f\r ");
std::string_view& trim(std::string_view& str, const std::string& chars = "\t\n\v\f\r ");
std::string GenerateRandomString(size_t length);
std::string GenerateRandomString(size_t length, std::string_view characters);
std::wstring GetSystemErrorMessageW();
std::wstring GetSystemErrorMessageW(DWORD error_code);
std::string GetSystemErrorMessage();
std::string GetSystemErrorMessage(DWORD error_code);
std::string GetSystemErrorMessage(const std::exception& ex);
std::string GetSystemErrorMessage(const std::error_code& ec);
template<class... Ts> struct overloaded : Ts... { using Ts::operator()...; };
template<class... Ts> overloaded(Ts...)->overloaded<Ts...>;
template<typename T>
bool equals(T v1, T v2)
{
/*
return std::fabs(x-y) <= std::numeric_limits<T>::epsilon() * std::fabs(x+y) * ulp
// unless the result is subnormal
|| std::fabs(x-y) < std::numeric_limits<T>::min();
*/
if constexpr (std::is_floating_point_v<T>)
return std::abs(v1 - v2) < (T)0.000001;
else if constexpr (std::is_same_v<T, const char*>)
return strcmp(v1, v2) == 0;
else
return v1 == v2;
}
template<typename T>
T ConvertString(std::string_view str, sint32 base)
{
if (str.empty())
return {};
static_assert(std::is_integral_v<T>);
T result;
ltrim(str);
// from_chars cant deal with hex numbers starting with "0x"
if (base == 16)
{
const sint32 index = str[0] == '-' ? 1 : 0;
if (str.size() >= 2 && str[index+0] == '0' && tolower(str[index+1]) == 'x')
str = str.substr(index + 2);
if (std::from_chars(str.data(), str.data() + str.size(), result, base).ec == std::errc())
{
if (index == 1)
{
if constexpr(std::is_unsigned_v<T>)
result = static_cast<T>(-static_cast<std::make_signed_t<T>>(result));
else
result = -result;
}
return result;
}
return {};
}
if(std::from_chars(str.data(), str.data() + str.size(), result, base).ec == std::errc())
return result;
return {};
}
template<typename T>
T ConvertString(std::string_view str)
{
if (str.empty())
return {};
T result;
ltrim(str);
if constexpr (std::is_same_v<T, bool>)
{
return str == "1" || boost::iequals(str, "true");
}
else if constexpr(std::is_floating_point_v<T>)
{
// from_chars can't deal with float conversation starting with "+"
ltrim(str, "+");
#ifdef __clang__
if (fast_float::from_chars(str.data(), str.data() + str.size(), result).ec == std::errc())
return result;
#else
if (std::from_chars(str.data(), str.data() + str.size(), result).ec == std::errc())
return result;
#endif
return {};
}
else if constexpr(std::is_enum_v<T>)
{
return (T)ConvertString<std::underlying_type_t<T>>(str);
}
else
{
const sint32 index = str[0] == '-' ? 1 : 0;
if (str.size() >= 2 && str[index + 0] == '0' && tolower(str[index + 1]) == 'x')
result = ConvertString<T>(str, 16);
else
result = ConvertString<T>(str, 10);
}
return result;
}
template <typename T>
constexpr T DegToRad(T deg) { return (T)((double)deg * M_PI / 180); }
template <typename T>
constexpr T RadToDeg(T rad) { return (T)((double)rad * 180 / M_PI); }
template<typename T>
std::string ToString(T value)
{
std::ostringstream str;
str.imbue(std::locale("C"));
str << value;
return str.str();
}
template<typename T>
T FromString(std::string value)
{
std::istringstream str(value);
str.imbue(std::locale("C"));
T tmp;
str >> tmp;
return tmp;
}
template<typename T>
size_t RemoveDuplicatesKeepOrder(std::vector<T>& vec)
{
std::set<T> tmp;
auto new_end = std::remove_if(vec.begin(), vec.end(), [&tmp](const T& value)
{
if (tmp.find(value) != std::end(tmp))
return true;
tmp.insert(value);
return false;
});
vec.erase(new_end, vec.end());
return vec.size();
}
void SetThreadName(const char* name);
inline uint64 MakeU64(uint32 high, uint32 low)
{
return ((uint64)high << 32) | ((uint64)low);
}
static bool IsValidFilename(std::string_view sv)
{
for (auto& it : sv)
{
uint8 c = (uint8)it;
if (c < 0x20)
return false;
if (c == '.' || c == '#' || c == '/' || c == '\\' ||
c == '<' || c == '>' || c == '|' || c == ':' ||
c == '\"')
return false;
}
if (!sv.empty())
{
if (sv.back() == ' ' || sv.back() == '.')
return false;
}
return true;
}
// MAJOR; MINOR
std::pair<DWORD, DWORD> GetWindowsVersion();
bool IsWindows81OrGreater();
bool IsWindows10OrGreater();
fs::path GetParentProcess();
std::optional<std::vector<uint8>> zlibDecompress(const std::vector<uint8>& compressed, size_t sizeHint = 32*1024);
| 6,921
|
C++
|
.h
| 217
| 29.718894
| 114
| 0.67343
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,344
|
ClassWrapper.h
|
cemu-project_Cemu/src/util/helpers/ClassWrapper.h
|
#pragma once
#include <mutex>
#include <memory>
template<typename T>
class SingletonClass
{
public:
static T* getInstance()
{
static T instance;
return &instance;
}
protected:
SingletonClass() = default;
};
template<typename T>
class SingletonRef
{
public:
/*static std::shared_ptr<T> getInstance() C++20 only
{
static std::atomic<std::weak_ptr<T>> s_instance;
std::shared_ptr<T> result;
s_instance.compare_exchange_weak(result, std::make_shared<T>());
return result;
}*/
static std::shared_ptr<T> getInstance()
{
std::scoped_lock lock(s_mutex);
auto result = s_instance.lock();
if(!result)
{
result = std::make_shared<T>();
s_instance = result;
}
return result;
}
protected:
SingletonRef() = default;
private:
static inline std::weak_ptr<T> s_instance;
static inline std::mutex s_mutex;
};
| 847
|
C++
|
.h
| 43
| 17.395349
| 66
| 0.719343
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,345
|
fspinlock.h
|
cemu-project_Cemu/src/util/helpers/fspinlock.h
|
#pragma once
// minimal but efficient non-recursive spinlock implementation
#include <atomic>
class FSpinlock
{
public:
bool is_locked() const
{
return m_lockBool.load(std::memory_order_relaxed);
}
// implement BasicLockable and Lockable
void lock() const
{
while (true)
{
if (!m_lockBool.exchange(true, std::memory_order_acquire))
break;
while (m_lockBool.load(std::memory_order_relaxed))
_mm_pause();
}
}
bool try_lock() const
{
return !m_lockBool.exchange(true, std::memory_order_acquire);
}
void unlock() const
{
m_lockBool.store(false, std::memory_order_release);
}
private:
mutable std::atomic<bool> m_lockBool = false;
};
| 691
|
C++
|
.h
| 32
| 18.65625
| 63
| 0.712308
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,346
|
SystemException.h
|
cemu-project_Cemu/src/util/helpers/SystemException.h
|
#pragma once
#include "util/helpers/helpers.h"
class SystemException : public std::runtime_error
{
public:
SystemException()
: std::runtime_error(GetSystemErrorMessage().c_str()), m_error_code(GetExceptionError())
{}
SystemException(const std::exception& ex)
: std::runtime_error(GetSystemErrorMessage(ex).c_str()), m_error_code(GetExceptionError())
{}
SystemException(const std::error_code& ec)
: std::runtime_error(GetSystemErrorMessage(ec).c_str()), m_error_code(GetExceptionError())
{}
[[nodiscard]] DWORD GetErrorCode() const { return m_error_code; }
private:
DWORD m_error_code;
};
| 608
|
C++
|
.h
| 18
| 31.666667
| 92
| 0.753425
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,347
|
MapAdaptor.h
|
cemu-project_Cemu/src/util/helpers/MapAdaptor.h
|
#pragma once
// https://ideone.com/k0H8Ei
#include <iostream>
#include <map>
#include <boost/iterator/transform_iterator.hpp>
template <typename T, typename F>
struct map_adaptor
{
map_adaptor(const T& t, const F& f) : _t(t), _f(f) {}
map_adaptor(map_adaptor& a) = delete;
map_adaptor(map_adaptor&& a) = default;
[[nodiscard]] auto begin() { return boost::make_transform_iterator(_t.begin(), _f); }
[[nodiscard]] auto end() { return boost::make_transform_iterator(_t.end(), _f); }
[[nodiscard]] auto cbegin() const { return boost::make_transform_iterator(_t.cbegin(), _f); }
[[nodiscard]] auto cend() const { return boost::make_transform_iterator(_t.cend(), _f); }
protected:
const T& _t;
F _f;
};
template <typename T, typename F>
auto get_map_adaptor(const T& t, const F& f) { return map_adaptor<T, F>(t, f); }
template <typename T>
auto get_keys(const T& t) { return get_map_adaptor(t, [](const auto& p) { return p.first; }); }
template <typename T>
auto get_values(const T& t) { return get_map_adaptor(t, [](const auto& p) { return p.second; }); }
| 1,071
|
C++
|
.h
| 25
| 41.08
| 98
| 0.681467
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,348
|
StringHelpers.h
|
cemu-project_Cemu/src/util/helpers/StringHelpers.h
|
#pragma once
#include "boost/nowide/convert.hpp"
#include <charconv>
// todo - move the Cafe/PPC specific parts to CafeString.h eventually
namespace StringHelpers
{
// convert Wii U big-endian wchar_t string to utf8 string
static std::string ToUtf8(const uint16be* ptr, size_t maxLength)
{
std::wstringstream result;
while (*ptr != 0 && maxLength > 0)
{
auto c = (uint16)*ptr;
result << static_cast<wchar_t>(c);
ptr++;
maxLength--;
}
return boost::nowide::narrow(result.str());
}
static std::string ToUtf8(std::span<uint16be> input)
{
return ToUtf8(input.data(), input.size());
}
// convert utf8 string to Wii U big-endian wchar_t string
static std::basic_string<uint16be> FromUtf8(std::string_view str)
{
std::basic_string<uint16be> tmpStr;
std::wstring w = boost::nowide::widen(str.data(), str.size());
for (auto& c : w)
tmpStr.push_back((uint16)c);
return tmpStr;
}
static sint32 ToInt(const std::string_view& input, sint32 defaultValue = 0)
{
sint32 value = defaultValue;
if (input.size() >= 2 && (input[0] == '0' && (input[1] == 'x' || input[1] == 'X')))
{
// hex number
const std::from_chars_result result = std::from_chars(input.data() + 2, input.data() + input.size(), value, 16);
if (result.ec == std::errc::invalid_argument || result.ec == std::errc::result_out_of_range)
return defaultValue;
}
else
{
// decimal value
const std::from_chars_result result = std::from_chars(input.data(), input.data() + input.size(), value);
if (result.ec == std::errc::invalid_argument || result.ec == std::errc::result_out_of_range)
return defaultValue;
}
return value;
}
static sint64 ToInt64(const std::string_view& input, sint64 defaultValue = 0)
{
sint64 value = defaultValue;
if (input.size() >= 2 && (input[0] == '0' && (input[1] == 'x' || input[1] == 'X')))
{
// hex number
const std::from_chars_result result = std::from_chars(input.data() + 2, input.data() + input.size(), value, 16);
if (result.ec == std::errc::invalid_argument || result.ec == std::errc::result_out_of_range)
return defaultValue;
}
else
{
// decimal value
const std::from_chars_result result = std::from_chars(input.data(), input.data() + input.size(), value);
if (result.ec == std::errc::invalid_argument || result.ec == std::errc::result_out_of_range)
return defaultValue;
}
return value;
}
static size_t ParseHexString(std::string_view input, uint8* output, size_t maxOutputLength)
{
size_t parsedLen = 0;
for (size_t i = 0; i < input.size() - 1; i += 2)
{
if (maxOutputLength <= 0)
break;
uint8 b = 0;
uint8 c = input[i + 0];
// high nibble
if (c >= '0' && c <= '9')
b |= ((c - '0') << 4);
else if (c >= 'a' && c <= 'f')
b |= ((c - 'a' + 10) << 4);
else if (c >= 'A' && c <= 'F')
b |= ((c - 'A' + 10) << 4);
else
break;
// low nibble
c = input[i + 1];
if (c >= '0' && c <= '9')
b |= (c - '0');
else if (c >= 'a' && c <= 'f')
b |= (c - 'a' + 10);
else if (c >= 'A' && c <= 'F')
b |= (c - 'A' + 10);
else
break;
*output = b;
output++;
maxOutputLength--;
parsedLen++;
}
return parsedLen;
}
class StringLineIterator
{
public:
class Iterator
{
public:
using iterator_category = std::input_iterator_tag;
using value_type = std::string_view;
using difference_type = std::ptrdiff_t;
using pointer = const std::string_view*;
using reference = const std::string_view&;
Iterator(std::string_view str, sint32 pos) : m_str(str), m_pos(pos)
{
update_line();
}
reference operator*() const
{
return m_line;
}
pointer operator->() const
{
return &m_line;
}
Iterator& operator++()
{
m_pos = m_nextPos;
update_line();
return *this;
}
friend bool operator==(const Iterator& lhs, const Iterator& rhs)
{
return lhs.m_str.data() == rhs.m_str.data() && lhs.m_pos == rhs.m_pos;
}
friend bool operator!=(const Iterator& lhs, const Iterator& rhs)
{
return !(lhs == rhs);
}
private:
void update_line()
{
if (m_pos >= m_str.size())
{
m_pos = -1;
m_line = {};
return;
}
auto pos = m_str.find('\n', m_pos);
m_nextPos = pos != std::string_view::npos ? pos : -1;
if(m_nextPos < 0)
m_line = m_str.substr(m_pos, std::string::npos);
else
{
m_line = m_str.substr(m_pos, m_nextPos - m_pos);
++m_nextPos; // skip \n
}
while (!m_line.empty() && m_line.back() == '\r')
m_line.remove_suffix(1);
}
std::string_view m_str;
sint32 m_pos;
sint32 m_nextPos;
std::string_view m_line;
};
StringLineIterator(std::string_view str) : m_str(str) {}
StringLineIterator(std::span<uint8> str) : m_str((const char*)str.data(), str.size()) {}
Iterator begin() const
{
return Iterator{m_str, 0 };
}
Iterator end() const
{
return Iterator{m_str, -1 };
}
private:
std::string_view m_str;
};
};
| 5,004
|
C++
|
.h
| 182
| 23.774725
| 115
| 0.605165
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,349
|
StringParser.h
|
cemu-project_Cemu/src/util/helpers/StringParser.h
|
#pragma once
class StringTokenParser
{
public:
StringTokenParser() : m_str(nullptr), m_len(0) {};
StringTokenParser(const char* input, sint32 inputLen) : m_str(input), m_len(inputLen) {};
StringTokenParser(std::string_view str) : m_str(str.data()), m_len((sint32)str.size()) {};
// skip whitespaces at current ptr position
void skipWhitespaces()
{
m_str = _skipWhitespaces(m_str, m_len);
}
// decrease string length as long as there is a whitespace at the end
void trimWhitespaces()
{
while (m_len > 0)
{
const char c = m_str[m_len - 1];
if (c != ' ' && c != '\t')
break;
m_len--;
}
}
bool isEndOfString()
{
return m_len <= 0;
}
sint32 skipToCharacter(const char c)
{
auto str = m_str;
auto len = m_len;
sint32 idx = 0;
while (len > 0)
{
if (*str == c)
{
m_str = str;
m_len = len;
return idx;
}
len--;
str++;
idx++;
}
return -1;
}
bool matchWordI(const char* word)
{
auto str = m_str;
auto length = m_len;
str = _skipWhitespaces(str, length);
for (sint32 i = 0; i <= length; i++)
{
if (word[i] == '\0')
{
m_str = str + i;
m_len = length - i;
return true;
}
if (i == length)
return false;
char c1 = str[i];
char c2 = word[i];
c1 = _toUpperCase(c1);
c2 = _toUpperCase(c2);
if (c1 != c2)
return false;
}
return false;
}
bool compareCharacter(sint32 relativeIndex, const char c)
{
if (relativeIndex >= m_len)
return false;
return m_str[relativeIndex] == c;
}
bool compareCharacterI(sint32 relativeIndex, const char c)
{
if (relativeIndex >= m_len)
return false;
return _toUpperCase(m_str[relativeIndex]) == _toUpperCase(c);
}
void skipCharacters(sint32 count)
{
if (count > m_len)
count = m_len;
m_str += count;
m_len -= count;
}
bool parseU32(uint32& val)
{
auto str = m_str;
auto length = m_len;
str = _skipWhitespaces(str, length);
uint32 value = 0;
sint32 index = 0;
bool isHex = false;
if (length <= 0)
return false;
if (length >= 2 && str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
{
isHex = true;
index += 2;
}
else if (str[index] == '0')
{
isHex = true;
index++;
}
if (length <= index)
return false;
if (isHex)
{
sint32 firstDigitIndex = index;
for (; index < length; index++)
{
const char c = str[index];
if (c >= '0' && c <= '9')
{
value *= 0x10;
value += (c - '0');
}
else if (c >= 'a' && c <= 'f')
{
value *= 0x10;
value += (c - 'a' + 10);
}
else if (c >= 'A' && c <= 'F')
{
value *= 0x10;
value += (c - 'A' + 10);
}
else
break;
}
if (index == firstDigitIndex)
return false;
m_str = str + index;
m_len = length - index;
}
else
{
sint32 firstDigitIndex = index;
for (; index < length; index++)
{
const char c = str[index];
if (c >= '0' && c <= '9')
{
value *= 10;
value += (c - '0');
}
else
break;
}
if (index == firstDigitIndex)
return false;
m_str = str + index;
m_len = length - index;
}
val = value;
return true;
}
bool parseSymbolName(const char*& symbolStr, sint32& symbolLength)
{
auto str = m_str;
auto length = m_len;
str = _skipWhitespaces(str, length);
// symbols must start with a letter or _
if (length <= 0)
return false;
if (!(str[0] >= 'a' && str[0] <= 'z') &&
!(str[0] >= 'A' && str[0] <= 'Z') &&
!(str[0] == '_'))
return false;
sint32 idx = 1;
while (idx < length)
{
const char c = str[idx];
if (!(c >= 'a' && c <= 'z') &&
!(c >= 'A' && c <= 'Z') &&
!(c >= '0' && c <= '9') &&
!(c == '_') && !(c == '.'))
break;
idx++;
}
symbolStr = str;
symbolLength = idx;
m_str = str + idx;
m_len = length - idx;
return true;
}
const char* getCurrentPtr()
{
return m_str;
}
sint32 getCurrentLen()
{
return m_len;
}
void storeParserState(StringTokenParser* bak)
{
bak->m_str = m_str;
bak->m_len = m_len;
}
void restoreParserState(const StringTokenParser* bak)
{
m_str = bak->m_str;
m_len = bak->m_len;
}
private:
const char* _skipWhitespaces(const char* str, sint32& length)
{
while (length > 0)
{
if (*str != ' ' && *str != '\t')
break;
str++;
length--;
}
return str;
}
char _toUpperCase(const char c)
{
if (c >= 'a' && c <= 'z')
return c + ('A' - 'a');
return c;
}
private:
const char* m_str;
sint32 m_len;
};
| 4,508
|
C++
|
.h
| 231
| 15.995671
| 91
| 0.556626
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,350
|
quaternion.h
|
cemu-project_Cemu/src/util/math/quaternion.h
|
#pragma once
#include <tuple>
#include <wx/math.h>
#include "util/math/vector3.h"
#define DEG2RAD(__d__) ((__d__ * M_PI) / 180.0f )
#define RAD2DEG(__r__) ((__r__ * 180.0f) / M_PI)
template<typename T>
class Quaternion
{
public:
T w;
T x;
T y;
T z;
Quaternion();
Quaternion(const T& w, const T& x, const T& y, const T& z);
Quaternion(float x, float y, float z);
void Assign(float w, float x, float y, float z)
{
this->w = w;
this->x = x;
this->y = y;
this->z = z;
}
static Quaternion FromAngleAxis(float inAngle, float inX, float inY, float inZ);
std::tuple<Vector3<T>, Vector3<T>, Vector3<T>> GetRotationMatrix();
std::tuple<Vector3<T>, Vector3<T>, Vector3<T>> GetTransposedRotationMatrix();
// normalize but keep W
void NormalizeXYZ()
{
const T xyzTargetLength = sqrtf((T)1.0 - w * w);
const T lengthScaler = xyzTargetLength / sqrtf(x * x + y * y + z * z);
x *= lengthScaler;
y *= lengthScaler;
z *= lengthScaler;
}
void NormalizeXYZW()
{
const T lengthScaler = 1.0f / sqrtf(w * w + x * x + y * y + z * z);
w *= lengthScaler;
x *= lengthScaler;
y *= lengthScaler;
z *= lengthScaler;
}
Vector3<T> GetVectorX() const
{
return Vector3<T>(
2.0f * (w * w + x * x) - 1.0f,
2.0f * (x * y - w * z),
2.0f * (x * z + w * y));
}
Vector3<T> GetVectorY() const
{
return Vector3<T>(
2.0f * (x * y + w * z),
2.0f * (w * w + y * y) - 1.0f,
2.0f * (y * z - w * x)
);
}
Vector3<T> GetVectorZ() const
{
return Vector3<T>(
2.0f * (x * z - w * y),
2.0f * (y * z + w * x),
2.0f * (w * w + z * z) - 1.0f);
}
Quaternion& operator*=(const Quaternion<T>& rhs)
{
Assign(w * rhs.w - x * rhs.x - y * rhs.y - z * rhs.z,
w * rhs.x + x * rhs.w + y * rhs.z - z * rhs.y,
w * rhs.y - x * rhs.z + y * rhs.w + z * rhs.x,
w * rhs.z + x * rhs.y - y * rhs.x + z * rhs.w);
return *this;
}
Quaternion& operator+=(const Quaternion<T>& rhs)
{
w += rhs.w;
x += rhs.x;
y += rhs.y;
z += rhs.z;
return *this;
}
friend Quaternion operator*(Quaternion<T> lhs, const Quaternion<T>& rhs)
{
lhs *= rhs;
return lhs;
}
};
template <typename T>
Quaternion<T>::Quaternion()
: w(), x(), y(), z()
{}
template <typename T>
Quaternion<T>::Quaternion(const T& w, const T& x, const T& y, const T& z)
: w(w), x(x), y(y), z(z)
{}
template <typename T>
Quaternion<T>::Quaternion(float x, float y, float z)
{
float pitch = DEG2RAD(x);
float yaw = DEG2RAD(y);
float roll = DEG2RAD(z);
float cyaw = cos(0.5f * yaw);
float cpitch = cos(0.5f * pitch);
float croll = cos(0.5f * roll);
float syaw = sin(0.5f * yaw);
float spitch = sin(0.5f * pitch);
float sroll = sin(0.5f * roll);
float cyawcpitch = cyaw * cpitch;
float syawspitch = syaw * spitch;
float cyawspitch = cyaw * spitch;
float syawcpitch = syaw * cpitch;
this->w = cyawcpitch * croll + syawspitch * sroll;
this->x = cyawspitch * croll + syawcpitch * sroll;
this->y = syawcpitch * croll - cyawspitch * sroll;
this->z = cyawcpitch * sroll - syawspitch * croll;
}
template<typename T>
Quaternion<T> Quaternion<T>::FromAngleAxis(float inAngle, float inX, float inY, float inZ)
{
Quaternion<T> result = Quaternion<T>(cosf(inAngle * 0.5f), inX, inY, inZ);
result.NormalizeXYZ();
return result;
}
template <typename T>
std::tuple<Vector3<T>, Vector3<T>, Vector3<T>> Quaternion<T>::GetRotationMatrix()
{
float sqw = w*w;
float sqx = x*x;
float sqy = y*y;
float sqz = z*z;
// invs (inverse square length) is only required if quaternion is not already normalised
float invs = 1.0f / (sqx + sqy + sqz + sqw);
Vector3<T> v1, v2, v3;
v1.x = (sqx - sqy - sqz + sqw) * invs; // since sqw + sqx + sqy + sqz =1/invs*invs
v2.y = (-sqx + sqy - sqz + sqw) * invs;
v3.z = (-sqx - sqy + sqz + sqw) * invs;
float tmp1 = x*y;
float tmp2 = z*w;
v2.x = 2.0 * (tmp1 + tmp2)*invs;
v1.y = 2.0 * (tmp1 - tmp2)*invs;
tmp1 = x*z;
tmp2 = y*w;
v3.x = 2.0 * (tmp1 - tmp2)*invs;
v1.z = 2.0 * (tmp1 + tmp2)*invs;
tmp1 = y*z;
tmp2 = x*w;
v3.y = 2.0 * (tmp1 + tmp2)*invs;
v2.z = 2.0 * (tmp1 - tmp2)*invs;
return std::make_tuple(v1, v2, v3);
}
template <typename T>
std::tuple<Vector3<T>, Vector3<T>, Vector3<T>> Quaternion<T>::GetTransposedRotationMatrix()
{
float sqw = w*w;
float sqx = x*x;
float sqy = y*y;
float sqz = z*z;
// invs (inverse square length) is only required if quaternion is not already normalised
float invs = 1.0f / (sqx + sqy + sqz + sqw);
Vector3<T> v1, v2, v3;
v1.x = (sqx - sqy - sqz + sqw) * invs; // since sqw + sqx + sqy + sqz =1/invs*invs
v2.y = (-sqx + sqy - sqz + sqw) * invs;
v3.z = (-sqx - sqy + sqz + sqw) * invs;
float tmp1 = x*y;
float tmp2 = z*w;
v1.y = 2.0 * (tmp1 + tmp2)*invs;
v2.x = 2.0 * (tmp1 - tmp2)*invs;
tmp1 = x*z;
tmp2 = y*w;
v1.z = 2.0 * (tmp1 - tmp2)*invs;
v3.x = 2.0 * (tmp1 + tmp2)*invs;
tmp1 = y*z;
tmp2 = x*w;
v2.z = 2.0 * (tmp1 + tmp2)*invs;
v3.y = 2.0 * (tmp1 - tmp2)*invs;
return std::make_tuple(v1, v2, v3);
}
using Quaternionf = Quaternion<float>;
| 4,996
|
C++
|
.h
| 179
| 25.586592
| 91
| 0.610588
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,351
|
glm.h
|
cemu-project_Cemu/src/util/math/glm.h
|
#pragma once
namespace glm
{
inline quat normalize_xyz(const quat& q)
{
const auto xyzTargetLength = std::sqrt(1.0f - q.w * q.w);
const auto lengthScaler = xyzTargetLength / sqrtf(q.x * q.x + q.y * q.y + q.z * q.z);
return quat(q.w, q.x * lengthScaler, q.y * lengthScaler, q.z * lengthScaler);
}
inline vec3 GetVectorX(const quat& q)
{
return vec3(
2.0f * (q.w * q.w + q.x * q.x) - 1.0f,
2.0f * (q.x * q.y - q.w * q.z),
2.0f * (q.x * q.z + q.w * q.y));
}
inline vec3 GetVectorY(const quat& q)
{
return vec3(
2.0f * (q.x * q.y + q.w * q.z),
2.0f * (q.w * q.w + q.y * q.y) - 1.0f,
2.0f * (q.y * q.z - q.w * q.x)
);
}
inline vec3 GetVectorZ(const quat& q)
{
return vec3 (
2.0f * (q.x * q.z - q.w * q.y),
2.0f * (q.y * q.z + q.w * q.x),
2.0f * (q.w * q.w + q.z * q.z) - 1.0f);
}
}
| 834
|
C++
|
.h
| 32
| 23.28125
| 87
| 0.535088
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,352
|
vector3.h
|
cemu-project_Cemu/src/util/math/vector3.h
|
#pragma once
#include <cassert>
template <typename T>
class Vector3 {
public:
T x;
T y;
T z;
Vector3() : x{}, y{}, z{} {}
Vector3(T x, T y, T z) : x(x), y(y), z(z) {}
template <typename U=T>
Vector3(const Vector3<U>& v)
: x((T)v.x), y((T)v.y), z((T)v.z) {}
float Length() const
{
return std::sqrt((x * x) + (y * y) + (z * z));
}
float Dot(const Vector3& v) const
{
return x * v.x + y * v.y + z * v.z;
}
Vector3 Cross(const Vector3& v) const
{
return Vector3(y * v.z - z * v.y, z * v.x - x * v.z, x * v.y - y * v.x);
}
Vector3 Normalized() const
{
const auto len = Length();
if (len == 0)
return {};
return *this / len;
}
Vector3& Normalize()
{
const auto len = Length();
if (len != 0)
*this /= len;
return *this;
}
//Vector3& Scale(const Vector3& v)
//{
// *this *= v;
// return *this;
//}
void Scale(const float s)
{
this->x *= s;
this->y *= s;
this->z *= s;
}
Vector3& RotateX(float theta);
Vector3& RotateY(float theta);
Vector3& RotateZ(float theta);
bool operator==(const Vector3& v)
{
return x == v.x && y == v.y && z == v.z;
}
bool operator!=(const Vector3& v)
{
return !(*this == v);
}
template <typename U = T>
Vector3& operator+=(const Vector3<U>& v)
{
x += (T)v.x;
y += (T)v.y;
z += (T)v.z;
return *this;
}
template <typename U = T>
Vector3& operator-=(const Vector3<U>& v)
{
x -= (T)v.x;
y -= (T)v.y;
z -= (T)v.z;
return *this;
}
template <typename U = T>
Vector3& operator*=(const Vector3<U>& v)
{
x *= (T)v.x;
y *= (T)v.y;
z *= (T)v.z;
return *this;
}
template <typename U = T>
Vector3& operator/=(const Vector3<U>& v)
{
assert(v.x != 0 && v.y != 0 && v.z != 0);
x /= (T)v.x;
y /= (T)v.y;
z /= (T)v.z;
return *this;
}
template <typename U = T>
Vector3 operator+(const Vector3<U>& v) const
{
return Vector3(x + (T)v.x, y + (T)v.y, z + (T)v.z);
}
template <typename U = T>
Vector3 operator-(const Vector3<U>& v) const
{
return Vector3(x - (T)v.x, y - (T)v.y, z - (T)v.z);
}
template <typename U = T>
Vector3 operator*(const Vector3<U>& v) const
{
return Vector3(x * (T)v.x, y * (T)v.y, z * (T)v.z);
}
template <typename U = T>
Vector3 operator/(const Vector3<U>& v) const
{
assert(v.x != 0 && v.y != 0 && v.z != 0);
return Vector3(x / (T)v.x, y / (T)v.y, z / (T)v.z);
}
Vector3& operator+=(T v)
{
x += v;
y += v;
z += v;
return *this;
}
Vector3& operator-=(T v)
{
x -= v;
y -= v;
z -= v;
return *this;
}
Vector3& operator*=(T v)
{
x *= v;
y *= v;
z *= v;
return *this;
}
Vector3& operator/=(T v)
{
assert(v != 0);
x /= v;
y /= v;
z /= v;
return *this;
}
Vector3 operator+(T v) const
{
return Vector3(x + v, y + v, z + v);
}
Vector3 operator-(T v) const
{
return Vector3(x - v, y - v, z - v);
}
Vector3 operator*(T v) const
{
return Vector3(x * v, y * v, z * v);
}
Vector3 operator/(T v) const
{
assert(v != 0);
return Vector3(x / (T)v, y / (T)v, z / (T)v);
}
bool IsZero() const
{
return x == 0 && y == 0 && z == 0;
}
bool HasZero() const
{
return x == 0 || y == 0 || z == 0;
}
};
template <typename T>
Vector3<T>& Vector3<T>::RotateX(float theta)
{
const float sin = std::sin(theta);
const float cos = std::cos(theta);
y = y * cos - z * sin;
z = y * sin + z * cos;
return *this;
}
template <typename T>
Vector3<T>& Vector3<T>::RotateY(float theta)
{
const float sin = std::sin(theta);
const float cos = std::cos(theta);
x = x * cos + z * sin;
z = -x * sin + z * cos;
return *this;
}
template <typename T>
Vector3<T>& Vector3<T>::RotateZ(float theta)
{
const float sin = std::sin(theta);
const float cos = std::cos(theta);
x = x * cos - y * sin;
y = x * sin + y * cos;
return *this;
}
using Vector3f = Vector3<float>;
using Vector3i = Vector3<int>;
| 3,840
|
C++
|
.h
| 199
| 16.894472
| 74
| 0.565567
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,353
|
vector2.h
|
cemu-project_Cemu/src/util/math/vector2.h
|
#pragma once
#include <cassert>
template <typename T>
class Vector2
{
public:
T x;
T y;
Vector2()
: x{}, y{} {}
Vector2(T x, T y)
: x(x), y(y) {}
template <typename U = T>
Vector2(const Vector2<U>& v)
: x((T)v.x), y((T)v.y) {}
float Length() const
{
return (float)std::sqrt((x * x) + (y * y));
}
float Cross(const Vector2& v) const
{
return x * v.y - y * v.x;
}
float Dot(const Vector2& v) const
{
return x * v.x + y * v.y;
}
Vector2 Ortho() const
{
return Vector2(y, -x);
}
Vector2 Normalized() const
{
const auto len = Length();
if (len == 0)
return Vector2<T>();
return Vector2<T>((T)((float)x / len), (T)((float)y / len));
}
Vector2& Normalize()
{
const auto len = Length();
if (len != 0)
{
x = (T)((float)x / len);
y = (T)((float)y / len);
}
return *this;
}
static Vector2 Max(const Vector2& v1, const Vector2& v2)
{
return Vector2(std::max(v1.x, v2.x), std::max(v1.y, v2.y));
}
static Vector2 Min(const Vector2& v1, const Vector2& v2)
{
return Vector2(std::min(v1.x, v2.x), std::min(v1.y, v2.y));
}
bool operator==(const Vector2& v) const
{
return x == v.x && y == v.y;
}
bool operator!=(const Vector2& v) const
{
return !(*this == v);
}
Vector2& operator+=(const Vector2& v)
{
x += v.x;
y += v.y;
return *this;
}
Vector2& operator-=(const Vector2& v)
{
x -= v.x;
y -= v.y;
return *this;
}
Vector2 operator+(const Vector2& v) const
{
return Vector2(x + v.x, y + v.y);
}
Vector2 operator-(const Vector2& v) const
{
return Vector2(x - v.x, y - v.y);
}
Vector2& operator+=(const T& v)
{
x += v;
y += v;
return *this;
}
Vector2& operator-=(const T& v)
{
x -= v;
y -= v;
return *this;
}
Vector2& operator*=(const T& v)
{
x *= v;
y *= v;
return *this;
}
Vector2& operator/=(const T& v)
{
assert(v != 0);
x /= v;
y /= v;
return *this;
}
Vector2 operator+(const T& v)
{
return Vector2(x + v, y + v);
}
Vector2 operator-(const T& v)
{
return Vector2(x - v, y - v);
}
Vector2 operator*(const T& v)
{
return Vector2(x * v, y * v);
}
Vector2 operator/(const T& v)
{
assert(v != 0);
return Vector2(x / v, y / v);
}
};
using Vector2f = Vector2<float>;
using Vector2i = Vector2<int>;
| 2,267
|
C++
|
.h
| 129
| 15.085271
| 62
| 0.589986
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,354
|
SystemInfo.h
|
cemu-project_Cemu/src/util/SystemInfo/SystemInfo.h
|
#pragma once
struct ProcessorTime
{
uint64 idle{}, kernel{}, user{};
uint64 work();
uint64 total();
static double Compare(ProcessorTime &last, ProcessorTime &now);
};
uint32 GetProcessorCount();
uint64 QueryRamUsage();
void QueryProcTime(uint64 &out_now, uint64 &out_user, uint64 &out_kernel);
void QueryProcTime(ProcessorTime &out);
void QueryCoreTimes(uint32 count, std::vector<ProcessorTime>& out);
| 411
|
C++
|
.h
| 13
| 29.923077
| 74
| 0.783715
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,355
|
ControllerFactory.h
|
cemu-project_Cemu/src/input/ControllerFactory.h
|
#pragma once
#include "input/api/InputAPI.h"
#include "input/api/Controller.h"
#include "input/emulated/EmulatedController.h"
class ControllerFactory
{
public:
static ControllerPtr CreateController(InputAPI::Type api, std::string_view uuid, std::string_view display_name);
static EmulatedControllerPtr CreateEmulatedController(size_t player_index, EmulatedController::Type type);
static ControllerProviderPtr CreateControllerProvider(InputAPI::Type api, const ControllerProviderSettings& settings);
};
| 507
|
C++
|
.h
| 11
| 44.636364
| 119
| 0.842105
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,356
|
InputManager.h
|
cemu-project_Cemu/src/input/InputManager.h
|
#pragma once
#if BOOST_OS_WINDOWS
#include "input/api/DirectInput/DirectInputControllerProvider.h"
#include "input/api/XInput/XInputControllerProvider.h"
#endif
#ifdef SUPPORTS_WIIMOTE
#include "input/api/Wiimote/WiimoteControllerProvider.h"
#endif
#include "util/helpers/Singleton.h"
#include "input/api/SDL/SDLControllerProvider.h"
#include "input/api/Keyboard/KeyboardControllerProvider.h"
#include "input/api/DSU/DSUControllerProvider.h"
#include "input/api/GameCube/GameCubeControllerProvider.h"
#include "input/emulated/VPADController.h"
#include "input/emulated/WPADController.h"
#include <atomic>
#include <optional>
class InputManager : public Singleton<InputManager>
{
friend class Singleton<InputManager>;
InputManager();
~InputManager();
friend class MainWindow;
friend class PadViewFrame;
public:
constexpr static size_t kMaxController = 8;
constexpr static size_t kMaxVPADControllers = 2;
constexpr static size_t kMaxWPADControllers = 7;
void load() noexcept;
bool load(size_t player_index, std::string_view filename = {});
bool migrate_config(const fs::path& file_path);
void save() noexcept;
bool save(size_t player_index, std::string_view filename = {});
bool is_gameprofile_set(size_t player_index) const;
EmulatedControllerPtr set_controller(EmulatedControllerPtr controller);
EmulatedControllerPtr set_controller(size_t player_index, EmulatedController::Type type);
EmulatedControllerPtr set_controller(size_t player_index, EmulatedController::Type type, const std::shared_ptr<ControllerBase>& controller);
EmulatedControllerPtr delete_controller(size_t player_index, bool delete_profile = false);
EmulatedControllerPtr get_controller(size_t player_index) const;
std::shared_ptr<VPADController> get_vpad_controller(size_t index) const;
std::shared_ptr<WPADController> get_wpad_controller(size_t index) const;
std::pair<size_t, size_t> get_controller_count() const;
bool is_api_available(InputAPI::Type api) const { return !m_api_available[api].empty(); }
ControllerProviderPtr get_api_provider(std::string_view api_name) const;
ControllerProviderPtr get_api_provider(InputAPI::Type api) const;
// will create the provider with the given settings if it doesn't exist yet
ControllerProviderPtr get_api_provider(InputAPI::Type api, const ControllerProviderSettings& settings);
const auto& get_api_providers() const
{
return m_api_available;
}
void apply_game_profile();
void on_device_changed();
static std::vector<std::string> get_profiles();
static bool is_valid_profilename(const std::string& name);
struct MouseInfo
{
mutable std::shared_mutex m_mutex;
glm::ivec2 position{};
bool left_down = false;
bool right_down = false;
bool left_down_toggle = false;
bool right_down_toggle = false;
} m_main_mouse{}, m_pad_mouse{}, m_main_touch{}, m_pad_touch{};
glm::ivec2 get_mouse_position(bool pad_window) const;
std::optional<glm::ivec2> get_left_down_mouse_info(bool* is_pad);
std::optional<glm::ivec2> get_right_down_mouse_info(bool* is_pad);
std::atomic<float> m_mouse_wheel;
private:
void update_thread();
std::thread m_update_thread;
std::atomic<bool> m_update_thread_shutdown{false};
std::array<std::vector<ControllerProviderPtr>, InputAPI::MAX> m_api_available{ };
mutable std::shared_mutex m_mutex;
std::array<EmulatedControllerPtr, kMaxVPADControllers> m_vpad;
std::array<EmulatedControllerPtr, kMaxWPADControllers> m_wpad;
std::array<bool, kMaxController> m_is_gameprofile_set{};
template <typename TProvider>
void create_provider() // lambda templates only work in c++20 -> define locally in ctor
{
static_assert(std::is_base_of_v<ControllerProviderBase, TProvider>);
try
{
auto controller = std::make_shared<TProvider>();
m_api_available[controller->api()] = std::vector<ControllerProviderPtr>{ controller };
}
catch (const std::exception& ex)
{
cemuLog_log(LogType::Force, ex.what());
}
}
};
| 3,944
|
C++
|
.h
| 92
| 40.521739
| 141
| 0.781037
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,357
|
Controller.h
|
cemu-project_Cemu/src/input/api/Controller.h
|
#pragma once
#include "input/InputManager.h"
#include "input/motion/MotionSample.h"
#include "input/api/ControllerState.h"
namespace pugi
{
class xml_node;
}
enum Buttons2 : uint64
{
// General
kButton0,
kButton1,
kButton2,
kButton3,
kButton4,
kButton5,
kButton6,
kButton7,
kButton8,
kButton9,
kButton10,
kButton11,
kButton12,
kButton13,
kButton14,
kButton15,
kButton16,
kButton17,
kButton18,
kButton19,
kButton20,
kButton21,
kButton22,
kButton23,
kButton24,
kButton25,
kButton26,
kButton27,
kButton28,
kButton29,
kButton30,
kButton31,
// Trigger
kButtonZL,
kButtonZR,
// DPAD
kButtonUp,
kButtonDown,
kButtonLeft,
kButtonRight,
// positive values
kAxisXP,
kAxisYP,
kRotationXP,
kRotationYP,
kTriggerXP,
kTriggerYP,
// negative values
kAxisXN,
kAxisYN,
kRotationXN,
kRotationYN,
kTriggerXN,
kTriggerYN,
kButtonMAX,
kButtonNoneAxisMAX = kButtonRight,
kButtonAxisStart = kAxisXP,
};
class ControllerBase
{
public:
ControllerBase(std::string_view uuid, std::string_view display_name);
virtual ~ControllerBase() = default;
const std::string& uuid() const { return m_uuid; }
const std::string& display_name() const { return m_display_name; }
virtual std::string_view api_name() const = 0;
virtual InputAPI::Type api() const = 0;
virtual void update() {}
virtual bool connect() { return is_connected(); }
virtual bool is_connected() = 0;
virtual bool has_battery() { return false; }
virtual bool has_low_battery() { return false; }
const ControllerState& calibrate();
const ControllerState& update_state();
const ControllerState& get_state() const { return m_last_state; }
const ControllerState& get_default_state() { return is_calibrated() ? m_default_state : calibrate(); }
virtual ControllerState raw_state() = 0;
bool is_calibrated() const { return m_is_calibrated; }
float get_axis_value(uint64 button) const;
virtual bool has_axis() const { return true; }
bool use_motion() { return has_motion() && m_settings.motion; }
virtual bool has_motion() { return false; }
virtual MotionSample get_motion_sample() { return {}; }
virtual bool has_position() { return false; }
virtual glm::vec2 get_position() { return {}; }
virtual glm::vec2 get_prev_position() { return {}; }
virtual PositionVisibility GetPositionVisibility() {return PositionVisibility::NONE;};
virtual bool has_rumble() { return false; }
virtual void start_rumble() {}
virtual void stop_rumble() {}
virtual std::string get_button_name(uint64 button) const;
virtual void save(pugi::xml_node& node){}
virtual void load(const pugi::xml_node& node){}
struct AxisSetting
{
AxisSetting(float deadzone = 0.25f) : deadzone(deadzone) {}
float deadzone;
float range = 1.0f;
};
struct Settings
{
AxisSetting axis{}, rotation{}, trigger{};
float rumble = 0;
bool motion = false; // only valid when has_motion is true
};
Settings get_settings() const;
void set_settings(const Settings& settings);
void set_axis_settings(const AxisSetting& settings);
void set_rotation_settings(const AxisSetting& settings);
void set_trigger_settings(const AxisSetting& settings);
void set_rumble(float rumble);
void set_use_motion(bool state);
void apply_axis_setting(glm::vec2& axis, const glm::vec2& default_value, const AxisSetting& setting) const;
bool operator==(const ControllerBase& c) const;
bool operator!=(const ControllerBase& c) const { return !(*this == c); }
protected:
std::string m_uuid;
std::string m_display_name;
ControllerState m_last_state{};
bool m_is_calibrated = false;
ControllerState m_default_state{};
mutable std::mutex m_settings_mutex;
Settings m_settings{};
};
template<class TProvider>
class Controller : public ControllerBase
{
public:
Controller(std::string_view uuid, std::string_view display_name)
: ControllerBase(uuid, display_name)
{
static_assert(std::is_base_of_v<ControllerProviderBase, TProvider>);
m_provider = std::dynamic_pointer_cast<TProvider>(InputManager::instance().get_api_provider(TProvider::kAPIType));
cemu_assert_debug(m_provider != nullptr);
}
Controller(std::string_view uuid, std::string_view display_name, const ControllerProviderSettings& settings)
: ControllerBase(uuid, display_name)
{
static_assert(std::is_base_of_v<ControllerProviderBase, TProvider>);
m_provider = std::dynamic_pointer_cast<TProvider>(InputManager::instance().get_api_provider(TProvider::kAPIType, settings));
cemu_assert_debug(m_provider != nullptr);
}
// update provider if settings are different from default provider
void update_provider(std::shared_ptr<TProvider> provider)
{
m_provider = std::move(provider);
}
protected:
using base_type = Controller<TProvider>;
std::shared_ptr<TProvider> m_provider;
};
using ControllerPtr = std::shared_ptr<ControllerBase>;
| 4,828
|
C++
|
.h
| 163
| 27.392638
| 126
| 0.760441
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,358
|
ControllerProvider.h
|
cemu-project_Cemu/src/input/api/ControllerProvider.h
|
#pragma once
#include "input/api/InputAPI.h"
class ControllerBase;
struct ControllerProviderSettings
{
virtual ~ControllerProviderSettings() = default;
virtual bool operator==(const ControllerProviderSettings&) const = 0;
};
class ControllerProviderBase
{
public:
ControllerProviderBase() = default;
virtual ~ControllerProviderBase() = default;
virtual InputAPI::Type api() const = 0;
std::string_view api_name() const { return to_string(api()); }
virtual std::vector<std::shared_ptr<ControllerBase>> get_controllers() = 0;
virtual bool has_settings() const
{
return false;
}
virtual bool operator==(const ControllerProviderBase& p) const
{
return api() == p.api();
}
virtual bool operator==(const ControllerProviderSettings& p) const
{
return false;
}
};
using ControllerProviderPtr = std::shared_ptr<ControllerProviderBase>;
template <typename TSettings>
class ControllerProvider : public ControllerProviderBase
{
using base_type = ControllerProviderBase;
public:
ControllerProvider() = default;
ControllerProvider(const TSettings& settings)
: m_settings(settings)
{}
bool has_settings() const override
{
return true;
}
const TSettings& get_settings() const
{
return m_settings;
}
bool operator==(const ControllerProviderBase& p) const override
{
if (!base_type::operator==(p))
return false;
if (!p.has_settings())
return false;
auto* ptr = dynamic_cast<const ControllerProvider<TSettings>*>(&p);
if (!ptr)
return false;
return base_type::operator==(p) && m_settings == ptr->m_settings;
}
bool operator==(const ControllerProviderSettings& p) const override
{
auto* ptr = dynamic_cast<const TSettings*>(&p);
if (!ptr)
return false;
return m_settings == *ptr;
}
protected:
TSettings m_settings{};
};
| 1,793
|
C++
|
.h
| 68
| 24
| 76
| 0.755425
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,359
|
InputAPI.h
|
cemu-project_Cemu/src/input/api/InputAPI.h
|
#pragma once
#include "util/helpers/helpers.h"
namespace InputAPI
{
enum Type
{
Keyboard,
SDLController,
XInput,
DirectInput,
DSUClient,
GameCube,
Wiimote,
WGIGamepad,
WGIRawController,
MAX
};
constexpr std::string_view to_string(Type type)
{
switch (type)
{
case Keyboard:
return "Keyboard";
case DirectInput:
return "DirectInput";
case XInput:
return "XInput";
case Wiimote:
return "Wiimote";
case GameCube:
return "GameCube";
case DSUClient:
return "DSUController";
case WGIGamepad:
return "WGIGamepad";
case WGIRawController:
return "WGIRawController";
case SDLController:
return "SDLController";
default:
break;
}
throw std::runtime_error(fmt::format("unknown input api: {}", to_underlying(type)));
}
constexpr Type from_string(std::string_view str)
{
if (str == to_string(Keyboard))
return Keyboard;
else if (str == to_string(DirectInput))
return DirectInput;
else if (str == to_string(XInput))
return XInput;
else if (str == to_string(Wiimote))
return Wiimote;
else if (str == to_string(GameCube))
return GameCube;
else if (str == to_string(DSUClient))
return DSUClient;
else if (str == to_string(SDLController))
return SDLController;
else if (str == "DSU") // legacy
return DSUClient;
//else if (str == "WGIGamepad")
// return WGIGamepad;
//
//else if (str == "WGIRawController")
// return WGIRawController;
throw std::runtime_error(fmt::format("unknown input api: {}", str));
}
}
| 1,539
|
C++
|
.h
| 70
| 18.842857
| 86
| 0.702332
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,360
|
ControllerState.h
|
cemu-project_Cemu/src/input/api/ControllerState.h
|
#pragma once
#include <glm/vec2.hpp>
#include "util/helpers/fspinlock.h"
enum class PositionVisibility {
NONE = 0,
FULL = 1,
PARTIAL = 2
};
// helper class for storing and managing button press states in a thread-safe manner
struct ControllerButtonState
{
ControllerButtonState() = default;
ControllerButtonState(const ControllerButtonState& other)
{
this->m_pressedButtons = other.m_pressedButtons;
}
ControllerButtonState(ControllerButtonState&& other)
{
this->m_pressedButtons = std::move(other.m_pressedButtons);
}
void SetButtonState(uint32 buttonId, bool isPressed)
{
std::lock_guard _l(this->m_spinlock);
if (isPressed)
{
if (std::find(m_pressedButtons.cbegin(), m_pressedButtons.cend(), buttonId) != m_pressedButtons.end())
return;
m_pressedButtons.emplace_back(buttonId);
}
else
{
std::erase(m_pressedButtons, buttonId);
}
}
// set multiple buttons at once within a single lock interval
void SetPressedButtons(std::span<uint32> buttonList)
{
std::lock_guard _l(this->m_spinlock);
for (auto& buttonId : buttonList)
{
if (std::find(m_pressedButtons.cbegin(), m_pressedButtons.cend(), buttonId) == m_pressedButtons.end())
m_pressedButtons.emplace_back(buttonId);
}
}
// returns true if pressed
bool GetButtonState(uint32 buttonId) const
{
std::lock_guard _l(this->m_spinlock);
bool r = std::find(m_pressedButtons.cbegin(), m_pressedButtons.cend(), buttonId) != m_pressedButtons.cend();
return r;
}
// remove pressed state for all pressed buttons in buttonsToUnset
void UnsetButtons(const ControllerButtonState& buttonsToUnset)
{
std::scoped_lock _l(this->m_spinlock, buttonsToUnset.m_spinlock);
for (auto it = m_pressedButtons.begin(); it != m_pressedButtons.end();)
{
if (std::find(buttonsToUnset.m_pressedButtons.cbegin(), buttonsToUnset.m_pressedButtons.cend(), *it) == buttonsToUnset.m_pressedButtons.cend())
{
++it;
continue;
}
it = m_pressedButtons.erase(it);
}
}
// returns true if no buttons are pressed
bool IsIdle() const
{
std::lock_guard _l(this->m_spinlock);
const bool r = m_pressedButtons.empty();
return r;
}
std::vector<uint32> GetButtonList() const
{
std::lock_guard _l(this->m_spinlock);
std::vector<uint32> copy = m_pressedButtons;
return copy;
}
bool operator==(const ControllerButtonState& other) const
{
std::scoped_lock _l(this->m_spinlock, other.m_spinlock);
auto& otherButtons = other.m_pressedButtons;
if (m_pressedButtons.size() != otherButtons.size())
{
return false;
}
for (auto& buttonId : m_pressedButtons)
{
if (std::find(otherButtons.cbegin(), otherButtons.cend(), buttonId) == otherButtons.cend())
{
return false;
}
}
return true;
}
ControllerButtonState& operator=(ControllerButtonState&& other)
{
cemu_assert_debug(!other.m_spinlock.is_locked());
std::scoped_lock _l(this->m_spinlock, other.m_spinlock);
this->m_pressedButtons = std::move(other.m_pressedButtons);
return *this;
}
private:
std::vector<uint32> m_pressedButtons; // since only very few buttons are pressed at a time, using a vector with linear scan is more efficient than a set/map
mutable FSpinlock m_spinlock;
};
struct ControllerState
{
// when does a axis counts as pressed
constexpr static float kAxisThreshold = 0.1f;
// on the real console the stick x or y values never really reach 0.0 if one of the axis is moved
// some games rely on this due to incorrectly checking if the stick is tilted via if (vstick.x != 0 && vstick.y != 0)
// here we simulate a slight bias if the axis is almost perfectly centered
constexpr static float kMinAxisValue = 0.0000001f;
// [-1; 1]
glm::vec2 axis{ };
glm::vec2 rotation{ };
glm::vec2 trigger{ };
ControllerButtonState buttons{};
uint64 last_state = 0;
bool operator==(const ControllerState& other) const;
bool operator!=(const ControllerState& other) const
{
return !(*this == other);
}
};
| 3,956
|
C++
|
.h
| 126
| 28.698413
| 157
| 0.732668
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,361
|
DirectInputController.h
|
cemu-project_Cemu/src/input/api/DirectInput/DirectInputController.h
|
#pragma once
#include "input/api/DirectInput/DirectInputControllerProvider.h"
#include "input/api/Controller.h"
class DirectInputController : public Controller<DirectInputControllerProvider>
{
public:
DirectInputController(const GUID& guid);
DirectInputController(const GUID& guid, std::string_view display_name);
~DirectInputController() override;
std::string_view api_name() const override
{
static_assert(to_string(InputAPI::DirectInput) == "DirectInput");
return to_string(InputAPI::DirectInput);
}
InputAPI::Type api() const override { return InputAPI::DirectInput; }
void save(pugi::xml_node& node) override;
void load(const pugi::xml_node& node) override;
bool connect() override;
bool is_connected() override;
bool has_rumble() override;
void start_rumble() override;
void stop_rumble() override;
std::string get_button_name(uint64 button) const override;
const GUID& get_guid() const { return m_guid; }
const GUID& get_product_guid() const { return m_product_guid; }
protected:
ControllerState raw_state() override;
private:
GUID m_guid;
GUID m_product_guid{};
std::shared_mutex m_mutex;
LPDIRECTINPUTDEVICE8 m_device = nullptr;
LPDIRECTINPUTEFFECT m_effect = nullptr;
std::array<LONG, 6> m_min_axis{};
std::array<LONG, 6> m_max_axis{};
};
| 1,293
|
C++
|
.h
| 36
| 33.694444
| 78
| 0.772947
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,362
|
DirectInputControllerProvider.h
|
cemu-project_Cemu/src/input/api/DirectInput/DirectInputControllerProvider.h
|
#pragma once
#if BOOST_OS_WINDOWS
#define DIRECTINPUT_VERSION 0x0800
#include <dinput.h>
#include "input/api/ControllerProvider.h"
#ifndef HAS_DIRECTINPUT
#define HAS_DIRECTINPUT 1
#endif
class DirectInputControllerProvider : public ControllerProviderBase
{
public:
DirectInputControllerProvider();
~DirectInputControllerProvider() override;
inline static InputAPI::Type kAPIType = InputAPI::DirectInput;
InputAPI::Type api() const override { return kAPIType; }
std::vector<std::shared_ptr<ControllerBase>> get_controllers() override;
IDirectInput8* get_dinput() const { return m_dinput8; }
LPCDIDATAFORMAT get_data_format() const;
private:
HMODULE m_module = nullptr;
decltype(&DirectInput8Create) m_DirectInput8Create;
decltype(&GetdfDIJoystick) m_GetdfDIJoystick = nullptr;
IDirectInput8* m_dinput8 = nullptr;
};
#endif
| 845
|
C++
|
.h
| 25
| 31.92
| 73
| 0.815822
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,363
|
XInputControllerProvider.h
|
cemu-project_Cemu/src/input/api/XInput/XInputControllerProvider.h
|
#pragma once
#if BOOST_OS_WINDOWS
#include "input/api/ControllerProvider.h"
#include <Xinput.h>
#ifndef HAS_XINPUT
#define HAS_XINPUT 1
#endif
class XInputControllerProvider : public ControllerProviderBase
{
friend class XInputController;
public:
XInputControllerProvider();
~XInputControllerProvider() override;
inline static InputAPI::Type kAPIType = InputAPI::XInput;
InputAPI::Type api() const override { return kAPIType; }
std::vector<std::shared_ptr<ControllerBase>> get_controllers() override;
private:
HMODULE m_module = nullptr;
decltype(&XInputGetBatteryInformation) m_XInputGetBatteryInformation;
decltype(&XInputGetCapabilities) m_XInputGetCapabilities;
decltype(&XInputSetState) m_XInputSetState;
decltype(&XInputGetState) m_XInputGetState;
};
#endif
| 782
|
C++
|
.h
| 24
| 30.833333
| 73
| 0.828229
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,364
|
XInputController.h
|
cemu-project_Cemu/src/input/api/XInput/XInputController.h
|
#pragma once
#include "input/api/XInput/XInputControllerProvider.h"
#include "input/api/Controller.h"
class XInputController : public Controller<XInputControllerProvider>
{
public:
XInputController(uint32 index);
std::string_view api_name() const override
{
static_assert(to_string(InputAPI::XInput) == "XInput");
return to_string(InputAPI::XInput);
}
InputAPI::Type api() const override { return InputAPI::XInput; }
bool connect() override;
bool is_connected() override;
bool has_rumble() override { return m_has_rumble; }
bool has_battery() override { return m_has_battery; }
bool has_low_battery() override;
void start_rumble() override;
void stop_rumble() override;
std::string get_button_name(uint64 button) const override;
protected:
ControllerState raw_state() override;
private:
uint32 m_index;
bool m_connected = false;
bool m_has_battery = false;
bool m_has_rumble = false;
};
| 922
|
C++
|
.h
| 29
| 29.586207
| 68
| 0.769318
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,365
|
DSUMessages.h
|
cemu-project_Cemu/src/input/api/DSU/DSUMessages.h
|
#pragma once
// https://v1993.github.io/cemuhook-protocol/
#include "Common/enumFlags.h"
#include "util/math/vector3.h"
#include <array>
#include <cstdint>
enum class DsState : uint8_t
{
Disconnected = 0x00,
Reserved = 0x01,
Connected = 0x02
};
enum class DsConnection : uint8_t
{
None = 0x00,
Usb = 0x01,
Bluetooth = 0x02
};
enum class DsModel : uint8_t
{
None = 0,
DS3 = 1,
DS4 = 2,
Generic = 3
};
enum class DsBattery : uint8_t
{
None = 0x00,
Dying = 0x01,
Low = 0x02,
Medium = 0x03,
High = 0x04,
Full = 0x05,
Charging = 0xEE,
Charged = 0xEF
};
enum class RegisterFlag : uint8_t
{
AllPads = 0x00,
Index = 0x01,
MACAddress = 0x02
};
ENABLE_BITMASK_OPERATORS(RegisterFlag);
enum class MessageType : uint32_t
{
Version = 0x100000,
Information = 0x100001,
Data = 0x100002,
Rumble = 0x100003, // TODO
};
using MACAddress_t = std::array<uint8_t, 6>;
#pragma pack(push,1)
class MessageHeader
{
public:
MessageHeader(uint32_t magic, uint32_t uid);
[[nodiscard]] uint16_t GetSize() const { return sizeof(MessageHeader) + m_packet_size; }
[[nodiscard]] bool IsClientMessage() const;
[[nodiscard]] bool IsServerMessage() const;
[[nodiscard]] uint32_t GetCRC32() const { return m_crc32; }
protected:
void Finalize(size_t size);
[[nodiscard]] uint32_t CRC32(size_t size) const;
private:
uint32_t m_magic;
uint16_t m_protocol_version;
uint16_t m_packet_size = 0;
mutable uint32_t m_crc32 = 0;
uint32_t m_uid;
};
static_assert(sizeof(MessageHeader) == 0x10);
class Message : public MessageHeader
{
public:
Message(uint32_t magic, uint32_t uid, MessageType type);
[[nodiscard]] MessageType GetMessageType() const { return m_message_type; }
private:
MessageType m_message_type;
};
static_assert(sizeof(Message) == 0x14);
// client messages
class ClientMessage : public Message
{
public:
ClientMessage(uint32_t uid, MessageType message_type);
};
static_assert(sizeof(ClientMessage) == sizeof(Message));
class VersionRequest : public ClientMessage
{
public:
VersionRequest(uint32_t uid);
};
static_assert(sizeof(VersionRequest) == sizeof(ClientMessage));
class ListPorts : public ClientMessage
{
public:
ListPorts(uint32_t uid, uint32_t num_pads_requests, const std::array<uint8_t, 4>& request_indices);
private:
uint32_t m_count;
std::array<uint8_t, 4> m_indices;
};
class DataRequest : public ClientMessage
{
public:
DataRequest(uint32_t uid);
DataRequest(uint32_t uid, uint8_t index);
DataRequest(uint32_t uid, const MACAddress_t& mac_address);
DataRequest(uint32_t uid, uint8_t index, const MACAddress_t& mac_address);
private:
RegisterFlag m_reg_flags;
uint8_t m_index;
MACAddress_t m_mac_address;
};
// server messages
class ServerMessage : public Message
{
public:
ServerMessage() = delete;
protected:
[[nodiscard]] bool ValidateCRC32(size_t size) const;
};
class VersionResponse : public ServerMessage
{
public:
[[nodiscard]] bool IsValid() const;
[[nodiscard]] uint16_t GetVersion() const { return m_version; }
private:
uint16_t m_version;
uint8_t padding[2];
};
static_assert(sizeof(VersionResponse) == 0x18);
struct PortInfoData
{
uint8_t index;
DsState state;
DsModel model;
DsConnection connection;
MACAddress_t mac_address;
DsBattery battery;
uint8_t is_active;
};
class PortInfo : public ServerMessage
{
public:
[[nodiscard]] bool IsValid() const;
[[nodiscard]] const PortInfoData& GetInfo() const { return m_info; }
[[nodiscard]] uint8_t GetIndex() const { return m_info.index; }
[[nodiscard]] DsState GetState() const { return m_info.state; }
[[nodiscard]] DsModel GetModel() const { return m_info.model; }
[[nodiscard]] DsConnection GetConnection() const { return m_info.connection; }
[[nodiscard]] MACAddress_t GetMacAddress() const { return m_info.mac_address; }
[[nodiscard]] DsBattery GetBattery() const { return m_info.battery; }
[[nodiscard]] bool IsActive() const { return m_info.is_active != 0; }
protected:
PortInfoData m_info;
};
static_assert(sizeof(PortInfo) == 0x20);
struct TouchPoint
{
uint8_t active;
uint8_t index;
int16_t x, y;
};
static_assert(sizeof(TouchPoint) == 0x6);
struct DataResponseData
{
uint32_t m_packet_index;
uint8_t state1;
uint8_t state2;
uint8_t ps;
uint8_t touch;
// y values are inverted by convention
uint8_t lx, ly;
uint8_t rx, ry;
uint8_t dpad_left;
uint8_t dpad_down;
uint8_t dpad_right;
uint8_t dpad_up;
uint8_t square;
uint8_t cross;
uint8_t circle;
uint8_t triangle;
uint8_t r1;
uint8_t l1;
uint8_t r2;
uint8_t l2;
TouchPoint tpad1, tpad2;
uint64_t motion_timestamp;
Vector3f accel;
Vector3f gyro;
};
class DataResponse : public PortInfo
{
public:
[[nodiscard]] bool IsValid() const;
[[nodiscard]] const DataResponseData& GetData() const { return m_data; }
uint32_t GetPacketIndex() const { return m_data.m_packet_index; }
uint8_t GetState1() const { return m_data.state1; }
uint8_t GetState2() const { return m_data.state2; }
uint8_t GetPs() const { return m_data.ps; }
uint8_t GetTouch() const { return m_data.touch; }
uint8_t GetLx() const { return m_data.lx; }
uint8_t GetLy() const { return m_data.ly; }
uint8_t GetRx() const { return m_data.rx; }
uint8_t GetRy() const { return m_data.ry; }
uint8_t GetDpadLeft() const { return m_data.dpad_left; }
uint8_t GetDpadDown() const { return m_data.dpad_down; }
uint8_t GetDpadRight() const { return m_data.dpad_right; }
uint8_t GetDpadUp() const { return m_data.dpad_up; }
uint8_t GetSquare() const { return m_data.square; }
uint8_t GetCross() const { return m_data.cross; }
uint8_t GetCircle() const { return m_data.circle; }
uint8_t GetTriangle() const { return m_data.triangle; }
uint8_t GetR1() const { return m_data.r1; }
uint8_t GetL1() const { return m_data.l1; }
uint8_t GetR2() const { return m_data.r2; }
uint8_t GetL2() const { return m_data.l2; }
const TouchPoint& GetTpad1() const { return m_data.tpad1; }
const TouchPoint& GetTpad2() const { return m_data.tpad2; }
uint64_t GetMotionTimestamp() const { return m_data.motion_timestamp; }
const Vector3f& GetAcceleration() const { return m_data.accel; }
const Vector3f& GetGyro() const { return m_data.gyro; }
private:
DataResponseData m_data;
};
//static_assert(sizeof(DataResponse) == 0x20);
#pragma pack(pop)
| 6,252
|
C++
|
.h
| 227
| 25.744493
| 100
| 0.740418
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,366
|
DSUControllerProvider.h
|
cemu-project_Cemu/src/input/api/DSU/DSUControllerProvider.h
|
#pragma once
#include "input/motion/MotionHandler.h"
#include "input/api/DSU/DSUMessages.h"
#include "input/api/ControllerProvider.h"
#include <boost/asio.hpp>
#ifndef HAS_DSU
#define HAS_DSU 1
#endif
// #define DEBUG_DSU_CLIENT
struct DSUProviderSettings : public ControllerProviderSettings
{
std::string ip;
uint16 port;
DSUProviderSettings() : ip("127.0.0.1"), port(26760) {}
DSUProviderSettings(std::string ip, uint16 port)
: ip(std::move(ip)), port(port)
{
}
bool operator==(const DSUProviderSettings& s) const
{
return port == s.port && ip == s.ip;
}
bool operator==(const ControllerProviderSettings& s) const override
{
const auto* ptr = dynamic_cast<const DSUProviderSettings*>(&s);
return ptr && *this == *ptr;
}
};
class DSUControllerProvider : public ControllerProvider<DSUProviderSettings>
{
friend class DSUController;
using base_type = ControllerProvider<DSUProviderSettings>;
public:
constexpr static int kMaxClients = 8;
struct ControllerState
{
// when was info updated last time
std::chrono::steady_clock::time_point last_update{};
uint64_t packet_index = 0; // our packet index count
PortInfoData info{};
DataResponseData data{};
MotionSample motion_sample{};
ControllerState& operator=(const PortInfo& port_info);
ControllerState& operator=(const DataResponse& data_response);
};
DSUControllerProvider();
DSUControllerProvider(const DSUProviderSettings& settings);
~DSUControllerProvider();
inline static InputAPI::Type kAPIType = InputAPI::DSUClient;
InputAPI::Type api() const override { return kAPIType; }
std::vector<std::shared_ptr<ControllerBase>> get_controllers() override;
bool connect();
bool is_connected(uint8_t index) const;
ControllerState get_state(uint8_t index) const;
ControllerState get_prev_state(uint8_t index) const;
MotionSample get_motion_sample(uint8_t index) const;
std::array<bool, kMaxClients> wait_update(const std::array<uint8_t, kMaxClients>& indices, size_t timeout) const;
bool wait_update(uint8_t index, uint32_t packet_index, size_t timeout) const;
uint32_t get_packet_index(uint8_t index) const;
// refresh pad info for all pads
void request_pad_info();
// refresh pad info for pad with given index
void request_pad_info(uint8_t index);
void request_version();
void request_pad_data();
void request_pad_data(uint8_t index);
private:
uint16 m_server_version = 0;
std::atomic_bool m_running = false;
std::thread m_reader_thread, m_writer_thread;
void reader_thread();
void writer_thread();
void integrate_motion(uint8_t index, const DataResponse& data_response);
std::mutex m_writer_mutex;
std::condition_variable m_writer_cond;
uint32 m_uid;
boost::asio::io_service m_io_service;
boost::asio::ip::udp::endpoint m_receiver_endpoint;
boost::asio::ip::udp::socket m_socket;
std::array<ControllerState, kMaxClients> m_state{};
std::array<ControllerState, kMaxClients> m_prev_state{};
mutable std::array<std::mutex, kMaxClients> m_mutex;
mutable std::array<std::condition_variable, kMaxClients> m_wait_cond;
std::queue<std::unique_ptr<ClientMessage>> m_writer_jobs;
std::array<WiiUMotionHandler, kMaxClients> m_motion_handler;
std::array<uint64, kMaxClients> m_last_motion_timestamp{};
};
| 3,252
|
C++
|
.h
| 87
| 35.08046
| 114
| 0.768028
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,367
|
DSUController.h
|
cemu-project_Cemu/src/input/api/DSU/DSUController.h
|
#pragma once
#include "input/api/Controller.h"
#include "input/api/DSU/DSUControllerProvider.h"
#include "Cafe/HW/AI/AI.h"
#include "Cafe/HW/AI/AI.h"
#include "Cafe/HW/AI/AI.h"
#include "Cafe/HW/AI/AI.h"
class DSUController : public Controller<DSUControllerProvider>
{
public:
DSUController(uint32 index);
DSUController(uint32 index, const DSUProviderSettings& settings);
std::string_view api_name() const override
{
static_assert(to_string(InputAPI::DSUClient) == "DSUController");
return to_string(InputAPI::DSUClient);
}
InputAPI::Type api() const override { return InputAPI::DSUClient; }
void save(pugi::xml_node& node) override;
void load(const pugi::xml_node& node) override;
bool connect() override;
bool is_connected() override;
bool has_motion() override { return true; }
MotionSample get_motion_sample() override;
bool has_position() override;
glm::vec2 get_position() override;
glm::vec2 get_prev_position() override;
PositionVisibility GetPositionVisibility() override;
std::string get_button_name(uint64 button) const override;
protected:
ControllerState raw_state() override;
private:
uint32 m_index;
};
| 1,154
|
C++
|
.h
| 34
| 31.882353
| 68
| 0.777778
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,368
|
GameCubeController.h
|
cemu-project_Cemu/src/input/api/GameCube/GameCubeController.h
|
#pragma once
#include "input/api/Controller.h"
#include "input/api/GameCube/GameCubeControllerProvider.h"
#ifdef HAS_GAMECUBE
class GameCubeController : public Controller<GameCubeControllerProvider>
{
public:
GameCubeController(uint32 adapter, uint32 index);
std::string_view api_name() const override
{
static_assert(to_string(InputAPI::GameCube) == "GameCube");
return to_string(InputAPI::GameCube);
}
InputAPI::Type api() const override { return InputAPI::GameCube; }
bool is_connected() override;
bool has_rumble() override;
void start_rumble() override;
void stop_rumble() override;
std::string get_button_name(uint64 button) const override;
protected:
ControllerState raw_state() override;
uint32 m_adapter;
uint32 m_index;
};
#endif
| 766
|
C++
|
.h
| 25
| 28.6
| 72
| 0.790984
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,369
|
GameCubeControllerProvider.h
|
cemu-project_Cemu/src/input/api/GameCube/GameCubeControllerProvider.h
|
#pragma once
#include "util/libusbWrapper/libusbWrapper.h"
#include "input/api/ControllerProvider.h"
#ifdef HAS_GAMECUBE
class GameCubeControllerProvider : public ControllerProviderBase
{
friend class DSUController;
public:
constexpr static size_t kMaxAdapters = 4;
constexpr static size_t kMaxIndex = 4;
GameCubeControllerProvider();
~GameCubeControllerProvider();
inline static InputAPI::Type kAPIType = InputAPI::GameCube;
InputAPI::Type api() const override { return kAPIType; }
std::vector<std::shared_ptr<ControllerBase>> get_controllers() override;
uint32 get_adapter_count() const;
bool has_rumble_connected(uint32 adapter_index) const;
bool is_connected(uint32 adapter_index) const;
void set_rumble_state(uint32 adapter_index, uint32 index, bool state);
struct GCState
{
bool valid = false;
uint16 button = 0;
uint8 lstick_x = 0;
uint8 lstick_y = 0;
uint8 rstick_x = 0;
uint8 rstick_y = 0;
uint8 lstick = 0;
uint8 rstick = 0;
};
GCState get_state(uint32 adapter_index, uint32 index);
private:
std::shared_ptr<libusbWrapper> m_libusb;
libusb_context* m_context = nullptr;
std::atomic_bool m_running = false;
std::thread m_reader_thread, m_writer_thread;
void reader_thread();
void writer_thread();
// handle, endpoint_reader, endpoint_writer
std::tuple<libusb_device_handle*, uint8, uint8> fetch_usb_device(uint32 adapter) const;
std::mutex m_writer_mutex;
std::condition_variable m_writer_cond;
bool m_rumble_changed = false;
struct Adapter
{
std::atomic<libusb_device_handle*> m_device_handle{};
uint8 m_endpoint_reader = 0xFF, m_endpoint_writer = 0xFF;
mutable std::mutex m_state_mutex;
std::array<GCState, kMaxIndex> m_states{};
bool m_rumble_connected = false;
std::array<bool, kMaxIndex> rumble_states{};
};
std::array<Adapter, kMaxAdapters> m_adapters;
libusb_hotplug_callback_handle m_callback_handle = 0;
static int hotplug_event(struct libusb_context* ctx, struct libusb_device* dev, libusb_hotplug_event event, void* user_data);
};
#endif
| 2,042
|
C++
|
.h
| 57
| 33.350877
| 126
| 0.766565
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,370
|
SDLControllerProvider.h
|
cemu-project_Cemu/src/input/api/SDL/SDLControllerProvider.h
|
#pragma once
#include <SDL2/SDL_joystick.h>
#include "input/motion/MotionHandler.h"
#include "input/api/ControllerProvider.h"
#ifndef HAS_SDL
#define HAS_SDL 1
#endif
static bool operator==(const SDL_JoystickGUID& g1, const SDL_JoystickGUID& g2)
{
return memcmp(&g1, &g2, sizeof(SDL_JoystickGUID)) == 0;
}
class SDLControllerProvider : public ControllerProviderBase
{
friend class SDLController;
public:
SDLControllerProvider();
~SDLControllerProvider();
inline static InputAPI::Type kAPIType = InputAPI::SDLController;
InputAPI::Type api() const override { return kAPIType; }
std::vector<std::shared_ptr<ControllerBase>> get_controllers() override;
int get_index(size_t guid_index, const SDL_JoystickGUID& guid) const;
MotionSample motion_sample(int diid);
private:
void event_thread();
std::atomic_bool m_running = false;
std::thread m_thread;
std::array<WiiUMotionHandler, 8> m_motion_handler{};
std::array<MotionSample, 8> m_motion_data{};
std::array<std::mutex, 8> m_motion_data_mtx{};
struct MotionInfoTracking
{
uint64 lastTimestampGyro{};
uint64 lastTimestampAccel{};
uint64 lastTimestampIntegrate{};
bool hasGyro{};
bool hasAcc{};
glm::vec3 gyro{};
glm::vec3 acc{};
};
std::array<MotionInfoTracking, 8> m_motion_tracking{};
};
| 1,284
|
C++
|
.h
| 41
| 29.146341
| 78
| 0.767101
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,371
|
SDLController.h
|
cemu-project_Cemu/src/input/api/SDL/SDLController.h
|
#pragma once
#include "input/api/Controller.h"
#include "input/api/SDL/SDLControllerProvider.h"
#include <SDL2/SDL_gamecontroller.h>
class SDLController : public Controller<SDLControllerProvider>
{
public:
SDLController(const SDL_JoystickGUID& guid, size_t guid_index);
SDLController(const SDL_JoystickGUID& guid, size_t guid_index, std::string_view display_name);
~SDLController() override;
std::string_view api_name() const override
{
static_assert(to_string(InputAPI::SDLController) == "SDLController");
return to_string(InputAPI::SDLController);
}
InputAPI::Type api() const override { return InputAPI::SDLController; }
bool is_connected() override;
bool connect() override;
bool has_motion() override { return m_has_gyro && m_has_accel; }
bool has_rumble() override { return m_has_rumble; }
void start_rumble() override;
void stop_rumble() override;
MotionSample get_motion_sample() override;
std::string get_button_name(uint64 button) const override;
const SDL_JoystickGUID& get_guid() const { return m_guid; }
constexpr static SDL_JoystickGUID kLeftJoyCon{ 0x03, 0x00, 0x00, 0x00, 0x7e, 0x05, 0x00, 0x00, 0x06, 0x20, 0x00, 0x00, 0x00, 0x00,0x68 ,0x00 };
constexpr static SDL_JoystickGUID kRightJoyCon{ 0x03, 0x00, 0x00, 0x00, 0x7e, 0x05, 0x00, 0x00, 0x07, 0x20, 0x00, 0x00, 0x00, 0x00, 0x68, 0x00 };
constexpr static SDL_JoystickGUID kSwitchProController{ 0x03, 0x00, 0x00, 0x00, 0x7e, 0x05, 0x00, 0x00, 0x09, 0x20, 0x00, 0x00, 0x00, 0x00, 0x68, 0x00 };
protected:
ControllerState raw_state() override;
private:
inline static SDL_JoystickGUID kEmptyGUID{};
size_t m_guid_index;
SDL_JoystickGUID m_guid;
std::recursive_mutex m_controller_mutex;
SDL_GameController* m_controller = nullptr;
SDL_JoystickID m_diid = -1;
bool m_has_gyro = false;
bool m_has_accel = false;
bool m_has_rumble = false;
std::array<bool, SDL_CONTROLLER_BUTTON_MAX> m_buttons{};
std::array<bool, SDL_CONTROLLER_AXIS_MAX> m_axis{};
};
| 1,970
|
C++
|
.h
| 43
| 43.488372
| 154
| 0.75958
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,372
|
KeyboardController.h
|
cemu-project_Cemu/src/input/api/Keyboard/KeyboardController.h
|
#pragma once
#include "input/api/Keyboard/KeyboardControllerProvider.h"
#include "input/api/Controller.h"
class KeyboardController : public Controller<KeyboardControllerProvider>
{
public:
KeyboardController();
std::string_view api_name() const override // TODO: use constexpr virtual function with c++20
{
static_assert(to_string(InputAPI::Keyboard) == "Keyboard");
return to_string(InputAPI::Keyboard);
}
InputAPI::Type api() const override { return InputAPI::Keyboard; }
bool is_connected() override { return true; }
bool has_axis() const override { return false; }
std::string get_button_name(uint64 button) const override;
protected:
ControllerState raw_state() override;
};
| 701
|
C++
|
.h
| 19
| 34.789474
| 94
| 0.778932
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,373
|
KeyboardControllerProvider.h
|
cemu-project_Cemu/src/input/api/Keyboard/KeyboardControllerProvider.h
|
#pragma once
#include "input/api/ControllerProvider.h"
#ifndef HAS_KEYBOARD
#define HAS_KEYBOARD 1
#endif
class KeyboardControllerProvider : public ControllerProviderBase
{
friend class KeyboardController;
public:
inline static InputAPI::Type kAPIType = InputAPI::Keyboard;
InputAPI::Type api() const override { return kAPIType; }
std::vector<std::shared_ptr<ControllerBase>> get_controllers() override;
};
| 415
|
C++
|
.h
| 13
| 30.307692
| 73
| 0.816583
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,374
|
WiimoteMessages.h
|
cemu-project_Cemu/src/input/api/Wiimote/WiimoteMessages.h
|
#pragma once
// https://wiibrew.org/wiki/Wiimote
enum InputReportId : uint8
{
kNone = 0,
kStatus = 0x20,
kRead = 0x21,
kAcknowledge = 0x22,
kDataCore = 0x30,
kDataCoreAcc = 0x31,
kDataCoreExt8 = 0x32,
kDataCoreAccIR = 0x33,
kDataCoreExt19 = 0x34,
kDataCoreAccExt = 0x35,
kDataCoreIRExt = 0x36,
kDataCoreAccIRExt = 0x37,
kDataExt = 0x3d,
};
enum RegisterAddress : uint32
{
kRegisterCalibration = 0x16,
kRegisterCalibration2 = 0x20, // backup calibration data
kRegisterIR = 0x4b00030,
kRegisterIRSensitivity1 = 0x4b00000,
kRegisterIRSensitivity2 = 0x4b0001a,
kRegisterIRMode = 0x4b00033,
kRegisterExtensionEncrypted = 0x4a40040,
kRegisterExtension1 = 0x4a400f0,
kRegisterExtension2 = 0x4a400fb,
kRegisterExtensionType = 0x4a400fa,
kRegisterExtensionCalibration = 0x4a40020,
kRegisterMotionPlusDetect = 0x4a600fa,
kRegisterMotionPlusInit = 0x4a600f0,
kRegisterMotionPlusEnable = 0x4a600fe,
};
enum ExtensionType : uint64
{
kExtensionNunchuck = 0x0000A4200000,
kExtensionClassic = 0x0000A4200101,
kExtensionClassicPro = 0x0100A4200101,
kExtensionDrawsome = 0xFF00A4200013,
kExtensionGuitar = 0x0000A4200103,
kExtensionDrums = 0x0100A4200103,
kExtensionBalanceBoard = 0x2A2C,
kExtensionMotionPlus = 0xa6200005,
kExtensionPartialyInserted = 0xffffffffffff,
};
enum MemoryType : uint8
{
kEEPROMMemory = 0,
kRegisterMemory = 0x4,
};
enum StatusBitmask : uint8
{
kBatteryEmpty = 0x1,
kExtensionConnected = 0x2,
kSpeakerEnabled = 0x4,
kIREnabled = 0x8,
kLed1 = 0x10,
kLed2 = 0x20,
kLed3 = 0x40,
kLed4 = 0x80
};
enum OutputReportId : uint8
{
kLED = 0x11,
kType = 0x12,
kIR = 0x13,
kSpeakerState = 0x14,
kStatusRequest = 0x15,
kWriteMemory = 0x16,
kReadMemory = 0x17,
kSpeakerData = 0x18,
kSpeakerMute = 0x19,
kIR2 = 0x1A,
};
enum IRMode : uint8
{
kIRDisabled,
kBasicIR = 1,
kExtendedIR = 3,
kFullIR = 5,
};
enum WiimoteButtons
{
kWiimoteButton_Left = 0,
kWiimoteButton_Right = 1,
kWiimoteButton_Down = 2,
kWiimoteButton_Up = 3,
kWiimoteButton_Plus = 4,
kWiimoteButton_Two = 8,
kWiimoteButton_One = 9,
kWiimoteButton_B = 10,
kWiimoteButton_A = 11,
kWiimoteButton_Minus = 12,
kWiimoteButton_Home = 15,
// self defined
kWiimoteButton_C = 16,
kWiimoteButton_Z = 17,
kHighestWiimote = 20,
};
enum ClassicButtons
{
kClassicButton_R = 1,
kClassicButton_Plus = 2,
kClassicButton_Home = 3,
kClassicButton_Minus = 4,
kClassicButton_L = 5,
kClassicButton_Down = 6,
kClassicButton_Right = 7,
kClassicButton_Up = 8,
kClassicButton_Left = 9,
kClassicButton_ZR = 10,
kClassicButton_X = 11,
kClassicButton_A = 12,
kClassicButton_Y = 13,
kClassicButton_B = 14,
kClassicButton_ZL = 15,
};
struct Calibration
{
glm::vec<3, uint16> zero{ 0x200, 0x200, 0x200 };
glm::vec<3, uint16> gravity{ 0x240, 0x240, 0x240 };
};
struct BasicIR
{
uint8 x1;
uint8 y1;
struct
{
uint8 x2 : 2;
uint8 y2 : 2;
uint8 x1 : 2;
uint8 y1 : 2;
} bits;
static_assert(sizeof(bits) == 1);
uint8 x2;
uint8 y2;
};
static_assert(sizeof(BasicIR) == 5);
struct ExtendedIR
{
uint8 x;
uint8 y;
struct
{
uint8 size : 4;
uint8 x : 2;
uint8 y : 2;
} bits;
static_assert(sizeof(bits) == 1);
};
static_assert(sizeof(ExtendedIR) == 3);
struct IRDot
{
bool visible = false;
glm::vec2 pos;
glm::vec<2, uint16> raw;
uint32 size;
};
struct IRCamera
{
IRMode mode;
std::array<IRDot, 4> dots{}, prev_dots{};
glm::vec2 position, m_prev_position;
glm::vec2 middle;
float distance;
std::pair<sint32, sint32> indices{ 0,1 };
};
struct NunchuchCalibration : Calibration
{
glm::vec<2, uint8> min{};
glm::vec<2, uint8> center{ 0x7f, 0x7f };
glm::vec<2, uint8> max{ 0xff, 0xff };
};
struct MotionPlusData
{
Calibration calibration{};
glm::vec3 orientation; // yaw, roll, pitch
bool slow_roll = false;
bool slow_pitch = false;
bool slow_yaw = false;
bool extension_connected = false;
};
struct NunchuckData
{
glm::vec3 acceleration{}, prev_acceleration{};
NunchuchCalibration calibration{};
bool c = false;
bool z = false;
glm::vec2 axis{};
glm::vec<2, uint8> raw_axis{};
MotionSample motion_sample{};
};
struct ClassicData
{
glm::vec2 left_axis{};
glm::vec<2, uint8> left_raw_axis{};
glm::vec2 right_axis{};
glm::vec<2, uint8> right_raw_axis{};
glm::vec2 trigger{};
glm::vec<2, uint8> raw_trigger{};
uint16 buttons = 0;
};
| 4,329
|
C++
|
.h
| 204
| 19.27451
| 57
| 0.749082
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,375
|
NativeWiimoteController.h
|
cemu-project_Cemu/src/input/api/Wiimote/NativeWiimoteController.h
|
#pragma once
#include "input/api/Controller.h"
#include "input/api/Wiimote/WiimoteControllerProvider.h"
// todo: find better name because of emulated nameclash
class NativeWiimoteController : public Controller<WiimoteControllerProvider>
{
public:
NativeWiimoteController(size_t index);
enum Extension
{
None,
Nunchuck,
Classic,
MotionPlus,
};
std::string_view api_name() const override
{
static_assert(to_string(InputAPI::Wiimote) == "Wiimote");
return to_string(InputAPI::Wiimote);
}
InputAPI::Type api() const override { return InputAPI::Wiimote; }
void save(pugi::xml_node& node) override;
void load(const pugi::xml_node& node) override;
bool connect() override;
bool is_connected() override;
void set_player_index(size_t player_index);
Extension get_extension() const;
bool is_mpls_attached() const;
ControllerState raw_state() override;
bool has_position() override;
glm::vec2 get_position() override;
glm::vec2 get_prev_position() override;
PositionVisibility GetPositionVisibility() override;
bool has_motion() override { return true; }
bool has_rumble() override { return true; }
bool has_battery() override { return true; }
bool has_low_battery() override;
void start_rumble() override;
void stop_rumble() override;
MotionSample get_motion_sample() override;
MotionSample get_nunchuck_motion_sample() const;
std::string get_button_name(uint64 button) const override;
uint32 get_packet_delay();
void set_packet_delay(uint32 delay);
private:
size_t m_index;
size_t m_player_index = 0;
uint32 m_packet_delay = WiimoteControllerProvider::kDefaultPacketDelay;
};
| 1,634
|
C++
|
.h
| 49
| 30.979592
| 76
| 0.775575
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,376
|
WiimoteDevice.h
|
cemu-project_Cemu/src/input/api/Wiimote/WiimoteDevice.h
|
#pragma once
class WiimoteDevice
{
friend class WiimoteInfo;
public:
virtual ~WiimoteDevice() = default;
virtual bool write_data(const std::vector<uint8>& data) = 0;
virtual std::optional<std::vector<uint8_t>> read_data() = 0;
virtual bool operator==(WiimoteDevice& o) const = 0;
bool operator!=(WiimoteDevice& o) const { return *this == o; }
};
using WiimoteDevicePtr = std::shared_ptr<WiimoteDevice>;
| 413
|
C++
|
.h
| 12
| 32.583333
| 63
| 0.745592
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,377
|
WiimoteControllerProvider.h
|
cemu-project_Cemu/src/input/api/Wiimote/WiimoteControllerProvider.h
|
#pragma once
#include "input/motion/MotionHandler.h"
#include "input/api/Wiimote/WiimoteDevice.h"
#include "input/api/Wiimote/WiimoteMessages.h"
#include "input/api/ControllerProvider.h"
#include "input/api/ControllerState.h"
#include <list>
#include <variant>
#include <boost/ptr_container/ptr_vector.hpp>
#ifndef HAS_WIIMOTE
#define HAS_WIIMOTE 1
#endif
#define WIIMOTE_DEBUG 1
class WiimoteControllerProvider : public ControllerProviderBase
{
friend class WiimoteController;
public:
constexpr static uint32 kDefaultPacketDelay = 25;
WiimoteControllerProvider();
~WiimoteControllerProvider();
inline static InputAPI::Type kAPIType = InputAPI::Wiimote;
InputAPI::Type api() const override { return kAPIType; }
std::vector<std::shared_ptr<ControllerBase>> get_controllers() override;
bool is_connected(size_t index);
bool is_registered_device(size_t index);
void set_rumble(size_t index, bool state);
void request_status(size_t index);
void set_led(size_t index, size_t player_index);
uint32 get_packet_delay(size_t index);
void set_packet_delay(size_t index, uint32 delay);
struct WiimoteState
{
uint16 buttons = 0;
uint8 flags = 0;
uint8 battery_level = 0;
glm::vec3 m_acceleration{}, m_prev_acceleration{};
float m_roll = 0;
std::chrono::high_resolution_clock::time_point m_last_motion_timestamp{};
MotionSample motion_sample{};
WiiUMotionHandler motion_handler{};
bool m_calibrated = false;
Calibration m_calib_acceleration{};
struct IRCamera
{
IRMode mode = kIRDisabled;
std::array<IRDot, 4> dots{}, prev_dots{};
glm::vec2 position{}, m_prev_position{};
PositionVisibility m_positionVisibility;
glm::vec2 middle {};
float distance = 0;
std::pair<sint32, sint32> indices{ 0,1 };
}ir_camera{};
std::optional<MotionPlusData> m_motion_plus;
std::variant<std::monostate, NunchuckData, ClassicData> m_extension{};
};
WiimoteState get_state(size_t index);
private:
std::atomic_bool m_running = false;
std::thread m_reader_thread, m_writer_thread;
std::shared_mutex m_device_mutex;
struct Wiimote
{
Wiimote(WiimoteDevicePtr device)
: device(std::move(device)) {}
WiimoteDevicePtr device;
std::atomic_bool connected = true;
std::atomic_bool rumble = false;
std::shared_mutex mutex;
WiimoteState state{};
std::atomic_uint32_t data_delay = kDefaultPacketDelay;
std::chrono::high_resolution_clock::time_point data_ts{};
};
boost::ptr_vector<Wiimote> m_wiimotes;
std::list<std::pair<size_t,std::vector<uint8>>> m_write_queue;
std::mutex m_writer_mutex;
std::condition_variable m_writer_cond;
void reader_thread();
void writer_thread();
void calibrate(size_t index);
IRMode set_ir_camera(size_t index, bool state);
void send_packet(size_t index, std::vector<uint8> data);
void send_read_packet(size_t index, MemoryType type, RegisterAddress address, uint16 size);
void send_write_packet(size_t index, MemoryType type, RegisterAddress address, const std::vector<uint8>& data);
void parse_acceleration(WiimoteState& wiimote_state, const uint8*& data);
void rotate_ir(WiimoteState& wiimote_state);
void calculate_ir_position(WiimoteState& wiimote_state);
int parse_ir(WiimoteState& wiimote_state, const uint8* data);
void request_extension(size_t index);
void detect_motion_plus(size_t index);
void set_motion_plus(size_t index, bool state);
void update_report_type(size_t index);
};
| 3,422
|
C++
|
.h
| 92
| 34.565217
| 112
| 0.763741
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,378
|
HidapiWiimote.h
|
cemu-project_Cemu/src/input/api/Wiimote/hidapi/HidapiWiimote.h
|
#pragma once
#include <api/Wiimote/WiimoteDevice.h>
#include <hidapi.h>
class HidapiWiimote : public WiimoteDevice {
public:
HidapiWiimote(hid_device* dev, std::string_view path);
~HidapiWiimote() override;
bool write_data(const std::vector<uint8> &data) override;
std::optional<std::vector<uint8>> read_data() override;
bool operator==(WiimoteDevice& o) const override;
static std::vector<WiimoteDevicePtr> get_devices();
private:
hid_device* m_handle;
const std::string m_path;
};
using WiimoteDevice_t = HidapiWiimote;
| 560
|
C++
|
.h
| 16
| 31.625
| 61
| 0.743494
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,379
|
WiimoteController.h
|
cemu-project_Cemu/src/input/emulated/WiimoteController.h
|
#pragma once
#include "input/emulated/WPADController.h"
class WiimoteController : public WPADController
{
using base_type = WPADController;
public:
enum ButtonId
{
kButtonId_None,
kButtonId_A,
kButtonId_B,
kButtonId_1,
kButtonId_2,
kButtonId_Nunchuck_Z,
kButtonId_Nunchuck_C,
kButtonId_Plus,
kButtonId_Minus,
kButtonId_Up,
kButtonId_Down,
kButtonId_Left,
kButtonId_Right,
kButtonId_Nunchuck_Up,
kButtonId_Nunchuck_Down,
kButtonId_Nunchuck_Left,
kButtonId_Nunchuck_Right,
kButtonId_Home,
kButtonId_Max,
};
WiimoteController(size_t player_index);
Type type() const override { return Type::Wiimote; }
WPADDeviceType get_device_type() const override { return m_device_type; }
void set_device_type(WPADDeviceType device_type);
bool is_mpls_attached() override;
uint32 get_emulated_button_flag(uint32 id) const override;
size_t get_highest_mapping_id() const override { return kButtonId_Max; }
bool is_axis_mapping(uint64 mapping) const override { return mapping >= kButtonId_Nunchuck_Up && mapping <= kButtonId_Nunchuck_Right; }
bool set_default_mapping(const std::shared_ptr<ControllerBase>& controller) override;
glm::vec2 get_axis() const override;
glm::vec2 get_rotation() const override;
glm::vec2 get_trigger() const override;
void load(const pugi::xml_node& node) override;
void save(pugi::xml_node& node) override;
static uint32 s_get_emulated_button_flag(uint32 id);
static std::string_view get_button_name(ButtonId id);
bool is_start_down() const override { return is_mapping_down(kButtonId_Plus); }
bool is_left_down() const override { return is_mapping_down(kButtonId_Left); }
bool is_right_down() const override { return is_mapping_down(kButtonId_Right); }
bool is_up_down() const override { return is_mapping_down(kButtonId_Up); }
bool is_down_down() const override { return is_mapping_down(kButtonId_Down); }
bool is_a_down() const override { return is_mapping_down(kButtonId_A); }
bool is_b_down() const override { return is_mapping_down(kButtonId_B); }
bool is_home_down() const override { return is_mapping_down(kButtonId_Home); }
private:
WPADDeviceType m_device_type = kWAPDevCore;
};
| 2,190
|
C++
|
.h
| 55
| 37.181818
| 136
| 0.767045
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,380
|
VPADController.h
|
cemu-project_Cemu/src/input/emulated/VPADController.h
|
#pragma once
#include "input/emulated/EmulatedController.h"
#include "Cafe/OS/libs/vpad/vpad.h"
class VPADController : public EmulatedController
{
public:
enum ButtonId
{
kButtonId_None,
kButtonId_A,
kButtonId_B,
kButtonId_X,
kButtonId_Y,
kButtonId_L,
kButtonId_R,
kButtonId_ZL,
kButtonId_ZR,
kButtonId_Plus,
kButtonId_Minus,
kButtonId_Up,
kButtonId_Down,
kButtonId_Left,
kButtonId_Right,
kButtonId_StickL,
kButtonId_StickR,
kButtonId_StickL_Up,
kButtonId_StickL_Down,
kButtonId_StickL_Left,
kButtonId_StickL_Right,
kButtonId_StickR_Up,
kButtonId_StickR_Down,
kButtonId_StickR_Left,
kButtonId_StickR_Right,
kButtonId_Mic,
kButtonId_Screen,
kButtonId_Home,
kButtonId_Max,
};
using EmulatedController::EmulatedController;
Type type() const override { return VPAD; }
void VPADRead(VPADStatus_t& status, const BtnRepeat& repeat);
void update() override;
uint32 get_emulated_button_flag(uint32 id) const override;
glm::vec2 get_axis() const override;
glm::vec2 get_rotation() const override;
glm::vec2 get_trigger() const override;
bool is_mic_active() { return m_mic_active; }
bool is_screen_active() { return m_screen_active; }
bool is_screen_active_toggle() { return m_screen_active_toggle; }
void set_screen_toggle(bool toggle) {m_screen_active_toggle = toggle;}
static std::string_view get_button_name(ButtonId id);
void clear_rumble();
bool push_rumble(uint8* pattern, uint8 length);
size_t get_highest_mapping_id() const override { return kButtonId_Max; }
bool is_axis_mapping(uint64 mapping) const override { return mapping >= kButtonId_StickL_Up && mapping <= kButtonId_StickR_Right; }
bool is_start_down() const override { return is_mapping_down(kButtonId_Plus); }
bool is_left_down() const override { return is_mapping_down(kButtonId_Left); }
bool is_right_down() const override { return is_mapping_down(kButtonId_Right); }
bool is_up_down() const override { return is_mapping_down(kButtonId_Up); }
bool is_down_down() const override { return is_mapping_down(kButtonId_Down); }
bool is_a_down() const override { return is_mapping_down(kButtonId_A); }
bool is_b_down() const override { return is_mapping_down(kButtonId_B); }
bool is_home_down() const override { return is_mapping_down(kButtonId_Home); }
bool set_default_mapping(const std::shared_ptr<ControllerBase>& controller) override;
void load(const pugi::xml_node& node) override;
void save(pugi::xml_node& node) override;
private:
bool m_mic_active = false;
bool m_screen_active = false;
bool m_screen_active_toggle = false;
uint32be m_last_holdvalue = 0;
std::chrono::high_resolution_clock::time_point m_last_hold_change{}, m_last_pulse{};
std::mutex m_rumble_mutex;
std::chrono::high_resolution_clock::time_point m_last_rumble_check{};
std::queue<std::vector<bool>> m_rumble_queue;
uint8 m_parser = 0;
void update_touch(VPADStatus_t& status);
void update_motion(VPADStatus_t& status);
glm::ivec2 m_last_touch_position{};
};
| 3,020
|
C++
|
.h
| 80
| 35.1125
| 132
| 0.757045
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,381
|
ClassicController.h
|
cemu-project_Cemu/src/input/emulated/ClassicController.h
|
#pragma once
#include "input/emulated/WPADController.h"
class ClassicController : public WPADController
{
public:
enum ButtonId
{
kButtonId_None,
kButtonId_A,
kButtonId_B,
kButtonId_X,
kButtonId_Y,
kButtonId_L,
kButtonId_R,
kButtonId_ZL,
kButtonId_ZR,
kButtonId_Plus,
kButtonId_Minus,
kButtonId_Home,
kButtonId_Up,
kButtonId_Down,
kButtonId_Left,
kButtonId_Right,
kButtonId_StickL_Up,
kButtonId_StickL_Down,
kButtonId_StickL_Left,
kButtonId_StickL_Right,
kButtonId_StickR_Up,
kButtonId_StickR_Down,
kButtonId_StickR_Left,
kButtonId_StickR_Right,
kButtonId_Max,
};
ClassicController(size_t player_index);
Type type() const override { return Type::Classic; }
WPADDeviceType get_device_type() const override { return kWAPDevClassic; }
uint32 get_emulated_button_flag(uint32 id) const override;
size_t get_highest_mapping_id() const override { return kButtonId_Max; }
bool is_axis_mapping(uint64 mapping) const override { return mapping >= kButtonId_StickL_Up && mapping <= kButtonId_StickR_Right; }
glm::vec2 get_axis() const override;
glm::vec2 get_rotation() const override;
glm::vec2 get_trigger() const override;
static uint32 s_get_emulated_button_flag(uint32 id);
static std::string_view get_button_name(ButtonId id);
bool is_start_down() const override { return is_mapping_down(kButtonId_Plus); }
bool is_left_down() const override { return is_mapping_down(kButtonId_Left); }
bool is_right_down() const override { return is_mapping_down(kButtonId_Right); }
bool is_up_down() const override { return is_mapping_down(kButtonId_Up); }
bool is_down_down() const override { return is_mapping_down(kButtonId_Down); }
bool is_a_down() const override { return is_mapping_down(kButtonId_A); }
bool is_b_down() const override { return is_mapping_down(kButtonId_B); }
bool is_home_down() const override { return is_mapping_down(kButtonId_Home); }
bool set_default_mapping(const std::shared_ptr<ControllerBase>& controller) override;
};
| 2,020
|
C++
|
.h
| 54
| 34.722222
| 132
| 0.76386
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,382
|
EmulatedController.h
|
cemu-project_Cemu/src/input/emulated/EmulatedController.h
|
#pragma once
#include <pugixml.hpp>
class ControllerBase;
#include "input/motion/MotionSample.h"
#include "input/api/ControllerState.h"
#include "input/api/InputAPI.h"
#include "util/helpers/helpers.h"
// mapping = wii u controller button id
// button = api button id
class EmulatedController
{
friend class InputManager;
public:
EmulatedController(size_t player_index);
virtual ~EmulatedController() = default;
virtual void load(const pugi::xml_node& node){};
virtual void save(pugi::xml_node& node){};
enum Type
{
VPAD,
Pro,
Classic,
Wiimote,
MAX
};
virtual Type type() const = 0;
std::string_view type_string() const { return type_to_string(type()); }
static std::string_view type_to_string(Type type);
static Type type_from_string(std::string_view str);
size_t player_index() const { return m_player_index; }
const std::string& get_profile_name() const { return m_profile_name; }
bool has_profile_name() const { return !m_profile_name.empty() && m_profile_name != "default"; }
void calibrate();
void connect();
virtual void update();
void controllers_update_states();
virtual glm::vec2 get_axis() const = 0;
virtual glm::vec2 get_rotation() const = 0;
virtual glm::vec2 get_trigger() const = 0;
void start_rumble();
void stop_rumble();
bool is_battery_low() const;
bool has_motion() const;
MotionSample get_motion_data() const;
// some controllers (nunchuck) provide extra motion data
bool has_second_motion() const;
MotionSample get_second_motion_data() const;
bool has_position() const;
glm::vec2 get_position() const;
glm::vec2 get_prev_position() const;
PositionVisibility GetPositionVisibility() const;
void add_controller(std::shared_ptr<ControllerBase> controller);
void remove_controller(const std::shared_ptr<ControllerBase>& controller);
void clear_controllers();
const std::vector<std::shared_ptr<ControllerBase>>& get_controllers() const { return m_controllers; }
bool is_mapping_down(uint64 mapping) const;
std::string get_mapping_name(uint64 mapping) const;
std::shared_ptr<ControllerBase> get_mapping_controller(uint64 mapping) const;
void delete_mapping(uint64 mapping);
void clear_mappings();
void set_mapping(uint64 mapping, const std::shared_ptr<ControllerBase>& controller_base, uint64 button);
virtual uint32 get_emulated_button_flag(uint32 mapping) const = 0;
bool operator==(const EmulatedController& o) const;
bool operator!=(const EmulatedController& o) const;
virtual size_t get_highest_mapping_id() const = 0;
virtual bool is_axis_mapping(uint64 mapping) const = 0;
virtual bool is_start_down() const = 0;
virtual bool is_left_down() const = 0;
virtual bool is_right_down() const = 0;
virtual bool is_up_down() const = 0;
virtual bool is_down_down() const = 0;
virtual bool is_a_down() const = 0;
virtual bool is_b_down() const = 0;
virtual bool is_home_down() const = 0;
bool was_home_button_down() { return std::exchange(m_homebutton_down, false); }
virtual bool set_default_mapping(const std::shared_ptr<ControllerBase>& controller) { return false; }
protected:
size_t m_player_index;
std::string m_profile_name = "default";
mutable std::shared_mutex m_mutex;
std::vector<std::shared_ptr<ControllerBase>> m_controllers;
float get_axis_value(uint64 mapping) const;
bool m_rumble = false;
struct Mapping
{
std::weak_ptr<ControllerBase> controller;
uint64 button;
};
std::unordered_map<uint64, Mapping> m_mappings;
bool m_homebutton_down = false;
};
using EmulatedControllerPtr = std::shared_ptr<EmulatedController>;
template <>
struct fmt::formatter<EmulatedController::Type> : formatter<string_view> {
template <typename FormatContext>
auto format(EmulatedController::Type v, FormatContext& ctx) const {
switch (v)
{
case EmulatedController::Type::VPAD: return formatter<string_view>::format("Wii U Gamepad", ctx);
case EmulatedController::Type::Pro: return formatter<string_view>::format("Wii U Pro Controller", ctx);
case EmulatedController::Type::Classic: return formatter<string_view>::format("Wii U Classic Controller Pro", ctx);
case EmulatedController::Type::Wiimote: return formatter<string_view>::format("Wiimote", ctx);
}
throw std::invalid_argument(fmt::format("invalid emulated controller type with value {}", to_underlying(v)));
}
};
| 4,317
|
C++
|
.h
| 106
| 38.433962
| 117
| 0.755806
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,383
|
WPADController.h
|
cemu-project_Cemu/src/input/emulated/WPADController.h
|
#pragma once
#include <wx/cmdargs.h>
#include "input/emulated/EmulatedController.h"
#include "Cafe/OS/libs/padscore/padscore.h"
#include "Cafe/OS/libs/vpad/vpad.h"
constexpr uint32 kWPADButtonRepeat = 0x80000000;
enum WPADDeviceType
{
kWAPDevCore = 0,
kWAPDevFreestyle = 1,
kWAPDevClassic = 2,
kWAPDevMPLS = 5,
kWAPDevMPLSFreeStyle = 6,
kWAPDevMPLSClassic = 7,
kWAPDevURCC = 31,
kWAPDevNotFound = 253,
kWAPDevUnknown = 255,
};
// core, balanceboard
enum WPADCoreButtons
{
kWPADButton_Left = 0x1,
kWPADButton_Right = 0x2,
kWPADButton_Down = 0x4,
kWPADButton_Up = 0x8,
kWPADButton_Plus = 0x10,
kWPADButton_2 = 0x100,
kWPADButton_1 = 0x200,
kWPADButton_B = 0x400,
kWPADButton_A = 0x800,
kWPADButton_Minus = 0x1000,
kWPADButton_Home = 0x8000,
};
// Nunchuck aka Freestyle
enum WPADNunchuckButtons
{
kWPADButton_Z = 0x2000,
kWPADButton_C = 0x4000,
};
// Classic Controller
enum WPADClassicButtons
{
kCLButton_Up = 0x1,
kCLButton_Left = 0x2,
kCLButton_ZR = 0x4,
kCLButton_X = 0x8,
kCLButton_A = 0x10,
kCLButton_Y = 0x20,
kCLButton_B = 0x40,
kCLButton_ZL = 0x80,
kCLButton_R = 0x200,
kCLButton_Plus = 0x400,
kCLButton_Home = 0x800,
kCLButton_Minus = 0x1000,
kCLButton_L = 0x2000,
kCLButton_Down = 0x4000,
kCLButton_Right = 0x8000
};
// Pro Controller aka URCC
enum WPADProButtons
{
kProButton_Up = 0x1,
kProButton_Left = 0x2,
kProButton_ZR = 0x4,
kProButton_X = 0x8,
kProButton_A = 0x10,
kProButton_Y = 0x20,
kProButton_B = 0x40,
kProButton_ZL = 0x80,
kProButton_R = 0x200,
kProButton_Plus = 0x400,
kProButton_Home = 0x800,
kProButton_Minus = 0x1000,
kProButton_L = 0x2000,
kProButton_Down = 0x4000,
kProButton_Right = 0x8000,
kProButton_StickR = 0x10000,
kProButton_StickL = 0x20000
};
enum WPADDataFormat {
kDataFormat_CORE = 0,
kDataFormat_CORE_ACC = 1,
kDataFormat_CORE_ACC_DPD = 2,
kDataFormat_FREESTYLE = 3,
kDataFormat_FREESTYLE_ACC = 4,
kDataFormat_FREESTYLE_ACC_DPD = 5,
kDataFormat_CLASSIC = 6,
kDataFormat_CLASSIC_ACC = 7,
kDataFormat_CLASSIC_ACC_DPD = 8,
kDataFormat_CORE_ACC_DPD_FULL = 9, // buttons, motion, pointing
kDataFormat_TRAIN = 10,
kDataFormat_GUITAR = 11,
kDataFormat_BALANCE_CHECKER = 12,
kDataFormat_DRUM = 15,
kDataFormat_MPLS = 16, // buttons, motion, pointing, motion plus
kDataFormat_TAIKO = 17,
kDataFormat_URCC = 22, // buttons, URCC aka pro
};
class WPADController : public EmulatedController
{
using base_type = EmulatedController;
public:
WPADController(size_t player_index, WPADDataFormat data_format);
uint32 get_emulated_button_flag(WPADDataFormat format, uint32 id) const;
virtual WPADDeviceType get_device_type() const = 0;
WPADDataFormat get_data_format() const { return m_data_format; }
void set_data_format(WPADDataFormat data_format) { m_data_format = data_format; }
void WPADRead(WPADStatus_t* status);
void KPADRead(KPADStatus_t& status, const BtnRepeat& repeat);
virtual bool is_mpls_attached() { return false; }
enum class ConnectCallbackStatus
{
None, // do nothing
ReportDisconnect, // call disconnect
ReportConnect, // call connect
};
ConnectCallbackStatus m_status = ConnectCallbackStatus::ReportConnect;
ConnectCallbackStatus m_extension_status = ConnectCallbackStatus::ReportConnect;
WPADDataFormat get_default_data_format() const;
protected:
WPADDataFormat m_data_format;
private:
uint32be m_last_holdvalue = 0;
std::chrono::steady_clock::time_point m_last_hold_change{}, m_last_pulse{};
};
| 3,474
|
C++
|
.h
| 125
| 25.712
| 82
| 0.766687
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,384
|
ProController.h
|
cemu-project_Cemu/src/input/emulated/ProController.h
|
#pragma once
#include "input/emulated/WPADController.h"
class ProController : public WPADController
{
public:
enum ButtonId
{
kButtonId_None,
kButtonId_A,
kButtonId_B,
kButtonId_X,
kButtonId_Y,
kButtonId_L,
kButtonId_R,
kButtonId_ZL,
kButtonId_ZR,
kButtonId_Plus,
kButtonId_Minus,
kButtonId_Home,
kButtonId_Up,
kButtonId_Down,
kButtonId_Left,
kButtonId_Right,
kButtonId_StickL,
kButtonId_StickR,
kButtonId_StickL_Up,
kButtonId_StickL_Down,
kButtonId_StickL_Left,
kButtonId_StickL_Right,
kButtonId_StickR_Up,
kButtonId_StickR_Down,
kButtonId_StickR_Left,
kButtonId_StickR_Right,
kButtonId_Max,
};
ProController(size_t player_index);
Type type() const override { return Type::Pro; }
WPADDeviceType get_device_type() const override { return kWAPDevURCC; }
uint32 get_emulated_button_flag(uint32 id) const override;
size_t get_highest_mapping_id() const override { return kButtonId_Max; }
bool is_axis_mapping(uint64 mapping) const override { return mapping >= kButtonId_StickL_Up && mapping <= kButtonId_StickR_Right; }
glm::vec2 get_axis() const override;
glm::vec2 get_rotation() const override;
glm::vec2 get_trigger() const override;
static uint32 s_get_emulated_button_flag(uint32 id);
static std::string_view get_button_name(ButtonId id);
bool is_start_down() const override { return is_mapping_down(kButtonId_Plus); }
bool is_left_down() const override { return is_mapping_down(kButtonId_Left); }
bool is_right_down() const override { return is_mapping_down(kButtonId_Right); }
bool is_up_down() const override { return is_mapping_down(kButtonId_Up); }
bool is_down_down() const override { return is_mapping_down(kButtonId_Down); }
bool is_a_down() const override { return is_mapping_down(kButtonId_A); }
bool is_b_down() const override { return is_mapping_down(kButtonId_B); }
bool is_home_down() const override { return is_mapping_down(kButtonId_Home); }
bool set_default_mapping(const std::shared_ptr<ControllerBase>& controller) override;
};
| 2,045
|
C++
|
.h
| 56
| 33.821429
| 132
| 0.762557
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,385
|
MotionSample.h
|
cemu-project_Cemu/src/input/motion/MotionSample.h
|
#pragma once
#include "util/math/vector3.h"
#include "util/math/quaternion.h"
struct Quat
{
float w;
float x;
float y;
float z;
Quat()
{
w = 1.0f;
x = 0.0f;
y = 0.0f;
z = 0.0f;
}
Quat(float inW, float inX, float inY, float inZ)
{
w = inW;
x = inX;
y = inY;
z = inZ;
}
static Quat AngleAxis(float inAngle, float inX, float inY, float inZ)
{
Quat result = Quat(cosf(inAngle * 0.5f), inX, inY, inZ);
result.Normalize();
return result;
}
void Set(float inW, float inX, float inY, float inZ)
{
w = inW;
x = inX;
y = inY;
z = inZ;
}
Quat& operator*=(const Quat& rhs)
{
Set(w * rhs.w - x * rhs.x - y * rhs.y - z * rhs.z,
w * rhs.x + x * rhs.w + y * rhs.z - z * rhs.y,
w * rhs.y - x * rhs.z + y * rhs.w + z * rhs.x,
w * rhs.z + x * rhs.y - y * rhs.x + z * rhs.w);
return *this;
}
friend Quat operator*(Quat lhs, const Quat& rhs)
{
lhs *= rhs;
return lhs;
}
void Normalize()
{
//printf("Normalizing: %.4f, %.4f, %.4f, %.4f\n", w, x, y, z);
const float length = sqrtf(x * x + y * y + z * z);
float targetLength = 1.0f - w * w;
if (targetLength <= 0.0f || length <= 0.0f)
{
Set(1.0f, 0.0f, 0.0f, 0.0f);
return;
}
targetLength = sqrtf(targetLength);
const float fixFactor = targetLength / length;
x *= fixFactor;
y *= fixFactor;
z *= fixFactor;
//printf("Normalized: %.4f, %.4f, %.4f, %.4f\n", w, x, y, z);
return;
}
Quat Normalized() const
{
Quat result = *this;
result.Normalize();
return result;
}
void Conjugate()
{
x = -x;
y = -y;
z = -z;
return;
}
Quat Conjugated() const
{
Quat result = *this;
result.Conjugate();
return result;
}
};
// helper class to store unified motion data
// supports retrieving values in their API-specific (VPAD, KPAD etc.) format
class MotionSample
{
public:
MotionSample() = default;
MotionSample(float acc[3], float accAcceleration, float gyro[3], float orientation[3],
float quaternion[4]
)
{
m_acc[0] = acc[0];
m_acc[1] = acc[1];
m_acc[2] = acc[2];
m_accAcceleration = accAcceleration;
m_gyro[0] = gyro[0];
m_gyro[1] = gyro[1];
m_gyro[2] = gyro[2];
m_orientation[0] = orientation[0];
m_orientation[1] = orientation[1];
m_orientation[2] = orientation[2];
m_q[0] = quaternion[0];
m_q[1] = quaternion[1];
m_q[2] = quaternion[2];
m_q[3] = quaternion[3];
m_accMagnitude = sqrtf(m_acc[0] * m_acc[0] + m_acc[1] * m_acc[1] + m_acc[2] * m_acc[2]);
}
void getVPADOrientation(float orientation[3])
{
orientation[0] = m_orientation[0];
orientation[1] = m_orientation[1];
orientation[2] = m_orientation[2];
}
void getVPADGyroChange(float gyro[3])
{
// filter noise
if (fabs(gyro[0]) < 0.012f)
gyro[0] = 0.0f;
if (fabs(gyro[1]) < 0.012f)
gyro[1] = 0.0f;
if (fabs(gyro[2]) < 0.012f)
gyro[2] = 0.0f;
// convert
gyro[0] = _radToOrientation(-m_gyro[0]);
gyro[1] = _radToOrientation(-m_gyro[1]);
gyro[2] = _radToOrientation(m_gyro[2]);
}
void getVPADAccelerometer(float acc[3])
{
acc[0] = -m_acc[0];
acc[1] = -m_acc[1];
acc[2] = m_acc[2];
}
float getVPADAccMagnitude()
{
return m_accMagnitude;
}
float getVPADAccAcceleration() // Possibly not entirely correct. Our results are smaller than VPAD API ones
{
return m_accAcceleration;
}
void getVPADAccXY(float accXY[2])
{
float invMag = 1.0f / m_accMagnitude;
float normAcc[3];
normAcc[0] = m_acc[0] * invMag;
normAcc[1] = m_acc[1] * invMag;
normAcc[2] = m_acc[2] * invMag;
accXY[0] = sqrtf(normAcc[0] * normAcc[0] + normAcc[1] * normAcc[1]);
accXY[1] = -sin(getAtanPitch(-normAcc[2], normAcc[0], -normAcc[1]));
}
void getXVector(float vOut[3], Quaternionf& q)
{
float X = q.x;
float Y = q.y;
float Z = q.z;
float W = q.w;
float xy = X * Y;
float xz = X * Z;
float yy = Y * Y;
float yw = Y * W;
float zz = Z * Z;
float zw = Z * W;
vOut[0] = 1.0f - 2.0f * (yy + zz); // x.x
vOut[2] = 2.0f * (xy + zw); // x.y
vOut[1] = 2.0f * (xz - yw); // x.z
}
void getVPADAttitudeMatrix(float mtx[9])
{
// VPADs attitude matrix has mixed axis handedness, the most sane way to replicate it is by generating Y and Z by rotating the X vector
Quaternionf qImu(m_q[0], m_q[1], m_q[2], m_q[3]);
Quaternionf qY = qImu * Quaternionf::FromAngleAxis(1.5708f * 1.0f, 0.0f, 0.0f, 1.0f);
Quaternionf qZ = qImu * Quaternionf::FromAngleAxis(1.5708f * 1.0f, 0.0f, 1.0f, 0.0f);
getXVector(mtx + 0, qImu);
getXVector(mtx + 3, qY);
getXVector(mtx + 6, qZ);
}
static float calculateAccAcceleration(float prevAcc[3], float currentAcc[3])
{
float ax = currentAcc[0] - prevAcc[0];
float ay = currentAcc[1] - prevAcc[1];
float az = currentAcc[2] - prevAcc[2];
return sqrtf(ax * ax + ay * ay + az * az);
}
void getAccelerometer(float acc[3])
{
acc[0] = m_acc[0];
acc[1] = m_acc[1];
acc[2] = m_acc[2];
}
void getGyrometer(float gyro[3])
{
gyro[0] = m_gyro[0];
gyro[1] = m_gyro[1];
gyro[2] = m_gyro[2];
}
private:
static float _radToOrientation(float rad)
{
return rad / (2.0f * 3.14159265f);
}
static float getAtanPitch(float X, float Y, float Z)
{
return atan2f(-X, sqrtf(Y * Y + Z * Z));
}
// provided values
float m_gyro[3]{};
float m_acc[3]{};
float m_accAcceleration{};
float m_orientation[3]{};
float m_q[4]{};
// calculated values
float m_accMagnitude{};
};
/*
Captured VPAD attitude values
Assuming GamePad is in a direct line between player (holder) and the monitor
DRC flat on table, screen facing up. Top pointing away (away from person, pointing towards monitor):
1.00 -0.03 -0.00
0.03 0.99 -0.13
0.01 0.13 0.99
Turned 45° to the right:
0.71 -0.03 0.71
0.12 0.99 -0.08
-0.70 0.14 0.70
Turned 45° to the right (top of GamePad pointing right now):
0.08 -0.03 1.00 -> Z points towards person
0.15 0.99 0.01
-0.99 0.15 0.09 -> DRC Z-Axis now points towards X-minus
Turned 90° to the right (top of gamepad now pointing towards holder, away from monitor):
-1.00 -0.01 0.06
0.00 0.99 0.15
-0.06 0.15 -0.99
Turned 90° to the right (pointing left):
-0.17 -0.01 -0.99
-0.13 0.99 0.02
0.98 0.13 -0.17
After another 90° we end up in the initial position:
0.99 -0.03 -0.11
0.01 0.99 -0.13
0.12 0.12 0.99
------
From initial position, lean the GamePad on its left side. 45° up. So the screen is pointing to the top left
0.66 -0.75 -0.03
0.74 0.66 -0.11
0.10 0.05 0.99
Further 45°, GamePad now on its left, screen pointing left:
-0.03 -1.00 -0.00
0.99 -0.03 -0.15
0.15 -0.01 0.99
From initial position, lean the GamePad on its right side. 45° up. So the screen is pointing to the top right
0.75 0.65 -0.11
-0.65 0.76 0.07
0.12 0.02 0.99
From initial position, tilt the GamePad up 90° (bottom side remains in touch with surface):
0.99 -0.05 -0.10
-0.10 0.01 -0.99
0.05 1.00 0.01
From initial position, stand the GamePad on its top side:
1.00 -0.01 -0.09
0.09 -0.01 1.00
-0.01 -1.00 -0.01
Rotate GamePad 180° around x axis, so it now lies on its screen (top of GamePad pointing to holder):
0.99 -0.03 -0.15
-0.04 -1.00 -0.08
-0.15 0.09 -0.99
*/
| 7,248
|
C++
|
.h
| 273
| 24.043956
| 137
| 0.62612
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,386
|
MotionHandler.h
|
cemu-project_Cemu/src/input/motion/MotionHandler.h
|
#pragma once
#include "Mahony.h"
#include "MotionSample.h"
// utility class to translate external motion input (DSU, SDL GamePad sensors) into the values expected by VPAD API (and maybe others in the future)
class WiiUMotionHandler
{
public:
// gyro is in radians/sec
void processMotionSample(
float deltaTime,
float gx, float gy, float gz,
float accx, float accy, float accz)
{
m_gyro[0] = gx;
m_gyro[1] = gy;
m_gyro[2] = gz;
m_prevAcc[0] = m_acc[0];
m_prevAcc[1] = m_acc[1];
m_prevAcc[2] = m_acc[2];
m_acc[0] = accx;
m_acc[1] = accy;
m_acc[2] = accz;
// integrate acc and gyro samples into IMU
m_imu.updateIMU(deltaTime, gx, gy, gz, accx, accy, accz);
// get orientation from IMU
m_orientation[0] = _radToOrientation(-m_imu.getYawRadians()) - 0.50f;
m_orientation[1] = _radToOrientation(-m_imu.getPitchRadians()) - 0.50f;
m_orientation[2] = _radToOrientation(m_imu.getRollRadians());
}
MotionSample getMotionSample()
{
float q[4];
m_imu.getQuaternion(q);
float gBias[3];
m_imu.getGyroBias(gBias);
float gyroDebiased[3];
gyroDebiased[0] = m_gyro[0] - gBias[0];
gyroDebiased[1] = m_gyro[1] - gBias[1];
gyroDebiased[2] = m_gyro[2] - gBias[2];
return MotionSample(m_acc, MotionSample::calculateAccAcceleration(m_prevAcc, m_acc), gyroDebiased, m_orientation, q);
}
private:
// VPAD orientation unit is 1.0 = one revolution around the axis
float _radToOrientation(float rad)
{
return rad / (2.0f * 3.14159265f);
}
MahonySensorFusion m_imu;
// state
float m_gyro[3]{};
float m_acc[3]{};
float m_prevAcc[3]{};
// calculated values
float m_orientation[3]{};
};
| 1,632
|
C++
|
.h
| 55
| 27.254545
| 148
| 0.700572
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,387
|
Mahony.h
|
cemu-project_Cemu/src/input/motion/Mahony.h
|
#pragma once
#include <math.h>
#include <cmath>
#include "util/math/quaternion.h"
class MahonySensorFusion
{
public:
MahonySensorFusion()
{
// assume default forward pose (holding controller in hand, tilted forward so the sticks/buttons face upward)
m_imuQ.Assign(sqrtf(0.5), sqrtf(0.5), 0.0f, 0.0f);
}
// gx, gy, gz are in radians/sec
void updateIMU(float deltaTime, float gx, float gy, float gz, float ax, float ay, float az)
{
Vector3f av(ax, ay, az);
Vector3f gv(gx, gy, gz);
if (deltaTime > 0.2f)
deltaTime = 0.2f; // dont let stutter mess up the internal state
updateGyroBias(gx, gy, gz);
gv.x -= m_gyroBias[0];
gv.y -= m_gyroBias[1];
gv.z -= m_gyroBias[2];
// ignore small angles to avoid drift due to bias (especially on yaw)
if (fabs(gv.x) < 0.015f)
gv.x = 0.0f;
if (fabs(gv.y) < 0.015f)
gv.y = 0.0f;
if (fabs(gv.z) < 0.015f)
gv.z = 0.0f;
// cemuLog_logDebug(LogType::Force, "[IMU Quat] time {:7.4} | {:7.2} {:7.2} {:7.2} {:7.2} | gyro( - bias) {:7.4} {:7.4} {:7.4} | acc {:7.2} {:7.2} {:7.2} | GyroBias {:7.4} {:7.4} {:7.4}", deltaTime, m_imuQ.x, m_imuQ.y, m_imuQ.z, m_imuQ.w, gv.x, gv.y, gv.z, ax, ay, az, m_gyroBias[0], m_gyroBias[1], m_gyroBias[2]);
if (fabs(av.x) > 0.000001f || fabs(av.y) > 0.000001f || fabs(av.z) > 0.000001f)
{
av.Normalize();
Vector3f grav = m_imuQ.GetVectorZ();
grav.Scale(0.5f);
Vector3f errorFeedback = grav.Cross(av);
// apply scaled feedback
gv -= errorFeedback;
}
gv.Scale(0.5f * deltaTime);
m_imuQ += (m_imuQ * Quaternionf(0.0f, gv.x, gv.y, gv.z));
m_imuQ.NormalizeXYZW();
updateOrientationAngles();
}
float getRollRadians()
{
return m_roll + (float)m_rollWinding * 2.0f * 3.14159265f;
}
float getPitchRadians()
{
return m_pitch + (float)m_pitchWinding * 2.0f * 3.14159265f;
}
float getYawRadians()
{
return m_yaw + (float)m_yawWinding * 2.0f * 3.14159265f;
}
void getQuaternion(float q[4]) const
{
q[0] = m_imuQ.w;
q[1] = m_imuQ.x;
q[2] = m_imuQ.y;
q[3] = m_imuQ.z;
}
void getGyroBias(float gBias[3]) const
{
gBias[0] = m_gyroBias[0];
gBias[1] = m_gyroBias[1];
gBias[2] = m_gyroBias[2];
}
private:
// calculate roll, yaw and pitch in radians. (-0.5 to 0.5)
void calcOrientation()
{
float sinr_cosp = 2.0f * (m_imuQ.z * m_imuQ.w + m_imuQ.x * m_imuQ.y);
float cosr_cosp = 1.0f - 2.0f * (m_imuQ.w * m_imuQ.w + m_imuQ.x * m_imuQ.x);
m_roll = std::atan2(sinr_cosp, cosr_cosp);
// pitch (y-axis rotation)
float sinp = 2.0f * (m_imuQ.z * m_imuQ.x - m_imuQ.y * m_imuQ.w);
if (std::abs(sinp) >= 1.0)
m_pitch = std::copysign(3.14159265359f / 2.0f, sinp);
else
m_pitch = std::asin(sinp);
// yaw (z-axis rotation)
float siny_cosp = 2.0f * (m_imuQ.z * m_imuQ.y + m_imuQ.w * m_imuQ.x);
float cosy_cosp = 1.0f - 2.0f * (m_imuQ.x * m_imuQ.x + m_imuQ.y * m_imuQ.y);
m_yaw = std::atan2(siny_cosp, cosy_cosp);
}
void updateOrientationAngles()
{
auto calcWindingCountChange = [](float prevAngle, float newAngle) -> int
{
if (newAngle > prevAngle)
{
float angleDif = newAngle - prevAngle;
if (angleDif > 3.14159265f)
return -1;
}
else if (newAngle < prevAngle)
{
float angleDif = prevAngle - newAngle;
if (angleDif > 3.14159265f)
return 1;
}
return 0;
};
float prevRoll = m_roll;
float prevPitch = m_pitch;
float prevYaw = m_yaw;
calcOrientation();
// calculate roll, yaw and pitch including winding count to match what VPAD API returns
m_rollWinding += calcWindingCountChange(prevRoll, m_roll);
m_pitchWinding += calcWindingCountChange(prevPitch, m_pitch);
m_yawWinding += calcWindingCountChange(prevYaw, m_yaw);
}
void updateGyroBias(float gx, float gy, float gz)
{
// dont let actual movement influence the bias
// but be careful about setting this too low, there are controllers out there with really bad bias (my Switch Pro had -0.0933 0.0619 0.0179 in resting state)
if (fabs(gx) >= 0.35f || fabs(gy) >= 0.35f || fabs(gz) >= 0.35f)
return;
m_gyroTotalSum[0] += gx;
m_gyroTotalSum[1] += gy;
m_gyroTotalSum[2] += gz;
m_gyroTotalSampleCount++;
if (m_gyroTotalSampleCount >= 200)
{
m_gyroBias[0] = (float)(m_gyroTotalSum[0] / (double)m_gyroTotalSampleCount);
m_gyroBias[1] = (float)(m_gyroTotalSum[1] / (double)m_gyroTotalSampleCount);
m_gyroBias[2] = (float)(m_gyroTotalSum[2] / (double)m_gyroTotalSampleCount);
}
}
private:
Quaternionf m_imuQ; // current orientation
// angle data
float m_roll{};
float m_pitch{};
float m_yaw{};
int m_rollWinding{};
int m_pitchWinding{};
int m_yawWinding{};
// gyro bias
float m_gyroBias[3]{};
double m_gyroTotalSum[3]{};
uint64 m_gyroTotalSampleCount{};
};
| 4,715
|
C++
|
.h
| 146
| 29.260274
| 316
| 0.652747
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,388
|
x64util.h
|
cemu-project_Cemu/src/asm/x64util.h
|
#pragma once
#if defined(ARCH_X86_64)
extern "C" void recompiler_fres();
extern "C" void recompiler_frsqrte();
#else
// stubbed on non-x86 for now
static void recompiler_fres()
{
cemu_assert_unimplemented();
}
static void recompiler_frsqrte()
{
cemu_assert_unimplemented();
}
#endif
| 293
|
C++
|
.h
| 15
| 17.866667
| 37
| 0.761905
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,389
|
version.h
|
cemu-project_Cemu/src/Common/version.h
|
#ifndef EMULATOR_NAME
#define EMULATOR_NAME "Cemu"
#define EMULATOR_VERSION_SUFFIX ""
#define _XSTRINGFY(s) _STRINGFY(s)
#define _STRINGFY(s) #s
#if EMULATOR_VERSION_MAJOR != 0
#define BUILD_VERSION_WITH_NAME_STRING (EMULATOR_NAME " " _XSTRINGFY(EMULATOR_VERSION_MAJOR) "." _XSTRINGFY(EMULATOR_VERSION_MINOR) EMULATOR_VERSION_SUFFIX)
#define BUILD_VERSION_STRING (_XSTRINGFY(EMULATOR_VERSION_MAJOR) "." _XSTRINGFY(EMULATOR_VERSION_MINOR) EMULATOR_VERSION_SUFFIX)
#else
// no version provided. Only show commit hash
#define BUILD_VERSION_STRING (_XSTRINGFY(EMULATOR_HASH) EMULATOR_VERSION_SUFFIX)
#define BUILD_VERSION_WITH_NAME_STRING (EMULATOR_NAME " " _XSTRINGFY(EMULATOR_HASH) EMULATOR_VERSION_SUFFIX)
#endif
#endif
| 730
|
C++
|
.h
| 14
| 50.785714
| 156
| 0.78481
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,390
|
SysAllocator.h
|
cemu-project_Cemu/src/Common/SysAllocator.h
|
#pragma once
uint32 coreinit_allocFromSysArea(uint32 size, uint32 alignment);
class SysAllocatorBase;
#define SYSALLOCATOR_GUARDS 0 // if 1, create a magic constant at the top of each memory allocation which is used to check for memory corruption
class SysAllocatorContainer
{
public:
void Initialize();
void PushSysAllocator(SysAllocatorBase* base);
static SysAllocatorContainer& GetInstance();
private:
std::vector<SysAllocatorBase*> m_sysAllocList;
};
class SysAllocatorBase
{
friend class SysAllocatorContainer;
public:
SysAllocatorBase();
virtual ~SysAllocatorBase() = default;
private:
virtual void Initialize() = 0;
};
template<typename T, size_t count = 1, size_t alignment = 32>
class SysAllocator : public SysAllocatorBase
{
public:
SysAllocator()
{
m_tempData.resize(count);
}
SysAllocator(std::initializer_list<T> l)
{
m_tempData.reserve(count);
m_tempData.insert(m_tempData.begin(), l);
if (count > l.size())
m_tempData.insert(m_tempData.end(), count - l.size(), T());
}
template <size_t N>
SysAllocator(const char(&str)[N])
{
m_tempData.reserve(count);
m_tempData.insert(m_tempData.begin(), str, str + N);
}
constexpr uint32 GetCount() const
{
return count;
}
constexpr size_t GetByteSize() const
{
return count * sizeof(T);
}
T* GetPtr() const
{
#if SYSALLOCATOR_GUARDS
cemu_assert(*(uint32*)((uint8*)m_sysMem.GetPtr()+(sizeof(T) * count)) == 0x112A33C4);
#endif
return m_sysMem.GetPtr();
}
uint32 GetMPTR() const
{
#if SYSALLOCATOR_GUARDS
cemu_assert(*(uint32*)((uint8*)m_sysMem.GetPtr()+(sizeof(T) * count)) == 0x112A33C4);
#endif
return m_sysMem.GetMPTR();
}
T& operator*()
{
return *GetPtr();
}
operator T*()
{
return GetPtr();
}
SysAllocator operator+(const SysAllocator& ptr)
{
return SysAllocator(this->GetMPTR() + ptr.GetMPTR());
}
SysAllocator operator-(const SysAllocator& ptr)
{
return SysAllocator(this->GetMPTR() - ptr.GetMPTR());
}
T* operator+(sint32 v)
{
return this->GetPtr() + v;
}
T* operator-(sint32 v)
{
return this->GetPtr() - v;
}
operator void*() { return m_sysMem->GetPtr(); }
// for all arrays except bool
template<class Q = T>
typename std::enable_if< count != 1 && !std::is_same<Q, bool>::value, Q >::type&
operator[](int index)
{
// return tmp data until we allocated in sys mem
if (m_sysMem.GetMPTR() == 0)
{
return m_tempData[index];
}
return m_sysMem[index];
}
private:
SysAllocator(uint32 memptr)
: m_sysMem(memptr)
{}
void Initialize() override
{
if (m_sysMem.GetMPTR() != 0)
return;
// alloc mem
uint32 guardSize = 0;
#if SYSALLOCATOR_GUARDS
guardSize = 4;
#endif
m_sysMem = { coreinit_allocFromSysArea(sizeof(T) * count + guardSize, alignment) };
// copy temp buffer to mem and clear it
memcpy(m_sysMem.GetPtr(), m_tempData.data(), sizeof(T)*count);
#if SYSALLOCATOR_GUARDS
*(uint32*)((uint8*)m_sysMem.GetPtr()+(sizeof(T) * count)) = 0x112A33C4;
#endif
m_tempData.clear();
}
MEMPTR<T> m_sysMem;
std::vector<T> m_tempData;
};
template <size_t N>
SysAllocator(const char(&str)[N]) -> SysAllocator<char, N>;
template<typename T>
class SysAllocator<T, 1> : public SysAllocatorBase
{
public:
SysAllocator()
{
m_tempData = {};
}
SysAllocator(const T& value)
{
m_tempData = value;
}
SysAllocator& operator=(const T& value)
{
*m_sysMem = value;
return *this;
}
operator T()
{
return *GetPtr();
}
operator T*()
{
return GetPtr();
}
T* GetPtr() const
{
return m_sysMem.GetPtr();
}
uint32 GetMPTR() const
{
return m_sysMem.GetMPTR();
}
T* operator&() { return (T*)m_sysMem.GetPtr(); }
T* operator->() const
{
return this->GetPtr();
}
private:
void Initialize() override
{
if (m_sysMem.GetMPTR() != 0)
return;
// alloc mem
m_sysMem = { coreinit_allocFromSysArea(sizeof(T), 32) };
// copy temp buffer to mem and clear it
*m_sysMem = m_tempData;
}
MEMPTR<T> m_sysMem;
T m_tempData;
};
| 3,960
|
C++
|
.h
| 179
| 19.798883
| 145
| 0.703446
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,391
|
cpu_features.h
|
cemu-project_Cemu/src/Common/cpu_features.h
|
#ifdef __GNUC__
#define ATTRIBUTE_AVX2 __attribute__((target("avx2")))
#define ATTRIBUTE_SSE41 __attribute__((target("sse4.1")))
#define ATTRIBUTE_AESNI __attribute__((target("aes")))
#else
#define ATTRIBUTE_AVX2
#define ATTRIBUTE_SSE41
#define ATTRIBUTE_AESNI
#endif
class CPUFeaturesImpl
{
public:
CPUFeaturesImpl();
std::string GetCPUName(); // empty if not available
std::string GetCommaSeparatedExtensionList();
struct
{
bool ssse3{ false };
bool sse4_1{ false };
bool avx{ false };
bool avx2{ false };
bool lzcnt{ false };
bool movbe{ false };
bool bmi2{ false };
bool aesni{ false };
bool invariant_tsc{ false };
}x86;
private:
char m_cpuBrandName[0x40]{ 0 };
};
extern CPUFeaturesImpl g_CPUFeatures;
| 737
|
C++
|
.h
| 31
| 21.83871
| 57
| 0.72792
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,392
|
platform.h
|
cemu-project_Cemu/src/Common/platform.h
|
#pragma once
#include <boost/predef/os.h>
#include <cstdint>
#if BOOST_OS_WINDOWS
#include "Common/windows/platform.h"
#elif BOOST_OS_LINUX
#include <byteswap.h>
#include <X11/Xlib.h>
#include <X11/extensions/Xrender.h>
#include <X11/Xutil.h>
#include "Common/unix/platform.h"
#elif BOOST_OS_MACOS
#include <libkern/OSByteOrder.h>
#include "Common/unix/platform.h"
#endif
| 374
|
C++
|
.h
| 15
| 23.8
| 36
| 0.784314
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,393
|
precompiled.h
|
cemu-project_Cemu/src/Common/precompiled.h
|
#pragma once
#include <stdlib.h> // for size_t
#include "version.h"
#include "platform.h"
#define FMT_HEADER_ONLY
#define FMT_USE_GRISU 1
#include <fmt/core.h>
#include <fmt/format.h>
#include <fmt/ranges.h>
#if FMT_VERSION > 80000
#include <fmt/xchar.h> // needed for wchar_t support
#endif
#define SDL_MAIN_HANDLED
// #if FMT_VERSION > 80102
// // restore generic formatter for enum (class) to underlying. We currently utilize this for HLE call logging
// template <typename Enum, std::enable_if_t<std::is_enum<Enum>::value, int> = 0>
// constexpr auto format_as(Enum e) noexcept -> std::underlying_type<Enum> {
// return static_cast<std::underlying_type<Enum>>(e);
// }
// #endif
// arch defines
#if defined(__x86_64__) || defined(_M_X64) || defined(_M_AMD64)
#define ARCH_X86_64
#endif
// c includes
#include <cstdint>
#include <cstdlib>
#include <cmath>
#include <ctime>
#include <cassert>
#if defined(ARCH_X86_64)
#include <immintrin.h>
#endif
// c++ includes
#include <string>
#include <string_view>
#include <fstream>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <mutex>
#include <shared_mutex>
#include <thread>
#include <future>
#include <atomic>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <array>
#include <bitset>
#include <bit>
#include <filesystem>
#include <memory>
#include <chrono>
#include <ctime>
#include <regex>
#include <type_traits>
#include <optional>
#include <span>
#include <ranges>
#include <boost/predef.h>
#include <boost/nowide/convert.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/asio.hpp>
#include <glm/glm.hpp>
#include <glm/gtc/quaternion.hpp>
namespace fs = std::filesystem;
#include "enumFlags.h"
// base types
using uint64 = uint64_t;
using uint32 = uint32_t;
using uint16 = uint16_t;
using uint8 = uint8_t;
using sint64 = int64_t;
using sint32 = int32_t;
using sint16 = int16_t;
using sint8 = int8_t;
// types with explicit big endian order
#include "betype.h"
// types with explicit little endian order (on a big-endian system these would be implemented like betype.h)
using uint64le = uint64_t;
using uint32le = uint32_t;
using uint16le = uint16_t;
using uint8le = uint8_t;
// logging
#include "Cemu/Logging/CemuDebugLogging.h"
#include "Cemu/Logging/CemuLogging.h"
// manual endian-swapping
#if _MSC_VER
inline uint64 _swapEndianU64(uint64 v)
{
return _byteswap_uint64(v);
}
inline uint32 _swapEndianU32(uint32 v)
{
return _byteswap_ulong(v);
}
inline sint32 _swapEndianS32(sint32 v)
{
return (sint32)_byteswap_ulong((uint32)v);
}
inline uint16 _swapEndianU16(uint16 v)
{
return (v >> 8) | (v << 8);
}
inline sint16 _swapEndianS16(sint16 v)
{
return (sint16)(((uint16)v >> 8) | ((uint16)v << 8));
}
#else
inline uint64 _swapEndianU64(uint64 v)
{
#if BOOST_OS_MACOS
return OSSwapInt64(v);
#else
return bswap_64(v);
#endif
}
inline uint32 _swapEndianU32(uint32 v)
{
#if BOOST_OS_MACOS
return OSSwapInt32(v);
#else
return bswap_32(v);
#endif
}
inline sint32 _swapEndianS32(sint32 v)
{
#if BOOST_OS_MACOS
return (sint32)OSSwapInt32((uint32)v);
#else
return (sint32)bswap_32((uint32)v);
#endif
}
inline uint16 _swapEndianU16(uint16 v)
{
return (v >> 8) | (v << 8);
}
inline sint16 _swapEndianS16(sint16 v)
{
return (sint16)(((uint16)v >> 8) | ((uint16)v << 8));
}
inline uint64 _umul128(uint64 multiplier, uint64 multiplicand, uint64 *highProduct) {
unsigned __int128 x = (unsigned __int128)multiplier * (unsigned __int128)multiplicand;
*highProduct = (x >> 64);
return x & 0xFFFFFFFFFFFFFFFF;
}
typedef uint8_t BYTE;
typedef uint32_t DWORD;
typedef int32_t LONG;
typedef int64_t LONGLONG;
typedef union _LARGE_INTEGER {
struct {
DWORD LowPart;
LONG HighPart;
};
struct {
DWORD LowPart;
LONG HighPart;
} u;
LONGLONG QuadPart;
} LARGE_INTEGER, *PLARGE_INTEGER;
#define DEFINE_ENUM_FLAG_OPERATORS(T) \
inline T operator~ (T a) { return static_cast<T>( ~static_cast<std::underlying_type<T>::type>(a) ); } \
inline T operator| (T a, T b) { return static_cast<T>( static_cast<std::underlying_type<T>::type>(a) | static_cast<std::underlying_type<T>::type>(b) ); } \
inline T operator& (T a, T b) { return static_cast<T>( static_cast<std::underlying_type<T>::type>(a) & static_cast<std::underlying_type<T>::type>(b) ); } \
inline T operator^ (T a, T b) { return static_cast<T>( static_cast<std::underlying_type<T>::type>(a) ^ static_cast<std::underlying_type<T>::type>(b) ); } \
inline T& operator|= (T& a, T b) { return reinterpret_cast<T&>( reinterpret_cast<std::underlying_type<T>::type&>(a) |= static_cast<std::underlying_type<T>::type>(b) ); } \
inline T& operator&= (T& a, T b) { return reinterpret_cast<T&>( reinterpret_cast<std::underlying_type<T>::type&>(a) &= static_cast<std::underlying_type<T>::type>(b) ); } \
inline T& operator^= (T& a, T b) { return reinterpret_cast<T&>( reinterpret_cast<std::underlying_type<T>::type&>(a) ^= static_cast<std::underlying_type<T>::type>(b) ); }
#endif
template<typename T>
inline T GetBits(T value, uint32 index, uint32 numBits)
{
T mask = (1<<numBits)-1;
return (value>>index) & mask;
}
template<typename T>
inline void SetBits(T& value, uint32 index, uint32 numBits, uint32 bitValue)
{
T mask = (1<<numBits)-1;
value &= ~(mask << index);
value |= (bitValue << index);
}
#if !defined(_MSC_VER) || defined(__clang__) // clang-cl does not have built-in _udiv128
inline uint64 _udiv128(uint64 highDividend, uint64 lowDividend, uint64 divisor, uint64 *remainder)
{
unsigned __int128 dividend = (((unsigned __int128)highDividend) << 64) | ((unsigned __int128)lowDividend);
*remainder = (uint64)((dividend % divisor) & 0xFFFFFFFFFFFFFFFF);
return (uint64)((dividend / divisor) & 0xFFFFFFFFFFFFFFFF);
}
#endif
#if defined(_MSC_VER)
#define UNREACHABLE __assume(false)
#define ASSUME(__cond) __assume(__cond)
#define TLS_WORKAROUND_NOINLINE // no-op for MSVC as it has a flag for fiber-safe TLS optimizations
#elif defined(__GNUC__) && !defined(__llvm__)
#define UNREACHABLE __builtin_unreachable()
#define ASSUME(__cond) __attribute__((assume(__cond)))
#define TLS_WORKAROUND_NOINLINE __attribute__((noinline))
#elif defined(__clang__)
#define UNREACHABLE __builtin_unreachable()
#define ASSUME(__cond) __builtin_assume(__cond)
#define TLS_WORKAROUND_NOINLINE __attribute__((noinline))
#else
#error Unknown compiler
#endif
#if defined(_MSC_VER)
#define DEBUG_BREAK __debugbreak()
#else
#include <csignal>
#define DEBUG_BREAK raise(SIGTRAP)
#endif
#if defined(_MSC_VER)
#define DLLEXPORT __declspec(dllexport)
#elif defined(__GNUC__)
#if BOOST_OS_WINDOWS
#define DLLEXPORT __attribute__((dllexport))
#else
#define DLLEXPORT
#endif
#else
#error No definition for DLLEXPORT
#endif
#if BOOST_OS_WINDOWS
#define NOEXPORT
#elif defined(__GNUC__)
#define NOEXPORT __attribute__ ((visibility ("hidden")))
#endif
// On aarch64 we handle some of the x86 intrinsics by implementing them as wrappers
#if defined(__aarch64__)
inline void _mm_pause()
{
asm volatile("yield");
}
inline uint64 __rdtsc()
{
uint64 t;
asm volatile("mrs %0, cntvct_el0" : "=r" (t));
return t;
}
inline void _mm_mfence()
{
}
inline unsigned char _addcarry_u64(unsigned char carry, unsigned long long a, unsigned long long b, unsigned long long *result)
{
*result = a + b + (unsigned long long)carry;
if (*result < a)
return 1;
return 0;
}
#endif
// asserts
inline void cemu_assert(bool _condition)
{
if ((_condition) == false)
{
DEBUG_BREAK;
}
}
#ifndef CEMU_DEBUG_ASSERT
//#define cemu_assert_debug(__cond) -> Forcing __cond not to be evaluated currently has unexpected side-effects
inline void cemu_assert_debug(bool _condition)
{
}
inline void cemu_assert_unimplemented()
{
}
inline void cemu_assert_suspicious()
{
}
inline void cemu_assert_error()
{
DEBUG_BREAK;
}
#else
inline void cemu_assert_debug(bool _condition)
{
if ((_condition) == false)
DEBUG_BREAK;
}
inline void cemu_assert_unimplemented()
{
DEBUG_BREAK;
}
inline void cemu_assert_suspicious()
{
DEBUG_BREAK;
}
inline void cemu_assert_error()
{
DEBUG_BREAK;
}
#endif
#define assert_dbg() DEBUG_BREAK // old style unconditional generic assert
// MEMPTR
#include "Common/MemPtr.h"
template <typename T1, typename T2>
constexpr bool HAS_FLAG(T1 flags, T2 test_flag) { return (flags & (T1)test_flag) == (T1)test_flag; }
template <typename T1, typename T2>
constexpr bool HAS_BIT(T1 value, T2 index) { return (value & ((T1)1 << index)) != 0; }
template <typename T>
constexpr void SAFE_RELEASE(T& p) { if (p) { p->Release(); p = nullptr; } }
template <typename T>
constexpr uint32_t ppcsizeof() { return (uint32_t) sizeof(T); }
// common utility functions
template <typename T>
void vectorAppendUnique(std::vector<T>& vec, const T& val) // for cases where a small vector is more efficient than a set
{
if (std::find(vec.begin(), vec.end(), val) != vec.end())
return;
vec.emplace_back(val);
}
template <typename T>
void vectorRemoveByValue(std::vector<T>& vec, const T& val)
{
vec.erase(std::remove(vec.begin(), vec.end(), val), vec.end());
}
template <typename T>
void vectorRemoveByIndex(std::vector<T>& vec, const size_t index)
{
vec.erase(vec.begin() + index);
}
template<typename T1, typename... Types>
bool match_any_of(T1&& value, Types&&... others)
{
return ((value == others) || ...);
}
// we cache the frequency in a static variable
[[nodiscard]] static std::chrono::high_resolution_clock::time_point now_cached() noexcept
{
#ifdef _WIN32
// get current time
static const long long _Freq = _Query_perf_frequency(); // doesn't change after system boot
const long long _Ctr = _Query_perf_counter();
static_assert(std::nano::num == 1, "This assumes period::num == 1.");
const long long _Whole = (_Ctr / _Freq) * std::nano::den;
const long long _Part = (_Ctr % _Freq) * std::nano::den / _Freq;
return (std::chrono::high_resolution_clock::time_point(std::chrono::nanoseconds(_Whole + _Part)));
#else
return std::chrono::high_resolution_clock::now();
#endif
}
[[nodiscard]] static std::chrono::steady_clock::time_point tick_cached() noexcept
{
#if BOOST_OS_WINDOWS
// get current time
static const long long _Freq = _Query_perf_frequency(); // doesn't change after system boot
const long long _Ctr = _Query_perf_counter();
static_assert(std::nano::num == 1, "This assumes period::num == 1.");
const long long _Whole = (_Ctr / _Freq) * std::nano::den;
const long long _Part = (_Ctr % _Freq) * std::nano::den / _Freq;
return (std::chrono::steady_clock::time_point(std::chrono::nanoseconds(_Whole + _Part)));
#elif BOOST_OS_LINUX
struct timespec tp;
clock_gettime(CLOCK_MONOTONIC_RAW, &tp);
return std::chrono::steady_clock::time_point(
std::chrono::seconds(tp.tv_sec) + std::chrono::nanoseconds(tp.tv_nsec));
#elif BOOST_OS_MACOS
return std::chrono::steady_clock::time_point(
std::chrono::nanoseconds(clock_gettime_nsec_np(CLOCK_MONOTONIC_RAW)));
#endif
}
// Some string conversion helpers because C++20 std::u8string is too cumbersome to use in practice
// mixing string types generally causes loads of issues and many of the libraries we use dont expose interfaces for u8string
inline const char* _utf8WrapperPtr(const char8_t* input)
{
// use with care
return (const char*)input;
}
inline std::string_view _utf8Wrapper(std::u8string_view input)
{
std::basic_string_view<char> v((char*)input.data(), input.size());
return v;
}
// convert fs::path to utf8 encoded string
inline std::string _pathToUtf8(const fs::path& path)
{
std::u8string strU8 = path.generic_u8string();
std::string v((const char*)strU8.data(), strU8.size());
return v;
}
// convert utf8 encoded string to fs::path
inline fs::path _utf8ToPath(std::string_view input)
{
std::basic_string_view<char8_t> v((char8_t*)input.data(), input.size());
return fs::path(v);
}
// locale-independent variant of tolower() which also matches Wii U behavior
inline char _ansiToLower(char c)
{
if (c >= 'A' && c <= 'Z')
c -= ('A' - 'a');
return c;
}
class RunAtCemuBoot // -> replaces this with direct function calls. Linkers other than MSVC may optimize way object files entirely if they are not referenced from outside. So a source file self-registering using this would be causing issues
{
public:
RunAtCemuBoot(void(*f)())
{
f();
}
};
// temporary wrapper until Concurrency TS gives us std::future .is_ready()
template<typename T>
bool future_is_ready(std::future<T>& f)
{
#if defined(__GNUC__)
return f.wait_for(std::chrono::nanoseconds(0)) == std::future_status::ready;
#else
return f._Is_ready();
#endif
}
// helper function to cast raw pointers to std::atomic
// this is technically not legal but works on most platforms as long as alignment restrictions are met and the implementation of atomic doesnt come with additional members
template<typename T>
std::atomic<T>* _rawPtrToAtomic(T* ptr)
{
static_assert(sizeof(T) == sizeof(std::atomic<T>));
cemu_assert_debug((reinterpret_cast<std::uintptr_t>(ptr) % alignof(std::atomic<T>)) == 0);
return reinterpret_cast<std::atomic<T>*>(ptr);
}
#if defined(__GNUC__)
#define ATTR_MS_ABI __attribute__((ms_abi))
#else
#define ATTR_MS_ABI
#endif
#if !defined(TRUE) or !defined(FALSE)
#define TRUE (1)
#define FALSE (0)
#endif
inline uint32 GetTitleIdHigh(uint64 titleId)
{
return titleId >> 32;
}
inline uint32 GetTitleIdLow(uint64 titleId)
{
return titleId & 0xFFFFFFFF;
}
#if defined(__GNUC__)
#define memcpy_dwords(__dest, __src, __numDwords) memcpy((__dest), (__src), (__numDwords) * sizeof(uint32))
#define memcpy_qwords(__dest, __src, __numQwords) memcpy((__dest), (__src), (__numQwords) * sizeof(uint64))
#else
#define memcpy_dwords(__dest, __src, __numDwords) __movsd((unsigned long*)(__dest), (const unsigned long*)(__src), __numDwords)
#define memcpy_qwords(__dest, __src, __numQwords) __movsq((unsigned long long*)(__dest), (const unsigned long long*)(__src), __numQwords)
#endif
// PPC context and memory functions
#include "Cafe/HW/MMU/MMU.h"
#include "Cafe/HW/Espresso/PPCState.h"
#include "Cafe/HW/Espresso/PPCCallback.h"
// PPC stack trace printer
void DebugLogStackTrace(struct OSThread_t* thread, MPTR sp, bool printSymbols = false);
// generic formatter for enums (to underlying)
template <typename Enum>
requires std::is_enum_v<Enum>
struct fmt::formatter<Enum> : fmt::formatter<underlying_t<Enum>>
{
auto format(const Enum& e, format_context& ctx) const
{
//return fmt::format_to(ctx.out(), "{}", fmt::underlying(e));
return formatter<underlying_t<Enum>>::format(fmt::underlying(e), ctx);
}
};
// formatter for betype<T>
template <typename T>
struct fmt::formatter<betype<T>> : fmt::formatter<T>
{
auto format(const betype<T>& e, format_context& ctx) const
{
return formatter<T>::format(static_cast<T>(e), ctx);
}
};
// useful future C++ stuff
namespace stdx
{
// std::to_underlying
template <typename EnumT, typename = std::enable_if_t < std::is_enum<EnumT>{} >>
constexpr std::underlying_type_t<EnumT> to_underlying(EnumT e) noexcept {
return static_cast<std::underlying_type_t<EnumT>>(e);
};
// std::scope_exit
template <typename Fn>
class scope_exit
{
Fn m_func;
bool m_released = false;
public:
explicit scope_exit(Fn&& f) noexcept
: m_func(std::forward<Fn>(f))
{}
~scope_exit()
{
if (!m_released) m_func();
}
scope_exit(scope_exit&& other) noexcept
: m_func(std::move(other.m_func)), m_released(std::exchange(other.m_released, true))
{}
scope_exit(const scope_exit&) = delete;
scope_exit& operator=(scope_exit) = delete;
void release() { m_released = true;}
};
}
| 16,204
|
C++
|
.h
| 506
| 29.83004
| 240
| 0.695212
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,394
|
socket.h
|
cemu-project_Cemu/src/Common/socket.h
|
#pragma once
#if BOOST_OS_WINDOWS
#include <WinSock2.h>
typedef int socklen_t;
#else
#include <sys/socket.h>
#define SOCKET int
#define closesocket close
#define SOCKET_ERROR -1
#define INVALID_SOCKET -1
#endif
| 216
|
C++
|
.h
| 11
| 18.181818
| 25
| 0.805
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,395
|
CafeString.h
|
cemu-project_Cemu/src/Common/CafeString.h
|
#pragma once
#include "betype.h"
#include "util/helpers/StringHelpers.h"
/* Helper classes to represent CafeOS strings in emulated memory */
template <size_t N>
class CafeString // fixed buffer size, null-terminated, PPC char
{
public:
bool assign(std::string_view sv)
{
if (sv.size()+1 >= N)
{
memcpy(data, sv.data(), sv.size()-1);
data[sv.size()-1] = '\0';
return false;
}
memcpy(data, sv.data(), sv.size());
data[sv.size()] = '\0';
return true;
}
const char* c_str()
{
return (const char*)data;
}
uint8be data[N];
};
template <size_t N>
class CafeWideString // fixed buffer size, null-terminated, PPC wchar_t (16bit big-endian)
{
public:
bool assign(const uint16be* input)
{
size_t i = 0;
while(input[i])
{
if(i >= N-1)
{
data[N-1] = 0;
return false;
}
data[i] = input[i];
i++;
}
data[i] = 0;
return true;
}
bool assignFromUTF8(std::string_view sv)
{
std::basic_string<uint16be> beStr = StringHelpers::FromUtf8(sv);
if(beStr.length() > N-1)
{
memcpy(data, beStr.data(), (N-1)*sizeof(uint16be));
data[N-1] = 0;
return false;
}
memcpy(data, beStr.data(), beStr.length()*sizeof(uint16be));
data[beStr.length()] = '\0';
return true;
}
uint16be data[N];
};
namespace CafeStringHelpers
{
static uint32 Length(const uint16be* input, uint32 maxLength)
{
uint32 i = 0;
while(input[i] && i < maxLength)
i++;
return i;
}
};
| 1,434
|
C++
|
.h
| 71
| 17.535211
| 90
| 0.651917
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,396
|
betype.h
|
cemu-project_Cemu/src/Common/betype.h
|
#pragma once
#include <type_traits>
namespace Latte
{
class LATTEREG;
};
template<class T, std::size_t... N>
constexpr T bswap_impl(T i, std::index_sequence<N...>)
{
return ((((i >> (N * CHAR_BIT)) & (T)(uint8_t)(-1)) << ((sizeof(T) - 1 - N) * CHAR_BIT)) | ...);
}
template<class T, class U = std::make_unsigned_t<T>>
constexpr T bswap(T i)
{
return (T)bswap_impl<U>((U)i, std::make_index_sequence<sizeof(T)>{});
}
template <typename T>
constexpr T SwapEndian(T value)
{
if constexpr (std::is_integral<T>::value)
{
#ifdef _MSC_VER
if constexpr (sizeof(T) == sizeof(uint32_t))
{
return (T)_byteswap_ulong(value);
}
#endif
return (T)bswap((std::make_unsigned_t<T>)value);
}
else if constexpr (std::is_floating_point<T>::value)
{
if constexpr (sizeof(T) == sizeof(uint32_t))
{
const auto tmp = bswap<uint32_t>(*(uint32_t*)&value);
return *(T*)&tmp;
}
if constexpr (sizeof(T) == sizeof(uint64_t))
{
const auto tmp = bswap<uint64_t>(*(uint64_t*)&value);
return *(T*)&tmp;
}
}
else if constexpr (std::is_enum<T>::value)
{
return (T)SwapEndian((std::underlying_type_t<T>)value);
}
else if constexpr (std::is_base_of<Latte::LATTEREG, T>::value)
{
const auto tmp = bswap<uint32_t>(*(uint32_t*)&value);
return *(T*)&tmp;
}
else
{
static_assert(std::is_integral<T>::value, "unsupported betype specialization!");
}
return value;
}
#ifndef WIN32
//static_assert(false, "_BE and _LE need to be adjusted");
#endif
// swap if native isn't big endian
template <typename T>
constexpr T _BE(T value)
{
return SwapEndian(value);
}
// swap if native isn't little endian
template <typename T>
constexpr T _LE(T value)
{
return value;
}
template <typename T>
class betype
{
public:
constexpr betype() = default;
// copy
constexpr betype(T value)
: m_value(SwapEndian(value)) {}
constexpr betype(const betype& value) = default; // required for trivially_copyable
//constexpr betype(const betype& value)
// : m_value(value.m_value) {}
template <typename U>
constexpr betype(const betype<U>& value)
: betype((T)value.value()) {}
// assigns
static betype from_bevalue(T value)
{
betype result;
result.m_value = value;
return result;
}
// returns LE value
constexpr T value() const { return SwapEndian<T>(m_value); }
// returns BE value
constexpr T bevalue() const { return m_value; }
constexpr operator T() const { return value(); }
betype<T>& operator+=(const betype<T>& v)
{
m_value = SwapEndian(T(value() + v.value()));
return *this;
}
betype<T>& operator+=(const T& v) requires std::integral<T>
{
m_value = SwapEndian(T(value() + v));
return *this;
}
betype<T>& operator-=(const betype<T>& v)
{
m_value = SwapEndian(T(value() - v.value()));
return *this;
}
betype<T>& operator*=(const betype<T>& v)
{
m_value = SwapEndian(T(value() * v.value()));
return *this;
}
betype<T>& operator/=(const betype<T>& v)
{
m_value = SwapEndian(T(value() / v.value()));
return *this;
}
betype<T>& operator&=(const betype<T>& v) requires (requires (T& x, const T& y) { x &= y; })
{
m_value &= v.m_value;
return *this;
}
betype<T>& operator|=(const betype<T>& v) requires (requires (T& x, const T& y) { x |= y; })
{
m_value |= v.m_value;
return *this;
}
betype<T>& operator|(const betype<T>& v) const requires (requires (T& x, const T& y) { x | y; })
{
betype<T> tmp(*this);
tmp.m_value = tmp.m_value | v.m_value;
return tmp;
}
betype<T> operator|(const T& v) const requires (requires (T& x, const T& y) { x | y; })
{
betype<T> tmp(*this);
tmp.m_value = tmp.m_value | SwapEndian(v);
return tmp;
}
betype<T>& operator^=(const betype<T>& v) requires std::integral<T>
{
m_value ^= v.m_value;
return *this;
}
betype<T>& operator>>=(std::size_t idx) requires std::integral<T>
{
m_value = SwapEndian(T(value() >> idx));
return *this;
}
betype<T>& operator<<=(std::size_t idx) requires std::integral<T>
{
m_value = SwapEndian(T(value() << idx));
return *this;
}
betype<T> operator~() const requires std::integral<T>
{
return from_bevalue(T(~m_value));
}
// pre-increment
betype<T>& operator++() requires std::integral<T>
{
m_value = SwapEndian(T(value() + 1));
return *this;
}
// post-increment
betype<T> operator++(int) requires std::integral<T>
{
betype<T> tmp(*this);
m_value = SwapEndian(T(value() + 1));
return tmp;
}
// pre-decrement
betype<T>& operator--() requires std::integral<T>
{
m_value = SwapEndian(T(value() - 1));
return *this;
}
// post-decrement
betype<T> operator--(int) requires std::integral<T>
{
betype<T> tmp(*this);
m_value = SwapEndian(T(value() - 1));
return tmp;
}
private:
//T m_value{}; // before 1.26.2
T m_value;
};
using uint64be = betype<uint64>;
using uint32be = betype<uint32>;
using uint16be = betype<uint16>;
using uint8be = betype<uint8>;
using sint64be = betype<sint64>;
using sint32be = betype<sint32>;
using sint16be = betype<sint16>;
using sint8be = betype<sint8>;
using float32be = betype<float>;
using float64be = betype<double>;
static_assert(sizeof(betype<uint64>) == sizeof(uint64));
static_assert(sizeof(betype<uint32>) == sizeof(uint32));
static_assert(sizeof(betype<uint16>) == sizeof(uint16));
static_assert(sizeof(betype<uint8>) == sizeof(uint8));
static_assert(sizeof(betype<float>) == sizeof(float));
static_assert(sizeof(betype<double>) == sizeof(double));
static_assert(std::is_trivially_copyable_v<uint32be>);
static_assert(std::is_trivially_constructible_v<uint32be>);
static_assert(std::is_copy_constructible_v<uint32be>);
static_assert(std::is_move_constructible_v<uint32be>);
static_assert(std::is_copy_assignable_v<uint32be>);
static_assert(std::is_move_assignable_v<uint32be>);
| 5,770
|
C++
|
.h
| 216
| 24.425926
| 97
| 0.674225
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,397
|
FileStream.h
|
cemu-project_Cemu/src/Common/FileStream.h
|
#pragma once
#include "Common/precompiled.h"
#ifdef _WIN32
#include "Common/windows/FileStream_win32.h"
#else
#include "Common/unix/FileStream_unix.h"
#endif
| 159
|
C++
|
.h
| 7
| 21.571429
| 44
| 0.807947
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,398
|
MemPtr.h
|
cemu-project_Cemu/src/Common/MemPtr.h
|
#pragma once
#include <type_traits>
#include "betype.h"
using MPTR = uint32; // generic address in PowerPC memory space
#define MPTR_NULL (0)
using VAddr = uint32; // virtual address
using PAddr = uint32; // physical address
extern uint8* memory_base;
extern uint8* PPCInterpreterGetStackPointer();
extern uint8* PPCInterpreter_PushAndReturnStackPointer(sint32 offset);
extern void PPCInterpreterModifyStackPointer(sint32 offset);
class MEMPTRBase
{
};
template<typename T>
class MEMPTR : MEMPTRBase
{
public:
constexpr MEMPTR() noexcept
: m_value(0) {}
explicit constexpr MEMPTR(uint32 offset) noexcept
: m_value(offset) {}
explicit constexpr MEMPTR(const uint32be& offset) noexcept
: m_value(offset) {}
constexpr MEMPTR(std::nullptr_t) noexcept
: m_value(0) {}
MEMPTR(T* ptr) noexcept
{
if (ptr == nullptr)
m_value = 0;
else
{
cemu_assert_debug((uint8*)ptr >= memory_base && (uint8*)ptr <= memory_base + 0x100000000);
m_value = (uint32)((uintptr_t)ptr - (uintptr_t)memory_base);
}
}
constexpr MEMPTR(const MEMPTR&) noexcept = default;
constexpr MEMPTR& operator=(const MEMPTR&) noexcept = default;
constexpr MEMPTR& operator=(const uint32& offset) noexcept
{
m_value = offset;
return *this;
}
constexpr MEMPTR& operator=(std::nullptr_t) noexcept
{
m_value = 0;
return *this;
}
MEMPTR& operator=(T* ptr) noexcept
{
if (ptr == nullptr)
m_value = 0;
else
{
cemu_assert_debug((uint8*)ptr >= memory_base && (uint8*)ptr <= memory_base + 0x100000000);
m_value = (uint32)((uintptr_t)ptr - (uintptr_t)memory_base);
}
return *this;
}
bool atomic_compare_exchange(T* comparePtr, T* newPtr) noexcept
{
MEMPTR<T> mp_compare = comparePtr;
MEMPTR<T> mp_new = newPtr;
auto* thisValueAtomic = reinterpret_cast<std::atomic<uint32be>*>(&m_value);
return thisValueAtomic->compare_exchange_strong(mp_compare.m_value, mp_new.m_value);
}
explicit constexpr operator bool() const noexcept
{
return m_value != 0;
}
// allow implicit cast to wrapped pointer type
constexpr operator T*() const noexcept
{
return GetPtr();
}
template<typename X>
explicit operator MEMPTR<X>() const noexcept
{
return MEMPTR<X>(this->m_value);
}
sint32 operator-(const MEMPTR& ptr) noexcept
requires(!std::is_void_v<T>)
{
return static_cast<sint32>(this->GetMPTR() - ptr.GetMPTR());
}
MEMPTR operator+(sint32 v) noexcept
requires(!std::is_void_v<T>)
{
// pointer arithmetic
return MEMPTR(this->GetMPTR() + v * sizeof(T));
}
MEMPTR operator-(sint32 v) noexcept
requires(!std::is_void_v<T>)
{
// pointer arithmetic
return MEMPTR(this->GetMPTR() - v * sizeof(T));
}
MEMPTR& operator+=(sint32 v) noexcept
requires(!std::is_void_v<T>)
{
m_value += v * sizeof(T);
return *this;
}
template<typename Q = T>
requires(!std::is_void_v<Q>)
Q& operator*() const noexcept
{
return *GetPtr();
}
constexpr T* operator->() const noexcept
{
return GetPtr();
}
template<typename Q = T>
requires(!std::is_void_v<Q>)
Q& operator[](int index) noexcept
{
return GetPtr()[index];
}
T* GetPtr() const noexcept
{
return (T*)(m_value == 0 ? nullptr : memory_base + (uint32)m_value);
}
template<typename C>
C* GetPtr() const noexcept
{
return static_cast<C*>(GetPtr());
}
[[nodiscard]] constexpr uint32 GetMPTR() const noexcept
{
return m_value.value();
}
[[nodiscard]] constexpr const uint32be& GetBEValue() const noexcept
{
return m_value;
}
[[nodiscard]] constexpr bool IsNull() const noexcept
{
return m_value == 0;
}
private:
uint32be m_value;
};
static_assert(sizeof(MEMPTR<void*>) == sizeof(uint32be));
static_assert(std::is_trivially_copyable_v<MEMPTR<void*>>);
#include "StackAllocator.h"
#include "SysAllocator.h"
template<typename T>
struct fmt::formatter<MEMPTR<T>> : formatter<string_view>
{
template<typename FormatContext>
auto format(const MEMPTR<T>& v, FormatContext& ctx) const -> format_context::iterator
{
return fmt::format_to(ctx.out(), "{:#x}", v.GetMPTR());
}
};
| 4,039
|
C++
|
.h
| 156
| 23.455128
| 93
| 0.712393
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,399
|
StackAllocator.h
|
cemu-project_Cemu/src/Common/StackAllocator.h
|
#pragma once
template<typename T, int count = 1>
class StackAllocator
{
public:
StackAllocator()
: StackAllocator(1)
{}
explicit StackAllocator(const uint32 items)
{
m_items = items;
m_modified_size = count * sizeof(T) * items + kStaticMemOffset * 2;
m_modified_size = (m_modified_size/8+7) * 8; // pad to 8 bytes
m_ptr = new(PPCInterpreter_PushAndReturnStackPointer(m_modified_size) + kStaticMemOffset) T[count * items]();
}
~StackAllocator()
{
for (size_t i = 0; i < count * m_items; ++i)
m_ptr[i].~T();
PPCInterpreterModifyStackPointer(-m_modified_size);
}
T* operator->() const
{
return GetPointer();
}
T* GetPointer() const { return m_ptr; }
uint32 GetMPTR() const { return MEMPTR<T>(m_ptr).GetMPTR(); }
T* operator&() { return GetPointer(); }
explicit operator T*() const { return GetPointer(); }
explicit operator uint32() const { return GetMPTR(); }
explicit operator bool() const { return *m_ptr != 0; }
// for arrays (count > 1) allow direct access via [] operator
template<int c = count>
requires (c > 1)
T& operator[](const uint32 index)
{
return m_ptr[index];
}
// if count is 1, then allow direct value assignment via = operator
template<int c = count>
requires (c == 1)
T& operator=(const T& rhs)
{
*m_ptr = rhs;
return *m_ptr;
}
// if count is 1, then allow == and != operators
template<int c = count>
requires (c == 1)
bool operator==(const T& rhs) const
{
return *m_ptr == rhs;
}
private:
static const uint32 kStaticMemOffset = 64;
T* m_ptr;
sint32 m_modified_size;
uint32 m_items;
};
| 1,579
|
C++
|
.h
| 59
| 24.474576
| 111
| 0.68543
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,400
|
enumFlags.h
|
cemu-project_Cemu/src/Common/enumFlags.h
|
#pragma once
#include <type_traits>
// enum flag helpers
template<typename TEnum>
struct EnableBitMaskOperators
{
static const bool enable = false;
};
template<typename TEnum>
typename std::enable_if<EnableBitMaskOperators<TEnum>::enable, TEnum>::type
operator &(TEnum lhs, TEnum rhs)
{
return static_cast<TEnum> (static_cast<typename std::underlying_type<TEnum>::type>(lhs) & static_cast<typename std::underlying_type<TEnum>::type>(rhs));
}
template<typename TEnum>
typename std::enable_if<EnableBitMaskOperators<TEnum>::enable, TEnum>::type
operator |(TEnum lhs, TEnum rhs)
{
return static_cast<TEnum> (static_cast<typename std::underlying_type<TEnum>::type>(lhs) | static_cast<typename std::underlying_type<TEnum>::type>(rhs));
}
template<typename TEnum>
typename std::enable_if<EnableBitMaskOperators<TEnum>::enable, TEnum>::type
operator ^(TEnum lhs, TEnum rhs)
{
return static_cast<TEnum> (static_cast<typename std::underlying_type<TEnum>::type>(lhs) ^ static_cast<typename std::underlying_type<TEnum>::type>(rhs));
}
template<typename TEnum>
typename std::enable_if<EnableBitMaskOperators<TEnum>::enable, TEnum>::type
operator ~(TEnum rhs)
{
return static_cast<TEnum> (~static_cast<typename std::underlying_type<TEnum>::type>(rhs));
}
template<typename TEnum>
typename std::enable_if<EnableBitMaskOperators<TEnum>::enable, TEnum>::type&
operator &=(TEnum& lhs, TEnum rhs)
{
lhs = static_cast<TEnum> (static_cast<typename std::underlying_type<TEnum>::type>(lhs) & static_cast<typename std::underlying_type<TEnum>::type>(rhs));
return lhs;
}
template<typename TEnum>
typename std::enable_if<EnableBitMaskOperators<TEnum>::enable, TEnum>::type&
operator |=(TEnum& lhs, TEnum rhs)
{
lhs = static_cast<TEnum> (static_cast<typename std::underlying_type<TEnum>::type>(lhs) | static_cast<typename std::underlying_type<TEnum>::type>(rhs));
return lhs;
}
template<typename TEnum>
typename std::enable_if<EnableBitMaskOperators<TEnum>::enable, TEnum>::type&
operator ^=(TEnum& lhs, TEnum rhs)
{
lhs = static_cast<TEnum> (static_cast<typename std::underlying_type<TEnum>::type>(lhs) ^ static_cast<typename std::underlying_type<TEnum>::type>(rhs));
return lhs;
}
template<typename TEnum, typename = std::enable_if_t<EnableBitMaskOperators<TEnum>::enable>>
constexpr bool operator==(TEnum lhs, std::underlying_type_t<TEnum> rhs)
{
return static_cast<std::underlying_type_t<TEnum>>(lhs) == rhs;
}
template<typename TEnum, typename = std::enable_if_t<EnableBitMaskOperators<TEnum>::enable>>
constexpr bool operator!=(TEnum lhs, std::underlying_type_t<TEnum> rhs)
{
return static_cast<std::underlying_type_t<TEnum>>(lhs) != rhs;
}
#define ENABLE_BITMASK_OPERATORS(x) template<> struct EnableBitMaskOperators<x> { static const bool enable = true; };
template<typename TEnum>
struct EnableEnumIterators
{
static const bool enable = false;
};
template<typename TEnum>
typename std::enable_if<EnableEnumIterators<TEnum>::enable, TEnum>::type&
operator++(TEnum& lhs)
{
lhs = static_cast<TEnum>(static_cast<typename std::underlying_type<TEnum>::type>(lhs) + 1);
return lhs;
}
template<typename TEnum>
typename std::enable_if<EnableEnumIterators<TEnum>::enable, TEnum>::type
operator*(TEnum rhs)
{
return rhs;
}
template<typename TEnum>
typename std::enable_if<EnableEnumIterators<TEnum>::enable, TEnum>::type
begin(TEnum value)
{
return EnableEnumIterators<TEnum>::begin;
}
template<typename TEnum>
typename std::enable_if<EnableEnumIterators<TEnum>::enable, TEnum>::type
rbegin(TEnum value)
{
return EnableEnumIterators<TEnum>::rbegin;
}
template<typename TEnum>
typename std::enable_if<EnableEnumIterators<TEnum>::enable, TEnum>::type
end(TEnum r) {
return EnableEnumIterators<TEnum>::end;
}
template<typename TEnum>
typename std::enable_if<EnableEnumIterators<TEnum>::enable, TEnum>::type
rend(TEnum r) {
return EnableEnumIterators<TEnum>::rend;
}
#define ENABLE_ENUM_ITERATORS(x, first_value, last_value) template<> struct EnableEnumIterators<x> {\
static const bool enable = true;\
static const x begin = first_value;\
static const x rbegin = last_value;\
static const x end = static_cast<x>(static_cast<typename std::underlying_type<x>::type>(last_value) + 1);\
static const x rend = static_cast<x>(static_cast<typename std::underlying_type<x>::type>(first_value) - 1);\
};
// todo: rend type must be signed?
| 4,348
|
C++
|
.h
| 112
| 37.383929
| 153
| 0.771164
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,401
|
ELFSymbolTable.h
|
cemu-project_Cemu/src/Common/ExceptionHandler/ELFSymbolTable.h
|
#pragma once
#include <memory>
#include <elf.h>
class ELFSymbolTable
{
public:
std::string_view OffsetToSymbol(uint64 ptr, uint64& fromStart) const;
ELFSymbolTable();
~ELFSymbolTable();
private:
uint8* mappedExecutable = nullptr;
size_t mappedExecutableSize = 0;
Elf64_Ehdr* header = nullptr;
Elf64_Shdr* shTable = nullptr;
char* shStrTable = nullptr;
Elf64_Sym* symTable = nullptr;
uint64 symTableLen = 0;
char* strTable = nullptr;
uint16 FindSection(int type, const std::string_view& name);
void* SectionPointer (uint16 index);
void* SectionPointer(const Elf64_Shdr& section);
// ownership of mapped memory, cannot copy.
ELFSymbolTable(const ELFSymbolTable&) = delete;
};
| 698
|
C++
|
.h
| 24
| 27.083333
| 70
| 0.774775
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,402
|
ExceptionHandler.h
|
cemu-project_Cemu/src/Common/ExceptionHandler/ExceptionHandler.h
|
#pragma once
void ExceptionHandler_Init();
bool CrashLog_Create();
void CrashLog_SetOutputChannels(bool writeToStdErr, bool writeToLogTxt);
void CrashLog_WriteLine(std::string_view text, bool newLine = true);
void CrashLog_WriteHeader(const char* header);
void ExceptionHandler_LogGeneralInfo();
| 299
|
C++
|
.h
| 7
| 41.285714
| 72
| 0.83045
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,405
|
GLInclude.h
|
cemu-project_Cemu/src/Common/GLInclude/GLInclude.h
|
#pragma once
#include "glext.h"
#if BOOST_OS_WINDOWS > 0
#include "wglext.h"
#endif
#if BOOST_OS_LINUX > 0
// from Xlib
#define Bool int
#define Status int
#define True 1
#define False 0
// from system glx.h
typedef XID GLXContextID;
typedef XID GLXPixmap;
typedef XID GLXDrawable;
typedef XID GLXPbuffer;
typedef XID GLXWindow;
typedef XID GLXFBConfigID;
typedef struct __GLXcontextRec *GLXContext;
typedef struct __GLXFBConfigRec *GLXFBConfig;
#define EGL_EGL_PROTOTYPES 0
#include "egl.h"
#undef EGL_EGL_PROTOTYPES
#include "glxext.h"
#undef Bool
#undef Status
#undef True
#undef False
#endif
namespace CemuGL
{
#define GLFUNC(__type, __name) extern __type __name;
#define EGLFUNC(__type, __name) extern __type __name;
#include "glFunctions.h"
#undef GLFUNC
#undef EGLFUNC
// DSA-style helpers with fallback to legacy API if DSA is not supported
#define DSA_FORCE_DISABLE false // set to true to simulate DSA not being supported
static GLenum GetGLBindingFromTextureTarget(GLenum texTarget)
{
switch(texTarget)
{
case GL_TEXTURE_1D: return GL_TEXTURE_BINDING_1D;
case GL_TEXTURE_2D: return GL_TEXTURE_BINDING_2D;
case GL_TEXTURE_3D: return GL_TEXTURE_BINDING_3D;
case GL_TEXTURE_2D_ARRAY: return GL_TEXTURE_BINDING_2D_ARRAY;
case GL_TEXTURE_CUBE_MAP: return GL_TEXTURE_BINDING_CUBE_MAP;
case GL_TEXTURE_CUBE_MAP_ARRAY: return GL_TEXTURE_BINDING_CUBE_MAP_ARRAY;
default:
cemu_assert_unimplemented();
return 0;
}
}
static GLuint glCreateTextureWrapper(GLenum target)
{
GLuint tex;
if (glCreateTextures && !DSA_FORCE_DISABLE)
{
glCreateTextures(target, 1, &tex);
return tex;
}
GLint originalTexture;
glGetIntegerv(GetGLBindingFromTextureTarget(target), &originalTexture);
glGenTextures(1, &tex);
glBindTexture(target, tex);
glBindTexture(target, originalTexture);
return tex;
}
static void glTextureStorage1DWrapper(GLenum target, GLuint texture, GLsizei levels, GLenum internalformat, GLsizei width)
{
if (glTextureStorage1D && !DSA_FORCE_DISABLE)
{
glTextureStorage1D(texture, levels, internalformat, width);
return;
}
GLenum binding = GetGLBindingFromTextureTarget(target);
GLint originalTexture;
glGetIntegerv(binding, &originalTexture);
glBindTexture(target, texture);
glTexStorage1D(target, levels, internalformat, width);
glBindTexture(target, originalTexture);
}
static void glTextureStorage2DWrapper(GLenum target, GLuint texture, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height)
{
if (glTextureStorage2D && !DSA_FORCE_DISABLE)
{
glTextureStorage2D(texture, levels, internalformat, width, height);
return;
}
GLenum binding = GetGLBindingFromTextureTarget(target);
GLint originalTexture;
glGetIntegerv(binding, &originalTexture);
glBindTexture(target, texture);
glTexStorage2D(target, levels, internalformat, width, height);
glBindTexture(target, originalTexture);
}
static void glTextureStorage3DWrapper(GLenum target, GLuint texture, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth)
{
if (glTextureStorage3D && !DSA_FORCE_DISABLE)
{
glTextureStorage3D(texture, levels, internalformat, width, height, depth);
return;
}
GLenum binding = GetGLBindingFromTextureTarget(target);
GLint originalTexture;
glGetIntegerv(binding, &originalTexture);
glBindTexture(target, texture);
glTexStorage3D(target, levels, internalformat, width, height, depth);
glBindTexture(target, originalTexture);
}
static void glTextureSubImage1DWrapper(GLenum target, GLuint texture, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const void* pixels)
{
if (glTextureSubImage1D && !DSA_FORCE_DISABLE)
{
glTextureSubImage1D(texture, level, xoffset, width, format, type, pixels);
return;
}
GLenum binding = GetGLBindingFromTextureTarget(target);
GLint originalTexture;
glGetIntegerv(binding, &originalTexture);
glBindTexture(target, texture);
glTexSubImage1D(target, level, xoffset, width, format, type, pixels);
glBindTexture(target, originalTexture);
}
static void glCompressedTextureSubImage1DWrapper(GLenum target, GLuint texture, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void* data)
{
if (glCompressedTextureSubImage1D && !DSA_FORCE_DISABLE)
{
glCompressedTextureSubImage1D(texture, level, xoffset, width, format, imageSize, data);
return;
}
GLenum binding = GetGLBindingFromTextureTarget(target);
GLint originalTexture;
glGetIntegerv(binding, &originalTexture);
glBindTexture(target, texture);
glCompressedTexSubImage1D(target, level, xoffset, width, format, imageSize, data);
glBindTexture(target, originalTexture);
}
static void glTextureSubImage2DWrapper(GLenum target, GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void* pixels)
{
if (glTextureSubImage2D && !DSA_FORCE_DISABLE)
{
glTextureSubImage2D(texture, level, xoffset, yoffset, width, height, format, type, pixels);
return;
}
GLenum binding = GetGLBindingFromTextureTarget(target);
GLint originalTexture;
glGetIntegerv(binding, &originalTexture);
glBindTexture(target, texture);
glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels);
glBindTexture(target, originalTexture);
}
static void glCompressedTextureSubImage2DWrapper(GLenum target, GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void* data)
{
if (glCompressedTextureSubImage2D && !DSA_FORCE_DISABLE)
{
glCompressedTextureSubImage2D(texture, level, xoffset, yoffset, width, height, format, imageSize, data);
return;
}
GLenum binding = GetGLBindingFromTextureTarget(target);
GLint originalTexture;
glGetIntegerv(binding, &originalTexture);
glBindTexture(target, texture);
glCompressedTexSubImage2D(target, level, xoffset, yoffset, width, height, format, imageSize, data);
glBindTexture(target, originalTexture);
}
static void glTextureSubImage3DWrapper(GLenum target, GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void* pixels)
{
if(glTextureSubImage3D && !DSA_FORCE_DISABLE)
{
glTextureSubImage3D(texture, level, xoffset, yoffset, zoffset, width, height, depth, format, type, pixels);
return;
}
GLenum binding = GetGLBindingFromTextureTarget(target);
GLint originalTexture;
glGetIntegerv(binding, &originalTexture);
glBindTexture(target, texture);
glTexSubImage3D(target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, pixels);
glBindTexture(target, originalTexture);
}
static void glCompressedTextureSubImage3DWrapper(GLenum target, GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void* data)
{
if(glCompressedTextureSubImage3D && !DSA_FORCE_DISABLE)
{
glCompressedTextureSubImage3D(texture, level, xoffset, yoffset, zoffset, width, height, depth, format, imageSize, data);
return;
}
GLenum binding = GetGLBindingFromTextureTarget(target);
GLint originalTexture;
glGetIntegerv(binding, &originalTexture);
glBindTexture(target, texture);
glCompressedTexSubImage3D(target, level, xoffset, yoffset, zoffset, width, height, depth, format, imageSize, data);
glBindTexture(target, originalTexture);
}
}
using namespace CemuGL;
// this prevents Windows GL.h from being included:
#define __gl_h_
#define __GL_H__
| 7,532
|
C++
|
.h
| 199
| 36.005025
| 235
| 0.805335
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,406
|
glxext.h
|
cemu-project_Cemu/src/Common/GLInclude/glxext.h
|
#ifndef __glx_glxext_h_
#define __glx_glxext_h_ 1
#ifdef __cplusplus
extern "C" {
#endif
/*
** Copyright 2013-2020 The Khronos Group Inc.
** SPDX-License-Identifier: MIT
**
** This header is generated from the Khronos OpenGL / OpenGL ES XML
** API Registry. The current version of the Registry, generator scripts
** used to make the header, and the header can be found at
** https://github.com/KhronosGroup/OpenGL-Registry
*/
#define GLX_GLXEXT_VERSION 20211115
/* Generated C header for:
* API: glx
* Versions considered: .*
* Versions emitted: 1\.[3-9]
* Default extensions included: glx
* Additional extensions included: _nomatch_^
* Extensions removed: _nomatch_^
*/
#ifndef GLX_VERSION_1_3
#define GLX_VERSION_1_3 1
typedef XID GLXContextID;
typedef struct __GLXFBConfigRec *GLXFBConfig;
typedef XID GLXWindow;
typedef XID GLXPbuffer;
#define GLX_WINDOW_BIT 0x00000001
#define GLX_PIXMAP_BIT 0x00000002
#define GLX_PBUFFER_BIT 0x00000004
#define GLX_RGBA_BIT 0x00000001
#define GLX_COLOR_INDEX_BIT 0x00000002
#define GLX_PBUFFER_CLOBBER_MASK 0x08000000
#define GLX_FRONT_LEFT_BUFFER_BIT 0x00000001
#define GLX_FRONT_RIGHT_BUFFER_BIT 0x00000002
#define GLX_BACK_LEFT_BUFFER_BIT 0x00000004
#define GLX_BACK_RIGHT_BUFFER_BIT 0x00000008
#define GLX_AUX_BUFFERS_BIT 0x00000010
#define GLX_DEPTH_BUFFER_BIT 0x00000020
#define GLX_STENCIL_BUFFER_BIT 0x00000040
#define GLX_ACCUM_BUFFER_BIT 0x00000080
#define GLX_CONFIG_CAVEAT 0x20
#define GLX_X_VISUAL_TYPE 0x22
#define GLX_TRANSPARENT_TYPE 0x23
#define GLX_TRANSPARENT_INDEX_VALUE 0x24
#define GLX_TRANSPARENT_RED_VALUE 0x25
#define GLX_TRANSPARENT_GREEN_VALUE 0x26
#define GLX_TRANSPARENT_BLUE_VALUE 0x27
#define GLX_TRANSPARENT_ALPHA_VALUE 0x28
#define GLX_DONT_CARE 0xFFFFFFFF
#define GLX_NONE 0x8000
#define GLX_SLOW_CONFIG 0x8001
#define GLX_TRUE_COLOR 0x8002
#define GLX_DIRECT_COLOR 0x8003
#define GLX_PSEUDO_COLOR 0x8004
#define GLX_STATIC_COLOR 0x8005
#define GLX_GRAY_SCALE 0x8006
#define GLX_STATIC_GRAY 0x8007
#define GLX_TRANSPARENT_RGB 0x8008
#define GLX_TRANSPARENT_INDEX 0x8009
#define GLX_VISUAL_ID 0x800B
#define GLX_SCREEN 0x800C
#define GLX_NON_CONFORMANT_CONFIG 0x800D
#define GLX_DRAWABLE_TYPE 0x8010
#define GLX_RENDER_TYPE 0x8011
#define GLX_X_RENDERABLE 0x8012
#define GLX_FBCONFIG_ID 0x8013
#define GLX_RGBA_TYPE 0x8014
#define GLX_COLOR_INDEX_TYPE 0x8015
#define GLX_MAX_PBUFFER_WIDTH 0x8016
#define GLX_MAX_PBUFFER_HEIGHT 0x8017
#define GLX_MAX_PBUFFER_PIXELS 0x8018
#define GLX_PRESERVED_CONTENTS 0x801B
#define GLX_LARGEST_PBUFFER 0x801C
#define GLX_WIDTH 0x801D
#define GLX_HEIGHT 0x801E
#define GLX_EVENT_MASK 0x801F
#define GLX_DAMAGED 0x8020
#define GLX_SAVED 0x8021
#define GLX_WINDOW 0x8022
#define GLX_PBUFFER 0x8023
#define GLX_PBUFFER_HEIGHT 0x8040
#define GLX_PBUFFER_WIDTH 0x8041
typedef GLXFBConfig *( *PFNGLXGETFBCONFIGSPROC) (Display *dpy, int screen, int *nelements);
typedef GLXFBConfig *( *PFNGLXCHOOSEFBCONFIGPROC) (Display *dpy, int screen, const int *attrib_list, int *nelements);
typedef int ( *PFNGLXGETFBCONFIGATTRIBPROC) (Display *dpy, GLXFBConfig config, int attribute, int *value);
typedef XVisualInfo *( *PFNGLXGETVISUALFROMFBCONFIGPROC) (Display *dpy, GLXFBConfig config);
typedef GLXWindow ( *PFNGLXCREATEWINDOWPROC) (Display *dpy, GLXFBConfig config, Window win, const int *attrib_list);
typedef void ( *PFNGLXDESTROYWINDOWPROC) (Display *dpy, GLXWindow win);
typedef GLXPixmap ( *PFNGLXCREATEPIXMAPPROC) (Display *dpy, GLXFBConfig config, Pixmap pixmap, const int *attrib_list);
typedef void ( *PFNGLXDESTROYPIXMAPPROC) (Display *dpy, GLXPixmap pixmap);
typedef GLXPbuffer ( *PFNGLXCREATEPBUFFERPROC) (Display *dpy, GLXFBConfig config, const int *attrib_list);
typedef void ( *PFNGLXDESTROYPBUFFERPROC) (Display *dpy, GLXPbuffer pbuf);
typedef void ( *PFNGLXQUERYDRAWABLEPROC) (Display *dpy, GLXDrawable draw, int attribute, unsigned int *value);
typedef GLXContext ( *PFNGLXCREATENEWCONTEXTPROC) (Display *dpy, GLXFBConfig config, int render_type, GLXContext share_list, Bool direct);
typedef Bool ( *PFNGLXMAKECONTEXTCURRENTPROC) (Display *dpy, GLXDrawable draw, GLXDrawable read, GLXContext ctx);
typedef GLXDrawable ( *PFNGLXGETCURRENTREADDRAWABLEPROC) (void);
typedef int ( *PFNGLXQUERYCONTEXTPROC) (Display *dpy, GLXContext ctx, int attribute, int *value);
typedef void ( *PFNGLXSELECTEVENTPROC) (Display *dpy, GLXDrawable draw, unsigned long event_mask);
typedef void ( *PFNGLXGETSELECTEDEVENTPROC) (Display *dpy, GLXDrawable draw, unsigned long *event_mask);
#ifdef GLX_GLXEXT_PROTOTYPES
GLXFBConfig *glXGetFBConfigs (Display *dpy, int screen, int *nelements);
GLXFBConfig *glXChooseFBConfig (Display *dpy, int screen, const int *attrib_list, int *nelements);
int glXGetFBConfigAttrib (Display *dpy, GLXFBConfig config, int attribute, int *value);
XVisualInfo *glXGetVisualFromFBConfig (Display *dpy, GLXFBConfig config);
GLXWindow glXCreateWindow (Display *dpy, GLXFBConfig config, Window win, const int *attrib_list);
void glXDestroyWindow (Display *dpy, GLXWindow win);
GLXPixmap glXCreatePixmap (Display *dpy, GLXFBConfig config, Pixmap pixmap, const int *attrib_list);
void glXDestroyPixmap (Display *dpy, GLXPixmap pixmap);
GLXPbuffer glXCreatePbuffer (Display *dpy, GLXFBConfig config, const int *attrib_list);
void glXDestroyPbuffer (Display *dpy, GLXPbuffer pbuf);
void glXQueryDrawable (Display *dpy, GLXDrawable draw, int attribute, unsigned int *value);
GLXContext glXCreateNewContext (Display *dpy, GLXFBConfig config, int render_type, GLXContext share_list, Bool direct);
Bool glXMakeContextCurrent (Display *dpy, GLXDrawable draw, GLXDrawable read, GLXContext ctx);
GLXDrawable glXGetCurrentReadDrawable (void);
int glXQueryContext (Display *dpy, GLXContext ctx, int attribute, int *value);
void glXSelectEvent (Display *dpy, GLXDrawable draw, unsigned long event_mask);
void glXGetSelectedEvent (Display *dpy, GLXDrawable draw, unsigned long *event_mask);
#endif
#endif /* GLX_VERSION_1_3 */
#ifndef GLX_VERSION_1_4
#define GLX_VERSION_1_4 1
typedef void ( *__GLXextFuncPtr)(void);
#define GLX_SAMPLE_BUFFERS 100000
#define GLX_SAMPLES 100001
typedef __GLXextFuncPtr ( *PFNGLXGETPROCADDRESSPROC) (const GLubyte *procName);
#ifdef GLX_GLXEXT_PROTOTYPES
__GLXextFuncPtr glXGetProcAddress (const GLubyte *procName);
#endif
#endif /* GLX_VERSION_1_4 */
#ifndef GLX_ARB_context_flush_control
#define GLX_ARB_context_flush_control 1
#define GLX_CONTEXT_RELEASE_BEHAVIOR_ARB 0x2097
#define GLX_CONTEXT_RELEASE_BEHAVIOR_NONE_ARB 0
#define GLX_CONTEXT_RELEASE_BEHAVIOR_FLUSH_ARB 0x2098
#endif /* GLX_ARB_context_flush_control */
#ifndef GLX_ARB_create_context
#define GLX_ARB_create_context 1
#define GLX_CONTEXT_DEBUG_BIT_ARB 0x00000001
#define GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB 0x00000002
#define GLX_CONTEXT_MAJOR_VERSION_ARB 0x2091
#define GLX_CONTEXT_MINOR_VERSION_ARB 0x2092
#define GLX_CONTEXT_FLAGS_ARB 0x2094
typedef GLXContext ( *PFNGLXCREATECONTEXTATTRIBSARBPROC) (Display *dpy, GLXFBConfig config, GLXContext share_context, Bool direct, const int *attrib_list);
#ifdef GLX_GLXEXT_PROTOTYPES
GLXContext glXCreateContextAttribsARB (Display *dpy, GLXFBConfig config, GLXContext share_context, Bool direct, const int *attrib_list);
#endif
#endif /* GLX_ARB_create_context */
#ifndef GLX_ARB_create_context_no_error
#define GLX_ARB_create_context_no_error 1
#define GLX_CONTEXT_OPENGL_NO_ERROR_ARB 0x31B3
#endif /* GLX_ARB_create_context_no_error */
#ifndef GLX_ARB_create_context_profile
#define GLX_ARB_create_context_profile 1
#define GLX_CONTEXT_CORE_PROFILE_BIT_ARB 0x00000001
#define GLX_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB 0x00000002
#define GLX_CONTEXT_PROFILE_MASK_ARB 0x9126
#endif /* GLX_ARB_create_context_profile */
#ifndef GLX_ARB_create_context_robustness
#define GLX_ARB_create_context_robustness 1
#define GLX_CONTEXT_ROBUST_ACCESS_BIT_ARB 0x00000004
#define GLX_LOSE_CONTEXT_ON_RESET_ARB 0x8252
#define GLX_CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB 0x8256
#define GLX_NO_RESET_NOTIFICATION_ARB 0x8261
#endif /* GLX_ARB_create_context_robustness */
#ifndef GLX_ARB_fbconfig_float
#define GLX_ARB_fbconfig_float 1
#define GLX_RGBA_FLOAT_TYPE_ARB 0x20B9
#define GLX_RGBA_FLOAT_BIT_ARB 0x00000004
#endif /* GLX_ARB_fbconfig_float */
#ifndef GLX_ARB_framebuffer_sRGB
#define GLX_ARB_framebuffer_sRGB 1
#define GLX_FRAMEBUFFER_SRGB_CAPABLE_ARB 0x20B2
#endif /* GLX_ARB_framebuffer_sRGB */
#ifndef GLX_ARB_get_proc_address
#define GLX_ARB_get_proc_address 1
typedef __GLXextFuncPtr ( *PFNGLXGETPROCADDRESSARBPROC) (const GLubyte *procName);
#ifdef GLX_GLXEXT_PROTOTYPES
__GLXextFuncPtr glXGetProcAddressARB (const GLubyte *procName);
#endif
#endif /* GLX_ARB_get_proc_address */
#ifndef GLX_ARB_multisample
#define GLX_ARB_multisample 1
#define GLX_SAMPLE_BUFFERS_ARB 100000
#define GLX_SAMPLES_ARB 100001
#endif /* GLX_ARB_multisample */
#ifndef GLX_ARB_robustness_application_isolation
#define GLX_ARB_robustness_application_isolation 1
#define GLX_CONTEXT_RESET_ISOLATION_BIT_ARB 0x00000008
#endif /* GLX_ARB_robustness_application_isolation */
#ifndef GLX_ARB_robustness_share_group_isolation
#define GLX_ARB_robustness_share_group_isolation 1
#endif /* GLX_ARB_robustness_share_group_isolation */
#ifndef GLX_ARB_vertex_buffer_object
#define GLX_ARB_vertex_buffer_object 1
#define GLX_CONTEXT_ALLOW_BUFFER_BYTE_ORDER_MISMATCH_ARB 0x2095
#endif /* GLX_ARB_vertex_buffer_object */
#ifndef GLX_3DFX_multisample
#define GLX_3DFX_multisample 1
#define GLX_SAMPLE_BUFFERS_3DFX 0x8050
#define GLX_SAMPLES_3DFX 0x8051
#endif /* GLX_3DFX_multisample */
#ifndef GLX_AMD_gpu_association
#define GLX_AMD_gpu_association 1
#define GLX_GPU_VENDOR_AMD 0x1F00
#define GLX_GPU_RENDERER_STRING_AMD 0x1F01
#define GLX_GPU_OPENGL_VERSION_STRING_AMD 0x1F02
#define GLX_GPU_FASTEST_TARGET_GPUS_AMD 0x21A2
#define GLX_GPU_RAM_AMD 0x21A3
#define GLX_GPU_CLOCK_AMD 0x21A4
#define GLX_GPU_NUM_PIPES_AMD 0x21A5
#define GLX_GPU_NUM_SIMD_AMD 0x21A6
#define GLX_GPU_NUM_RB_AMD 0x21A7
#define GLX_GPU_NUM_SPI_AMD 0x21A8
typedef unsigned int ( *PFNGLXGETGPUIDSAMDPROC) (unsigned int maxCount, unsigned int *ids);
typedef int ( *PFNGLXGETGPUINFOAMDPROC) (unsigned int id, int property, GLenum dataType, unsigned int size, void *data);
typedef unsigned int ( *PFNGLXGETCONTEXTGPUIDAMDPROC) (GLXContext ctx);
typedef GLXContext ( *PFNGLXCREATEASSOCIATEDCONTEXTAMDPROC) (unsigned int id, GLXContext share_list);
typedef GLXContext ( *PFNGLXCREATEASSOCIATEDCONTEXTATTRIBSAMDPROC) (unsigned int id, GLXContext share_context, const int *attribList);
typedef Bool ( *PFNGLXDELETEASSOCIATEDCONTEXTAMDPROC) (GLXContext ctx);
typedef Bool ( *PFNGLXMAKEASSOCIATEDCONTEXTCURRENTAMDPROC) (GLXContext ctx);
typedef GLXContext ( *PFNGLXGETCURRENTASSOCIATEDCONTEXTAMDPROC) (void);
typedef void ( *PFNGLXBLITCONTEXTFRAMEBUFFERAMDPROC) (GLXContext dstCtx, GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter);
#ifdef GLX_GLXEXT_PROTOTYPES
unsigned int glXGetGPUIDsAMD (unsigned int maxCount, unsigned int *ids);
int glXGetGPUInfoAMD (unsigned int id, int property, GLenum dataType, unsigned int size, void *data);
unsigned int glXGetContextGPUIDAMD (GLXContext ctx);
GLXContext glXCreateAssociatedContextAMD (unsigned int id, GLXContext share_list);
GLXContext glXCreateAssociatedContextAttribsAMD (unsigned int id, GLXContext share_context, const int *attribList);
Bool glXDeleteAssociatedContextAMD (GLXContext ctx);
Bool glXMakeAssociatedContextCurrentAMD (GLXContext ctx);
GLXContext glXGetCurrentAssociatedContextAMD (void);
void glXBlitContextFramebufferAMD (GLXContext dstCtx, GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter);
#endif
#endif /* GLX_AMD_gpu_association */
#ifndef GLX_EXT_buffer_age
#define GLX_EXT_buffer_age 1
#define GLX_BACK_BUFFER_AGE_EXT 0x20F4
#endif /* GLX_EXT_buffer_age */
#ifndef GLX_EXT_context_priority
#define GLX_EXT_context_priority 1
#define GLX_CONTEXT_PRIORITY_LEVEL_EXT 0x3100
#define GLX_CONTEXT_PRIORITY_HIGH_EXT 0x3101
#define GLX_CONTEXT_PRIORITY_MEDIUM_EXT 0x3102
#define GLX_CONTEXT_PRIORITY_LOW_EXT 0x3103
#endif /* GLX_EXT_context_priority */
#ifndef GLX_EXT_create_context_es2_profile
#define GLX_EXT_create_context_es2_profile 1
#define GLX_CONTEXT_ES2_PROFILE_BIT_EXT 0x00000004
#endif /* GLX_EXT_create_context_es2_profile */
#ifndef GLX_EXT_create_context_es_profile
#define GLX_EXT_create_context_es_profile 1
#define GLX_CONTEXT_ES_PROFILE_BIT_EXT 0x00000004
#endif /* GLX_EXT_create_context_es_profile */
#ifndef GLX_EXT_fbconfig_packed_float
#define GLX_EXT_fbconfig_packed_float 1
#define GLX_RGBA_UNSIGNED_FLOAT_TYPE_EXT 0x20B1
#define GLX_RGBA_UNSIGNED_FLOAT_BIT_EXT 0x00000008
#endif /* GLX_EXT_fbconfig_packed_float */
#ifndef GLX_EXT_framebuffer_sRGB
#define GLX_EXT_framebuffer_sRGB 1
#define GLX_FRAMEBUFFER_SRGB_CAPABLE_EXT 0x20B2
#endif /* GLX_EXT_framebuffer_sRGB */
#ifndef GLX_EXT_get_drawable_type
#define GLX_EXT_get_drawable_type 1
#endif /* GLX_EXT_get_drawable_type */
#ifndef GLX_EXT_import_context
#define GLX_EXT_import_context 1
#define GLX_SHARE_CONTEXT_EXT 0x800A
#define GLX_VISUAL_ID_EXT 0x800B
#define GLX_SCREEN_EXT 0x800C
typedef Display *( *PFNGLXGETCURRENTDISPLAYEXTPROC) (void);
typedef int ( *PFNGLXQUERYCONTEXTINFOEXTPROC) (Display *dpy, GLXContext context, int attribute, int *value);
typedef GLXContextID ( *PFNGLXGETCONTEXTIDEXTPROC) (const GLXContext context);
typedef GLXContext ( *PFNGLXIMPORTCONTEXTEXTPROC) (Display *dpy, GLXContextID contextID);
typedef void ( *PFNGLXFREECONTEXTEXTPROC) (Display *dpy, GLXContext context);
#ifdef GLX_GLXEXT_PROTOTYPES
Display *glXGetCurrentDisplayEXT (void);
int glXQueryContextInfoEXT (Display *dpy, GLXContext context, int attribute, int *value);
GLXContextID glXGetContextIDEXT (const GLXContext context);
GLXContext glXImportContextEXT (Display *dpy, GLXContextID contextID);
void glXFreeContextEXT (Display *dpy, GLXContext context);
#endif
#endif /* GLX_EXT_import_context */
#ifndef GLX_EXT_libglvnd
#define GLX_EXT_libglvnd 1
#define GLX_VENDOR_NAMES_EXT 0x20F6
#endif /* GLX_EXT_libglvnd */
#ifndef GLX_EXT_no_config_context
#define GLX_EXT_no_config_context 1
#endif /* GLX_EXT_no_config_context */
#ifndef GLX_EXT_stereo_tree
#define GLX_EXT_stereo_tree 1
typedef struct {
int type;
unsigned long serial;
Bool send_event;
Display *display;
int extension;
int evtype;
GLXDrawable window;
Bool stereo_tree;
} GLXStereoNotifyEventEXT;
#define GLX_STEREO_TREE_EXT 0x20F5
#define GLX_STEREO_NOTIFY_MASK_EXT 0x00000001
#define GLX_STEREO_NOTIFY_EXT 0x00000000
#endif /* GLX_EXT_stereo_tree */
#ifndef GLX_EXT_swap_control
#define GLX_EXT_swap_control 1
#define GLX_SWAP_INTERVAL_EXT 0x20F1
#define GLX_MAX_SWAP_INTERVAL_EXT 0x20F2
typedef void ( *PFNGLXSWAPINTERVALEXTPROC) (Display *dpy, GLXDrawable drawable, int interval);
#ifdef GLX_GLXEXT_PROTOTYPES
void glXSwapIntervalEXT (Display *dpy, GLXDrawable drawable, int interval);
#endif
#endif /* GLX_EXT_swap_control */
#ifndef GLX_EXT_swap_control_tear
#define GLX_EXT_swap_control_tear 1
#define GLX_LATE_SWAPS_TEAR_EXT 0x20F3
#endif /* GLX_EXT_swap_control_tear */
#ifndef GLX_EXT_texture_from_pixmap
#define GLX_EXT_texture_from_pixmap 1
#define GLX_TEXTURE_1D_BIT_EXT 0x00000001
#define GLX_TEXTURE_2D_BIT_EXT 0x00000002
#define GLX_TEXTURE_RECTANGLE_BIT_EXT 0x00000004
#define GLX_BIND_TO_TEXTURE_RGB_EXT 0x20D0
#define GLX_BIND_TO_TEXTURE_RGBA_EXT 0x20D1
#define GLX_BIND_TO_MIPMAP_TEXTURE_EXT 0x20D2
#define GLX_BIND_TO_TEXTURE_TARGETS_EXT 0x20D3
#define GLX_Y_INVERTED_EXT 0x20D4
#define GLX_TEXTURE_FORMAT_EXT 0x20D5
#define GLX_TEXTURE_TARGET_EXT 0x20D6
#define GLX_MIPMAP_TEXTURE_EXT 0x20D7
#define GLX_TEXTURE_FORMAT_NONE_EXT 0x20D8
#define GLX_TEXTURE_FORMAT_RGB_EXT 0x20D9
#define GLX_TEXTURE_FORMAT_RGBA_EXT 0x20DA
#define GLX_TEXTURE_1D_EXT 0x20DB
#define GLX_TEXTURE_2D_EXT 0x20DC
#define GLX_TEXTURE_RECTANGLE_EXT 0x20DD
#define GLX_FRONT_LEFT_EXT 0x20DE
#define GLX_FRONT_RIGHT_EXT 0x20DF
#define GLX_BACK_LEFT_EXT 0x20E0
#define GLX_BACK_RIGHT_EXT 0x20E1
#define GLX_FRONT_EXT 0x20DE
#define GLX_BACK_EXT 0x20E0
#define GLX_AUX0_EXT 0x20E2
#define GLX_AUX1_EXT 0x20E3
#define GLX_AUX2_EXT 0x20E4
#define GLX_AUX3_EXT 0x20E5
#define GLX_AUX4_EXT 0x20E6
#define GLX_AUX5_EXT 0x20E7
#define GLX_AUX6_EXT 0x20E8
#define GLX_AUX7_EXT 0x20E9
#define GLX_AUX8_EXT 0x20EA
#define GLX_AUX9_EXT 0x20EB
typedef void ( *PFNGLXBINDTEXIMAGEEXTPROC) (Display *dpy, GLXDrawable drawable, int buffer, const int *attrib_list);
typedef void ( *PFNGLXRELEASETEXIMAGEEXTPROC) (Display *dpy, GLXDrawable drawable, int buffer);
#ifdef GLX_GLXEXT_PROTOTYPES
void glXBindTexImageEXT (Display *dpy, GLXDrawable drawable, int buffer, const int *attrib_list);
void glXReleaseTexImageEXT (Display *dpy, GLXDrawable drawable, int buffer);
#endif
#endif /* GLX_EXT_texture_from_pixmap */
#ifndef GLX_EXT_visual_info
#define GLX_EXT_visual_info 1
#define GLX_X_VISUAL_TYPE_EXT 0x22
#define GLX_TRANSPARENT_TYPE_EXT 0x23
#define GLX_TRANSPARENT_INDEX_VALUE_EXT 0x24
#define GLX_TRANSPARENT_RED_VALUE_EXT 0x25
#define GLX_TRANSPARENT_GREEN_VALUE_EXT 0x26
#define GLX_TRANSPARENT_BLUE_VALUE_EXT 0x27
#define GLX_TRANSPARENT_ALPHA_VALUE_EXT 0x28
#define GLX_NONE_EXT 0x8000
#define GLX_TRUE_COLOR_EXT 0x8002
#define GLX_DIRECT_COLOR_EXT 0x8003
#define GLX_PSEUDO_COLOR_EXT 0x8004
#define GLX_STATIC_COLOR_EXT 0x8005
#define GLX_GRAY_SCALE_EXT 0x8006
#define GLX_STATIC_GRAY_EXT 0x8007
#define GLX_TRANSPARENT_RGB_EXT 0x8008
#define GLX_TRANSPARENT_INDEX_EXT 0x8009
#endif /* GLX_EXT_visual_info */
#ifndef GLX_EXT_visual_rating
#define GLX_EXT_visual_rating 1
#define GLX_VISUAL_CAVEAT_EXT 0x20
#define GLX_SLOW_VISUAL_EXT 0x8001
#define GLX_NON_CONFORMANT_VISUAL_EXT 0x800D
#endif /* GLX_EXT_visual_rating */
#ifndef GLX_INTEL_swap_event
#define GLX_INTEL_swap_event 1
#define GLX_BUFFER_SWAP_COMPLETE_INTEL_MASK 0x04000000
#define GLX_EXCHANGE_COMPLETE_INTEL 0x8180
#define GLX_COPY_COMPLETE_INTEL 0x8181
#define GLX_FLIP_COMPLETE_INTEL 0x8182
#endif /* GLX_INTEL_swap_event */
#ifndef GLX_MESA_agp_offset
#define GLX_MESA_agp_offset 1
typedef unsigned int ( *PFNGLXGETAGPOFFSETMESAPROC) (const void *pointer);
#ifdef GLX_GLXEXT_PROTOTYPES
unsigned int glXGetAGPOffsetMESA (const void *pointer);
#endif
#endif /* GLX_MESA_agp_offset */
#ifndef GLX_MESA_copy_sub_buffer
#define GLX_MESA_copy_sub_buffer 1
typedef void ( *PFNGLXCOPYSUBBUFFERMESAPROC) (Display *dpy, GLXDrawable drawable, int x, int y, int width, int height);
#ifdef GLX_GLXEXT_PROTOTYPES
void glXCopySubBufferMESA (Display *dpy, GLXDrawable drawable, int x, int y, int width, int height);
#endif
#endif /* GLX_MESA_copy_sub_buffer */
#ifndef GLX_MESA_pixmap_colormap
#define GLX_MESA_pixmap_colormap 1
typedef GLXPixmap ( *PFNGLXCREATEGLXPIXMAPMESAPROC) (Display *dpy, XVisualInfo *visual, Pixmap pixmap, Colormap cmap);
#ifdef GLX_GLXEXT_PROTOTYPES
GLXPixmap glXCreateGLXPixmapMESA (Display *dpy, XVisualInfo *visual, Pixmap pixmap, Colormap cmap);
#endif
#endif /* GLX_MESA_pixmap_colormap */
#ifndef GLX_MESA_query_renderer
#define GLX_MESA_query_renderer 1
#define GLX_RENDERER_VENDOR_ID_MESA 0x8183
#define GLX_RENDERER_DEVICE_ID_MESA 0x8184
#define GLX_RENDERER_VERSION_MESA 0x8185
#define GLX_RENDERER_ACCELERATED_MESA 0x8186
#define GLX_RENDERER_VIDEO_MEMORY_MESA 0x8187
#define GLX_RENDERER_UNIFIED_MEMORY_ARCHITECTURE_MESA 0x8188
#define GLX_RENDERER_PREFERRED_PROFILE_MESA 0x8189
#define GLX_RENDERER_OPENGL_CORE_PROFILE_VERSION_MESA 0x818A
#define GLX_RENDERER_OPENGL_COMPATIBILITY_PROFILE_VERSION_MESA 0x818B
#define GLX_RENDERER_OPENGL_ES_PROFILE_VERSION_MESA 0x818C
#define GLX_RENDERER_OPENGL_ES2_PROFILE_VERSION_MESA 0x818D
typedef Bool ( *PFNGLXQUERYCURRENTRENDERERINTEGERMESAPROC) (int attribute, unsigned int *value);
typedef const char *( *PFNGLXQUERYCURRENTRENDERERSTRINGMESAPROC) (int attribute);
typedef Bool ( *PFNGLXQUERYRENDERERINTEGERMESAPROC) (Display *dpy, int screen, int renderer, int attribute, unsigned int *value);
typedef const char *( *PFNGLXQUERYRENDERERSTRINGMESAPROC) (Display *dpy, int screen, int renderer, int attribute);
#ifdef GLX_GLXEXT_PROTOTYPES
Bool glXQueryCurrentRendererIntegerMESA (int attribute, unsigned int *value);
const char *glXQueryCurrentRendererStringMESA (int attribute);
Bool glXQueryRendererIntegerMESA (Display *dpy, int screen, int renderer, int attribute, unsigned int *value);
const char *glXQueryRendererStringMESA (Display *dpy, int screen, int renderer, int attribute);
#endif
#endif /* GLX_MESA_query_renderer */
#ifndef GLX_MESA_release_buffers
#define GLX_MESA_release_buffers 1
typedef Bool ( *PFNGLXRELEASEBUFFERSMESAPROC) (Display *dpy, GLXDrawable drawable);
#ifdef GLX_GLXEXT_PROTOTYPES
Bool glXReleaseBuffersMESA (Display *dpy, GLXDrawable drawable);
#endif
#endif /* GLX_MESA_release_buffers */
#ifndef GLX_MESA_set_3dfx_mode
#define GLX_MESA_set_3dfx_mode 1
#define GLX_3DFX_WINDOW_MODE_MESA 0x1
#define GLX_3DFX_FULLSCREEN_MODE_MESA 0x2
typedef GLboolean ( *PFNGLXSET3DFXMODEMESAPROC) (GLint mode);
#ifdef GLX_GLXEXT_PROTOTYPES
GLboolean glXSet3DfxModeMESA (GLint mode);
#endif
#endif /* GLX_MESA_set_3dfx_mode */
#ifndef GLX_MESA_swap_control
#define GLX_MESA_swap_control 1
typedef int ( *PFNGLXGETSWAPINTERVALMESAPROC) (void);
typedef int ( *PFNGLXSWAPINTERVALMESAPROC) (unsigned int interval);
#ifdef GLX_GLXEXT_PROTOTYPES
int glXGetSwapIntervalMESA (void);
int glXSwapIntervalMESA (unsigned int interval);
#endif
#endif /* GLX_MESA_swap_control */
#ifndef GLX_NV_copy_buffer
#define GLX_NV_copy_buffer 1
typedef void ( *PFNGLXCOPYBUFFERSUBDATANVPROC) (Display *dpy, GLXContext readCtx, GLXContext writeCtx, GLenum readTarget, GLenum writeTarget, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size);
typedef void ( *PFNGLXNAMEDCOPYBUFFERSUBDATANVPROC) (Display *dpy, GLXContext readCtx, GLXContext writeCtx, GLuint readBuffer, GLuint writeBuffer, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size);
#ifdef GLX_GLXEXT_PROTOTYPES
void glXCopyBufferSubDataNV (Display *dpy, GLXContext readCtx, GLXContext writeCtx, GLenum readTarget, GLenum writeTarget, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size);
void glXNamedCopyBufferSubDataNV (Display *dpy, GLXContext readCtx, GLXContext writeCtx, GLuint readBuffer, GLuint writeBuffer, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size);
#endif
#endif /* GLX_NV_copy_buffer */
#ifndef GLX_NV_copy_image
#define GLX_NV_copy_image 1
typedef void ( *PFNGLXCOPYIMAGESUBDATANVPROC) (Display *dpy, GLXContext srcCtx, GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srcY, GLint srcZ, GLXContext dstCtx, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei width, GLsizei height, GLsizei depth);
#ifdef GLX_GLXEXT_PROTOTYPES
void glXCopyImageSubDataNV (Display *dpy, GLXContext srcCtx, GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srcY, GLint srcZ, GLXContext dstCtx, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei width, GLsizei height, GLsizei depth);
#endif
#endif /* GLX_NV_copy_image */
#ifndef GLX_NV_delay_before_swap
#define GLX_NV_delay_before_swap 1
typedef Bool ( *PFNGLXDELAYBEFORESWAPNVPROC) (Display *dpy, GLXDrawable drawable, GLfloat seconds);
#ifdef GLX_GLXEXT_PROTOTYPES
Bool glXDelayBeforeSwapNV (Display *dpy, GLXDrawable drawable, GLfloat seconds);
#endif
#endif /* GLX_NV_delay_before_swap */
#ifndef GLX_NV_float_buffer
#define GLX_NV_float_buffer 1
#define GLX_FLOAT_COMPONENTS_NV 0x20B0
#endif /* GLX_NV_float_buffer */
#ifndef GLX_NV_multigpu_context
#define GLX_NV_multigpu_context 1
#define GLX_CONTEXT_MULTIGPU_ATTRIB_NV 0x20AA
#define GLX_CONTEXT_MULTIGPU_ATTRIB_SINGLE_NV 0x20AB
#define GLX_CONTEXT_MULTIGPU_ATTRIB_AFR_NV 0x20AC
#define GLX_CONTEXT_MULTIGPU_ATTRIB_MULTICAST_NV 0x20AD
#define GLX_CONTEXT_MULTIGPU_ATTRIB_MULTI_DISPLAY_MULTICAST_NV 0x20AE
#endif /* GLX_NV_multigpu_context */
#ifndef GLX_NV_multisample_coverage
#define GLX_NV_multisample_coverage 1
#define GLX_COVERAGE_SAMPLES_NV 100001
#define GLX_COLOR_SAMPLES_NV 0x20B3
#endif /* GLX_NV_multisample_coverage */
#ifndef GLX_NV_present_video
#define GLX_NV_present_video 1
#define GLX_NUM_VIDEO_SLOTS_NV 0x20F0
typedef unsigned int *( *PFNGLXENUMERATEVIDEODEVICESNVPROC) (Display *dpy, int screen, int *nelements);
typedef int ( *PFNGLXBINDVIDEODEVICENVPROC) (Display *dpy, unsigned int video_slot, unsigned int video_device, const int *attrib_list);
#ifdef GLX_GLXEXT_PROTOTYPES
unsigned int *glXEnumerateVideoDevicesNV (Display *dpy, int screen, int *nelements);
int glXBindVideoDeviceNV (Display *dpy, unsigned int video_slot, unsigned int video_device, const int *attrib_list);
#endif
#endif /* GLX_NV_present_video */
#ifndef GLX_NV_robustness_video_memory_purge
#define GLX_NV_robustness_video_memory_purge 1
#define GLX_GENERATE_RESET_ON_VIDEO_MEMORY_PURGE_NV 0x20F7
#endif /* GLX_NV_robustness_video_memory_purge */
#ifndef GLX_NV_swap_group
#define GLX_NV_swap_group 1
typedef Bool ( *PFNGLXJOINSWAPGROUPNVPROC) (Display *dpy, GLXDrawable drawable, GLuint group);
typedef Bool ( *PFNGLXBINDSWAPBARRIERNVPROC) (Display *dpy, GLuint group, GLuint barrier);
typedef Bool ( *PFNGLXQUERYSWAPGROUPNVPROC) (Display *dpy, GLXDrawable drawable, GLuint *group, GLuint *barrier);
typedef Bool ( *PFNGLXQUERYMAXSWAPGROUPSNVPROC) (Display *dpy, int screen, GLuint *maxGroups, GLuint *maxBarriers);
typedef Bool ( *PFNGLXQUERYFRAMECOUNTNVPROC) (Display *dpy, int screen, GLuint *count);
typedef Bool ( *PFNGLXRESETFRAMECOUNTNVPROC) (Display *dpy, int screen);
#ifdef GLX_GLXEXT_PROTOTYPES
Bool glXJoinSwapGroupNV (Display *dpy, GLXDrawable drawable, GLuint group);
Bool glXBindSwapBarrierNV (Display *dpy, GLuint group, GLuint barrier);
Bool glXQuerySwapGroupNV (Display *dpy, GLXDrawable drawable, GLuint *group, GLuint *barrier);
Bool glXQueryMaxSwapGroupsNV (Display *dpy, int screen, GLuint *maxGroups, GLuint *maxBarriers);
Bool glXQueryFrameCountNV (Display *dpy, int screen, GLuint *count);
Bool glXResetFrameCountNV (Display *dpy, int screen);
#endif
#endif /* GLX_NV_swap_group */
#ifndef GLX_NV_video_capture
#define GLX_NV_video_capture 1
typedef XID GLXVideoCaptureDeviceNV;
#define GLX_DEVICE_ID_NV 0x20CD
#define GLX_UNIQUE_ID_NV 0x20CE
#define GLX_NUM_VIDEO_CAPTURE_SLOTS_NV 0x20CF
typedef int ( *PFNGLXBINDVIDEOCAPTUREDEVICENVPROC) (Display *dpy, unsigned int video_capture_slot, GLXVideoCaptureDeviceNV device);
typedef GLXVideoCaptureDeviceNV *( *PFNGLXENUMERATEVIDEOCAPTUREDEVICESNVPROC) (Display *dpy, int screen, int *nelements);
typedef void ( *PFNGLXLOCKVIDEOCAPTUREDEVICENVPROC) (Display *dpy, GLXVideoCaptureDeviceNV device);
typedef int ( *PFNGLXQUERYVIDEOCAPTUREDEVICENVPROC) (Display *dpy, GLXVideoCaptureDeviceNV device, int attribute, int *value);
typedef void ( *PFNGLXRELEASEVIDEOCAPTUREDEVICENVPROC) (Display *dpy, GLXVideoCaptureDeviceNV device);
#ifdef GLX_GLXEXT_PROTOTYPES
int glXBindVideoCaptureDeviceNV (Display *dpy, unsigned int video_capture_slot, GLXVideoCaptureDeviceNV device);
GLXVideoCaptureDeviceNV *glXEnumerateVideoCaptureDevicesNV (Display *dpy, int screen, int *nelements);
void glXLockVideoCaptureDeviceNV (Display *dpy, GLXVideoCaptureDeviceNV device);
int glXQueryVideoCaptureDeviceNV (Display *dpy, GLXVideoCaptureDeviceNV device, int attribute, int *value);
void glXReleaseVideoCaptureDeviceNV (Display *dpy, GLXVideoCaptureDeviceNV device);
#endif
#endif /* GLX_NV_video_capture */
#ifndef GLX_NV_video_out
#define GLX_NV_video_out 1
typedef unsigned int GLXVideoDeviceNV;
#define GLX_VIDEO_OUT_COLOR_NV 0x20C3
#define GLX_VIDEO_OUT_ALPHA_NV 0x20C4
#define GLX_VIDEO_OUT_DEPTH_NV 0x20C5
#define GLX_VIDEO_OUT_COLOR_AND_ALPHA_NV 0x20C6
#define GLX_VIDEO_OUT_COLOR_AND_DEPTH_NV 0x20C7
#define GLX_VIDEO_OUT_FRAME_NV 0x20C8
#define GLX_VIDEO_OUT_FIELD_1_NV 0x20C9
#define GLX_VIDEO_OUT_FIELD_2_NV 0x20CA
#define GLX_VIDEO_OUT_STACKED_FIELDS_1_2_NV 0x20CB
#define GLX_VIDEO_OUT_STACKED_FIELDS_2_1_NV 0x20CC
typedef int ( *PFNGLXGETVIDEODEVICENVPROC) (Display *dpy, int screen, int numVideoDevices, GLXVideoDeviceNV *pVideoDevice);
typedef int ( *PFNGLXRELEASEVIDEODEVICENVPROC) (Display *dpy, int screen, GLXVideoDeviceNV VideoDevice);
typedef int ( *PFNGLXBINDVIDEOIMAGENVPROC) (Display *dpy, GLXVideoDeviceNV VideoDevice, GLXPbuffer pbuf, int iVideoBuffer);
typedef int ( *PFNGLXRELEASEVIDEOIMAGENVPROC) (Display *dpy, GLXPbuffer pbuf);
typedef int ( *PFNGLXSENDPBUFFERTOVIDEONVPROC) (Display *dpy, GLXPbuffer pbuf, int iBufferType, unsigned long *pulCounterPbuffer, GLboolean bBlock);
typedef int ( *PFNGLXGETVIDEOINFONVPROC) (Display *dpy, int screen, GLXVideoDeviceNV VideoDevice, unsigned long *pulCounterOutputPbuffer, unsigned long *pulCounterOutputVideo);
#ifdef GLX_GLXEXT_PROTOTYPES
int glXGetVideoDeviceNV (Display *dpy, int screen, int numVideoDevices, GLXVideoDeviceNV *pVideoDevice);
int glXReleaseVideoDeviceNV (Display *dpy, int screen, GLXVideoDeviceNV VideoDevice);
int glXBindVideoImageNV (Display *dpy, GLXVideoDeviceNV VideoDevice, GLXPbuffer pbuf, int iVideoBuffer);
int glXReleaseVideoImageNV (Display *dpy, GLXPbuffer pbuf);
int glXSendPbufferToVideoNV (Display *dpy, GLXPbuffer pbuf, int iBufferType, unsigned long *pulCounterPbuffer, GLboolean bBlock);
int glXGetVideoInfoNV (Display *dpy, int screen, GLXVideoDeviceNV VideoDevice, unsigned long *pulCounterOutputPbuffer, unsigned long *pulCounterOutputVideo);
#endif
#endif /* GLX_NV_video_out */
#ifndef GLX_OML_swap_method
#define GLX_OML_swap_method 1
#define GLX_SWAP_METHOD_OML 0x8060
#define GLX_SWAP_EXCHANGE_OML 0x8061
#define GLX_SWAP_COPY_OML 0x8062
#define GLX_SWAP_UNDEFINED_OML 0x8063
#endif /* GLX_OML_swap_method */
#ifndef GLX_OML_sync_control
#define GLX_OML_sync_control 1
#ifndef GLEXT_64_TYPES_DEFINED
/* This code block is duplicated in glext.h, so must be protected */
#define GLEXT_64_TYPES_DEFINED
/* Define int32_t, int64_t, and uint64_t types for UST/MSC */
/* (as used in the GLX_OML_sync_control extension). */
#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
#include <inttypes.h>
#elif defined(__sun__) || defined(__digital__)
#include <inttypes.h>
#if defined(__STDC__)
#if defined(__arch64__) || defined(_LP64)
typedef long int int64_t;
typedef unsigned long int uint64_t;
#else
typedef long long int int64_t;
typedef unsigned long long int uint64_t;
#endif /* __arch64__ */
#endif /* __STDC__ */
#elif defined( __VMS ) || defined(__sgi)
#include <inttypes.h>
#elif defined(__SCO__) || defined(__USLC__)
#include <stdint.h>
#elif defined(__UNIXOS2__) || defined(__SOL64__)
typedef long int int32_t;
typedef long long int int64_t;
typedef unsigned long long int uint64_t;
#elif defined(_WIN32) && defined(__GNUC__)
#include <stdint.h>
#elif defined(_WIN32)
typedef __int32 int32_t;
typedef __int64 int64_t;
typedef unsigned __int64 uint64_t;
#else
/* Fallback if nothing above works */
#include <inttypes.h>
#endif
#endif
typedef Bool ( *PFNGLXGETSYNCVALUESOMLPROC) (Display *dpy, GLXDrawable drawable, int64_t *ust, int64_t *msc, int64_t *sbc);
typedef Bool ( *PFNGLXGETMSCRATEOMLPROC) (Display *dpy, GLXDrawable drawable, int32_t *numerator, int32_t *denominator);
typedef int64_t ( *PFNGLXSWAPBUFFERSMSCOMLPROC) (Display *dpy, GLXDrawable drawable, int64_t target_msc, int64_t divisor, int64_t remainder);
typedef Bool ( *PFNGLXWAITFORMSCOMLPROC) (Display *dpy, GLXDrawable drawable, int64_t target_msc, int64_t divisor, int64_t remainder, int64_t *ust, int64_t *msc, int64_t *sbc);
typedef Bool ( *PFNGLXWAITFORSBCOMLPROC) (Display *dpy, GLXDrawable drawable, int64_t target_sbc, int64_t *ust, int64_t *msc, int64_t *sbc);
#ifdef GLX_GLXEXT_PROTOTYPES
Bool glXGetSyncValuesOML (Display *dpy, GLXDrawable drawable, int64_t *ust, int64_t *msc, int64_t *sbc);
Bool glXGetMscRateOML (Display *dpy, GLXDrawable drawable, int32_t *numerator, int32_t *denominator);
int64_t glXSwapBuffersMscOML (Display *dpy, GLXDrawable drawable, int64_t target_msc, int64_t divisor, int64_t remainder);
Bool glXWaitForMscOML (Display *dpy, GLXDrawable drawable, int64_t target_msc, int64_t divisor, int64_t remainder, int64_t *ust, int64_t *msc, int64_t *sbc);
Bool glXWaitForSbcOML (Display *dpy, GLXDrawable drawable, int64_t target_sbc, int64_t *ust, int64_t *msc, int64_t *sbc);
#endif
#endif /* GLX_OML_sync_control */
#ifndef GLX_SGIS_blended_overlay
#define GLX_SGIS_blended_overlay 1
#define GLX_BLENDED_RGBA_SGIS 0x8025
#endif /* GLX_SGIS_blended_overlay */
#ifndef GLX_SGIS_multisample
#define GLX_SGIS_multisample 1
#define GLX_SAMPLE_BUFFERS_SGIS 100000
#define GLX_SAMPLES_SGIS 100001
#endif /* GLX_SGIS_multisample */
#ifndef GLX_SGIS_shared_multisample
#define GLX_SGIS_shared_multisample 1
#define GLX_MULTISAMPLE_SUB_RECT_WIDTH_SGIS 0x8026
#define GLX_MULTISAMPLE_SUB_RECT_HEIGHT_SGIS 0x8027
#endif /* GLX_SGIS_shared_multisample */
#ifndef GLX_SGIX_dmbuffer
#define GLX_SGIX_dmbuffer 1
typedef XID GLXPbufferSGIX;
#ifdef _DM_BUFFER_H_
#define GLX_DIGITAL_MEDIA_PBUFFER_SGIX 0x8024
typedef Bool ( *PFNGLXASSOCIATEDMPBUFFERSGIXPROC) (Display *dpy, GLXPbufferSGIX pbuffer, DMparams *params, DMbuffer dmbuffer);
#ifdef GLX_GLXEXT_PROTOTYPES
Bool glXAssociateDMPbufferSGIX (Display *dpy, GLXPbufferSGIX pbuffer, DMparams *params, DMbuffer dmbuffer);
#endif
#endif /* _DM_BUFFER_H_ */
#endif /* GLX_SGIX_dmbuffer */
#ifndef GLX_SGIX_fbconfig
#define GLX_SGIX_fbconfig 1
typedef struct __GLXFBConfigRec *GLXFBConfigSGIX;
#define GLX_WINDOW_BIT_SGIX 0x00000001
#define GLX_PIXMAP_BIT_SGIX 0x00000002
#define GLX_RGBA_BIT_SGIX 0x00000001
#define GLX_COLOR_INDEX_BIT_SGIX 0x00000002
#define GLX_DRAWABLE_TYPE_SGIX 0x8010
#define GLX_RENDER_TYPE_SGIX 0x8011
#define GLX_X_RENDERABLE_SGIX 0x8012
#define GLX_FBCONFIG_ID_SGIX 0x8013
#define GLX_RGBA_TYPE_SGIX 0x8014
#define GLX_COLOR_INDEX_TYPE_SGIX 0x8015
typedef int ( *PFNGLXGETFBCONFIGATTRIBSGIXPROC) (Display *dpy, GLXFBConfigSGIX config, int attribute, int *value);
typedef GLXFBConfigSGIX *( *PFNGLXCHOOSEFBCONFIGSGIXPROC) (Display *dpy, int screen, int *attrib_list, int *nelements);
typedef GLXPixmap ( *PFNGLXCREATEGLXPIXMAPWITHCONFIGSGIXPROC) (Display *dpy, GLXFBConfigSGIX config, Pixmap pixmap);
typedef GLXContext ( *PFNGLXCREATECONTEXTWITHCONFIGSGIXPROC) (Display *dpy, GLXFBConfigSGIX config, int render_type, GLXContext share_list, Bool direct);
typedef XVisualInfo *( *PFNGLXGETVISUALFROMFBCONFIGSGIXPROC) (Display *dpy, GLXFBConfigSGIX config);
typedef GLXFBConfigSGIX ( *PFNGLXGETFBCONFIGFROMVISUALSGIXPROC) (Display *dpy, XVisualInfo *vis);
#ifdef GLX_GLXEXT_PROTOTYPES
int glXGetFBConfigAttribSGIX (Display *dpy, GLXFBConfigSGIX config, int attribute, int *value);
GLXFBConfigSGIX *glXChooseFBConfigSGIX (Display *dpy, int screen, int *attrib_list, int *nelements);
GLXPixmap glXCreateGLXPixmapWithConfigSGIX (Display *dpy, GLXFBConfigSGIX config, Pixmap pixmap);
GLXContext glXCreateContextWithConfigSGIX (Display *dpy, GLXFBConfigSGIX config, int render_type, GLXContext share_list, Bool direct);
XVisualInfo *glXGetVisualFromFBConfigSGIX (Display *dpy, GLXFBConfigSGIX config);
GLXFBConfigSGIX glXGetFBConfigFromVisualSGIX (Display *dpy, XVisualInfo *vis);
#endif
#endif /* GLX_SGIX_fbconfig */
#ifndef GLX_SGIX_hyperpipe
#define GLX_SGIX_hyperpipe 1
typedef struct {
char pipeName[80]; /* Should be [GLX_HYPERPIPE_PIPE_NAME_LENGTH_SGIX] */
int networkId;
} GLXHyperpipeNetworkSGIX;
typedef struct {
char pipeName[80]; /* Should be [GLX_HYPERPIPE_PIPE_NAME_LENGTH_SGIX] */
int channel;
unsigned int participationType;
int timeSlice;
} GLXHyperpipeConfigSGIX;
typedef struct {
char pipeName[80]; /* Should be [GLX_HYPERPIPE_PIPE_NAME_LENGTH_SGIX] */
int srcXOrigin, srcYOrigin, srcWidth, srcHeight;
int destXOrigin, destYOrigin, destWidth, destHeight;
} GLXPipeRect;
typedef struct {
char pipeName[80]; /* Should be [GLX_HYPERPIPE_PIPE_NAME_LENGTH_SGIX] */
int XOrigin, YOrigin, maxHeight, maxWidth;
} GLXPipeRectLimits;
#define GLX_HYPERPIPE_PIPE_NAME_LENGTH_SGIX 80
#define GLX_BAD_HYPERPIPE_CONFIG_SGIX 91
#define GLX_BAD_HYPERPIPE_SGIX 92
#define GLX_HYPERPIPE_DISPLAY_PIPE_SGIX 0x00000001
#define GLX_HYPERPIPE_RENDER_PIPE_SGIX 0x00000002
#define GLX_PIPE_RECT_SGIX 0x00000001
#define GLX_PIPE_RECT_LIMITS_SGIX 0x00000002
#define GLX_HYPERPIPE_STEREO_SGIX 0x00000003
#define GLX_HYPERPIPE_PIXEL_AVERAGE_SGIX 0x00000004
#define GLX_HYPERPIPE_ID_SGIX 0x8030
typedef GLXHyperpipeNetworkSGIX *( *PFNGLXQUERYHYPERPIPENETWORKSGIXPROC) (Display *dpy, int *npipes);
typedef int ( *PFNGLXHYPERPIPECONFIGSGIXPROC) (Display *dpy, int networkId, int npipes, GLXHyperpipeConfigSGIX *cfg, int *hpId);
typedef GLXHyperpipeConfigSGIX *( *PFNGLXQUERYHYPERPIPECONFIGSGIXPROC) (Display *dpy, int hpId, int *npipes);
typedef int ( *PFNGLXDESTROYHYPERPIPECONFIGSGIXPROC) (Display *dpy, int hpId);
typedef int ( *PFNGLXBINDHYPERPIPESGIXPROC) (Display *dpy, int hpId);
typedef int ( *PFNGLXQUERYHYPERPIPEBESTATTRIBSGIXPROC) (Display *dpy, int timeSlice, int attrib, int size, void *attribList, void *returnAttribList);
typedef int ( *PFNGLXHYPERPIPEATTRIBSGIXPROC) (Display *dpy, int timeSlice, int attrib, int size, void *attribList);
typedef int ( *PFNGLXQUERYHYPERPIPEATTRIBSGIXPROC) (Display *dpy, int timeSlice, int attrib, int size, void *returnAttribList);
#ifdef GLX_GLXEXT_PROTOTYPES
GLXHyperpipeNetworkSGIX *glXQueryHyperpipeNetworkSGIX (Display *dpy, int *npipes);
int glXHyperpipeConfigSGIX (Display *dpy, int networkId, int npipes, GLXHyperpipeConfigSGIX *cfg, int *hpId);
GLXHyperpipeConfigSGIX *glXQueryHyperpipeConfigSGIX (Display *dpy, int hpId, int *npipes);
int glXDestroyHyperpipeConfigSGIX (Display *dpy, int hpId);
int glXBindHyperpipeSGIX (Display *dpy, int hpId);
int glXQueryHyperpipeBestAttribSGIX (Display *dpy, int timeSlice, int attrib, int size, void *attribList, void *returnAttribList);
int glXHyperpipeAttribSGIX (Display *dpy, int timeSlice, int attrib, int size, void *attribList);
int glXQueryHyperpipeAttribSGIX (Display *dpy, int timeSlice, int attrib, int size, void *returnAttribList);
#endif
#endif /* GLX_SGIX_hyperpipe */
#ifndef GLX_SGIX_pbuffer
#define GLX_SGIX_pbuffer 1
#define GLX_PBUFFER_BIT_SGIX 0x00000004
#define GLX_BUFFER_CLOBBER_MASK_SGIX 0x08000000
#define GLX_FRONT_LEFT_BUFFER_BIT_SGIX 0x00000001
#define GLX_FRONT_RIGHT_BUFFER_BIT_SGIX 0x00000002
#define GLX_BACK_LEFT_BUFFER_BIT_SGIX 0x00000004
#define GLX_BACK_RIGHT_BUFFER_BIT_SGIX 0x00000008
#define GLX_AUX_BUFFERS_BIT_SGIX 0x00000010
#define GLX_DEPTH_BUFFER_BIT_SGIX 0x00000020
#define GLX_STENCIL_BUFFER_BIT_SGIX 0x00000040
#define GLX_ACCUM_BUFFER_BIT_SGIX 0x00000080
#define GLX_SAMPLE_BUFFERS_BIT_SGIX 0x00000100
#define GLX_MAX_PBUFFER_WIDTH_SGIX 0x8016
#define GLX_MAX_PBUFFER_HEIGHT_SGIX 0x8017
#define GLX_MAX_PBUFFER_PIXELS_SGIX 0x8018
#define GLX_OPTIMAL_PBUFFER_WIDTH_SGIX 0x8019
#define GLX_OPTIMAL_PBUFFER_HEIGHT_SGIX 0x801A
#define GLX_PRESERVED_CONTENTS_SGIX 0x801B
#define GLX_LARGEST_PBUFFER_SGIX 0x801C
#define GLX_WIDTH_SGIX 0x801D
#define GLX_HEIGHT_SGIX 0x801E
#define GLX_EVENT_MASK_SGIX 0x801F
#define GLX_DAMAGED_SGIX 0x8020
#define GLX_SAVED_SGIX 0x8021
#define GLX_WINDOW_SGIX 0x8022
#define GLX_PBUFFER_SGIX 0x8023
typedef GLXPbufferSGIX ( *PFNGLXCREATEGLXPBUFFERSGIXPROC) (Display *dpy, GLXFBConfigSGIX config, unsigned int width, unsigned int height, int *attrib_list);
typedef void ( *PFNGLXDESTROYGLXPBUFFERSGIXPROC) (Display *dpy, GLXPbufferSGIX pbuf);
typedef void ( *PFNGLXQUERYGLXPBUFFERSGIXPROC) (Display *dpy, GLXPbufferSGIX pbuf, int attribute, unsigned int *value);
typedef void ( *PFNGLXSELECTEVENTSGIXPROC) (Display *dpy, GLXDrawable drawable, unsigned long mask);
typedef void ( *PFNGLXGETSELECTEDEVENTSGIXPROC) (Display *dpy, GLXDrawable drawable, unsigned long *mask);
#ifdef GLX_GLXEXT_PROTOTYPES
GLXPbufferSGIX glXCreateGLXPbufferSGIX (Display *dpy, GLXFBConfigSGIX config, unsigned int width, unsigned int height, int *attrib_list);
void glXDestroyGLXPbufferSGIX (Display *dpy, GLXPbufferSGIX pbuf);
void glXQueryGLXPbufferSGIX (Display *dpy, GLXPbufferSGIX pbuf, int attribute, unsigned int *value);
void glXSelectEventSGIX (Display *dpy, GLXDrawable drawable, unsigned long mask);
void glXGetSelectedEventSGIX (Display *dpy, GLXDrawable drawable, unsigned long *mask);
#endif
#endif /* GLX_SGIX_pbuffer */
#ifndef GLX_SGIX_swap_barrier
#define GLX_SGIX_swap_barrier 1
typedef void ( *PFNGLXBINDSWAPBARRIERSGIXPROC) (Display *dpy, GLXDrawable drawable, int barrier);
typedef Bool ( *PFNGLXQUERYMAXSWAPBARRIERSSGIXPROC) (Display *dpy, int screen, int *max);
#ifdef GLX_GLXEXT_PROTOTYPES
void glXBindSwapBarrierSGIX (Display *dpy, GLXDrawable drawable, int barrier);
Bool glXQueryMaxSwapBarriersSGIX (Display *dpy, int screen, int *max);
#endif
#endif /* GLX_SGIX_swap_barrier */
#ifndef GLX_SGIX_swap_group
#define GLX_SGIX_swap_group 1
typedef void ( *PFNGLXJOINSWAPGROUPSGIXPROC) (Display *dpy, GLXDrawable drawable, GLXDrawable member);
#ifdef GLX_GLXEXT_PROTOTYPES
void glXJoinSwapGroupSGIX (Display *dpy, GLXDrawable drawable, GLXDrawable member);
#endif
#endif /* GLX_SGIX_swap_group */
#ifndef GLX_SGIX_video_resize
#define GLX_SGIX_video_resize 1
#define GLX_SYNC_FRAME_SGIX 0x00000000
#define GLX_SYNC_SWAP_SGIX 0x00000001
typedef int ( *PFNGLXBINDCHANNELTOWINDOWSGIXPROC) (Display *display, int screen, int channel, Window window);
typedef int ( *PFNGLXCHANNELRECTSGIXPROC) (Display *display, int screen, int channel, int x, int y, int w, int h);
typedef int ( *PFNGLXQUERYCHANNELRECTSGIXPROC) (Display *display, int screen, int channel, int *dx, int *dy, int *dw, int *dh);
typedef int ( *PFNGLXQUERYCHANNELDELTASSGIXPROC) (Display *display, int screen, int channel, int *x, int *y, int *w, int *h);
typedef int ( *PFNGLXCHANNELRECTSYNCSGIXPROC) (Display *display, int screen, int channel, GLenum synctype);
#ifdef GLX_GLXEXT_PROTOTYPES
int glXBindChannelToWindowSGIX (Display *display, int screen, int channel, Window window);
int glXChannelRectSGIX (Display *display, int screen, int channel, int x, int y, int w, int h);
int glXQueryChannelRectSGIX (Display *display, int screen, int channel, int *dx, int *dy, int *dw, int *dh);
int glXQueryChannelDeltasSGIX (Display *display, int screen, int channel, int *x, int *y, int *w, int *h);
int glXChannelRectSyncSGIX (Display *display, int screen, int channel, GLenum synctype);
#endif
#endif /* GLX_SGIX_video_resize */
#ifndef GLX_SGIX_video_source
#define GLX_SGIX_video_source 1
typedef XID GLXVideoSourceSGIX;
#ifdef _VL_H
typedef GLXVideoSourceSGIX ( *PFNGLXCREATEGLXVIDEOSOURCESGIXPROC) (Display *display, int screen, VLServer server, VLPath path, int nodeClass, VLNode drainNode);
typedef void ( *PFNGLXDESTROYGLXVIDEOSOURCESGIXPROC) (Display *dpy, GLXVideoSourceSGIX glxvideosource);
#ifdef GLX_GLXEXT_PROTOTYPES
GLXVideoSourceSGIX glXCreateGLXVideoSourceSGIX (Display *display, int screen, VLServer server, VLPath path, int nodeClass, VLNode drainNode);
void glXDestroyGLXVideoSourceSGIX (Display *dpy, GLXVideoSourceSGIX glxvideosource);
#endif
#endif /* _VL_H */
#endif /* GLX_SGIX_video_source */
#ifndef GLX_SGIX_visual_select_group
#define GLX_SGIX_visual_select_group 1
#define GLX_VISUAL_SELECT_GROUP_SGIX 0x8028
#endif /* GLX_SGIX_visual_select_group */
#ifndef GLX_SGI_cushion
#define GLX_SGI_cushion 1
typedef void ( *PFNGLXCUSHIONSGIPROC) (Display *dpy, Window window, float cushion);
#ifdef GLX_GLXEXT_PROTOTYPES
void glXCushionSGI (Display *dpy, Window window, float cushion);
#endif
#endif /* GLX_SGI_cushion */
#ifndef GLX_SGI_make_current_read
#define GLX_SGI_make_current_read 1
typedef Bool ( *PFNGLXMAKECURRENTREADSGIPROC) (Display *dpy, GLXDrawable draw, GLXDrawable read, GLXContext ctx);
typedef GLXDrawable ( *PFNGLXGETCURRENTREADDRAWABLESGIPROC) (void);
#ifdef GLX_GLXEXT_PROTOTYPES
Bool glXMakeCurrentReadSGI (Display *dpy, GLXDrawable draw, GLXDrawable read, GLXContext ctx);
GLXDrawable glXGetCurrentReadDrawableSGI (void);
#endif
#endif /* GLX_SGI_make_current_read */
#ifndef GLX_SGI_swap_control
#define GLX_SGI_swap_control 1
typedef int ( *PFNGLXSWAPINTERVALSGIPROC) (int interval);
#ifdef GLX_GLXEXT_PROTOTYPES
int glXSwapIntervalSGI (int interval);
#endif
#endif /* GLX_SGI_swap_control */
#ifndef GLX_SGI_video_sync
#define GLX_SGI_video_sync 1
typedef int ( *PFNGLXGETVIDEOSYNCSGIPROC) (unsigned int *count);
typedef int ( *PFNGLXWAITVIDEOSYNCSGIPROC) (int divisor, int remainder, unsigned int *count);
#ifdef GLX_GLXEXT_PROTOTYPES
int glXGetVideoSyncSGI (unsigned int *count);
int glXWaitVideoSyncSGI (int divisor, int remainder, unsigned int *count);
#endif
#endif /* GLX_SGI_video_sync */
#ifndef GLX_SUN_get_transparent_index
#define GLX_SUN_get_transparent_index 1
typedef Status ( *PFNGLXGETTRANSPARENTINDEXSUNPROC) (Display *dpy, Window overlay, Window underlay, unsigned long *pTransparentIndex);
#ifdef GLX_GLXEXT_PROTOTYPES
Status glXGetTransparentIndexSUN (Display *dpy, Window overlay, Window underlay, unsigned long *pTransparentIndex);
#endif
#endif /* GLX_SUN_get_transparent_index */
#ifdef __cplusplus
}
#endif
#endif
| 47,796
|
C++
|
.h
| 878
| 53.256264
| 317
| 0.762072
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| false
| false
| false
|
23,407
|
glFunctions.h
|
cemu-project_Cemu/src/Common/GLInclude/glFunctions.h
|
// OpenGL 1.1 - 2.0
GLFUNC(PFNGLDRAWBUFFERPROC, glDrawBuffer)
GLFUNC(PFNGLGENTEXTURESPROC, glGenTextures)
GLFUNC(PFNGLDELETETEXTURESPROC, glDeleteTextures)
GLFUNC(PFNGLBINDTEXTUREPROC, glBindTexture)
GLFUNC(PFNGLTEXPARAMETERIPROC, glTexParameteri)
GLFUNC(PFNGLTEXIMAGE2DPROC, glTexImage2D)
GLFUNC(PFNGLTEXSUBIMAGE2DPROC, glTexSubImage2D)
GLFUNC(PFNGLTEXIMAGE1DPROC, glTexImage1D)
GLFUNC(PFNGLTEXSUBIMAGE1DPROC, glTexSubImage1D)
GLFUNC(PFNGLGETTEXIMAGEPROC, glGetTexImage)
GLFUNC(PFNGLENABLEPROC, glEnable)
GLFUNC(PFNGLDISABLEPROC, glDisable)
GLFUNC(PFNGLISENABLEDPROC, glIsEnabled)
GLFUNC(PFNGLCLEARPROC, glClear)
GLFUNC(PFNGLCLEARCOLORPROC, glClearColor)
GLFUNC(PFNGLCLEARDEPTHPROC, glClearDepth)
GLFUNC(PFNGLCLEARSTENCILPROC, glClearStencil)
GLFUNC(PFNGLFLUSHPROC, glFlush)
GLFUNC(PFNGLFINISHPROC, glFinish)
GLFUNC(PFNGLPIXELSTOREIPROC, glPixelStorei)
GLFUNC(PFNGLGETSTRINGPROC, glGetString)
GLFUNC(PFNGLGETINTEGERVPROC, glGetIntegerv)
GLFUNC(PFNGLGETTEXLEVELPARAMETERIVPROC, glGetTexLevelParameteriv)
GLFUNC(PFNGLTEXPARAMETERFPROC, glTexParameterf)
GLFUNC(PFNGLTEXPARAMETERFVPROC, glTexParameterfv)
GLFUNC(PFNGLDEPTHFUNCPROC, glDepthFunc)
GLFUNC(PFNGLDEPTHMASKPROC, glDepthMask)
GLFUNC(PFNGLDEPTHRANGEPROC, glDepthRange)
GLFUNC(PFNGLFRONTFACEPROC, glFrontFace)
GLFUNC(PFNGLCULLFACEPROC, glCullFace)
GLFUNC(PFNGLPOLYGONOFFSETPROC, glPolygonOffset)
GLFUNC(PFNGLPOINTSIZEPROC, glPointSize)
GLFUNC(PFNGLLOGICOPPROC, glLogicOp)
GLFUNC(PFNGLPOLYGONMODEPROC, glPolygonMode)
GLFUNC(PFNGLSCISSORPROC, glScissor)
GLFUNC(PFNGLVIEWPORTPROC, glViewport)
GLFUNC(PFNGLGETERRORPROC, glGetError)
GLFUNC(PFNGLDRAWARRAYSPROC, glDrawArrays)
// everything else
GLFUNC(PFNGLUNIFORM1IPROC, glUniform1i)
GLFUNC(PFNGLUNIFORM2IPROC, glUniform2i)
GLFUNC(PFNGLUNIFORM2FPROC, glUniform2f)
GLFUNC(PFNGLUNIFORM4FVPROC, glUniform4fv)
GLFUNC(PFNGLUNIFORMMATRIX4FVPROC, glUniformMatrix4fv)
GLFUNC(PFNGLGETSHADERINFOLOGPROC, glGetShaderInfoLog)
GLFUNC(PFNGLUSEPROGRAMPROC, glUseProgram)
GLFUNC(PFNGLGETUNIFORMLOCATIONPROC, glGetUniformLocation)
GLFUNC(PFNGLACTIVETEXTUREPROC, glActiveTexture)
GLFUNC(PFNGLCLIENTACTIVETEXTUREPROC, glClientActiveTexture)
GLFUNC(PFNGLPRIMITIVERESTARTINDEXPROC, glPrimitiveRestartIndex)
GLFUNC(PFNGLDRAWRANGEELEMENTSPROC, glDrawRangeElements)
GLFUNC(PFNGLDRAWRANGEELEMENTSBASEVERTEXPROC, glDrawRangeElementsBaseVertex)
GLFUNC(PFNGLGENBUFFERSPROC, glGenBuffers)
GLFUNC(PFNGLBINDBUFFERPROC, glBindBuffer)
GLFUNC(PFNGLBUFFERDATAPROC, glBufferData)
GLFUNC(PFNGLBUFFERSUBDATAPROC, glBufferSubData)
GLFUNC(PFNGLMAPBUFFERPROC, glMapBuffer)
GLFUNC(PFNGLUNMAPBUFFERPROC, glUnmapBuffer)
GLFUNC(PFNGLDELETEBUFFERSARBPROC, glDeleteBuffers)
GLFUNC(PFNGLENABLEVERTEXATTRIBARRAYPROC, glEnableVertexAttribArray)
GLFUNC(PFNGLDISABLEVERTEXATTRIBARRAYPROC, glDisableVertexAttribArray)
GLFUNC(PFNGLGETATTRIBLOCATIONPROC, glGetAttribLocation)
GLFUNC(PFNGLBINDATTRIBLOCATIONPROC, glBindAttribLocation)
GLFUNC(PFNGLVERTEXATTRIBPOINTERPROC, glVertexAttribPointer)
GLFUNC(PFNGLVERTEXATTRIBIPOINTERPROC, glVertexAttribIPointer)
GLFUNC(PFNGLBLENDEQUATIONPROC, glBlendEquation)
GLFUNC(PFNGLBLENDFUNCSEPARATEEXTPROC, glBlendFuncSeparate)
GLFUNC(PFNGLBLENDEQUATIONSEPARATEEXTPROC, glBlendEquationSeparate)
GLFUNC(PFNGLBLENDEQUATIONSEPARATEIPROC, glBlendEquationSeparatei)
GLFUNC(PFNGLBLENDFUNCSEPARATEIPROC, glBlendFuncSeparatei)
GLFUNC(PFNGLBLENDCOLORPROC, glBlendColor)
GLFUNC(PFNGLDRAWBUFFERSPROC, glDrawBuffers)
GLFUNC(PFNGLCLAMPCOLORARBPROC, glClampColor)
GLFUNC(PFNGLBINDFRAGDATALOCATIONEXTPROC, glBindFragDataLocation)
GLFUNC(PFNGLSHADERSOURCEPROC, glShaderSource)
GLFUNC(PFNGLCOMPILESHADERPROC, glCompileShader)
GLFUNC(PFNGLATTACHSHADERPROC, glAttachShader)
GLFUNC(PFNGLLINKPROGRAMPROC, glLinkProgram)
GLFUNC(PFNGLGETSHADERIVPROC, glGetShaderiv)
GLFUNC(PFNGLGETPROGRAMIVPROC, glGetProgramiv)
GLFUNC(PFNGLGETPROGRAMINFOLOGPROC, glGetProgramInfoLog)
GLFUNC(PFNGLGETPROGRAMBINARYPROC, glGetProgramBinary)
GLFUNC(PFNGLPROGRAMBINARYPROC, glProgramBinary)
GLFUNC(PFNGLPROGRAMPARAMETERIPROC, glProgramParameteri)
GLFUNC(PFNGLCREATEPROGRAMPROC, glCreateProgram)
GLFUNC(PFNGLCREATESHADERPROC, glCreateShader)
GLFUNC(PFNGLDELETEPROGRAMPROC, glDeleteProgram)
GLFUNC(PFNGLDELETESHADERPROC, glDeleteShader)
GLFUNC(PFNGLDETACHSHADERPROC, glDetachShader)
GLFUNC(PFNGLGETATTACHEDSHADERSPROC, glGetAttachedShaders)
GLFUNC(PFNGLCREATESHADERPROGRAMVPROC, glCreateShaderProgramv)
GLFUNC(PFNGLUSEPROGRAMSTAGESPROC, glUseProgramStages)
GLFUNC(PFNGLBINDPROGRAMPIPELINEPROC, glBindProgramPipeline)
GLFUNC(PFNGLGENPROGRAMPIPELINESPROC, glGenProgramPipelines)
GLFUNC(PFNGLACTIVESHADERPROGRAMPROC, glActiveShaderProgram)
GLFUNC(PFNGLDELETEPROGRAMPIPELINESPROC, glDeleteProgramPipelines)
GLFUNC(PFNGLPROGRAMUNIFORM1IPROC, glProgramUniform1i)
GLFUNC(PFNGLPROGRAMUNIFORM2IPROC, glProgramUniform2i)
GLFUNC(PFNGLPROGRAMUNIFORM1IVPROC, glProgramUniform1iv)
GLFUNC(PFNGLPROGRAMUNIFORM4IVPROC, glProgramUniform4iv)
GLFUNC(PFNGLPROGRAMUNIFORM1FVPROC, glProgramUniform1fv)
GLFUNC(PFNGLPROGRAMUNIFORM2FVPROC, glProgramUniform2fv)
// FBO
GLFUNC(PFNGLGENFRAMEBUFFERSPROC, glGenFramebuffers)
GLFUNC(PFNGLBINDFRAMEBUFFERPROC, glBindFramebuffer)
GLFUNC(PFNGLFRAMEBUFFERTEXTURE2DPROC, glFramebufferTexture2D)
GLFUNC(PFNGLFRAMEBUFFERTEXTURELAYERPROC, glFramebufferTextureLayer)
GLFUNC(PFNGLNAMEDFRAMEBUFFERTEXTUREPROC, glNamedFramebufferTexture)
GLFUNC(PFNGLCHECKFRAMEBUFFERSTATUSPROC, glCheckFramebufferStatus)
GLFUNC(PFNGLINVALIDATEFRAMEBUFFERPROC, glInvalidateFramebuffer)
GLFUNC(PFNGLDELETEFRAMEBUFFERSPROC, glDeleteFramebuffers)
//GLFUNC(PFNGLNAMEDFRAMEBUFFERTEXTUREPROC, glNamedFramebufferTexture)
GLFUNC(PFNGLNAMEDFRAMEBUFFERTEXTURE2DEXTPROC, glNamedFramebufferTexture2DEXT)
GLFUNC(PFNGLNAMEDFRAMEBUFFERTEXTURELAYERPROC, glNamedFramebufferTextureLayer)
GLFUNC(PFNGLENABLEIPROC, glEnablei)
GLFUNC(PFNGLDISABLEIPROC, glDisablei)
GLFUNC(PFNGLBEGINQUERYINDEXEDPROC, glBeginQueryIndexed)
GLFUNC(PFNGLENDQUERYINDEXEDPROC, glEndQueryIndexed)
GLFUNC(PFNGLGETQUERYINDEXEDIVPROC, glGetQueryIndexediv)
GLFUNC(PFNGLGETQUERYOBJECTI64VPROC, glGetQueryObjecti64v)
GLFUNC(PFNGLGENQUERIESPROC, glGenQueries)
GLFUNC(PFNGLDELETEQUERIESPROC, glDeleteQueries)
GLFUNC(PFNGLQUERYCOUNTERPROC, glQueryCounter)
GLFUNC(PFNGLGETQUERYOBJECTIVPROC, glGetQueryObjectiv)
// FBO DSA
GLFUNC(PFNGLCREATEFRAMEBUFFERSPROC, glCreateFramebuffers)
GLFUNC(PFNGLINVALIDATENAMEDFRAMEBUFFERDATAPROC, glInvalidateNamedFramebufferData)
// misc
GLFUNC(PFNGLCOLORMASKIPROC, glColorMaski)
GLFUNC(PFNGLTEXTUREBARRIERPROC, glTextureBarrier)
GLFUNC(PFNGLCLIPCONTROLPROC, glClipControl)
GLFUNC(PFNGLVIEWPORTINDEXEDFPROC, glViewportIndexedf)
GLFUNC(PFNGLMAXSHADERCOMPILERTHREADSARBPROC, glMaxShaderCompilerThreadsARB)
GLFUNC(PFNGLDEPTHRANGEDNVPROC, glDepthRangedNV)
GLFUNC(PFNGLPOLYGONOFFSETCLAMPEXTPROC, glPolygonOffsetClampEXT)
// texture
GLFUNC(PFNGLTEXTUREVIEWPROC, glTextureView)
GLFUNC(PFNGLTEXSTORAGE1DPROC, glTexStorage1D)
GLFUNC(PFNGLTEXSTORAGE2DPROC, glTexStorage2D)
GLFUNC(PFNGLTEXSTORAGE3DPROC, glTexStorage3D)
GLFUNC(PFNGLTEXIMAGE3DPROC, glTexImage3D)
GLFUNC(PFNGLTEXSUBIMAGE3DPROC, glTexSubImage3D)
GLFUNC(PFNGLCOMPRESSEDTEXIMAGE1DPROC, glCompressedTexImage1D)
GLFUNC(PFNGLCOMPRESSEDTEXIMAGE2DPROC, glCompressedTexImage2D)
GLFUNC(PFNGLCOMPRESSEDTEXIMAGE3DPROC, glCompressedTexImage3D)
GLFUNC(PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC, glCompressedTexSubImage1D)
GLFUNC(PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC, glCompressedTexSubImage2D)
GLFUNC(PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC, glCompressedTexSubImage3D)
GLFUNC(PFNGLCOMPRESSEDTEXTURESUBIMAGE1DPROC, glCompressedTextureSubImage1D)
GLFUNC(PFNGLCOMPRESSEDTEXTURESUBIMAGE2DPROC, glCompressedTextureSubImage2D)
GLFUNC(PFNGLCOMPRESSEDTEXTURESUBIMAGE3DPROC, glCompressedTextureSubImage3D)
GLFUNC(PFNGLCOPYIMAGESUBDATAPROC, glCopyImageSubData)
GLFUNC(PFNGLCLEARTEXIMAGEPROC, glClearTexImage)
GLFUNC(PFNGLCLEARTEXSUBIMAGEPROC, glClearTexSubImage)
GLFUNC(PFNGLINVALIDATETEXIMAGEPROC, glInvalidateTexImage)
// texture DSA
GLFUNC(PFNGLCREATETEXTURESPROC, glCreateTextures)
GLFUNC(PFNGLBINDTEXTUREUNITPROC, glBindTextureUnit)
GLFUNC(PFNGLGETTEXTURELEVELPARAMETERIVPROC, glGetTextureLevelParameteriv)
GLFUNC(PFNGLTEXTUREPARAMETERIPROC, glTextureParameteri)
GLFUNC(PFNGLGETTEXTURESUBIMAGEPROC, glGetTextureSubImage)
GLFUNC(PFNGLTEXTURESUBIMAGE1DPROC, glTextureSubImage1D)
GLFUNC(PFNGLTEXTURESUBIMAGE2DPROC, glTextureSubImage2D);
GLFUNC(PFNGLTEXTURESUBIMAGE3DPROC, glTextureSubImage3D)
GLFUNC(PFNGLTEXTURESTORAGE1DPROC, glTextureStorage1D)
GLFUNC(PFNGLTEXTURESTORAGE2DPROC, glTextureStorage2D)
GLFUNC(PFNGLTEXTURESTORAGE3DPROC, glTextureStorage3D)
// instancing / draw
GLFUNC(PFNGLDRAWELEMENTSBASEVERTEXPROC, glDrawElementsBaseVertex)
GLFUNC(PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXBASEINSTANCEPROC, glDrawElementsInstancedBaseVertexBaseInstance)
GLFUNC(PFNGLDRAWARRAYSINSTANCEDPROC, glDrawArraysInstanced)
// vertex array
GLFUNC(PFNGLGENVERTEXARRAYSPROC, glGenVertexArrays)
GLFUNC(PFNGLBINDVERTEXARRAYPROC, glBindVertexArray)
GLFUNC(PFNGLDELETEVERTEXARRAYSPROC, glDeleteVertexArrays)
GLFUNC(PFNGLBINDVERTEXBUFFERPROC, glBindVertexBuffer)
GLFUNC(PFNGLVERTEXATTRIBFORMATPROC, glVertexAttribFormat)
GLFUNC(PFNGLVERTEXATTRIBIFORMATPROC, glVertexAttribIFormat)
GLFUNC(PFNGLVERTEXATTRIBBINDINGPROC, glVertexAttribBinding)
GLFUNC(PFNGLVERTEXBINDINGDIVISORPROC, glVertexBindingDivisor)
GLFUNC(PFNGLVERTEXATTRIBDIVISORPROC, glVertexAttribDivisor)
// vertex array DSA
GLFUNC(PFNGLCREATEVERTEXARRAYSPROC, glCreateVertexArrays)
GLFUNC(PFNGLDISABLEVERTEXARRAYATTRIBPROC, glDisableVertexArrayAttrib)
GLFUNC(PFNGLENABLEVERTEXARRAYATTRIBPROC, glEnableVertexArrayAttrib)
GLFUNC(PFNGLVERTEXARRAYELEMENTBUFFERPROC, glVertexArrayElementBuffer)
GLFUNC(PFNGLVERTEXARRAYVERTEXBUFFERPROC, glVertexArrayVertexBuffer)
GLFUNC(PFNGLVERTEXARRAYATTRIBBINDINGPROC, glVertexArrayAttribBinding)
GLFUNC(PFNGLVERTEXARRAYATTRIBIFORMATPROC, glVertexArrayAttribIFormat)
GLFUNC(PFNGLVERTEXARRAYBINDINGDIVISORPROC, glVertexArrayBindingDivisor)
// sampler
GLFUNC(PFNGLGENSAMPLERSPROC, glGenSamplers)
GLFUNC(PFNGLBINDSAMPLERPROC, glBindSampler)
GLFUNC(PFNGLSAMPLERPARAMETERIPROC, glSamplerParameteri)
GLFUNC(PFNGLSAMPLERPARAMETERFPROC, glSamplerParameterf)
GLFUNC(PFNGLSAMPLERPARAMETERIVPROC, glSamplerParameteriv)
GLFUNC(PFNGLSAMPLERPARAMETERFVPROC, glSamplerParameterfv)
// buffer object
GLFUNC(PFNGLGETUNIFORMBLOCKINDEXPROC, glGetUniformBlockIndex)
GLFUNC(PFNGLUNIFORMBLOCKBINDINGPROC, glUniformBlockBinding)
GLFUNC(PFNGLBINDBUFFERBASEPROC, glBindBufferBase)
GLFUNC(PFNGLBINDBUFFERRANGEPROC, glBindBufferRange)
GLFUNC(PFNGLGETBUFFERSUBDATAPROC, glGetBufferSubData)
// uniform storage buffer object
GLFUNC(PFNGLGETPROGRAMRESOURCEINDEXPROC, glGetProgramResourceIndex)
GLFUNC(PFNGLSHADERSTORAGEBLOCKBINDINGPROC, glShaderStorageBlockBinding)
// stencil
GLFUNC(PFNGLSTENCILOPSEPARATEPROC, glStencilOpSeparate)
GLFUNC(PFNGLSTENCILFUNCSEPARATEPROC, glStencilFuncSeparate)
GLFUNC(PFNGLSTENCILMASKSEPARATEPROC, glStencilMaskSeparate)
// buffer
GLFUNC(PFNGLCREATEBUFFERSPROC, glCreateBuffers)
GLFUNC(PFNGLBUFFERSTORAGEPROC, glBufferStorage)
GLFUNC(PFNGLNAMEDBUFFERSTORAGEPROC, glNamedBufferStorage)
GLFUNC(PFNGLMAPNAMEDBUFFERPROC, glMapNamedBuffer)
GLFUNC(PFNGLMAPNAMEDBUFFERRANGEPROC, glMapNamedBufferRange)
GLFUNC(PFNGLMAPBUFFERRANGEPROC, glMapBufferRange)
GLFUNC(PFNGLFLUSHMAPPEDBUFFERRANGEPROC, glFlushMappedBufferRange)
GLFUNC(PFNGLMEMORYBARRIERPROC, glMemoryBarrier)
GLFUNC(PFNGLCOPYBUFFERSUBDATAPROC, glCopyBufferSubData)
GLFUNC(PFNGLCOPYNAMEDBUFFERSUBDATAPROC, glCopyNamedBufferSubData)
GLFUNC(PFNGLNAMEDBUFFERSUBDATAPROC, glNamedBufferSubData)
GLFUNC(PFNGLGETNAMEDBUFFERSUBDATAPROC, glGetNamedBufferSubData);
// transform feedback
GLFUNC(PFNGLBEGINTRANSFORMFEEDBACKPROC, glBeginTransformFeedback)
GLFUNC(PFNGLENDTRANSFORMFEEDBACKPROC, glEndTransformFeedback)
GLFUNC(PFNGLTRANSFORMFEEDBACKVARYINGSPROC, glTransformFeedbackVaryings)
// sync / fence
GLFUNC(PFNGLFENCESYNCPROC, glFenceSync)
GLFUNC(PFNGLCLIENTWAITSYNCPROC, glClientWaitSync)
GLFUNC(PFNGLDELETESYNCPROC, glDeleteSync)
// debugging
GLFUNC(PFNGLOBJECTLABELPROC, glObjectLabel)
GLFUNC(PFNGLDEBUGMESSAGECALLBACKPROC, glDebugMessageCallback)
GLFUNC(PFNGLDEBUGMESSAGECONTROLPROC, glDebugMessageControl)
// wgl
#if BOOST_OS_WINDOWS
GLFUNC(PFNWGLSWAPINTERVALEXTPROC, wglSwapIntervalEXT)
#endif
// x
#if BOOST_OS_LINUX
EGLFUNC(PFNEGLSWAPINTERVALPROC, eglSwapInterval)
EGLFUNC(PFNEGLGETCURRENTDISPLAYPROC, eglGetCurrentDisplay)
#endif
| 12,320
|
C++
|
.h
| 245
| 49.040816
| 107
| 0.918199
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,408
|
egl.h
|
cemu-project_Cemu/src/Common/GLInclude/egl.h
|
#ifndef __egl_h_
#define __egl_h_ 1
#ifdef __cplusplus
extern "C" {
#endif
/*
** Copyright 2013-2020 The Khronos Group Inc.
** SPDX-License-Identifier: Apache-2.0
**
** This header is generated from the Khronos EGL XML API Registry.
** The current version of the Registry, generator scripts
** used to make the header, and the header can be found at
** http://www.khronos.org/registry/egl
**
** Khronos $Git commit SHA1: 8c62b915dd $ on $Git commit date: 2021-11-05 23:32:01 -0400 $
*/
#include <EGL/eglplatform.h>
#ifndef EGL_EGL_PROTOTYPES
#define EGL_EGL_PROTOTYPES 1
#endif
/* Generated on date 20211116 */
/* Generated C header for:
* API: egl
* Versions considered: .*
* Versions emitted: .*
* Default extensions included: None
* Additional extensions included: _nomatch_^
* Extensions removed: _nomatch_^
*/
#ifndef EGL_VERSION_1_0
#define EGL_VERSION_1_0 1
typedef unsigned int EGLBoolean;
typedef void *EGLDisplay;
#include <KHR/khrplatform.h>
#include <EGL/eglplatform.h>
typedef void *EGLConfig;
typedef void *EGLSurface;
typedef void *EGLContext;
typedef void (*__eglMustCastToProperFunctionPointerType)(void);
#define EGL_ALPHA_SIZE 0x3021
#define EGL_BAD_ACCESS 0x3002
#define EGL_BAD_ALLOC 0x3003
#define EGL_BAD_ATTRIBUTE 0x3004
#define EGL_BAD_CONFIG 0x3005
#define EGL_BAD_CONTEXT 0x3006
#define EGL_BAD_CURRENT_SURFACE 0x3007
#define EGL_BAD_DISPLAY 0x3008
#define EGL_BAD_MATCH 0x3009
#define EGL_BAD_NATIVE_PIXMAP 0x300A
#define EGL_BAD_NATIVE_WINDOW 0x300B
#define EGL_BAD_PARAMETER 0x300C
#define EGL_BAD_SURFACE 0x300D
#define EGL_BLUE_SIZE 0x3022
#define EGL_BUFFER_SIZE 0x3020
#define EGL_CONFIG_CAVEAT 0x3027
#define EGL_CONFIG_ID 0x3028
#define EGL_CORE_NATIVE_ENGINE 0x305B
#define EGL_DEPTH_SIZE 0x3025
#define EGL_DONT_CARE EGL_CAST(EGLint,-1)
#define EGL_DRAW 0x3059
#define EGL_EXTENSIONS 0x3055
#define EGL_FALSE 0
#define EGL_GREEN_SIZE 0x3023
#define EGL_HEIGHT 0x3056
#define EGL_LARGEST_PBUFFER 0x3058
#define EGL_LEVEL 0x3029
#define EGL_MAX_PBUFFER_HEIGHT 0x302A
#define EGL_MAX_PBUFFER_PIXELS 0x302B
#define EGL_MAX_PBUFFER_WIDTH 0x302C
#define EGL_NATIVE_RENDERABLE 0x302D
#define EGL_NATIVE_VISUAL_ID 0x302E
#define EGL_NATIVE_VISUAL_TYPE 0x302F
#define EGL_NONE 0x3038
#define EGL_NON_CONFORMANT_CONFIG 0x3051
#define EGL_NOT_INITIALIZED 0x3001
#define EGL_NO_CONTEXT EGL_CAST(EGLContext,0)
#define EGL_NO_DISPLAY EGL_CAST(EGLDisplay,0)
#define EGL_NO_SURFACE EGL_CAST(EGLSurface,0)
#define EGL_PBUFFER_BIT 0x0001
#define EGL_PIXMAP_BIT 0x0002
#define EGL_READ 0x305A
#define EGL_RED_SIZE 0x3024
#define EGL_SAMPLES 0x3031
#define EGL_SAMPLE_BUFFERS 0x3032
#define EGL_SLOW_CONFIG 0x3050
#define EGL_STENCIL_SIZE 0x3026
#define EGL_SUCCESS 0x3000
#define EGL_SURFACE_TYPE 0x3033
#define EGL_TRANSPARENT_BLUE_VALUE 0x3035
#define EGL_TRANSPARENT_GREEN_VALUE 0x3036
#define EGL_TRANSPARENT_RED_VALUE 0x3037
#define EGL_TRANSPARENT_RGB 0x3052
#define EGL_TRANSPARENT_TYPE 0x3034
#define EGL_TRUE 1
#define EGL_VENDOR 0x3053
#define EGL_VERSION 0x3054
#define EGL_WIDTH 0x3057
#define EGL_WINDOW_BIT 0x0004
typedef EGLBoolean (EGLAPIENTRYP PFNEGLCHOOSECONFIGPROC) (EGLDisplay dpy, const EGLint *attrib_list, EGLConfig *configs, EGLint config_size, EGLint *num_config);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLCOPYBUFFERSPROC) (EGLDisplay dpy, EGLSurface surface, EGLNativePixmapType target);
typedef EGLContext (EGLAPIENTRYP PFNEGLCREATECONTEXTPROC) (EGLDisplay dpy, EGLConfig config, EGLContext share_context, const EGLint *attrib_list);
typedef EGLSurface (EGLAPIENTRYP PFNEGLCREATEPBUFFERSURFACEPROC) (EGLDisplay dpy, EGLConfig config, const EGLint *attrib_list);
typedef EGLSurface (EGLAPIENTRYP PFNEGLCREATEPIXMAPSURFACEPROC) (EGLDisplay dpy, EGLConfig config, EGLNativePixmapType pixmap, const EGLint *attrib_list);
typedef EGLSurface (EGLAPIENTRYP PFNEGLCREATEWINDOWSURFACEPROC) (EGLDisplay dpy, EGLConfig config, EGLNativeWindowType win, const EGLint *attrib_list);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLDESTROYCONTEXTPROC) (EGLDisplay dpy, EGLContext ctx);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLDESTROYSURFACEPROC) (EGLDisplay dpy, EGLSurface surface);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLGETCONFIGATTRIBPROC) (EGLDisplay dpy, EGLConfig config, EGLint attribute, EGLint *value);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLGETCONFIGSPROC) (EGLDisplay dpy, EGLConfig *configs, EGLint config_size, EGLint *num_config);
typedef EGLDisplay (EGLAPIENTRYP PFNEGLGETCURRENTDISPLAYPROC) (void);
typedef EGLSurface (EGLAPIENTRYP PFNEGLGETCURRENTSURFACEPROC) (EGLint readdraw);
typedef EGLDisplay (EGLAPIENTRYP PFNEGLGETDISPLAYPROC) (EGLNativeDisplayType display_id);
typedef EGLint (EGLAPIENTRYP PFNEGLGETERRORPROC) (void);
typedef __eglMustCastToProperFunctionPointerType (EGLAPIENTRYP PFNEGLGETPROCADDRESSPROC) (const char *procname);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLINITIALIZEPROC) (EGLDisplay dpy, EGLint *major, EGLint *minor);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLMAKECURRENTPROC) (EGLDisplay dpy, EGLSurface draw, EGLSurface read, EGLContext ctx);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYCONTEXTPROC) (EGLDisplay dpy, EGLContext ctx, EGLint attribute, EGLint *value);
typedef const char *(EGLAPIENTRYP PFNEGLQUERYSTRINGPROC) (EGLDisplay dpy, EGLint name);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYSURFACEPROC) (EGLDisplay dpy, EGLSurface surface, EGLint attribute, EGLint *value);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLSWAPBUFFERSPROC) (EGLDisplay dpy, EGLSurface surface);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLTERMINATEPROC) (EGLDisplay dpy);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLWAITGLPROC) (void);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLWAITNATIVEPROC) (EGLint engine);
#if EGL_EGL_PROTOTYPES
EGLAPI EGLBoolean EGLAPIENTRY eglChooseConfig (EGLDisplay dpy, const EGLint *attrib_list, EGLConfig *configs, EGLint config_size, EGLint *num_config);
EGLAPI EGLBoolean EGLAPIENTRY eglCopyBuffers (EGLDisplay dpy, EGLSurface surface, EGLNativePixmapType target);
EGLAPI EGLContext EGLAPIENTRY eglCreateContext (EGLDisplay dpy, EGLConfig config, EGLContext share_context, const EGLint *attrib_list);
EGLAPI EGLSurface EGLAPIENTRY eglCreatePbufferSurface (EGLDisplay dpy, EGLConfig config, const EGLint *attrib_list);
EGLAPI EGLSurface EGLAPIENTRY eglCreatePixmapSurface (EGLDisplay dpy, EGLConfig config, EGLNativePixmapType pixmap, const EGLint *attrib_list);
EGLAPI EGLSurface EGLAPIENTRY eglCreateWindowSurface (EGLDisplay dpy, EGLConfig config, EGLNativeWindowType win, const EGLint *attrib_list);
EGLAPI EGLBoolean EGLAPIENTRY eglDestroyContext (EGLDisplay dpy, EGLContext ctx);
EGLAPI EGLBoolean EGLAPIENTRY eglDestroySurface (EGLDisplay dpy, EGLSurface surface);
EGLAPI EGLBoolean EGLAPIENTRY eglGetConfigAttrib (EGLDisplay dpy, EGLConfig config, EGLint attribute, EGLint *value);
EGLAPI EGLBoolean EGLAPIENTRY eglGetConfigs (EGLDisplay dpy, EGLConfig *configs, EGLint config_size, EGLint *num_config);
EGLAPI EGLDisplay EGLAPIENTRY eglGetCurrentDisplay (void);
EGLAPI EGLSurface EGLAPIENTRY eglGetCurrentSurface (EGLint readdraw);
EGLAPI EGLDisplay EGLAPIENTRY eglGetDisplay (EGLNativeDisplayType display_id);
EGLAPI EGLint EGLAPIENTRY eglGetError (void);
EGLAPI __eglMustCastToProperFunctionPointerType EGLAPIENTRY eglGetProcAddress (const char *procname);
EGLAPI EGLBoolean EGLAPIENTRY eglInitialize (EGLDisplay dpy, EGLint *major, EGLint *minor);
EGLAPI EGLBoolean EGLAPIENTRY eglMakeCurrent (EGLDisplay dpy, EGLSurface draw, EGLSurface read, EGLContext ctx);
EGLAPI EGLBoolean EGLAPIENTRY eglQueryContext (EGLDisplay dpy, EGLContext ctx, EGLint attribute, EGLint *value);
EGLAPI const char *EGLAPIENTRY eglQueryString (EGLDisplay dpy, EGLint name);
EGLAPI EGLBoolean EGLAPIENTRY eglQuerySurface (EGLDisplay dpy, EGLSurface surface, EGLint attribute, EGLint *value);
EGLAPI EGLBoolean EGLAPIENTRY eglSwapBuffers (EGLDisplay dpy, EGLSurface surface);
EGLAPI EGLBoolean EGLAPIENTRY eglTerminate (EGLDisplay dpy);
EGLAPI EGLBoolean EGLAPIENTRY eglWaitGL (void);
EGLAPI EGLBoolean EGLAPIENTRY eglWaitNative (EGLint engine);
#endif
#endif /* EGL_VERSION_1_0 */
#ifndef EGL_VERSION_1_1
#define EGL_VERSION_1_1 1
#define EGL_BACK_BUFFER 0x3084
#define EGL_BIND_TO_TEXTURE_RGB 0x3039
#define EGL_BIND_TO_TEXTURE_RGBA 0x303A
#define EGL_CONTEXT_LOST 0x300E
#define EGL_MIN_SWAP_INTERVAL 0x303B
#define EGL_MAX_SWAP_INTERVAL 0x303C
#define EGL_MIPMAP_TEXTURE 0x3082
#define EGL_MIPMAP_LEVEL 0x3083
#define EGL_NO_TEXTURE 0x305C
#define EGL_TEXTURE_2D 0x305F
#define EGL_TEXTURE_FORMAT 0x3080
#define EGL_TEXTURE_RGB 0x305D
#define EGL_TEXTURE_RGBA 0x305E
#define EGL_TEXTURE_TARGET 0x3081
typedef EGLBoolean (EGLAPIENTRYP PFNEGLBINDTEXIMAGEPROC) (EGLDisplay dpy, EGLSurface surface, EGLint buffer);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLRELEASETEXIMAGEPROC) (EGLDisplay dpy, EGLSurface surface, EGLint buffer);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLSURFACEATTRIBPROC) (EGLDisplay dpy, EGLSurface surface, EGLint attribute, EGLint value);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLSWAPINTERVALPROC) (EGLDisplay dpy, EGLint interval);
#if EGL_EGL_PROTOTYPES
EGLAPI EGLBoolean EGLAPIENTRY eglBindTexImage (EGLDisplay dpy, EGLSurface surface, EGLint buffer);
EGLAPI EGLBoolean EGLAPIENTRY eglReleaseTexImage (EGLDisplay dpy, EGLSurface surface, EGLint buffer);
EGLAPI EGLBoolean EGLAPIENTRY eglSurfaceAttrib (EGLDisplay dpy, EGLSurface surface, EGLint attribute, EGLint value);
EGLAPI EGLBoolean EGLAPIENTRY eglSwapInterval (EGLDisplay dpy, EGLint interval);
#endif
#endif /* EGL_VERSION_1_1 */
#ifndef EGL_VERSION_1_2
#define EGL_VERSION_1_2 1
typedef unsigned int EGLenum;
typedef void *EGLClientBuffer;
#define EGL_ALPHA_FORMAT 0x3088
#define EGL_ALPHA_FORMAT_NONPRE 0x308B
#define EGL_ALPHA_FORMAT_PRE 0x308C
#define EGL_ALPHA_MASK_SIZE 0x303E
#define EGL_BUFFER_PRESERVED 0x3094
#define EGL_BUFFER_DESTROYED 0x3095
#define EGL_CLIENT_APIS 0x308D
#define EGL_COLORSPACE 0x3087
#define EGL_COLORSPACE_sRGB 0x3089
#define EGL_COLORSPACE_LINEAR 0x308A
#define EGL_COLOR_BUFFER_TYPE 0x303F
#define EGL_CONTEXT_CLIENT_TYPE 0x3097
#define EGL_DISPLAY_SCALING 10000
#define EGL_HORIZONTAL_RESOLUTION 0x3090
#define EGL_LUMINANCE_BUFFER 0x308F
#define EGL_LUMINANCE_SIZE 0x303D
#define EGL_OPENGL_ES_BIT 0x0001
#define EGL_OPENVG_BIT 0x0002
#define EGL_OPENGL_ES_API 0x30A0
#define EGL_OPENVG_API 0x30A1
#define EGL_OPENVG_IMAGE 0x3096
#define EGL_PIXEL_ASPECT_RATIO 0x3092
#define EGL_RENDERABLE_TYPE 0x3040
#define EGL_RENDER_BUFFER 0x3086
#define EGL_RGB_BUFFER 0x308E
#define EGL_SINGLE_BUFFER 0x3085
#define EGL_SWAP_BEHAVIOR 0x3093
#define EGL_UNKNOWN EGL_CAST(EGLint,-1)
#define EGL_VERTICAL_RESOLUTION 0x3091
typedef EGLBoolean (EGLAPIENTRYP PFNEGLBINDAPIPROC) (EGLenum api);
typedef EGLenum (EGLAPIENTRYP PFNEGLQUERYAPIPROC) (void);
typedef EGLSurface (EGLAPIENTRYP PFNEGLCREATEPBUFFERFROMCLIENTBUFFERPROC) (EGLDisplay dpy, EGLenum buftype, EGLClientBuffer buffer, EGLConfig config, const EGLint *attrib_list);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLRELEASETHREADPROC) (void);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLWAITCLIENTPROC) (void);
#if EGL_EGL_PROTOTYPES
EGLAPI EGLBoolean EGLAPIENTRY eglBindAPI (EGLenum api);
EGLAPI EGLenum EGLAPIENTRY eglQueryAPI (void);
EGLAPI EGLSurface EGLAPIENTRY eglCreatePbufferFromClientBuffer (EGLDisplay dpy, EGLenum buftype, EGLClientBuffer buffer, EGLConfig config, const EGLint *attrib_list);
EGLAPI EGLBoolean EGLAPIENTRY eglReleaseThread (void);
EGLAPI EGLBoolean EGLAPIENTRY eglWaitClient (void);
#endif
#endif /* EGL_VERSION_1_2 */
#ifndef EGL_VERSION_1_3
#define EGL_VERSION_1_3 1
#define EGL_CONFORMANT 0x3042
#define EGL_CONTEXT_CLIENT_VERSION 0x3098
#define EGL_MATCH_NATIVE_PIXMAP 0x3041
#define EGL_OPENGL_ES2_BIT 0x0004
#define EGL_VG_ALPHA_FORMAT 0x3088
#define EGL_VG_ALPHA_FORMAT_NONPRE 0x308B
#define EGL_VG_ALPHA_FORMAT_PRE 0x308C
#define EGL_VG_ALPHA_FORMAT_PRE_BIT 0x0040
#define EGL_VG_COLORSPACE 0x3087
#define EGL_VG_COLORSPACE_sRGB 0x3089
#define EGL_VG_COLORSPACE_LINEAR 0x308A
#define EGL_VG_COLORSPACE_LINEAR_BIT 0x0020
#endif /* EGL_VERSION_1_3 */
#ifndef EGL_VERSION_1_4
#define EGL_VERSION_1_4 1
#define EGL_DEFAULT_DISPLAY EGL_CAST(EGLNativeDisplayType,0)
#define EGL_MULTISAMPLE_RESOLVE_BOX_BIT 0x0200
#define EGL_MULTISAMPLE_RESOLVE 0x3099
#define EGL_MULTISAMPLE_RESOLVE_DEFAULT 0x309A
#define EGL_MULTISAMPLE_RESOLVE_BOX 0x309B
#define EGL_OPENGL_API 0x30A2
#define EGL_OPENGL_BIT 0x0008
#define EGL_SWAP_BEHAVIOR_PRESERVED_BIT 0x0400
typedef EGLContext (EGLAPIENTRYP PFNEGLGETCURRENTCONTEXTPROC) (void);
#if EGL_EGL_PROTOTYPES
EGLAPI EGLContext EGLAPIENTRY eglGetCurrentContext (void);
#endif
#endif /* EGL_VERSION_1_4 */
#ifndef EGL_VERSION_1_5
#define EGL_VERSION_1_5 1
typedef void *EGLSync;
typedef intptr_t EGLAttrib;
typedef khronos_utime_nanoseconds_t EGLTime;
typedef void *EGLImage;
#define EGL_CONTEXT_MAJOR_VERSION 0x3098
#define EGL_CONTEXT_MINOR_VERSION 0x30FB
#define EGL_CONTEXT_OPENGL_PROFILE_MASK 0x30FD
#define EGL_CONTEXT_OPENGL_RESET_NOTIFICATION_STRATEGY 0x31BD
#define EGL_NO_RESET_NOTIFICATION 0x31BE
#define EGL_LOSE_CONTEXT_ON_RESET 0x31BF
#define EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT 0x00000001
#define EGL_CONTEXT_OPENGL_COMPATIBILITY_PROFILE_BIT 0x00000002
#define EGL_CONTEXT_OPENGL_DEBUG 0x31B0
#define EGL_CONTEXT_OPENGL_FORWARD_COMPATIBLE 0x31B1
#define EGL_CONTEXT_OPENGL_ROBUST_ACCESS 0x31B2
#define EGL_OPENGL_ES3_BIT 0x00000040
#define EGL_CL_EVENT_HANDLE 0x309C
#define EGL_SYNC_CL_EVENT 0x30FE
#define EGL_SYNC_CL_EVENT_COMPLETE 0x30FF
#define EGL_SYNC_PRIOR_COMMANDS_COMPLETE 0x30F0
#define EGL_SYNC_TYPE 0x30F7
#define EGL_SYNC_STATUS 0x30F1
#define EGL_SYNC_CONDITION 0x30F8
#define EGL_SIGNALED 0x30F2
#define EGL_UNSIGNALED 0x30F3
#define EGL_SYNC_FLUSH_COMMANDS_BIT 0x0001
#define EGL_FOREVER 0xFFFFFFFFFFFFFFFFull
#define EGL_TIMEOUT_EXPIRED 0x30F5
#define EGL_CONDITION_SATISFIED 0x30F6
#define EGL_NO_SYNC EGL_CAST(EGLSync,0)
#define EGL_SYNC_FENCE 0x30F9
#define EGL_GL_COLORSPACE 0x309D
#define EGL_GL_COLORSPACE_SRGB 0x3089
#define EGL_GL_COLORSPACE_LINEAR 0x308A
#define EGL_GL_RENDERBUFFER 0x30B9
#define EGL_GL_TEXTURE_2D 0x30B1
#define EGL_GL_TEXTURE_LEVEL 0x30BC
#define EGL_GL_TEXTURE_3D 0x30B2
#define EGL_GL_TEXTURE_ZOFFSET 0x30BD
#define EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_X 0x30B3
#define EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_X 0x30B4
#define EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_Y 0x30B5
#define EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Y 0x30B6
#define EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_Z 0x30B7
#define EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Z 0x30B8
#define EGL_IMAGE_PRESERVED 0x30D2
#define EGL_NO_IMAGE EGL_CAST(EGLImage,0)
typedef EGLSync (EGLAPIENTRYP PFNEGLCREATESYNCPROC) (EGLDisplay dpy, EGLenum type, const EGLAttrib *attrib_list);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLDESTROYSYNCPROC) (EGLDisplay dpy, EGLSync sync);
typedef EGLint (EGLAPIENTRYP PFNEGLCLIENTWAITSYNCPROC) (EGLDisplay dpy, EGLSync sync, EGLint flags, EGLTime timeout);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLGETSYNCATTRIBPROC) (EGLDisplay dpy, EGLSync sync, EGLint attribute, EGLAttrib *value);
typedef EGLImage (EGLAPIENTRYP PFNEGLCREATEIMAGEPROC) (EGLDisplay dpy, EGLContext ctx, EGLenum target, EGLClientBuffer buffer, const EGLAttrib *attrib_list);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLDESTROYIMAGEPROC) (EGLDisplay dpy, EGLImage image);
typedef EGLDisplay (EGLAPIENTRYP PFNEGLGETPLATFORMDISPLAYPROC) (EGLenum platform, void *native_display, const EGLAttrib *attrib_list);
typedef EGLSurface (EGLAPIENTRYP PFNEGLCREATEPLATFORMWINDOWSURFACEPROC) (EGLDisplay dpy, EGLConfig config, void *native_window, const EGLAttrib *attrib_list);
typedef EGLSurface (EGLAPIENTRYP PFNEGLCREATEPLATFORMPIXMAPSURFACEPROC) (EGLDisplay dpy, EGLConfig config, void *native_pixmap, const EGLAttrib *attrib_list);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLWAITSYNCPROC) (EGLDisplay dpy, EGLSync sync, EGLint flags);
#if EGL_EGL_PROTOTYPES
EGLAPI EGLSync EGLAPIENTRY eglCreateSync (EGLDisplay dpy, EGLenum type, const EGLAttrib *attrib_list);
EGLAPI EGLBoolean EGLAPIENTRY eglDestroySync (EGLDisplay dpy, EGLSync sync);
EGLAPI EGLint EGLAPIENTRY eglClientWaitSync (EGLDisplay dpy, EGLSync sync, EGLint flags, EGLTime timeout);
EGLAPI EGLBoolean EGLAPIENTRY eglGetSyncAttrib (EGLDisplay dpy, EGLSync sync, EGLint attribute, EGLAttrib *value);
EGLAPI EGLImage EGLAPIENTRY eglCreateImage (EGLDisplay dpy, EGLContext ctx, EGLenum target, EGLClientBuffer buffer, const EGLAttrib *attrib_list);
EGLAPI EGLBoolean EGLAPIENTRY eglDestroyImage (EGLDisplay dpy, EGLImage image);
EGLAPI EGLDisplay EGLAPIENTRY eglGetPlatformDisplay (EGLenum platform, void *native_display, const EGLAttrib *attrib_list);
EGLAPI EGLSurface EGLAPIENTRY eglCreatePlatformWindowSurface (EGLDisplay dpy, EGLConfig config, void *native_window, const EGLAttrib *attrib_list);
EGLAPI EGLSurface EGLAPIENTRY eglCreatePlatformPixmapSurface (EGLDisplay dpy, EGLConfig config, void *native_pixmap, const EGLAttrib *attrib_list);
EGLAPI EGLBoolean EGLAPIENTRY eglWaitSync (EGLDisplay dpy, EGLSync sync, EGLint flags);
#endif
#endif /* EGL_VERSION_1_5 */
#ifdef __cplusplus
}
#endif
#endif
| 19,286
|
C++
|
.h
| 328
| 57.734756
| 177
| 0.735061
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| true
| true
| false
| false
| false
| false
| false
| false
|
23,409
|
FileStream_unix.h
|
cemu-project_Cemu/src/Common/unix/FileStream_unix.h
|
#pragma once
#include "Common/precompiled.h"
class FileStream
{
public:
static FileStream* openFile(std::string_view path);
static FileStream* openFile(const wchar_t* path, bool allowWrite = false);
static FileStream* openFile2(const fs::path& path, bool allowWrite = false);
static FileStream* createFile(const wchar_t* path);
static FileStream* createFile(std::string_view path);
static FileStream* createFile2(const fs::path& path);
// helper function to load a file into memory
static std::optional<std::vector<uint8>> LoadIntoMemory(const fs::path& path);
// size and seek
void SetPosition(uint64 pos);
uint64 GetSize();
bool SetEndOfFile();
void extract(std::vector<uint8>& data);
// reading
uint32 readData(void* data, uint32 length);
bool readU64(uint64& v);
bool readU32(uint32& v);
bool readU16(uint16& v);
bool readU8(uint8& v);
bool readLine(std::string& line);
// writing (binary)
sint32 writeData(const void* data, sint32 length);
void writeU64(uint64 v);
void writeU32(uint32 v);
void writeU16(uint16 v);
void writeU8(uint8 v);
// writing (strings)
void writeStringFmt(const char* format, ...);
void writeString(const char* str);
void writeLine(const char* str);
~FileStream();
FileStream() {};
private:
void SyncReadWriteSeek(bool nextOpIsWrite);
FileStream(const fs::path& path, bool isOpen, bool isWriteable);
bool m_isValid{};
std::fstream m_fileStream;
bool m_prevOperationWasWrite{false};
};
| 1,464
|
C++
|
.h
| 44
| 31.113636
| 79
| 0.759233
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,411
|
platform.h
|
cemu-project_Cemu/src/Common/unix/platform.h
|
#include <shared_mutex>
class SlimRWLock
{
public:
void LockRead()
{
m_sm.lock_shared();
}
void UnlockRead()
{
m_sm.unlock_shared();
}
void LockWrite()
{
m_sm.lock();
}
void UnlockWrite()
{
m_sm.unlock();
}
private:
std::shared_mutex m_sm;
};
inline uint32_t GetExceptionError()
{
return errno;
}
#undef False
#undef True
#undef None
#undef Bool
#undef Status
#undef Success
#undef ClientMessage
// placeholder
uint32_t GetTickCount();
// strcpy_s and strcat_s implementations
template<size_t N>
void strcpy_s(char (&dst)[N], const char* src)
{
if(N == 0)
return;
char* dstP = dst;
const char* end = src + N - 1;
while(src < end)
{
char c = *src;
*dstP = c;
if(c == '\0')
return;
dstP++;
src++;
c++;
}
*dstP = '\0';
return;
}
template<size_t N>
void strcat_s(char (&dst)[N], const char* src)
{
if(N == 0)
return;
char* dstP = dst;
const char* end = dstP + N - 1;
while(dstP < end && *dstP != '\0')
dstP++;
while(dstP < end)
{
char c = *src;
*dstP = c;
if(c == '\0')
return;
dstP++;
src++;
c++;
}
*dstP = '\0';
return;
}
| 1,115
|
C++
|
.h
| 79
| 11.911392
| 48
| 0.620858
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,413
|
FileStream_win32.h
|
cemu-project_Cemu/src/Common/windows/FileStream_win32.h
|
#pragma once
#include "Common/precompiled.h"
class FileStream
{
public:
static FileStream* openFile(std::string_view path);
static FileStream* openFile(const wchar_t* path, bool allowWrite = false);
static FileStream* openFile2(const fs::path& path, bool allowWrite = false);
static FileStream* createFile(const wchar_t* path);
static FileStream* createFile(std::string_view path);
static FileStream* createFile2(const fs::path& path);
// helper function to load a file into memory
static std::optional<std::vector<uint8>> LoadIntoMemory(const fs::path& path);
// size and seek
void SetPosition(uint64 pos);
uint64 GetSize();
bool SetEndOfFile();
void extract(std::vector<uint8>& data);
// reading
uint32 readData(void* data, uint32 length);
bool readU64(uint64& v);
bool readU32(uint32& v);
bool readU16(uint16& v);
bool readU8(uint8& v);
bool readLine(std::string& line);
// writing (binary)
sint32 writeData(const void* data, sint32 length);
void writeU64(uint64 v);
void writeU32(uint32 v);
void writeU16(uint16 v);
void writeU8(uint8 v);
// writing (strings)
void writeStringFmt(const char* format, ...);
void writeString(const char* str);
void writeLine(const char* str);
~FileStream();
FileStream() = default;
private:
FileStream(HANDLE hFile);
bool m_isValid{};
HANDLE m_hFile;
};
| 1,337
|
C++
|
.h
| 42
| 29.690476
| 79
| 0.754673
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,414
|
platform.h
|
cemu-project_Cemu/src/Common/windows/platform.h
|
#pragma once
#ifndef NOMINMAX
#define NOMINMAX
#endif
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <Windows.h>
#define AF_BLUETOOTH AF_BTH
#define BTPROTO_RFCOMM BT_PORT_ANY
class SlimRWLock
{
public:
SlimRWLock();
void LockRead();
void UnlockRead();
void LockWrite();
void UnlockWrite();
private:
/*SRWLOCK*/ void* m_lock;
};
uint32_t GetExceptionError();
| 395
|
C++
|
.h
| 22
| 16.454545
| 34
| 0.785326
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,415
|
ppcAssembler.h
|
cemu-project_Cemu/src/Cemu/PPCAssembler/ppcAssembler.h
|
#pragma once
#include <boost/container/small_vector.hpp>
#define PPCASM_OPERAND_COUNT 5
#define PPCASM_OPERAND_TYPE_GPR 0 // r0 - r31
#define PPCASM_OPERAND_TYPE_FPR 1 // f0 - f31
#define PPCASM_OPERAND_TYPE_SPR 2 // spr0 - spr511
#define PPCASM_OPERAND_TYPE_IMM 3 // integer constants. E.g. 0x123
#define PPCASM_OPERAND_TYPE_MEM 4 // [r0 + 1234]
#define PPCASM_OPERAND_TYPE_CIMM 5 // virtual addr of code destination (used for branches)
#define PPCASM_OPERAND_TYPE_CR 6 // cr0-cr7
#define PPCASM_OPERAND_TYPE_CR_BIT 7 // cr bit 0-31. Example display form: '4*cr1+eq'
#define PPCASM_OPERAND_TYPE_PSQMODE 8 // single or paired mode control for PSQ_L*/PSQ_ST* instructions
enum PPCASM_OP
{
PPCASM_OP_UKN,
PPCASM_OP_ADDI,
PPCASM_OP_SUBI, // special form of ADDI
PPCASM_OP_ADDIS,
PPCASM_OP_ADDIC,
PPCASM_OP_ADDIC_,
PPCASM_OP_ADD,
PPCASM_OP_ADD_,
PPCASM_OP_SUBF,
PPCASM_OP_SUBF_,
PPCASM_OP_SUBFC,
PPCASM_OP_SUBFC_,
PPCASM_OP_SUBFE,
PPCASM_OP_SUBFE_,
PPCASM_OP_SUBFIC,
PPCASM_OP_SUB, // alias mnemonic for subf with second and third operand swapped
PPCASM_OP_SUB_,
PPCASM_OP_MULLI,
PPCASM_OP_MULLW,
PPCASM_OP_MULLW_,
PPCASM_OP_MULHW,
PPCASM_OP_MULHW_,
PPCASM_OP_MULHWU,
PPCASM_OP_MULHWU_,
PPCASM_OP_DIVW,
PPCASM_OP_DIVW_,
PPCASM_OP_DIVWU,
PPCASM_OP_DIVWU_,
PPCASM_OP_AND,
PPCASM_OP_AND_,
PPCASM_OP_ANDC,
PPCASM_OP_ANDC_,
PPCASM_OP_OR,
PPCASM_OP_OR_,
PPCASM_OP_ORC,
PPCASM_OP_XOR,
PPCASM_OP_NOR,
PPCASM_OP_NOR_,
PPCASM_OP_NOT, // alias to NOR
PPCASM_OP_NOT_,
PPCASM_OP_NEG,
PPCASM_OP_NEG_,
PPCASM_OP_ANDI_,
PPCASM_OP_ANDIS_,
PPCASM_OP_ORI,
PPCASM_OP_ORIS,
PPCASM_OP_XORI,
PPCASM_OP_XORIS,
PPCASM_OP_CNTLZW,
PPCASM_OP_EXTSB,
PPCASM_OP_EXTSH,
PPCASM_OP_CNTLZW_,
PPCASM_OP_EXTSB_,
PPCASM_OP_EXTSH_,
PPCASM_OP_SRAW,
PPCASM_OP_SRAW_,
PPCASM_OP_SRAWI,
PPCASM_OP_SRAWI_,
PPCASM_OP_SLW,
PPCASM_OP_SLW_,
PPCASM_OP_SRW,
PPCASM_OP_SRW_,
PPCASM_OP_RLWINM,
PPCASM_OP_RLWINM_,
PPCASM_OP_RLWIMI,
PPCASM_OP_RLWIMI_,
// rlwinm extended mnemonics
PPCASM_OP_EXTLWI,
PPCASM_OP_EXTLWI_,
PPCASM_OP_EXTRWI,
PPCASM_OP_EXTRWI_,
PPCASM_OP_ROTLWI,
PPCASM_OP_ROTLWI_,
PPCASM_OP_ROTRWI,
PPCASM_OP_ROTRWI_,
PPCASM_OP_SLWI,
PPCASM_OP_SLWI_,
PPCASM_OP_SRWI,
PPCASM_OP_SRWI_,
PPCASM_OP_CLRLWI,
PPCASM_OP_CLRLWI_,
PPCASM_OP_CLRRWI,
PPCASM_OP_CLRRWI_,
// rlwimi extended mnemonics
//PPCASM_OP_INSLWI, rlwimi
//PPCASM_OP_INSLWI_, rlwimi
//PPCASM_OP_INSRWI, rlwimi
//PPCASM_OP_INSRWI_, rlwimi
// rlwnm extended mnemonics
PPCASM_OP_RLWNM,
PPCASM_OP_RLWNM_,
PPCASM_OP_ROTLW,
PPCASM_OP_ROTLW_,
PPCASM_OP_CMPWI,
PPCASM_OP_CMPLWI,
PPCASM_OP_CMPW,
PPCASM_OP_CMPLW,
PPCASM_OP_MR,
PPCASM_OP_MR_,
PPCASM_OP_MFSPR,
PPCASM_OP_MTSPR,
PPCASM_OP_LMW,
PPCASM_OP_LWZ,
PPCASM_OP_LWZU,
PPCASM_OP_LWZX,
PPCASM_OP_LWZUX,
PPCASM_OP_LHZ,
PPCASM_OP_LHZU,
PPCASM_OP_LHZX,
PPCASM_OP_LHZUX,
PPCASM_OP_LHA,
PPCASM_OP_LHAU,
PPCASM_OP_LHAX,
PPCASM_OP_LHAUX,
PPCASM_OP_LBZ,
PPCASM_OP_LBZU,
PPCASM_OP_LBZX,
PPCASM_OP_LBZUX,
PPCASM_OP_STMW,
PPCASM_OP_STW,
PPCASM_OP_STWU,
PPCASM_OP_STWX,
PPCASM_OP_STWUX,
PPCASM_OP_STH,
PPCASM_OP_STHU,
PPCASM_OP_STHX,
PPCASM_OP_STHUX,
PPCASM_OP_STB,
PPCASM_OP_STBU,
PPCASM_OP_STBX,
PPCASM_OP_STBUX,
PPCASM_OP_STWBRX,
PPCASM_OP_STHBRX,
PPCASM_OP_STSWI,
PPCASM_OP_LWARX,
PPCASM_OP_STWCX_,
PPCASM_OP_B,
PPCASM_OP_BA,
PPCASM_OP_BL,
PPCASM_OP_BLA,
PPCASM_OP_BC,
PPCASM_OP_BNE,
PPCASM_OP_BEQ,
PPCASM_OP_BGE,
PPCASM_OP_BGT,
PPCASM_OP_BLT,
PPCASM_OP_BLE,
PPCASM_OP_BDZ,
PPCASM_OP_BDNZ,
PPCASM_OP_BLR,
PPCASM_OP_BLTLR, // less
PPCASM_OP_BLELR, // less or equal
PPCASM_OP_BEQLR, // equal
PPCASM_OP_BGELR, // greater or equal
PPCASM_OP_BGTLR, // greater
PPCASM_OP_BNELR, // not equal
PPCASM_OP_BCTR,
PPCASM_OP_BCTRL,
// CR
PPCASM_OP_CROR,
PPCASM_OP_CRORC,
PPCASM_OP_CRXOR,
PPCASM_OP_CREQV,
PPCASM_OP_CRNOR,
PPCASM_OP_CRAND,
PPCASM_OP_CRNAND,
PPCASM_OP_CRANDC,
PPCASM_OP_CRSET, // simplified mnemonic for CREQV
PPCASM_OP_CRCLR, // simplified mnemonic for CRXOR
PPCASM_OP_CRMOVE, // simplified mnemonic for CROR
PPCASM_OP_CRNOT, // simplified mnemonic for CRNOR
// floating point load/store
PPCASM_OP_LFS,
PPCASM_OP_LFSU,
PPCASM_OP_LFSX,
PPCASM_OP_LFSUX,
PPCASM_OP_LFD,
PPCASM_OP_LFDU,
PPCASM_OP_LFDX,
PPCASM_OP_LFDUX,
PPCASM_OP_STFS,
PPCASM_OP_STFSU,
PPCASM_OP_STFSX,
PPCASM_OP_STFSUX,
PPCASM_OP_STFD,
PPCASM_OP_STFDU,
PPCASM_OP_STFDX,
PPCASM_OP_STFDUX,
PPCASM_OP_STFIWX,
// FP
PPCASM_OP_FMR,
PPCASM_OP_FNEG,
PPCASM_OP_FRSP,
PPCASM_OP_FRSQRTE,
PPCASM_OP_FADD,
PPCASM_OP_FADDS,
PPCASM_OP_FSUB,
PPCASM_OP_FSUBS,
PPCASM_OP_FMUL,
PPCASM_OP_FMULS,
PPCASM_OP_FDIV,
PPCASM_OP_FDIVS,
PPCASM_OP_FMADD,
PPCASM_OP_FMADDS,
PPCASM_OP_FNMADD,
PPCASM_OP_FNMADDS,
PPCASM_OP_FMSUB,
PPCASM_OP_FMSUBS,
PPCASM_OP_FNMSUB,
PPCASM_OP_FNMSUBS,
PPCASM_OP_FCTIWZ,
PPCASM_OP_FCMPU,
PPCASM_OP_FCMPO,
// PS
PPCASM_OP_PS_MERGE00,
PPCASM_OP_PS_MERGE01,
PPCASM_OP_PS_MERGE10,
PPCASM_OP_PS_MERGE11,
PPCASM_OP_PS_ADD,
PPCASM_OP_PS_SUB,
PPCASM_OP_PS_DIV,
PPCASM_OP_PS_MUL,
PPCASM_OP_PS_MADD,
PPCASM_OP_PS_MSUB,
PPCASM_OP_PS_NMADD,
PPCASM_OP_PS_NMSUB,
// cache & misc
PPCASM_OP_ISYNC,
// extended mnemonics
PPCASM_OP_NOP, // ORI
PPCASM_OP_LI, // ADDI
PPCASM_OP_LIS, // ADDIS
PPCASM_OP_MFLR, // MFSPR
PPCASM_OP_MTLR, // MTSPR
PPCASM_OP_MFCTR, // MFSPR
PPCASM_OP_MTCTR, // MTSPR
};
struct PPCDisassemblerOperand
{
uint8 type;
uint16 registerIndex;
union
{
sint32 immS32;
uint32 immU32;
};
bool isSignedImm;
uint8 immWidth; // in bits. E.g. 16 for ADDI
};
struct PPCDisassembledInstruction
{
// output
uint32 ppcAsmCode;
uint8 operandMask;
PPCDisassemblerOperand operand[PPCASM_OPERAND_COUNT];
// conditional branches
bool branchHintBitSet{false};
};
const char* ppcAssembler_getInstructionName(uint32 ppcAsmOp);
void ppcAssembler_disassemble(uint32 virtualAddress, uint32 opcode, PPCDisassembledInstruction* disInstr);
enum class PPCASM_RELOC
{
// code
U32_MASKED_IMM,
BRANCH_S16,
BRANCH_S26,
// data constants
FLOAT, // 4 byte float data
DOUBLE, // 8 byte double precision float data
U32, // 4 byte unsigned integer
U16, // 2 byte unsigned integer
U8, // 1 byte unsigned integer
};
struct PPCAssemblerReloc
{
PPCAssemblerReloc(PPCASM_RELOC relocType, std::string expression, uint32 byteOffset, uint8 bitOffset, uint8 bitCount) : m_relocType(relocType), m_expression(expression), m_byteOffset(byteOffset), m_bitOffset(bitOffset), m_bitCount(bitCount) {};
PPCASM_RELOC m_relocType;
std::string m_expression;
uint32 m_byteOffset;
uint8 m_bitOffset;
uint8 m_bitCount;
bool m_isApplied{};
bool isApplied() { return m_isApplied; };
void setApplied() { m_isApplied = true; };
};
struct PPCAssemblerInOut
{
// in
uint32 virtualAddress;
bool forceNoAlignment{}; // if set, alignment will always be set to 1 (even for .align directive!)
// out
boost::container::small_vector<uint8, 16> outputData;
std::vector<PPCAssemblerReloc> list_relocs;
std::string errorMsg;
uint32 alignmentRequirement{}; // alignment requirement, 0 if none
uint32 alignmentPaddingSize{}; // number of bytes to fill with alignment padding before instruction
uint32 virtualAddressAligned{}; // effective virtualAddress
};
bool ppcAssembler_assembleSingleInstruction(char const* text, PPCAssemblerInOut* ctx);
static uint32 ppcAssembler_generateMaskRLW(int MB, int ME)
{
uint32 maskMB = 0xFFFFFFFF >> MB;
uint32 maskME = 0xFFFFFFFF << (31 - ME);
uint32 mask = (MB <= ME) ? maskMB & maskME : maskMB | maskME;
return mask;
}
| 7,534
|
C++
|
.h
| 320
| 21.5
| 245
| 0.753453
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,416
|
FileCache.h
|
cemu-project_Cemu/src/Cemu/FileCache/FileCache.h
|
#pragma once
#include <mutex>
class FileCache
{
public:
struct FileName
{
FileName(uint64 name1, uint64 name2) : name1(name1), name2(name2) {};
FileName(std::string_view filePath)
{
// name from string hash
uint64 h1 = 0xa2cc2c49386a75fdull;
uint64 h2 = 0x5182d367734c2ce8ull;
const char* c = filePath.data();
const char* cEnd = filePath.data() + filePath.size();
while (c < cEnd)
{
uint64 t = (uint64)*c;
c++;
h1 = (h1 << 7) | (h1 >> (64 - 7));
h1 += t;
h2 = h2 * 7841u + t;
}
name1 = h1;
name2 = h2;
};
FileName(const std::string& filePath) : FileName(std::basic_string_view(filePath.data(), filePath.size())) {};
uint64 name1;
uint64 name2;
};
~FileCache();
static FileCache* Create(const fs::path& path, uint32 extraVersion = 0);
static FileCache* Open(const fs::path& path, bool allowCreate, uint32 extraVersion = 0);
static FileCache* Open(const fs::path& path); // open without extraVersion check
void UseCompression(bool enable) { enableCompression = enable; };
void AddFile(const FileName&& name, const uint8* fileData, sint32 fileSize);
void AddFileAsync(const FileName& name, const uint8* fileData, sint32 fileSize);
bool DeleteFile(const FileName&& name);
bool GetFile(const FileName&& name, std::vector<uint8>& dataOut);
bool GetFileByIndex(sint32 index, uint64* name1, uint64* name2, std::vector<uint8>& dataOut);
bool HasFile(const FileName&& name);
sint32 GetFileCount();
sint32 GetMaximumFileIndex();
private:
struct FileTableEntry
{
enum FLAGS : uint8
{
FLAG_NONE = 0x00,
FLAG_COMPRESSED = (1 << 0), // zLib compressed
};
uint64 name1;
uint64 name2;
uint64 fileOffset;
uint32 fileSize;
FLAGS flags;
uint8 extraReserved1;
uint8 extraReserved2;
uint8 extraReserved3;
};
static_assert(sizeof(FileTableEntry) == 0x20);
FileCache() {};
static FileCache* _OpenExisting(const fs::path& path, bool compareExtraVersion, uint32 extraVersion = 0);
void fileCache_updateFiletable(sint32 extraEntriesToAllocate);
void _addFileInternal(uint64 name1, uint64 name2, const uint8* fileData, sint32 fileSize, bool noCompression);
bool _getFileDataInternal(const FileTableEntry* entry, std::vector<uint8>& dataOut);
class FileStream* fileStream{};
uint64 dataOffset{};
uint32 extraVersion{};
// file table
FileTableEntry* fileTableEntries{};
sint32 fileTableEntryCount{};
// file table (as stored in file)
uint64 fileTableOffset{};
uint32 fileTableSize{};
// options
bool enableCompression{true};
std::recursive_mutex mutex;
};
| 2,573
|
C++
|
.h
| 79
| 29.708861
| 112
| 0.73153
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,417
|
napi_helper.h
|
cemu-project_Cemu/src/Cemu/napi/napi_helper.h
|
#pragma once
#include "napi.h"
#include "curl/curl.h"
#include "pugixml.hpp"
typedef void CURL;
class CurlRequestHelper
{
struct HeaderExtraField
{
HeaderExtraField(std::string_view name, std::string_view value)
{
data.assign(name);
data.append(": ");
data.append(value);
};
std::string data;
};
public:
enum class SERVER_SSL_CONTEXT
{
ACT, // account.nintendo.net
ECS, // ecs.
IAS, // ias.
CCS, // ccs.
IDBE, // idbe-wup.
TAGAYA, // tagaya.wup.shop.nintendo.net
OLIVE, // olv.
};
CurlRequestHelper();
~CurlRequestHelper();
CURL* getCURL()
{
return m_curl;
}
void initate(NetworkService service, std::string url, SERVER_SSL_CONTEXT sslContext);
void addHeaderField(const char* fieldName, std::string_view value);
void addPostField(const char* fieldName, std::string_view value);
void setWriteCallback(bool(*cbWriteCallback)(void* userData, const void* ptr, size_t len, bool isLast), void* userData);
void setTimeout(sint32 timeoutSeconds); // maximum duration of the request after connecting. Set to zero to disable limit
bool submitRequest(bool isPost = false);
std::vector<uint8>& getReceivedData()
{
return m_receiveBuffer;
}
void setUseMultipartFormData(bool isUsingMultipartFormData)
{
m_isUsingMultipartFormData = isUsingMultipartFormData;
}
private:
static size_t __curlWriteCallback(char* ptr, size_t size, size_t nmemb, void* userdata);
CURL* m_curl;
std::vector<uint8> m_receiveBuffer;
// input parameters
std::vector<HeaderExtraField> m_headerExtraFields;
std::vector<uint8> m_postData;
// write callback redirect
bool (*m_cbWriteCallback)(void* userData, const void* ptr, size_t len, bool isLast);
void* m_writeCallbackUserData{};
bool m_isUsingMultipartFormData = false;
};
class CurlSOAPHelper // todo - make this use CurlRequestHelper
{
public:
CurlSOAPHelper(NetworkService service);
~CurlSOAPHelper();
CURL* getCURL()
{
return m_curl;
}
void SOAP_initate(std::string_view serviceType, std::string url, std::string_view requestMethod, std::string_view requestVersion);
void SOAP_addRequestField(const char* fieldName, std::string_view value);
bool submitRequest();
const std::vector<uint8>& getReceivedData() const
{
return m_receiveBuffer;
}
private:
void SOAP_generateEnvelope();
static size_t __curlWriteCallback(char* ptr, size_t size, size_t nmemb, void* userdata)
{
CurlSOAPHelper* curlHelper = (CurlSOAPHelper*)userdata;
sint32 writeByteSize = (sint32)(size * nmemb);
curlHelper->m_receiveBuffer.insert(curlHelper->m_receiveBuffer.end(), ptr, ptr + writeByteSize);
return writeByteSize;
}
CURL* m_curl;
std::vector<uint8> m_receiveBuffer;
// input parameters
std::string m_serviceType;
std::string m_requestMethod;
std::string m_requestVersion;
// generated / internal
std::string m_envelopeStr;
std::string m_envelopeExtraParam;
};
namespace NAPI
{
bool _findXmlNode(pugi::xml_node& doc, pugi::xml_node& nodeOut, const char* name);
bool _parseResponseInit(const CurlSOAPHelper& soapHelper, const char* responseNodeName, pugi::xml_node& node, _NAPI_CommonResultSOAP& result, pugi::xml_document& doc, pugi::xml_node& responseNode);
};
| 3,187
|
C++
|
.h
| 100
| 29.57
| 198
| 0.761501
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,418
|
napi.h
|
cemu-project_Cemu/src/Cemu/napi/napi.h
|
#pragma once
#include "config/CemuConfig.h" // for ConsoleLanguage
#include "config/NetworkSettings.h" // for NetworkService
#include "config/ActiveSettings.h" // for GetNetworkService()
enum class NAPI_RESULT
{
SUCCESS = 0,
FAILED = 1, // general failure
XML_ERROR = 2, // XML response unexpected
DATA_ERROR = 3, // incorrect values
SERVICE_ERROR = 4, // server reply indicates error. Extended error code (serviceError) is set
};
namespace NAPI
{
// common auth info structure shared by ACT, ECS and IAS service
struct AuthInfo
{
// nnid
std::string accountId;
std::array<uint8, 32> passwordHash;
// console
uint32 deviceId;
std::string serial;
CafeConsoleRegion region;
std::string country;
std::string deviceCertBase64;
uint64 getDeviceIdWithPlatform()
{
uint64 deviceType = 5;
return (deviceType << 32) | ((uint64)deviceId);
}
// IAS token (for ECS and other SOAP service requests)
struct
{
std::string accountId; // console account id
std::string deviceToken;
}IASToken;
// service selection, if not set fall back to global setting
std::optional<NetworkService> serviceOverwrite;
NetworkService GetService() const
{
return serviceOverwrite.value_or(ActiveSettings::GetNetworkService());
}
};
bool NAPI_MakeAuthInfoFromCurrentAccount(AuthInfo& authInfo); // helper function. Returns false if online credentials/dumped files are not available
/* Shared result */
// ErrorCodes IAS:
// 928 -> IAS - Device cert does not verify.
// 954 -> IAS - Invalid Challenge
enum class EC_ERROR_CODE
{
NONE = 0,
ECS_INVALID_DEVICE_TOKEN = 903,
IAS_DEVICE_CERT_ERROR = 928, // either invalid signature or mismatching incorrect device cert chain
IAS_INVALID_CHALLENGE = 954,
ECS_NO_PERMISSION = 701, // AccountGetETickets
NUS_SOAP_INVALID_VERSION = 1301, // seen when accidentally passing wrong SOAP version to GetSystemCommonETicket
};
enum class ACT_ERROR_CODE // are these shared with EC_ERROR_CODE?
{
NONE = 0,
ACT_GAME_SERVER_NOT_FOUND = 1021, // seen when passing wrong serverId to nex token request
};
struct _NAPI_CommonResultSOAP
{
NAPI_RESULT apiError{ NAPI_RESULT::FAILED };
EC_ERROR_CODE serviceError{ EC_ERROR_CODE::NONE };
bool isValid() const
{
return apiError == NAPI_RESULT::SUCCESS;
}
};
struct _NAPI_CommonResultACT
{
NAPI_RESULT apiError{ NAPI_RESULT::FAILED };
ACT_ERROR_CODE serviceError{ ACT_ERROR_CODE::NONE };
bool isValid() const
{
return apiError == NAPI_RESULT::SUCCESS;
}
};
/* account service (account.nintendo.net) */
struct ACTGetProfileResult
{
int todo;
};
bool ACT_GetProfile(AuthInfo& authInfo, ACTGetProfileResult& result);
struct ACTNexToken
{
/* +0x000 */ char token[0x201];
/* +0x201 */ uint8 _padding201[3];
/* +0x204 */ char nexPassword[0x41];
/* +0x245 */ uint8 _padding245[3];
/* +0x248 */ char host[0x10];
/* +0x258 */ uint16be port;
/* +0x25A */ uint8 _padding25A[2];
};
static_assert(sizeof(ACTNexToken) == 0x25C);
struct ACTGetNexTokenResult : public _NAPI_CommonResultACT
{
ACTNexToken nexToken;
};
ACTGetNexTokenResult ACT_GetNexToken_WithCache(AuthInfo& authInfo, uint64 titleId, uint16 titleVersion, uint32 serverId);
struct ACTGetIndependentTokenResult : public _NAPI_CommonResultACT
{
std::string token;
sint64 expiresIn{};
};
ACTGetIndependentTokenResult ACT_GetIndependentToken_WithCache(AuthInfo& authInfo, uint64 titleId, uint16 titleVersion, std::string_view clientId);
struct ACTConvertNnidToPrincipalIdResult : public _NAPI_CommonResultACT
{
bool isFound{false};
uint32 principalId{};
};
ACTConvertNnidToPrincipalIdResult ACT_ACTConvertNnidToPrincipalId(AuthInfo& authInfo, std::string_view nnid);
/* NUS */
struct NAPI_NUSGetSystemCommonETicket_Result : public _NAPI_CommonResultSOAP
{
std::vector<uint8> eTicket;
std::vector<std::vector<uint8>> certs;
};
NAPI_NUSGetSystemCommonETicket_Result NUS_GetSystemCommonETicket(AuthInfo& authInfo, uint64 titleId);
/* IAS/ECS */
struct NAPI_IASGetChallenge_Result : public _NAPI_CommonResultSOAP
{
std::string challenge;
};
struct NAPI_IASGetRegistrationInfo_Result : public _NAPI_CommonResultSOAP
{
std::string accountId;
std::string deviceToken;
};
struct NAPI_ECSGetAccountStatus_Result : public _NAPI_CommonResultSOAP
{
enum class AccountStatus
{
REGISTERED = 'R',
TRANSFERRED = 'T',
UNREGISTERED = 'U',
UNKNOWN = '\0',
};
std::string accountId;
AccountStatus accountStatus{ AccountStatus::UNKNOWN };
struct
{
std::string ContentPrefixURL;
std::string UncachedContentPrefixURL;
std::string SystemContentPrefixURL;
std::string SystemUncachedContentPrefixURL;
std::string EcsURL;
std::string IasURL;
std::string CasURL;
std::string NusURL;
}serviceURLs;
};
struct NAPI_ECSAccountListETicketIds_Result : public _NAPI_CommonResultSOAP
{
struct TIV
{
sint64 ticketId;
uint32 ticketVersion;
};
std::vector<TIV> tivs;
};
struct NAPI_ECSAccountGetETickets_Result : public _NAPI_CommonResultSOAP
{
std::vector<uint8> eTickets;
std::vector<std::vector<uint8>> certs;
};
NAPI_IASGetChallenge_Result IAS_GetChallenge(AuthInfo& authInfo);
NAPI_IASGetRegistrationInfo_Result IAS_GetRegistrationInfo_QueryInfo(AuthInfo& authInfo, std::string challenge);
NAPI_ECSGetAccountStatus_Result ECS_GetAccountStatus(AuthInfo& authInfo);
NAPI_ECSAccountListETicketIds_Result ECS_AccountListETicketIds(AuthInfo& authInfo);
NAPI_ECSAccountGetETickets_Result ECS_AccountGetETickets(AuthInfo& authInfo, sint64 ticketId);
/* CCS */
struct NAPI_CCSGetTMD_Result
{
bool isValid{ false };
std::vector<uint8> tmdData;
};
struct NAPI_CCSGetETicket_Result
{
bool isValid{ false };
std::vector<uint8> cetkData;
};
struct NAPI_CCSGetContentH3_Result
{
bool isValid{ false };
std::vector<uint8> tmdData;
};
NAPI_CCSGetTMD_Result CCS_GetTMD(AuthInfo& authInfo, uint64 titleId, uint16 titleVersion);
NAPI_CCSGetTMD_Result CCS_GetTMD(AuthInfo& authInfo, uint64 titleId);
NAPI_CCSGetETicket_Result CCS_GetCETK(NetworkService service, uint64 titleId, uint16 titleVersion);
bool CCS_GetContentFile(NetworkService service, uint64 titleId, uint32 contentId, bool(*cbWriteCallback)(void* userData, const void* ptr, size_t len, bool isLast), void* userData);
NAPI_CCSGetContentH3_Result CCS_GetContentH3File(NetworkService service, uint64 titleId, uint32 contentId);
/* IDBE */
struct IDBEIconDataV0
{
struct LanguageInfo
{
std::string GetGameNameUTF8();
std::string GetGameLongNameUTF8();
std::string GetPublisherNameUTF8();
private:
uint16be gameName[0x40]{};
uint16be gameLongName[0x80]{};
uint16be publisherName[0x40]{};
};
LanguageInfo& GetLanguageStrings(CafeConsoleLanguage index)
{
if ((uint32)index >= 16)
return languageInfo[0];
return languageInfo[(uint32)index];
}
private:
/* +0x00000 */ uint32be titleIdHigh{};
/* +0x00004 */ uint32be titleIdLow{};
/* +0x00008 */ uint32 ukn00008;
/* +0x0000C */ uint32 ukn0000C;
/* +0x00010 */ uint32 ukn00010;
/* +0x00014 */ uint32 ukn00014;
/* +0x00018 */ uint32 ukn00018;
/* +0x0001C */ uint32 ukn0001C;
/* +0x00020 */ uint32 ukn00020;
/* +0x00024 */ uint32 ukn00024;
/* +0x00028 */ uint32 ukn00028;
/* +0x0002C */ uint32 ukn0002C;
/* +0x00030 */ LanguageInfo languageInfo[16];
/* +0x02030 */ uint8 tgaData[0x10030]{};
};
static_assert(sizeof(IDBEIconDataV0) == 0x12060);
struct IDBEHeader
{
uint8 formatVersion;
uint8 keyIndex;
uint8 hashSHA256[32];
};
static_assert(sizeof(IDBEHeader) == 2+32);
std::optional<IDBEIconDataV0> IDBE_Request(NetworkService networkService, uint64 titleId);
std::vector<uint8> IDBE_RequestRawEncrypted(NetworkService networkService, uint64 titleId); // same as IDBE_Request but doesn't strip the header and decrypt the IDBE
/* Version list */
struct NAPI_VersionListVersion_Result
{
bool isValid{false};
uint32 version{0};
std::string fqdnURL;
};
NAPI_VersionListVersion_Result TAG_GetVersionListVersion(AuthInfo& authInfo);
struct NAPI_VersionList_Result
{
bool isValid{ false };
std::unordered_map<uint64, uint16> titleVersionList; // key = titleId, value = version
};
NAPI_VersionList_Result TAG_GetVersionList(AuthInfo& authInfo, std::string_view fqdnURL, uint32 versionListVersion);
}
void NAPI_NUS_GetSystemUpdate();
void NAPI_NUS_GetSystemTitleHash();
| 8,469
|
C++
|
.h
| 257
| 30.101167
| 181
| 0.755858
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,419
|
DownloadManager.h
|
cemu-project_Cemu/src/Cemu/Tools/DownloadManager/DownloadManager.h
|
#pragma once
#include "util/helpers/Semaphore.h"
#include "Cemu/ncrypto/ncrypto.h"
#include "Cafe/TitleList/TitleId.h"
#include "util/helpers/ConcurrentQueue.h"
#include "config/NetworkSettings.h"
// forward declarations
namespace NAPI
{
struct IDBEIconDataV0;
struct AuthInfo;
}
namespace NCrypto
{
class TMDParser;
}
struct DlMgrTitleReport
{
enum class STATUS
{
INSTALLABLE, // not a package
INSTALLABLE_UNFINISHED, // same as INSTALLABLE, but a previous unfinished package was detected
INSTALLABLE_UPDATE, // same as INSTALLABLE, but an older version is already installed (used for DLC updates after purchasing more content)
// below are packages
QUEUED,
PAUSED,
INITIALIZING, // not active yet, downloading TMD
CHECKING, // checking for previously downloaded files
DOWNLOADING, // downloading content files
VERIFYING, // verifying downloaded files
INSTALLING,
INSTALLED,
HAS_ERROR
};
DlMgrTitleReport(STATUS status, uint64 titleId, uint16 version, std::string name, uint32 progress, uint32 progressMax, bool isPaused) : status(status), titleId(titleId), version(version), name(name), progress(progress), progressMax(progressMax), isPaused(isPaused) {}
uint64 titleId;
uint16 version;
std::string name; // utf8
STATUS status;
uint32 progress;
uint32 progressMax;
bool isPaused;
std::string errorMsg;
};
enum class DLMGR_STATUS_CODE
{
UNINITIALIZED,
CONNECTING,
FAILED,
CONNECTED
};
class DownloadManager
{
public:
/* singleton */
static DownloadManager* GetInstance(bool createIfNotExist = true)
{
static DownloadManager* s_instance = nullptr;
if (s_instance)
return s_instance;
if (createIfNotExist)
s_instance = new DownloadManager();
return s_instance;
}
// login
void connect(
std::string_view nnidAccountName,
const std::array<uint8, 32>& passwordHash,
CafeConsoleRegion region,
std::string_view country,
uint32 deviceId,
std::string_view serial,
std::string_view deviceCertBase64);
bool IsConnected() const;
private:
/* connect / login */
enum class CONNECT_STATE
{
UNINITIALIZED = 0, // connect() not called
REQUESTED = 1, // connect() requested, but not being processed yet
PROCESSING = 2, // processing login request
COMPLETE = 3, // login complete / succeeded
FAILED = 4, // failed to login
};
struct
{
std::string cachefileName;
std::string nnidAccountName;
std::array<uint8, 32> passwordHash;
std::string deviceCertBase64;
CafeConsoleRegion region;
std::string country;
uint32 deviceId; // deviceId without platform (0x5<<32 for WiiU)
std::string serial;
}m_authInfo{};
struct
{
// auth info we have to request from the server
std::string serviceAccountId; // internal account id (integer) provided by server when registering account (GetRegistrationInfo)
std::string deviceToken;
}m_iasToken{};
std::atomic<CONNECT_STATE> m_connectState{ CONNECT_STATE::UNINITIALIZED };
void _handle_connect();
bool _connect_refreshIASAccountIdAndDeviceToken();
bool _connect_queryAccountStatusAndServiceURLs();
NetworkService GetDownloadMgrNetworkService();
NAPI::AuthInfo GetAuthInfo(bool withIasToken);
/* idbe cache */
public:
void prepareIDBE(uint64 titleId);
std::string getNameFromCachedIDBE(uint64 titleId);
private:
NAPI::IDBEIconDataV0* getIDBE(uint64 titleId);
/* ticket cache */
public:
struct ETicketInfo
{
enum class SOURCE : uint8
{
ECS_TICKET = 0, // personalized ticket of owned title
PUBLIC_TICKET = 1, // public ticket file (available as /CETK from NUS server or via SOAP GetSystemCommonETicket. The former is from Wii era while the latter is how Wii U requests public tickets?)
// note: These ids are baked into the serialized cache format. Do not modify
};
ETicketInfo(SOURCE source, uint64 ticketId, uint32 ticketVersion, std::vector<uint8>& eTicket);
ETicketInfo(SOURCE source, uint64 ticketId, uint32 ticketVersion, std::vector<uint8>& eTicket, std::vector<std::vector<uint8>>& eTicketCerts);
void GetTitleKey(NCrypto::AesKey& key);
SOURCE source;
// tiv
uint64 ticketId;
uint32 ticketVersion;
// titleInfo
uint64 titleId{0}; // parsed from eTicket
std::vector<uint8> eTicket;
std::vector<std::vector<uint8>> eTicketCerts;
};
std::vector<ETicketInfo> m_ticketCache;
struct UnfinishedDownload
{
UnfinishedDownload(uint64 titleId, uint16 titleVersion) : titleId(titleId), titleVersion(titleVersion) {};
uint64 titleId;
uint16 titleVersion;
};
std::vector<UnfinishedDownload> m_unfinishedDownloads;
void loadTicketCache();
void storeTicketCache();
bool syncAccountTickets();
bool syncSystemTitleTickets();
bool syncUpdateTickets();
bool syncTicketCache();
void searchForIncompleteDownloads();
void reportAvailableTitles();
private:
ETicketInfo* findTicketByTicketId(uint64 ticketId)
{
for (auto& itr : m_ticketCache)
{
if (itr.ticketId == ticketId)
return &itr;
}
return nullptr;
}
void deleteTicketByTicketId(uint64 ticketId)
{
auto itr = m_ticketCache.begin();
while (itr != m_ticketCache.end())
{
if (itr->ticketId == ticketId)
{
m_ticketCache.erase(itr);
return;
}
itr++;
}
cemu_assert_debug(false); // ticketId not found
}
ETicketInfo* findTicketByTitleIdAndVersion(uint64 titleId, uint16 version)
{
for (auto& itr : m_ticketCache)
{
if (itr.titleId == titleId && itr.ticketVersion == version)
return &itr;
}
return nullptr;
}
ETicketInfo* findFirstTicketByTitleId(uint64 titleId)
{
for (auto& itr : m_ticketCache)
{
if (itr.titleId == titleId)
return &itr;
}
return nullptr;
}
bool hasPartialDownload(uint64 titleId, uint16 titleVersion)
{
for (auto& itr : m_unfinishedDownloads)
{
if (itr.titleId == titleId && itr.titleVersion == titleVersion)
return true;
}
return false;
}
void deleteUnfinishedDownloadRecord(uint64 titleId)
{
auto itr = m_unfinishedDownloads.begin();
while (itr != m_unfinishedDownloads.end())
{
if (itr->titleId == titleId)
{
itr = m_unfinishedDownloads.erase(itr);
continue;
}
itr++;
}
}
/* packages / downloading */
struct Package
{
Package(uint64 titleId, uint16 version, std::span<uint8> ticketData) : titleId(titleId), version(version), eTicketData(ticketData.data(), ticketData.data() + ticketData.size())
{
NCrypto::ETicketParser eTicketParser;
cemu_assert(eTicketParser.parse(ticketData.data(), ticketData.size()));
eTicketParser.GetTitleKey(ticketKey);
};
~Package()
{
delete state.tmd;
}
enum class STATE
{
INITIAL,
CHECKING,
DOWNLOADING,
VERIFYING,
INSTALLING,
INSTALLED // done
};
uint64 titleId;
uint16 version;
std::vector<uint8> eTicketData;
NCrypto::AesKey ticketKey;
// internal
struct ContentFile
{
ContentFile(uint16 index, uint32 contentId, uint64 size, NCrypto::TMDParser::TMDContentFlags contentFlags, uint8 hash[32]) : index(index), contentId(contentId), size(size), contentFlags(contentFlags)
{
std::memcpy(contentHash, hash, 32);
CalcPaddedSize();
};
const uint16 index;
const uint32 contentId;
const uint64 size;
uint64 paddedSize; // includes padding forced by encryption/hashing (e.g. Nintendo Land update has one non-hashed content size of 0x8001, padded to 0x8010)
const NCrypto::TMDParser::TMDContentFlags contentFlags;
uint8 contentHash[32];
enum class STATE
{
CHECK,
DOWNLOAD,
VERIFY,
INSTALL,
ENUM_COUNT, // for enum_array
};
STATE currentState{STATE::CHECK};
bool isBeingProcessed{false}; // worked thread assigned and processing current state
void finishProcessing(STATE newState)
{
currentState = newState;
isBeingProcessed = false;
};
// progress tracking
uint64 amountDownloaded{};
private:
void CalcPaddedSize()
{
if (HAS_FLAG(contentFlags, NCrypto::TMDParser::TMDContentFlags::FLAG_HASHED_CONTENT))
{
// pad to 0x10000 bytes
paddedSize = (size + 0xFFFFull) & ~0xFFFFull;
}
else
{
// pad to 16 bytes
paddedSize = (size + 0xFull) & ~0xFull;
}
}
};
struct
{
bool isActive{}; // actively downloading
bool isPaused{};
STATE currentState{ STATE::INITIAL };
// tmd
bool isDownloadingTMD{};
std::vector<uint8> tmdData;
NCrypto::TMDParser* tmd{};
// app/h3 tracking
std::unordered_map<uint16, ContentFile> contentFiles;
// progress of current operation
uint32 progress{}; // for downloading: in 1/10th of a percent (0-1000), for installing: number of files
uint32 progressMax{}; // maximum (downloading: unused, installing: total number of files)
// installing
bool isInstalling{};
// error state
bool hasError{};
std::string errorMsg;
}state;
};
std::recursive_mutex m_mutex;
std::vector<Package*> m_packageList;
public:
void initiateDownload(uint64 titleId, uint16 version);
void pauseDownload(uint64 titleId, uint16 version);
private:
Package* getPackage(uint64 titleId, uint16 version);
fs::path getPackageDownloadPath(Package* package);
fs::path getPackageInstallPath(Package* package);
void updatePackage(Package* package);
void checkPackagesState();
void setPackageError(Package* package, std::string errorMsg);
void reportPackageStatus(Package* package);
void reportPackageProgress(Package* package, uint32 newProgress);
void asyncPackageDownloadTMD(Package* package);
void calcPackageDownloadProgress(Package* package);
void asyncPackageDownloadContentFile(Package* package, uint16 index);
void asyncPackageVerifyFile(Package* package, uint16 index, bool isCheckState);
void asyncPackageInstall(Package* package);
bool asyncPackageInstallRecursiveExtractFiles(Package* package, class FSTVolume* fstVolume, const std::string& sourcePath, const fs::path& destinationPath);
/* callback interface */
public:
void setUserData(void* ptr)
{
m_userData = ptr;
}
void* getUserData() const
{
return m_userData;
}
// register/unregister callbacks
// setting valid callbacks will also trigger transfer of the entire title/package state and the current status message
void registerCallbacks(
void(*cbUpdateConnectStatus)(std::string statusText, DLMGR_STATUS_CODE statusCode),
void(*cbAddDownloadableTitle)(const DlMgrTitleReport& titleInfo),
void(*cbRemoveDownloadableTitle)(uint64 titleId, uint16 version)
)
{
std::unique_lock<std::recursive_mutex> _l(m_mutex);
m_cbUpdateConnectStatus = cbUpdateConnectStatus;
m_cbAddDownloadableTitle = cbAddDownloadableTitle;
m_cbRemoveDownloadableTitle = cbRemoveDownloadableTitle;
// resend data
if (m_cbUpdateConnectStatus || m_cbAddDownloadableTitle)
{
std::unique_lock<std::recursive_mutex> _l(m_mutex);
setStatusMessage(m_statusMessage, m_statusCode);
reportAvailableTitles();
for (auto& p : m_packageList)
reportPackageStatus(p);
}
}
void setStatusMessage(std::string_view msg, DLMGR_STATUS_CODE statusCode)
{
m_statusMessage = msg;
m_statusCode = statusCode;
if (m_cbUpdateConnectStatus)
m_cbUpdateConnectStatus(m_statusMessage, statusCode);
}
std::string m_statusMessage{};
DLMGR_STATUS_CODE m_statusCode{ DLMGR_STATUS_CODE::UNINITIALIZED };
bool hasActiveDownloads()
{
std::unique_lock<std::recursive_mutex> _l(m_mutex);
for (auto& p : m_packageList)
{
if (p->state.isActive && !p->state.hasError &&
(p->state.currentState != Package::STATE::INSTALLED))
{
return true;
}
}
return false;
}
void reset()
{
std::unique_lock<std::recursive_mutex> _l(m_mutex);
m_packageList.clear();
m_statusCode = DLMGR_STATUS_CODE::UNINITIALIZED;
m_statusMessage.clear();
}
private:
void(*m_cbUpdateConnectStatus)(std::string statusText, DLMGR_STATUS_CODE statusCode) { nullptr };
void(*m_cbAddDownloadableTitle)(const DlMgrTitleReport& titleInfo);
void(*m_cbRemoveDownloadableTitle)(uint64 titleId, uint16 version);
void* m_userData{};
/* title version list */
bool m_hasTitleVersionList{};
std::unordered_map<uint64, uint16> m_titleVersionList;
void downloadTitleVersionList();
bool getTitleLatestVersion(TitleId titleId, uint16& version);
/* helper for building list of owned titles (is installed or has cached ticket) */
struct TitleInstallState
{
TitleInstallState(DownloadManager* dlMgr, uint64 titleId);
uint64 titleId;
bool isInstalled;
uint16 installedTitleVersion;
uint16 installedTicketVersion{};
bool operator<(const TitleInstallState& comp) const
{
return this->titleId < comp.titleId;
}
};
struct TitleDownloadAvailableState : TitleInstallState
{
TitleDownloadAvailableState(DownloadManager* dlMgr, uint64 titleId);
bool isUpdateAvailable; // update available for this specific titleId
uint16 availableTitleVersion;
};
std::set<TitleInstallState> getOwnedTitleList();
std::set<TitleDownloadAvailableState> getFullDownloadList();
/* thread */
void threadFunc();
void runManager();
void notifyManager();
void queueManagerJob(const std::function<void()>& callback);
std::atomic_bool m_threadLaunched{ false };
CounterSemaphore m_queuedEvents;
ConcurrentQueue<std::function<void()>> m_jobQueue;
std::mutex m_updateList; // not needed?
};
| 13,218
|
C++
|
.h
| 430
| 27.730233
| 268
| 0.755447
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,420
|
ncrypto.h
|
cemu-project_Cemu/src/Cemu/ncrypto/ncrypto.h
|
#pragma once
#include "Common/betype.h"
#include "config/CemuConfig.h" // for ConsoleRegion
/* OpenSSL forward declarations */
typedef struct ec_key_st EC_KEY;
typedef struct ec_point_st EC_POINT;
typedef struct ECDSA_SIG_st ECDSA_SIG;
namespace NCrypto
{
/* Base 64 */
std::string base64Encode(const void* inputMem, size_t inputLen);
std::vector<uint8> base64Decode(std::string_view inputStr);
/* key helper struct */
struct AesKey
{
uint8 b[16];
};
/* ECC Certificate */
struct ECCPrivKey
{
uint8 keyData[30];
void setPrivateKey(EC_KEY* key);
EC_KEY* getPrivateKey() const;
static ECCPrivKey getDeviceCertPrivateKey();
};
struct ECCPubKey
{
uint8 x[30];
uint8 y[30];
EC_KEY* getPublicKey();
EC_POINT* getPublicKeyAsPoint();
[[nodiscard]] static ECCPubKey generateFromPrivateKey(ECCPrivKey& privKey);
};
struct ECCSig
{
uint8 r[30];
uint8 s[30];
ECDSA_SIG* getSignature();
void setSignature(ECDSA_SIG* sig);
bool doesMatch(ECCSig& otherSig) const
{
return memcmp(this->r, otherSig.r, sizeof(this->r)) == 0 && memcmp(this->s, otherSig.s, sizeof(this->s)) == 0;
}
std::string encodeToBase64()
{
return base64Encode(this, 60);
}
};
struct CHash256 // SHA256
{
uint8 b[32];
};
struct CHash160 // SHA1
{
uint8 b[20];
};
struct CertECC
{
enum class SIGTYPE : uint32
{
ECC_SHA1 = 0x00010002, // guessed
ECC_SHA256 = 0x00010005
};
/* +0x000 */ betype<SIGTYPE> signatureType; // 01 00 02 00
/* +0x004 */ ECCSig signature; //uint8 signature[0x3C]; // from OTP 0xA3*4
/* +0x040 */ uint8 ukn040[0x40]; // seems to be just padding
/* +0x080 */ char issuer[0x40]; // "Root - CA%08x - MS%08x"
/* +0x0C0 */ char ukn0C0[0x4]; // ??? 00 00 00 02 ?
/* +0x0C4 */ char ngName[0x40]; // "NG%08X"
/* +0x104 */ uint32 date; // big endian? (from OTP 0xA2*4)
/* +0x108 */ ECCPubKey publicKey; //uint8 publicKey[0x3C];
/* +0x144 */ uint8 padding[0x180 - 0x144];
bool decodeFromBase64(std::string_view input);
std::string encodeToBase64();
bool verifySignatureViaPubKey(ECCPubKey& signerPubKey);
void sign(ECCPrivKey& signerPrivKey);
static CertECC GetDeviceCertificate();
static CertECC generateCertificate(uint32 signerTitleIdHigh, uint32 signerTitleIdLow, ECCPrivKey& privKeySigner, ECCPrivKey& privKeyIn, ECCPubKey& pubKeyOut);
};
static_assert(sizeof(CertECC) == 0x180);
/* ETicket */
class ETicketParser // .tik parser
{
public:
bool parse(const uint8* data, size_t size);
static bool Depersonalize(uint8* ticketData, size_t ticketSize, uint32 deviceId, const ECCPrivKey& devicePrivKey);
uint64 GetTicketId() const
{
return m_ticketId;
}
uint64 GetTitleId() const
{
return m_titleId;
}
uint16 GetTicketVersion() const
{
return m_titleVersion;
}
void GetTitleKey(AesKey& key);
bool IsPersonalized()
{
return m_isPersonalized;
}
bool CheckRight(size_t index)
{
if (index >= m_contentRights.size())
return false;
return m_contentRights[index];
}
private:
uint64 m_titleId;
uint16 m_titleVersion;
uint64 m_ticketId;
uint8 m_ticketFormatVersion;
uint8 m_encryptedTitleKey[16];
// personalized data
bool m_isPersonalized;
uint32 m_deviceId;
ECCPubKey m_publicKey;
// rights
std::vector<bool> m_contentRights;
};
/* Title meta data */
class TMDParser
{
public:
enum class TMDContentFlags : uint16
{
// 0x0001 -> Is encrypted?
FLAG_SHA1 = 0x2000, // if not set, use SHA256
FLAG_HASHED_CONTENT = 0x0002, // .app uses hashed format
};
struct ContentEntry
{
uint32 contentId;
uint16 index;
TMDContentFlags contentFlags;
uint64 size;
uint8 hash32[32];
};
uint64 getTitleId() const
{
return m_titleId;
}
uint16 getTitleVersion() const
{
return m_titleVersion;
}
bool parse(const uint8* data, size_t size);
std::vector<ContentEntry>& GetContentList()
{
return m_content;
}
private:
uint64 m_titleId;
uint16 m_titleVersion;
std::vector<ContentEntry> m_content;
};
DEFINE_ENUM_FLAG_OPERATORS(TMDParser::TMDContentFlags);
void GenerateHashSHA256(const void* data, size_t len, CHash256& hashOut);
ECCSig signHash(uint32 signerTitleIdHigh, uint32 signerTitleIdLow, uint8* hash, sint32 hashLen, CertECC& certChainOut);
uint32 GetDeviceId();
std::string GetSerial();
CafeConsoleRegion SEEPROM_GetRegion();
std::string GetRegionAsString(CafeConsoleRegion regionCode);
const char* GetCountryAsString(sint32 index); // returns NN if index is not valid or known
size_t GetCountryCount();
bool SEEPROM_IsPresent();
bool OTP_IsPresent();
bool HasDataForConsoleCert();
void unitTests();
}
| 4,712
|
C++
|
.h
| 172
| 24.418605
| 160
| 0.717145
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,421
|
nexTypes.h
|
cemu-project_Cemu/src/Cemu/nex/nexTypes.h
|
#pragma once
#include<string>
#ifndef FFL_SIZE
#define FFL_SIZE (0x60)
#endif
class nexPacketBuffer;
class nexMetaType
{
public:
virtual const char* getMetaName() const = 0;
virtual void writeData(nexPacketBuffer* pb) const = 0;
};
class nexType
{
public:
virtual ~nexType(){};
virtual const char* getMetaName()
{
cemu_assert_unimplemented();
return "";
}
virtual void writeData(nexPacketBuffer* pb) const = 0;
virtual void readData(nexPacketBuffer* pb) = 0;
};
class nexPacketBuffer
{
public:
nexPacketBuffer(uint8* data, sint32 size, bool isWrite)
{
this->buffer = data;
this->size = size;
this->currentIndex = 0;
this->isWrite = isWrite;
this->readOutOfBounds = false;
}
nexPacketBuffer()
{
this->buffer = 0;
this->size = 0;
this->currentIndex = 0;
}
void writeData(const uint8* data, sint32 len)
{
if (this->currentIndex + len > this->size)
return;
memcpy(this->buffer + this->currentIndex, data, len);
this->currentIndex += len;
}
void writeU8(uint8 v)
{
if (this->currentIndex + sizeof(uint8) > this->size)
return;
*(uint8*)(this->buffer + this->currentIndex) = v;
this->currentIndex += sizeof(uint8);
}
void writeU16(uint16 v)
{
if (this->currentIndex + sizeof(uint16) > this->size)
return;
*(uint16*)(this->buffer + this->currentIndex) = v;
this->currentIndex += sizeof(uint16);
}
void writeU32(uint32 v)
{
if (this->currentIndex + sizeof(uint32) > this->size)
return;
*(uint32*)(this->buffer + this->currentIndex) = v;
this->currentIndex += sizeof(uint32);
}
void writeU64(uint64 v)
{
if (this->currentIndex + sizeof(uint64) > this->size)
return;
*(uint64*)(this->buffer + this->currentIndex) = v;
this->currentIndex += sizeof(uint64);
}
void writeString(const char* v)
{
sint32 len = (sint32)strlen(v) + 1;
writeU16(len);
writeData((uint8*)v, len);
}
void writeBuffer(const uint8* v, sint32 len)
{
writeU32(len);
writeData(v, len);
}
void writeCustomType(const nexMetaType& v)
{
// write meta name
writeString(v.getMetaName());
// write length 0 placeholder
uint32* lengthPtr0 = (uint32*)(this->buffer + this->currentIndex);
writeU32(0);
// write length 1 placeholder
uint32* lengthPtr1 = (uint32*)(this->buffer + this->currentIndex);
writeU32(0);
// write data
uint32 preWriteIndex = this->currentIndex;
v.writeData(this);
uint32 writeSize = this->currentIndex - preWriteIndex;
// update lengths
*lengthPtr1 = writeSize;
*lengthPtr0 = writeSize + 4;
}
uint64 readU64()
{
if (this->currentIndex + sizeof(uint64) > this->size)
{
readOutOfBounds = true;
return 0;
}
uint64 v = *(uint64*)(this->buffer + this->currentIndex);
this->currentIndex += sizeof(uint64);
return v;
}
uint32 readU32()
{
if (this->currentIndex + sizeof(uint32) > this->size)
{
readOutOfBounds = true;
return 0;
}
uint32 v = *(uint32*)(this->buffer + this->currentIndex);
this->currentIndex += sizeof(uint32);
return v;
}
uint16 readU16()
{
if (this->currentIndex + sizeof(uint16) > this->size)
{
readOutOfBounds = true;
return 0;
}
uint16 v = *(uint16*)(this->buffer + this->currentIndex);
this->currentIndex += sizeof(uint16);
return v;
}
uint8 readU8()
{
if (this->currentIndex + sizeof(uint8) > this->size)
{
readOutOfBounds = true;
return 0;
}
uint8 v = *(uint8*)(this->buffer + this->currentIndex);
this->currentIndex += sizeof(uint8);
return v;
}
sint32 readData(void* buffer, sint32 length)
{
if (this->currentIndex + length > this->size)
{
readOutOfBounds = true;
return 0;
}
memcpy(buffer, (this->buffer + this->currentIndex), length);
this->currentIndex += length;
return length;
}
// reads buffer data from packet and returns amount of bytes copied into buffer
// if buffer is larger than maxLength, the read data is silently truncated
sint32 readBuffer(void* buffer, sint32 maxLength)
{
sint32 bufferLength = (sint32)readU32();
if (bufferLength < 0 || bufferLength >= 0x10000000)
{
readOutOfBounds = true;
return 0;
}
if (this->currentIndex + bufferLength > this->size)
{
readOutOfBounds = true;
return 0;
}
uint32 copiedLength = std::min(bufferLength, maxLength);
memcpy(buffer, (this->buffer + this->currentIndex), copiedLength);
this->currentIndex += bufferLength;
return copiedLength;
}
sint32 readString(char* buffer, sint32 maxLength)
{
sint32 bufferLength = readU16();
if (this->currentIndex + bufferLength > this->size)
{
readOutOfBounds = true;
buffer[0] = '\0';
return 0;
}
uint32 copiedLength = std::min(bufferLength, maxLength - 1);
memcpy(buffer, (this->buffer + this->currentIndex), copiedLength);
buffer[copiedLength] = '\0';
this->currentIndex += bufferLength;
return copiedLength;
}
sint32 readStdString(std::string& outputStr)
{
sint32 bufferLength = readU16();
if (this->currentIndex + bufferLength > this->size)
{
readOutOfBounds = true;
outputStr.clear();
return 0;
}
sint32 copiedLength = bufferLength;
if (bufferLength > 0 && this->buffer[this->currentIndex+bufferLength-1] == '\0')
{
// cut off trailing '\0'
copiedLength--;
}
outputStr = std::string((char*)(this->buffer + this->currentIndex), copiedLength);
this->currentIndex += bufferLength;
return copiedLength;
}
bool readPlaceholderType(nexType& v)
{
char name[128];
readString(name, sizeof(name));
name[sizeof(name)-1] = '\0';
if (hasReadOutOfBounds())
return false;
if (strcmp(name, v.getMetaName()) != 0)
return false;
// read sizes
uint32 len0 = readU32();
uint32 len1 = readU32();
if (hasReadOutOfBounds())
return false;
if (len1 != (len0 - 4))
return false;
// parse type data
v.readData(this);
if (hasReadOutOfBounds())
return false;
return true;
//// write meta name
//writeString(v.getMetaName());
//// write length 0 placeholder
//uint32* lengthPtr0 = (uint32*)(this->buffer + this->currentIndex);
//writeU32(0);
//// write length 1 placeholder
//uint32* lengthPtr1 = (uint32*)(this->buffer + this->currentIndex);
//writeU32(0);
//// write data
//uint32 preWriteIndex = this->currentIndex;
//v.writeData(this);
//uint32 writeSize = this->currentIndex - preWriteIndex;
//// update lengths
//*lengthPtr1 = writeSize;
//*lengthPtr0 = writeSize + 4;
}
bool hasReadOutOfBounds()
{
return readOutOfBounds;
}
uint8* getDataPtr()
{
return buffer;
}
sint32 getWriteIndex()
{
return currentIndex;
}
sint32 getSize()
{
return size;
}
void setSize(sint32 length)
{
size = length;
}
private:
uint8* buffer;
sint32 size;
sint32 currentIndex;
bool isWrite;
bool readOutOfBounds; // set if any read operation failed because it exceeded the buffer
};
class nexNintendoLoginData : public nexMetaType
{
public:
nexNintendoLoginData(const char* nexToken)
{
this->nexToken = new std::string(nexToken);
}
const char* getMetaName() const override
{
return "NintendoLoginData";
}
void writeData(nexPacketBuffer* pb) const override
{
pb->writeString(nexToken->c_str());
}
private:
std::string* nexToken;
};
class nexNotificationEventGeneral : public nexType
{
public:
nexNotificationEventGeneral()
{
}
nexNotificationEventGeneral(nexPacketBuffer* pb)
{
readData(pb);
}
const char* getMetaName() override
{
return "NintendoNotificationEventGeneral";
}
void writeData(nexPacketBuffer* pb) const override
{
cemu_assert_unimplemented();
}
void readData(nexPacketBuffer* pb) override
{
param1 = pb->readU32();
param2 = pb->readU64();
param3 = pb->readU64();
pb->readStdString(paramStr);
}
public:
uint32 param1;
uint64 param2;
uint64 param3;
std::string paramStr;
};
| 7,775
|
C++
|
.h
| 327
| 21.079511
| 89
| 0.706224
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,422
|
prudp.h
|
cemu-project_Cemu/src/Cemu/nex/prudp.h
|
#pragma once
#include "nexTypes.h"
#include "Common/socket.h"
#define RC4_N 256
struct RC4Ctx
{
unsigned char S[RC4_N];
int i;
int j;
};
void RC4_initCtx(RC4Ctx* rc4Ctx, const char* key);
void RC4_initCtx(RC4Ctx* rc4Ctx, unsigned char* key, int keyLen);
void RC4_transform(RC4Ctx* rc4Ctx, unsigned char* input, int len, unsigned char* output);
struct prudpStreamSettings
{
uint8 checksumBase; // calculated from key
uint8 accessKeyDigest[16]; // MD5 hash of key
RC4Ctx rc4Client;
RC4Ctx rc4Server;
};
struct prudpStationUrl
{
uint32 ip;
uint16 port;
sint32 cid;
sint32 pid;
sint32 sid;
sint32 stream;
sint32 type;
};
struct prudpAuthServerInfo
{
uint32 userPid;
uint8 secureKey[16];
uint8 kerberosKey[16];
uint8 secureTicket[1024];
sint32 secureTicketLength;
prudpStationUrl server;
};
class prudpPacket
{
public:
static const int PACKET_RAW_SIZE_MAX = 500;
static const int TYPE_SYN = 0;
static const int TYPE_CON = 1;
static const int TYPE_DATA = 2;
static const int TYPE_DISCONNECT = 3;
static const int TYPE_PING = 4;
static const int STREAM_TYPE_SECURE = 0xA;
static const int FLAG_ACK = 0x1;
static const int FLAG_RELIABLE = 0x2; // if this flag is set, increase sequenceId
static const int FLAG_NEED_ACK = 0x4;
static const int FLAG_HAS_SIZE = 0x8;
static sint32 calculateSizeFromPacketData(uint8* data, sint32 length);
prudpPacket(prudpStreamSettings* streamSettings, uint8 src, uint8 dst, uint8 type, uint16 flags, uint8 sessionId, uint16 sequenceId, uint32 packetSignature);
bool requiresAck();
void setData(uint8* data, sint32 length);
void setFragmentIndex(uint8 fragmentIndex);
sint32 buildData(uint8* output, sint32 maxLength);
uint8 GetType() const { return type; }
uint16 GetSequenceId() const { return m_sequenceId; }
private:
uint32 packetSignature();
uint8 calculateChecksum(uint8* data, sint32 length);
private:
uint8 src;
uint8 dst;
uint8 type;
uint8 fragmentIndex;
uint16 flags;
uint8 sessionId;
uint32 specifiedPacketSignature;
prudpStreamSettings* streamSettings;
std::vector<uint8> packetData;
bool isEncrypted;
uint16 m_sequenceId{0};
};
class prudpIncomingPacket
{
public:
prudpIncomingPacket(prudpStreamSettings* streamSettings, uint8* data, sint32 length);
bool hasError();
uint8 calculateChecksum(uint8* data, sint32 length);
void decrypt();
private:
prudpIncomingPacket();
public:
// prudp header
uint8 src;
uint8 dst;
uint16 flags;
uint8 type;
uint8 sessionId;
uint32 packetSignature;
uint16 sequenceId;
uint8 fragmentIndex;
bool hasData = false;
std::vector<uint8> packetData;
private:
bool isInvalid = false;
prudpStreamSettings* streamSettings = nullptr;
};
class prudpClient
{
struct PacketWithAckRequired
{
PacketWithAckRequired(prudpPacket* packet, uint32 initialSendTimestamp) :
packet(packet), initialSendTimestamp(initialSendTimestamp), lastRetryTimestamp(initialSendTimestamp) { }
prudpPacket* packet;
uint32 initialSendTimestamp;
uint32 lastRetryTimestamp;
sint32 retryCount{0};
};
public:
enum class ConnectionState : uint8
{
Connecting,
Connected,
Disconnected
};
prudpClient(uint32 dstIp, uint16 dstPort, const char* key);
prudpClient(uint32 dstIp, uint16 dstPort, const char* key, prudpAuthServerInfo* authInfo);
~prudpClient();
bool IsConnected() const { return m_currentConnectionState == ConnectionState::Connected; }
ConnectionState GetConnectionState() const { return m_currentConnectionState; }
uint16 GetSourcePort() const { return m_srcPort; }
bool Update(); // update connection state and check for incoming packets. Returns true if ReceiveDatagram() should be called
sint32 ReceiveDatagram(std::vector<uint8>& outputBuffer);
void SendDatagram(uint8* input, sint32 length, bool reliable = true);
private:
prudpClient();
void HandleIncomingPacket(std::unique_ptr<prudpIncomingPacket> incomingPacket);
void DirectSendPacket(prudpPacket* packet);
sint32 KerberosEncryptData(uint8* input, sint32 length, uint8* output);
void QueuePacket(prudpPacket* packet);
void AcknowledgePacket(uint16 sequenceId);
void SortIncomingDataPacket(std::unique_ptr<prudpIncomingPacket> incomingPacket);
void SendCurrentHandshakePacket();
private:
uint16 m_srcPort;
uint32 m_dstIp;
uint16 m_dstPort;
uint8 m_srcVPort;
uint8 m_dstVPort;
prudpStreamSettings m_streamSettings;
std::vector<PacketWithAckRequired> m_dataPacketsWithAckReq;
std::vector<std::unique_ptr<prudpIncomingPacket>> m_incomingPacketQueue;
// connection handshake state
bool m_hasSynAck{false};
bool m_hasConAck{false};
uint32 m_lastHandshakeTimestamp{0};
uint8 m_handshakeRetryCount{0};
// connection
ConnectionState m_currentConnectionState;
uint32 m_serverConnectionSignature;
uint32 m_clientConnectionSignature;
uint32 m_lastPingTimestamp;
uint16 m_outgoingReliableSequenceId{2}; // 1 is reserved for CON
uint16 m_incomingSequenceId;
uint16 m_outgoingSequenceId_ping{0};
uint8 m_unacknowledgedPingCount{0};
uint8 m_clientSessionId;
uint8 m_serverSessionId;
// secure
bool m_isSecureConnection{false};
prudpAuthServerInfo m_authInfo;
// socket
SOCKET m_socketUdp;
};
uint32 prudpGetMSTimestamp();
| 5,183
|
C++
|
.h
| 170
| 28.405882
| 158
| 0.803177
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,423
|
nexFriends.h
|
cemu-project_Cemu/src/Cemu/nex/nexFriends.h
|
#pragma once
#ifndef FFL_SIZE
#define FFL_SIZE 0x60
#endif
class nexGameKey : public nexType
{
public:
nexGameKey() = default;
nexGameKey(uint64 titleId, uint16 ukn)
{
this->titleId = titleId;
this->ukn = ukn;
}
nexGameKey(nexPacketBuffer* pb)
{
readData(pb);
}
void writeData(nexPacketBuffer* pb) const override
{
pb->writeU64(titleId);
pb->writeU16(ukn);
}
void readData(nexPacketBuffer* pb) override
{
titleId = pb->readU64();
ukn = pb->readU16();
}
public:
uint64 titleId;
uint16 ukn;
};
class nexMiiV2 : public nexType
{
public:
nexMiiV2()
{
miiNickname[0] = '\0';
}
nexMiiV2(const char* miiNickname, uint8* miiData)
{
strncpy(this->miiNickname, miiNickname, 127);
this->miiNickname[127] = '\0';
memcpy(this->miiData, miiData, FFL_SIZE);
}
nexMiiV2(nexPacketBuffer* pb)
{
readData(pb);
}
void writeData(nexPacketBuffer* pb) const override
{
pb->writeString(this->miiNickname);
pb->writeU8(0); // ukn
pb->writeU8(0); // ukn
pb->writeBuffer(this->miiData, FFL_SIZE);
pb->writeU64(0); // ukn
}
void readData(nexPacketBuffer* pb) override
{
pb->readString(this->miiNickname, sizeof(this->miiNickname));
this->miiNickname[127] = '\0';
pb->readU8(); // ukn
pb->readU8(); // ukn
memset(miiData, 0, sizeof(miiData));
pb->readBuffer(this->miiData, FFL_SIZE);
pb->readU64(); // ukn
}
public:
uint8 miiData[FFL_SIZE];
char miiNickname[128];
};
class nexPresenceV2 : public nexType
{
public:
nexPresenceV2()
{
}
nexPresenceV2(int ukn)
{
// todo
}
nexPresenceV2(nexPacketBuffer* pb)
{
readData(pb);
}
const char* getMetaName() override
{
return "NintendoPresenceV2";
}
void writeData(nexPacketBuffer* pb) const override
{
pb->writeU32(1); // isValid?
pb->writeU8(isOnline ? 1 : 0);
// gameKey:
pb->writeU64(gameKey.titleId);
pb->writeU16(gameKey.ukn);
pb->writeU8(1); // uint8 ukn3(example value : 1)
pb->writeString("");// String msg(current game ? )
pb->writeU32(joinFlagMask);
pb->writeU8(joinAvailability);
pb->writeU32(gameId);
pb->writeU32(gameMode);
pb->writeU32(hostPid);
pb->writeU32(groupId);
pb->writeBuffer(appSpecificData, sizeof(appSpecificData));
pb->writeU8(3); // ukn
pb->writeU8(1); // ukn
pb->writeU8(3); // ukn
}
void readData(nexPacketBuffer* pb) override
{
ukn0 = pb->readU32();
isOnline = pb->readU8();
gameKey.readData(pb);
ukn3 = pb->readU8();
char msgBuffer[1024];
pb->readString(msgBuffer, sizeof(msgBuffer));
msgBuffer[1023] = '\0';
this->msg = std::string(msgBuffer);
joinFlagMask = pb->readU32();
joinAvailability = pb->readU8();
gameId = pb->readU32();
gameMode = pb->readU32();
hostPid = pb->readU32();
groupId = pb->readU32();
pb->readBuffer(appSpecificData, sizeof(appSpecificData));
ukn11 = pb->readU8();
ukn12 = pb->readU8();
ukn13 = pb->readU8();
}
public:
uint32 ukn0; // seen values: 0 -> offline, 1 -> online (menu, but not always), 8 and 0x1E6 -> in Splatoon
uint8 isOnline;
nexGameKey gameKey;
uint8 ukn3; // message language?
std::string msg;
uint32 joinFlagMask;
uint8 joinAvailability;
uint32 gameId;
uint32 gameMode;
uint32 hostPid;
uint32 groupId;
uint8 appSpecificData[0x14];
uint8 ukn11;
uint8 ukn12;
uint8 ukn13;
};
class nexPrincipalBasicInfo : public nexType
{
public:
nexPrincipalBasicInfo()
{
this->nnid[0] = '\0';
}
nexPrincipalBasicInfo(uint32 principalId, char* nnid, const nexMiiV2& mii)
: principalId(principalId), mii(mii)
{
strcpy(this->nnid, nnid);
}
nexPrincipalBasicInfo(nexPacketBuffer* pb)
{
readData(pb);
}
void writeData(nexPacketBuffer* pb) const override
{
pb->writeU32(principalId);
pb->writeString(this->nnid);
mii.writeData(pb);
pb->writeU8(2); // todo
}
void readData(nexPacketBuffer* pb) override
{
principalId = pb->readU32();
pb->readString(nnid, sizeof(nnid));
mii.readData(pb);
regionGuessed = pb->readU8();
}
public:
uint32 principalId;
char nnid[32];
nexMiiV2 mii;
uint8 regionGuessed;
};
class nexNNAInfo : public nexType
{
public:
nexNNAInfo()
{
}
nexNNAInfo(uint8 countryCode, uint8 countrySubCode, const nexPrincipalBasicInfo& principalBasicInfo)
: countryCode(countryCode), countrySubCode(countrySubCode), principalInfo(principalBasicInfo)
{
}
nexNNAInfo(nexPacketBuffer* pb)
{
readData(pb);
}
void writeData(nexPacketBuffer* pb) const override
{
principalInfo.writeData(pb);
pb->writeU8(countryCode);
pb->writeU8(countrySubCode);
}
void readData(nexPacketBuffer* pb) override
{
principalInfo.readData(pb);
countryCode = pb->readU8();
countrySubCode = pb->readU8();
}
public:
uint8 countryCode;
uint8 countrySubCode;
nexPrincipalBasicInfo principalInfo;
};
class nexPrincipalPreference : public nexType
{
public:
nexPrincipalPreference() = default;
nexPrincipalPreference(uint8 ukn0, uint8 ukn1, uint8 ukn2)
{
this->showOnline = ukn0;
this->showGame = ukn1;
this->blockFriendRequests = ukn2;
}
nexPrincipalPreference(nexPacketBuffer* pb)
{
readData(pb);
}
void writeData(nexPacketBuffer* pb) const override
{
pb->writeU8(showOnline);
pb->writeU8(showGame);
pb->writeU8(blockFriendRequests);
}
void readData(nexPacketBuffer* pb) override
{
showOnline = pb->readU8();
showGame = pb->readU8();
blockFriendRequests = pb->readU8();
}
public:
uint8 showOnline;
uint8 showGame;
uint8 blockFriendRequests;
};
class nexComment : public nexType
{
public:
nexComment()
{
}
nexComment(uint8 todo)
{
cemu_assert_unimplemented();
}
nexComment(nexPacketBuffer* pb)
{
readData(pb);
}
void writeData(nexPacketBuffer* pb) const override
{
pb->writeU8(ukn0);
pb->writeString(commentString.c_str());
pb->writeU64(ukn1);
}
void readData(nexPacketBuffer* pb) override
{
ukn0 = pb->readU8();
char stringBuffer[1024];
pb->readString(stringBuffer, 1024);
stringBuffer[1023] = '\0';
commentString = std::string(stringBuffer);
ukn1 = pb->readU64();
}
public:
uint8 ukn0;
std::string commentString;
uint64 ukn1;
};
class nexFriendRequestMessage : public nexType
{
public:
nexFriendRequestMessage()
{
}
nexFriendRequestMessage(uint8 todo)
{
cemu_assert_unimplemented();
}
nexFriendRequestMessage(nexPacketBuffer* pb)
{
readData(pb);
}
void writeData(nexPacketBuffer* pb) const override
{
cemu_assert_unimplemented();
}
void readData(nexPacketBuffer* pb) override
{
messageId = pb->readU64();
isMarkedAsReceived = pb->readU8();
ukn2 = pb->readU8();
char stringBuffer[1024];
pb->readString(stringBuffer, sizeof(stringBuffer));
stringBuffer[1023] = '\0';
commentStr = std::string(stringBuffer);
ukn4 = pb->readU8();
pb->readString(stringBuffer, sizeof(stringBuffer));
stringBuffer[1023] = '\0';
ukn5Str = std::string(stringBuffer);
gameKey.readData(pb);
ukn7 = pb->readU64();
expireTimestamp = pb->readU64();
}
public:
uint64 messageId;
uint8 isMarkedAsReceived;
uint8 ukn2;
std::string commentStr;
uint8 ukn4;
std::string ukn5Str;
nexGameKey gameKey;
uint64 ukn7;
uint64 expireTimestamp;
};
class nexFriendRequest : public nexType
{
public:
nexFriendRequest()
{
}
nexFriendRequest(uint64 titleId, uint16 ukn)
{
cemu_assert_unimplemented();
}
nexFriendRequest(nexPacketBuffer* pb)
{
readData(pb);
}
const char* getMetaName() override
{
return "FriendRequest";
}
void writeData(nexPacketBuffer* pb) const override
{
cemu_assert_unimplemented();
}
void readData(nexPacketBuffer* pb) override
{
principalInfo.readData(pb);
message.readData(pb);
ukn = pb->readU64();
}
public:
nexPrincipalBasicInfo principalInfo;
nexFriendRequestMessage message;
uint64 ukn;
};
class nexFriend : public nexType
{
public:
nexFriend()
{
}
nexFriend(nexPacketBuffer* pb)
{
readData(pb);
}
const char* getMetaName() override
{
return "FriendInfo";
}
void writeData(nexPacketBuffer* pb) const override
{
cemu_assert_unimplemented();
}
void readData(nexPacketBuffer* pb) override
{
nnaInfo.readData(pb);
presence.readData(pb);
comment.readData(pb);
friendsSinceTimestamp = pb->readU64();
lastOnlineTimestamp = pb->readU64();
ukn6 = pb->readU64();
}
public:
nexNNAInfo nnaInfo;
nexPresenceV2 presence;
nexComment comment;
uint64 friendsSinceTimestamp;
uint64 lastOnlineTimestamp;
uint64 ukn6;
};
class nexBlacklisted : public nexType
{
public:
nexBlacklisted()
{
}
nexBlacklisted(nexPacketBuffer* pb)
{
readData(pb);
}
void writeData(nexPacketBuffer* pb) const override
{
cemu_assert_unimplemented();
}
void readData(nexPacketBuffer* pb) override
{
basicInfo.readData(pb);
gameKey.readData(pb);
ukn = pb->readU64();
}
public:
nexPrincipalBasicInfo basicInfo;
nexGameKey gameKey;
uint64 ukn;
};
class nexPersistentNotification : public nexType
{
public:
nexPersistentNotification()
{
}
nexPersistentNotification(nexPacketBuffer* pb)
{
readData(pb);
}
void writeData(nexPacketBuffer* pb) const override
{
cemu_assert_unimplemented();
}
void readData(nexPacketBuffer* pb) override
{
messageId = pb->readU64();
pid1 = pb->readU32();
pid2 = pb->readU32();
type = pb->readU32();
pb->readStdString(msg);
}
public:
uint64 messageId;
uint32 pid1; // principal id 1 (might differ depending on type)
uint32 pid2; // principal id 2 (might differ depending on type)
uint32 type;
std::string msg;
};
class NexFriends
{
public:
using RpcErrorCode = int; // replace with enum class later
static const int ERR_NONE = 0;
static const int ERR_RPC_FAILED = 1;
static const int ERR_UNEXPECTED_RESULT = 2;
static const int ERR_NOT_CONNECTED = 3;
enum NOTIFICATION_TYPE
{
NOTIFICATION_TYPE_ONLINE = 0,
NOTIFICATION_TYPE_FRIEND_LOGIN = 4,
NOTIFICATION_TYPE_FRIEND_LOGOFF = 5,
NOTIFICATION_TYPE_FRIEND_PRESENCE_CHANGE = 6,
NOTIFICATION_TYPE_ADDED_FRIEND = 9,
NOTIFICATION_TYPE_REMOVED_FRIEND = 10,
NOTIFICATION_TYPE_ADDED_OUTGOING_REQUEST = 11,
NOTIFICATION_TYPE_REMOVED_OUTGOING_REQUEST = 12,
NOTIFICATION_TYPE_ADDED_INCOMING_REQUEST = 17,
NOTIFICATION_TYPE_REMOVED_INCOMING_REQUEST = 18
};
public:
NexFriends(uint32 authServerIp, uint16 authServerPort, const char* accessKey, uint32 pid, const char* nexPassword, const char* nexToken, const char* nnid, uint8* miiData, const wchar_t* miiNickname, uint8 countryCode, nexPresenceV2& myPresence);
~NexFriends();
std::string getAccountNameByPid(uint32 principalId);
int getPendingFriendRequestCount();
bool requestGetAllInformation();
bool addProvisionalFriendByPidGuessed(uint32 principalId);
// synchronous API (returns immediately)
bool requestGetAllInformation(std::function<void(uint32)> cb);
void getFriendPIDs(uint32* pidList, uint32* pidCount, sint32 offset, sint32 count, bool includeFriendRequests);
void getFriendRequestPIDs(uint32* pidList, uint32* pidCount, sint32 offset, sint32 count, bool includeIncoming, bool includeOutgoing);
bool getFriendByPID(nexFriend& friendData, uint32 pid);
bool getFriendRequestByPID(nexFriendRequest& friendRequestData, bool* isIncoming, uint32 searchedPid);
bool getFriendRequestByMessageId(nexFriendRequest& friendRequestData, bool* isIncoming, uint64 messageId);
bool isOnline();
void getMyPreference(nexPrincipalPreference& preference);
void getMyComment(nexComment& comment);
// asynchronous API (data has to be requested)
bool addProvisionalFriend(char* name, std::function<void(RpcErrorCode)> cb);
void addFriendRequest(uint32 pid, const char* comment, std::function<void(RpcErrorCode)> cb);
void requestPrincipleBaseInfoByPID(uint32* pidList, sint32 count, const std::function<void(RpcErrorCode result, std::span<nexPrincipalBasicInfo> basicInfo)>& cb);
void removeFriend(uint32 pid, std::function<void(RpcErrorCode)> cb);
void cancelOutgoingProvisionalFriendRequest(uint32 pid, std::function<void(RpcErrorCode)> cb);
void markFriendRequestsAsReceived(uint64* messageIdList, sint32 count, std::function<void(RpcErrorCode)> cb);
void acceptFriendRequest(uint64 messageId, std::function<void(RpcErrorCode)> cb);
void deleteFriendRequest(uint64 messageId, std::function<void(RpcErrorCode)> cb); // rejecting incoming friend request (differs from blocking friend requests)
bool updatePreferencesAsync(const nexPrincipalPreference newPreferences, std::function<void(RpcErrorCode)> cb);
bool updateCommentAsync(const nexComment newComment, std::function<void(RpcErrorCode)> cb);
void updateMyPresence(nexPresenceV2& myPresence);
void setNotificationHandler(void(*notificationHandler)(NOTIFICATION_TYPE notificationType, uint32 pid));
void update();
void processServerNotification(uint32 notificationType, uint32 pid, nexPacketBuffer* notificationData);
private:
void doAsyncLogin();
void initiateLogin();
static void handleResponse_acceptFriendRequest(nexService* nex, nexServiceResponse_t* response);
static void handleResponse_getAllInformation(nexServiceResponse_t* response, NexFriends* nexFriends, std::function<void(uint32)> cb);
void generateNotification(NOTIFICATION_TYPE notificationType, uint32 pid);
void trackNotifications();
// notification-service handlers
void processServerNotification_friendOffline(uint32 pid);
void processServerNotification_presenceChange(uint32 pid, nexPresenceV2& presence);
void processServerNotification_removeFriendOrFriendRequest(uint32 pid);
void processServerNotification_incomingFriendRequest(uint32 pid, nexFriendRequest& friendRequest);
void processServerNotification_addedFriend(uint32 pid, nexFriend& frd);
private:
void(*notificationHandler)(NOTIFICATION_TYPE notificationType, uint32 pid);
bool isCurrentlyConnected;
bool hasData; // set after connect when information request response was received
bool firstInformationRequest;
nexService* nexCon;
uint8 miiData[FFL_SIZE];
std::string miiNickname;
char nnid[96];
uint32 pid;
uint8 countryCode;
// login tracking
std::recursive_mutex mtx_login;
bool loginInProcess;
uint32 lastLoginAttemptTime;
uint32 numFailedLogins;
uint32 numSuccessfulLogins;
// auth
struct
{
uint32 serverIp;
uint16 port;
std::string accessKey;
std::string nexPassword;
std::string nexToken;
}auth;
// local friend state
nexPresenceV2 myPresence;
nexPrincipalPreference myPreference;
nexComment myComment;
std::recursive_mutex mtx_lists;
std::vector<nexFriend> list_friends;
std::vector<nexFriendRequest> list_friendReqOutgoing;
std::vector<nexFriendRequest> list_friendReqIncoming;
struct
{
std::vector<nexFriend> list_friends;
std::vector<nexFriendRequest> list_friendReqOutgoing;
std::vector<nexFriendRequest> list_friendReqIncoming;
}previousState;
};
| 14,679
|
C++
|
.h
| 553
| 24.20434
| 246
| 0.768431
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,424
|
nex.h
|
cemu-project_Cemu/src/Cemu/nex/nex.h
|
#pragma once
#include "nexTypes.h"
#include<mutex>
const int NEX_PROTOCOL_AUTHENTICATION = 0xA;
const int NEX_PROTOCOL_SECURE = 0xB;
const int NEX_PROTOCOL_FRIENDS_WIIU = 0x66;
class nexService;
typedef struct
{
nexService* nex;
bool isSuccessful;
uint32 errorCode;
uint32 callId;
uint32 methodId;
uint8 protocolId;
nexPacketBuffer data;
void* custom;
}nexServiceResponse_t;
typedef struct
{
nexService* nex;
uint32 callId;
uint32 methodId;
uint8 protocolId;
nexPacketBuffer data;
void* custom;
}nexServiceRequest_t;
class prudpClient;
class nexService
{
private:
typedef struct
{
uint8 protocolId;
uint32 methodId;
uint32 callId;
void(*nexServiceResponse)(nexService* nex, nexServiceResponse_t* serviceResponse);
void* custom;
bool handleError; // if set to true, call nexServiceResponse with errorCode set (else the callback is skipped when the call is not successful)
uint32 requestTime; // timestamp of when the request was sent
// alternative callback handler
std::function<void(nexServiceResponse_t*)> cb2;
}nexActiveRequestInfo_t;
typedef struct
{
uint8 protocolId;
uint32 methodId;
bool callHandlerIfError;
//nexPacketBuffer* parameter;
std::vector<uint8> parameterData;
void(*nexServiceResponse)(nexService* nex, nexServiceResponse_t* serviceResponse);
void* custom;
// alternative callback handler
std::function<void(nexServiceResponse_t*)> cb2;
}queuedRequest_t;
typedef struct
{
uint8 protocol;
void(*processRequest)(nexServiceRequest_t* request);
void* custom;
}protocolHandler_t;
public:
static const int STATE_CONNECTING = 0;
static const int STATE_CONNECTED = 1;
static const int STATE_DISCONNECTED = 2;
static const unsigned int ERR_TIMEOUT = (0xFFFFFFFF);
static const unsigned int ERR_NO_CONNECTION = (0xFFFFFFFE);
nexService(prudpClient* con);
nexService(uint32 ip, uint16 port, const char* accessKey);
const uint8 PROTOCOL_BIT_REQUEST = 0x80;
void callMethod(uint8 protocolId, uint32 methodId, nexPacketBuffer* parameter, void(*nexServiceResponse)(nexService* nex, nexServiceResponse_t* serviceResponse), void* custom, bool callHandlerIfError = false);
void callMethod(uint8 protocolId, uint32 methodId, nexPacketBuffer* parameter, std::function<void(nexServiceResponse_t*)> cb, bool callHandlerIfError);
void registerProtocolRequestHandler(uint8 protocol, void(*processRequest)(nexServiceRequest_t* request), void* custom);
void sendRequestResponse(nexServiceRequest_t* request, uint32 errorCode, uint8* data, sint32 length);
void update();
prudpClient* getPRUDPConnection();
sint32 getState();
void registerForAsyncProcessing();
void destroy();
bool isMarkedForDestruction();
private:
nexService();
~nexService();
void updateTemporaryConnections();
void updateNexServiceConnection();
void processQueuedRequest(queuedRequest_t* queuedRequest);
private:
//bool serviceIsConnected;
uint8 connectionState;
prudpClient* conNexService;
bool isAsync;
bool isDestroyed; // if set, delete object asynchronously
std::vector<nexActiveRequestInfo_t> list_activeRequests;
// protocol request handlers
std::vector<protocolHandler_t> list_requestHandlers;
// packet buffer
std::vector<uint8> bufferReceive;
// auth
bool isSecureService;
// request queue
std::mutex mtx_queuedRequests;
std::vector<queuedRequest_t> queuedRequests;
};
nexService* nex_establishSecureConnection(uint32 authServerIp, uint16 authServerPort, const char* accessKey, uint32 pid, const char* nexPassword, const char* nexToken);
| 3,531
|
C++
|
.h
| 104
| 31.807692
| 210
| 0.803985
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,425
|
DiscordPresence.h
|
cemu-project_Cemu/src/Cemu/DiscordPresence/DiscordPresence.h
|
#pragma once
#ifdef ENABLE_DISCORD_RPC
class DiscordPresence
{
public:
enum State
{
Idling,
Playing,
};
DiscordPresence();
~DiscordPresence();
void UpdatePresence(State state, const std::string& text = {}) const;
void ClearPresence() const;
};
#endif
| 267
|
C++
|
.h
| 16
| 14.6875
| 70
| 0.760163
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,426
|
ExpressionParser.h
|
cemu-project_Cemu/src/Cemu/ExpressionParser/ExpressionParser.h
|
#pragma once
#include "Common/precompiled.h"
#include <string>
#include <queue>
#include <stack>
#include <unordered_map>
#include <memory>
#include <charconv>
#include "boost/functional/hash_fwd.hpp"
#include <fmt/format.h>
#ifdef __clang__
#include "Common/unix/fast_float.h"
#define _EP_FROM_CHARS_DBL(...) _convFastFloatResult(fast_float::from_chars(__VA_ARGS__))
inline std::from_chars_result _convFastFloatResult(fast_float::from_chars_result r)
{
std::from_chars_result nr;
nr.ptr = r.ptr;
nr.ec = r.ec;
return nr;
}
#else
#define _EP_FROM_CHARS_DBL(...) std::from_chars(__VA_ARGS__)
#endif
template<class TType = double>
class TExpressionParser
{
public:
static_assert(std::is_arithmetic_v<TType>);
using ConstantCallback_t = TType(*)(std::string_view var_name);
using FunctionCallback_t = TType(*)(std::string_view var_name, TType parameter);
template<typename T>
T Evaluate(std::string_view expression) const
{
static_assert(std::is_arithmetic<T>::value, "type T must be an arithmetic type");
return (T)Evaluate(expression);
}
[[nodiscard]] TType Evaluate(std::string_view expression) const
{
std::queue<std::shared_ptr<TokenBase>> output;
std::stack<std::shared_ptr<TokenBase>> operators;
if (expression.empty())
{
throw std::runtime_error(fmt::format("empty expression is not allowed"));
}
bool last_operator_token = true;
// tokenize and apply shunting-yard
for (size_t i = 0; i < expression.size(); )
{
const char c = expression[i];
// skip whitespaces
if (isblank(c))
{
++i;
continue;
}
// extract numbers
if (isdigit(c) || (last_operator_token && (c == '-' || c == '+')))
{
const std::string_view view(expression.data() + i, expression.size() - i);
size_t offset = 0;
auto converted = (TType)ConvertString(view, &offset);
output.emplace(std::make_shared<TokenNumber>(converted));
i += offset;
last_operator_token = false;
continue;
}
// check for variables
if (isalpha(c) || c == '_' || c == '$')
{
size_t j;
for (j = i + 1; j < expression.size(); ++j)
{
const char v = expression[j];
if (!isalpha(v) && !isdigit(v) && v != '_' && v != '@' && v != '.')
{
break;
}
}
const size_t len = j - i;
const std::string_view view = expression.substr(i, len);
// check for function
if (m_function_callback)
{
// todo skip whitespaces
if (j < expression.size() && expression[j] == '(')
{
operators.emplace(std::make_shared<TokenUnaryOperator>(TokenUnaryOperator::kFunction, view));
operators.emplace(std::make_shared<TokenParenthese>());
i += len + 1;
last_operator_token = true;
continue;
}
}
TType value;
const auto it = m_constants.find(std::string{ view });
if (it == m_constants.cend())
{
if (m_constant_callback == nullptr)
throw std::runtime_error(fmt::format("unknown constant found \"{}\" in expression: {}", view, expression));
value = m_constant_callback(view);
}
else
value = it->second;
output.emplace(std::make_shared<TokenNumber>(value));
i += len;
last_operator_token = false;
continue;
}
// parenthese
if (c == '(')
{
operators.emplace(std::make_shared<TokenParenthese>());
++i;
last_operator_token = true;
continue;
}
if (c == ')')
{
bool match = false;
while (!operators.empty())
{
const auto op = std::dynamic_pointer_cast<TokenParenthese>(operators.top());
if (!op)
{
output.emplace(operators.top());
operators.pop();
continue;
}
operators.pop();
match = true;
break;
}
if (!match && operators.empty())
{
throw std::runtime_error(fmt::format("parentheses mismatch: {}", expression));
}
++i;
continue;
}
// supported operations
std::shared_ptr<TokenOperator> operator_token;
switch (c)
{
case '+':
operator_token = std::make_shared<TokenOperator>(TokenOperator::kAddition, 2);
break;
case '-':
operator_token = std::make_shared<TokenOperator>(TokenOperator::kSubtraction, 2);
break;
case '*':
operator_token = std::make_shared<TokenOperator>(TokenOperator::kMultiplication, 3);
break;
case '/':
operator_token = std::make_shared<TokenOperator>(TokenOperator::kDivision, 3);
break;
case '^':
operator_token = std::make_shared<TokenOperator>(TokenOperator::kPow, 4, true);
break;
case '%':
operator_token = std::make_shared<TokenOperator>(TokenOperator::kModulo, 3);
break;
case '=':
if ((i + 1) < expression.size() && expression[i + 1] == '=')
{
operator_token = std::make_shared<TokenOperator>(TokenOperator::kEqual, 1);
++i;
}
break;
case '!':
if ((i + 1) < expression.size() && expression[i + 1] == '=')
{
operator_token = std::make_shared<TokenOperator>(TokenOperator::kNotEqual, 1);
++i;
}
break;
case '<':
if ((i + 1) < expression.size() && expression[i + 1] == '=')
{
operator_token = std::make_shared<TokenOperator>(TokenOperator::kLessOrEqual, 1);
++i;
}
else
{
operator_token = std::make_shared<TokenOperator>(TokenOperator::kLessThan, 1);
}
break;
case '>':
if ((i + 1) < expression.size() && expression[i + 1] == '=')
{
operator_token = std::make_shared<TokenOperator>(TokenOperator::kGreaterOrEqual, 1);
++i;
}
else
{
operator_token = std::make_shared<TokenOperator>(TokenOperator::kGreaterThan, 1);
}
break;
}
if (!operator_token)
throw std::runtime_error(fmt::format("invalid operator found in expression: {}", expression));
while (!operators.empty())
{
const auto op = std::dynamic_pointer_cast<TokenOperator>(operators.top());
if (op && ((!operator_token->right_ass && operator_token->prec <= op->prec) || (operator_token->right_ass && operator_token->prec < op->prec)))
{
output.emplace(operators.top());
operators.pop();
continue;
}
break;
}
operators.emplace(operator_token);
++i;
last_operator_token = true;
}
while (!operators.empty())
{
const auto parenthese = std::dynamic_pointer_cast<TokenParenthese>(operators.top());
if (parenthese)
{
throw std::runtime_error(fmt::format("parentheses mismatch in expression: {}", expression));
}
output.push(operators.top());
operators.pop();
}
// evaluate tokens in output queue
std::stack<TType> evaluation;
while (!output.empty())
{
const auto number = std::dynamic_pointer_cast<TokenNumber>(output.front());
if (number)
{
evaluation.emplace(number->number);
output.pop();
continue;
}
if (const auto unop = std::dynamic_pointer_cast<TokenUnaryOperator>(output.front()))
{
if (evaluation.size() < 1)
throw std::runtime_error("not enough parameters for equation");
const auto parameter = evaluation.top();
evaluation.pop();
switch (unop->op)
{
case TokenUnaryOperator::kFunction:
evaluation.emplace(m_function_callback(unop->symbol, parameter));
break;
default:
throw std::runtime_error("unsupported operation constant");
}
output.pop();
continue;
}
else if (const auto op = std::dynamic_pointer_cast<TokenOperator>(output.front()))
{
if (evaluation.size() < 2)
throw std::runtime_error("not enough parameters for equation");
const auto rhs = evaluation.top();
evaluation.pop();
const auto lhs = evaluation.top();
evaluation.pop();
switch (op->op)
{
case TokenOperator::kAddition:
evaluation.emplace(lhs + rhs);
break;
case TokenOperator::kSubtraction:
evaluation.emplace(lhs - rhs);
break;
case TokenOperator::kMultiplication:
evaluation.emplace(lhs * rhs);
break;
case TokenOperator::kDivision:
if (rhs == 0.0) evaluation.emplace((TType)0.0);
else evaluation.emplace(lhs / rhs);
break;
case TokenOperator::kPow:
evaluation.emplace((TType)std::pow(lhs, rhs));
break;
case TokenOperator::kModulo:
if (std::round(rhs) == 0.0)
evaluation.emplace((TType)0.0);
else
evaluation.emplace((TType)((sint64)std::round(lhs) % (sint64)std::round(rhs)));
break;
case TokenOperator::kEqual:
if constexpr (std::is_floating_point_v<TType>)
evaluation.emplace((TType)(std::abs(lhs - rhs) <= 0.0000000001 ? 1 : 0));
else
evaluation.emplace(lhs == rhs ? 1 : 0);
break;
case TokenOperator::kNotEqual:
if constexpr (std::is_floating_point_v<TType>)
evaluation.emplace((TType)(std::abs(lhs - rhs) > 0.0000000001 ? 1 : 0));
else
evaluation.emplace(lhs != rhs ? 1 : 0);
break;
case TokenOperator::kLessThan:
evaluation.emplace((TType)(lhs < rhs ? 1 : 0));
break;
case TokenOperator::kLessOrEqual:
evaluation.emplace((TType)(lhs <= rhs ? 1 : 0));
break;
case TokenOperator::kGreaterThan:
evaluation.emplace((TType)(lhs > rhs ? 1 : 0));
break;
case TokenOperator::kGreaterOrEqual:
evaluation.emplace((TType)(lhs >= rhs ? 1 : 0));
break;
default:
throw std::runtime_error("unsupported operation constant");
}
output.pop();
continue;
}
}
return evaluation.top();
}
[[nodiscard]] bool IsValidExpression(std::string_view expression) const
{
try
{
TExpressionParser<TType> ep;
ep.AddConstantCallback(
[](std::string_view sv) -> TType
{
return (TType)1;
});
static_cast<void>(ep.Evaluate(expression));
return true;
}
catch (...)
{
return false;
}
}
[[nodiscard]] bool IsConstantExpression(std::string_view expression) const
{
try
{
static_cast<void>(this->Evaluate(expression));
return true;
}
catch (...)
{
return false;
}
}
void AddConstant(std::string_view name, TType value)
{
m_constants[std::string(name)] = value;
}
// only adds constant if not added yet
void TryAddConstant(std::string_view name, TType value)
{
m_constants.try_emplace(std::string{ name }, value);
}
void AddConstant(std::string_view name, std::string_view value)
{
AddConstant(name, ConvertString(value));
}
void AddConstantCallback(ConstantCallback_t callback)
{
m_constant_callback = callback;
}
void SetFunctionCallback(FunctionCallback_t callback)
{
m_function_callback = callback;
}
private:
std::unordered_map<std::string, TType> m_constants;
ConstantCallback_t m_constant_callback = nullptr;
FunctionCallback_t m_function_callback = nullptr;
static bool _isNumberWithDecimalPoint(std::string_view str)
{
return str.find('.') != std::string_view::npos;
}
double ConvertString(std::string_view str, size_t* index_after = nullptr) const
{
const char* strInitial = str.data();
if (str.empty())
throw std::runtime_error("can't parse empty number");
double result;
std::from_chars_result chars_result;
const bool is_negative = str[0] == '-';
if (is_negative || str[0] == '+')
str = str.substr(1);
if (str.size() >= 3 && str[0] == '0' && tolower(str[1]) == 'x')
{
str = str.substr(2);
// find end of number
const auto end = std::find_if_not(str.cbegin(), str.cend(), isxdigit);
int64_t tmp;
chars_result = std::from_chars(str.data(), str.data() + std::distance(str.cbegin(), end), tmp, 16);
result = (double)tmp;
}
// a number prefixed with 0 and no decimal point is considered a hex number
else if (str.size() >= 2 && str[0] == '0' && isxdigit(str[1]) && !_isNumberWithDecimalPoint(str))
{
str = str.substr(1);
// find end of number
const auto end = std::find_if_not(str.cbegin(), str.cend(), isxdigit);
int64_t tmp;
chars_result = std::from_chars(str.data(), str.data() + std::distance(str.cbegin(), end), tmp, 16);
result = (double)tmp;
}
else
{
if (str[0] == '+')
str = str.substr(1);
bool has_point = false;
bool has_exponent = false;
const auto end = std::find_if_not(str.cbegin(), str.cend(),
[&has_point, &has_exponent](char c) -> bool
{
if (isdigit(c))
return true;
if (c == '.' && !has_point)
{
has_point = true;
return true;
}
if (tolower(c) == 'e' && !has_exponent)
{
has_exponent = true;
// TODO: after exponent might be + and - allowed?
return true;
}
return false;
});
chars_result = _EP_FROM_CHARS_DBL(str.data(), str.data() + std::distance(str.cbegin(), end), result);
}
if (chars_result.ec == std::errc())
{
if (index_after)
*index_after = chars_result.ptr - strInitial;
if (is_negative)
result *= -1.0;
return result;
}
else
throw std::runtime_error(fmt::format("can't parse number: {}", str));
}
struct TokenBase
{
virtual ~TokenBase() = default;
};
struct TokenUnaryOperator : TokenBase
{
enum Operator
{
kFunction,
};
TokenUnaryOperator(Operator op) : op(op) {}
TokenUnaryOperator(Operator op, std::string_view symbol) : op(op), symbol(symbol) {}
Operator op;
std::string_view symbol;
};
struct TokenOperator : TokenBase
{
enum Operator
{
kAddition,
kSubtraction,
kMultiplication,
kDivision,
kPow,
kModulo,
kEqual,
kNotEqual,
kLessThan,
kLessOrEqual,
kGreaterThan,
kGreaterOrEqual,
};
TokenOperator(Operator op, int prec, bool right_ass = false) : op(op), prec(prec), right_ass(right_ass) {}
Operator op;
int prec;
bool right_ass;
};
struct TokenParenthese : TokenBase {};
struct TokenNumber : TokenBase
{
TokenNumber(TType number) : number(number) {}
TType number;
};
};
class ExpressionParser : public TExpressionParser<double> {};
void ExpressionParser_test();
| 13,832
|
C++
|
.h
| 489
| 23.981595
| 147
| 0.645436
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.