first commit

This commit is contained in:
ClansChen committed 2022-04-14 14:20:32 +08:00
commit a61351d928
76 files changed
+13794

No files matched your search

+1
View File
@@ -0,0 +1 @@
build/
+23
View File
@@ -0,0 +1,23 @@
{
"configurations": [
{
"name": "Win32",
"includePath": [
"${workspaceFolder}/**",
"${vcpkgRoot}/x86-windows-static/include"
],
"defines": [
"_DEBUG",
"UNICODE",
"_UNICODE"
],
"windowsSdkVersion": "10.0.22000.0",
"compilerPath": "C:/Program Files/Microsoft Visual Studio/2022/Community/VC/Tools/MSVC/14.31.31103/bin/Hostx64/x86/cl.exe",
"cStandard": "c17",
"cppStandard": "c++20",
"intelliSenseMode": "windows-msvc-x86",
"configurationProvider": "ms-vscode.cmake-tools"
}
],
"version": 4
}
+27
View File
@@ -0,0 +1,27 @@
cmake_minimum_required(VERSION 3.15.0)
cmake_policy(SET CMP0079 NEW)
set(CMAKE_CXX_STANDARD 20)
set(VCPKG_TARGET_TRIPLET "x86-windows-static")
set(CMAKE_GENERATOR_PLATFORM "Win32")
project(gta4_chs)
if(MSVC)
set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>$<$<CONFIG:Debug>:DLL>")
include("VC-LTL helper for cmake.cmake")
endif()
file(GLOB common_sources "common/*.cpp")
find_package(utf8cpp CONFIG REQUIRED)
find_package(range-v3 CONFIG REQUIRED)
find_package(ZLIB REQUIRED)
add_subdirectory(gta4.chs)
add_subdirectory(gxt_tool)
add_subdirectory(whm_io)
target_link_libraries(gta4.chs PRIVATE utf8cpp range-v3 range-v3-meta range-v3::meta range-v3-concepts ZLIB::ZLIB)
target_link_libraries(gxt_tool PRIVATE utf8cpp range-v3 range-v3-meta range-v3::meta range-v3-concepts ZLIB::ZLIB)
target_link_libraries(whm_io PRIVATE utf8cpp range-v3 range-v3-meta range-v3::meta range-v3-concepts ZLIB::ZLIB)
+44
View File
@@ -0,0 +1,44 @@
-----------issue list-----------
将全角空格当成空格?
字库塞不下的话,将字块高度改为65px
能否解决'Game'菜单项不亮的问题
5D6D57:
xmm1: 链接区域w
xmm3: 链接区域h
xmm4: 链接区域y
xmm5: 链接区域x
xmm6: 鼠标y
xmm7: 鼠标x
EBK25: 0x46263DB3 & 0x2F5B101D
第二段有一个行首超链接无效
链接位置x坐标跑到上一段的空白去了
但是绘制位置是在下一行
跟gta_html最后两个hook有关,大概要额外的数值判断
将没问题的网址替换成纯文本方便测试
无效:
xmm1: -378.788
xmm3: 15.0047
xmm4: 120.019
xmm5: 58
xmm6: 129.701
xmm7: 76.9347
有效:
xmm1: 45.3375
xmm3: 15.0047
xmm4: 90.0094
xmm5: 78.475
xmm6: 129.701
xmm7: 76.9347
R6AUD: 0x7555CEB7 字幕不居中
MAIN: 0x9899E5EE
考虑迁移成cmake+vscode+vcpkg项目
+8
View File
@@ -0,0 +1,8 @@
适用于GTA4三合一版本(1.2.0.43)的汉化程序<br/><br/>
[汉化项目网站](https://b9348.gitee.io)<br/><br/>
依赖库<br/>
[char8_t-remediation](https://github.com/tahonermann/char8_t-remediation)<br/><br/>
[VC-LTL](https://github.com/Chuyu-Team/VC-LTL5)<br/><br/>
[Vcpkg](https://github.com/microsoft/vcpkg)<br/>
[utfcpp(Vcpkg)](https://github.com/nemtrif/utfcpp)<br/>
[range-v3(Vcpkg)](https://github.com/ericniebler/range-v3)<br/>
+88
View File
@@ -0,0 +1,88 @@
cmake_minimum_required(VERSION 3.5.2)
#
# VC-LTL自动化加载配置,建议你将此文件单独复制到你的工程再使用,该文件能自动识别当前环境是否存在VC-LTL,并且自动应用。
#
# 使用方法:
# 1. 在“CMakeLists.txt” 添加 “include("VC-LTL helper for cmake.cmake")”。
#
# VC-LTL默认搜索顺序
# 1. “VC-LTL helper for cmake.cmake”所在根目录,即 ${CMAKE_CURRENT_LIST_DIR}
# 2. 当前CMake根目录,即 ${CMAKE_CURRENT_SOURCE_DIR}/VC-LTL
# 3. 当前项目根目录,即 ${PROJECT_SOURCE_DIR}/VC-LTL
# 4. 当前CMake父目录,即 ${CMAKE_CURRENT_SOURCE_DIR}/../VC-LTL
# 5. 当前项目根目录,即 ${PROJECT_SOURCE_DIR}/../VC-LTL
# 6. 注册表HKEY_CURRENT_USER\Code\VC-LTL@Root
#
# 把VC-LTL放在其中一个位置即可,VC-LTL就能被自动引用。
#
# 如果你对默认搜索顺序不满,你可以修改此文件。你也可以直接指定${VC_LTL_Root}宏更加任性的去加载VC-LTL。
#
#####################################################################VC-LTL设置#####################################################################
#控制TargetPlatform版本,目前可用版本为5.1.2600.0 6.0.6000.0(默认) 6.2.9200.0 10.0.10240.0 10.0.19041.0
#set(WindowsTargetPlatformMinVersion "10.0.10240.0")
#启用干净的导入表,消除 ucrt apiset(如:api-ms-win-crt-time-l1-1-0.dll),满足强迫症患者。
#set(CleanImport "true")
####################################################################################################################################################
if(NOT VC_LTL_Root)
if(EXISTS ${CMAKE_CURRENT_LIST_DIR}/_msvcrt.h)
set(VC_LTL_Root ${CMAKE_CURRENT_LIST_DIR})
endif()
endif()
if(NOT VC_LTL_Root)
if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/VC-LTL/_msvcrt.h)
set(VC_LTL_Root ${CMAKE_CURRENT_SOURCE_DIR}/VC-LTL)
endif()
endif()
if(NOT VC_LTL_Root)
if(EXISTS ${PROJECT_SOURCE_DIR}/VC-LTL/_msvcrt.h)
set(VC_LTL_Root ${PROJECT_SOURCE_DIR}/VC-LTL)
endif()
endif()
if(NOT VC_LTL_Root)
if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/../VC-LTL/_msvcrt.h)
set(VC_LTL_Root ${CMAKE_CURRENT_SOURCE_DIR}/../VC-LTL)
endif()
endif()
if(NOT VC_LTL_Root)
if(EXISTS ${PROJECT_SOURCE_DIR}/../VC-LTL/_msvcrt.h)
set(VC_LTL_Root ${PROJECT_SOURCE_DIR}/../VC-LTL)
endif()
endif()
if(NOT VC_LTL_Root)
EXECUTE_PROCESS(COMMAND reg query "HKEY_CURRENT_USER\\Code\\VC-LTL" -v "Root"
OUTPUT_VARIABLE FOUND_FILE
ERROR_VARIABLE ERROR_INFO
)
string(REGEX MATCH "[a-zA-Z]:\\\\.+\\\\"
FOUND_LTL
${FOUND_FILE})
if (NOT ${FOUND_LTL} STREQUAL "")
set(VC_LTL_Root ${FOUND_LTL})
endif()
if(NOT DEFINED VC_LTL_Root)
string(REGEX MATCH "\\\\\\\\.+\\\\" FOUND_LTL ${FOUND_FILE})
if (NOT ${FOUND_LTL} STREQUAL "")
set(VC_LTL_Root ${FOUND_LTL})
endif()
endif()
endif()
if(VC_LTL_Root)
include("${VC_LTL_Root}\\config\\config.cmake")
endif()
+221
View File
@@ -0,0 +1,221 @@
#pragma once
#include <cstddef>
#include <filesystem>
#include <cstdio>
#include <type_traits>
#include <vector>
class BinaryFile
{
public:
template <typename Elem, typename Ret>
using tElemTrait = std::enable_if_t<std::is_trivially_copyable_v<Elem>, Ret>;
BinaryFile() :m_pFile(nullptr) {}
~BinaryFile() { Close(); }
BinaryFile(const BinaryFile&) = delete;
BinaryFile& operator=(const BinaryFile&) = delete;
BinaryFile(BinaryFile&& rv) noexcept
:BinaryFile()
{
std::exchange(m_pFile, rv.m_pFile);
}
BinaryFile& operator=(BinaryFile&& rv) noexcept
{
Close();
std::exchange(m_pFile, rv.m_pFile);
return *this;
}
BinaryFile(const std::filesystem::path& filename, const char* mode)
:BinaryFile()
{
Open(filename, mode);
}
bool Open(const std::filesystem::path& filename, const char* mode)
{
Close();
m_pFile = std::fopen(filename.string().c_str(), mode);
return (m_pFile != nullptr);
}
void Close()
{
if (m_pFile != nullptr)
{
std::fclose(m_pFile);
m_pFile = nullptr;
}
}
bool Opened() const
{
return m_pFile != nullptr;
}
operator bool() const
{
return Opened();
}
BinaryFile& Seek(long offset, int mode)
{
fseek(m_pFile, offset, mode);
return *this;
}
long Tell() const
{
return ftell(m_pFile);
}
BinaryFile& Read(void* buffer, std::size_t size)
{
std::fread(buffer, size, 1, m_pFile);
return *this;
}
template <typename T>
tElemTrait<T, BinaryFile&> Read(T& object)
{
Read(&object, sizeof(object));
return *this;
}
//读取到内置数组
template <typename T, std::size_t C>
tElemTrait<T, BinaryFile&> ReadArray(T(&arr)[C])
{
Read(arr, sizeof(T) * C);
return *this;
}
//读取到std::array
template <typename T, std::size_t C>
tElemTrait<T, BinaryFile&> ReadArray(std::array<T, C>& objects)
{
Read(objects.data(), sizeof(T) * C);
return *this;
}
//读取指定大小到vector
template <typename T>
tElemTrait<T, BinaryFile&> ReadArray(std::size_t count, std::vector<T>& objects)
{
objects.resize(count);
Read(objects.data(), sizeof(T) * count);
return *this;
}
//读取到已经分配好内存的vector
template <typename T>
tElemTrait<T, BinaryFile&> ReadArray(std::vector<T>& objects)
{
Read(objects.data(), sizeof(T) * objects.size());
return *this;
}
//读取到span
template <typename T>
tElemTrait<T, BinaryFile&> ReadArray(std::span<T>& objects)
{
Read(objects.data(), sizeof(T) * objects.size());
return *this;
}
template <typename T>
tElemTrait<T, BinaryFile&> ReadArray2(std::vector<T>& objects)
{
std::size_t count;
Read(count);
ReadArray(count, objects);
return *this;
}
BinaryFile& Write(const void* buffer, std::size_t size)
{
std::fwrite(buffer, size, 1, m_pFile);
return *this;
}
template <typename T>
tElemTrait<T, BinaryFile&> Write(const T& object)
{
Write(&object, sizeof(object));
return *this;
}
//内置数组
template <typename T, std::size_t C>
tElemTrait<T, BinaryFile&> WriteArray(T(&arr)[C])
{
Write(arr, sizeof(T) * C);
return *this;
}
//std::array
template <typename T, std::size_t C>
tElemTrait<T, BinaryFile&> WriteArray(const std::array<T, C>& arr)
{
Write(arr, sizeof(T) * C);
return *this;
}
//std::vector
template <typename T>
tElemTrait<T, BinaryFile&> WriteArray(const std::vector<T>& objects)
{
Write(objects.data(), sizeof(T) * objects.size());
return *this;
}
//span
template <typename T>
tElemTrait<T, BinaryFile&> WriteArray(const std::span<T>& objects)
{
Write(objects.data(), sizeof(T) * objects.size());
return *this;
}
template <typename T, std::size_t C>
tElemTrait<T, BinaryFile&> WriteArray2(T(&arr)[C])
{
Write(C);
WriteArray(arr);
return *this;
}
template <typename T, std::size_t C>
tElemTrait<T, BinaryFile&> WriteArray2(const std::array<T, C>& arr)
{
Write(C);
WriteArray(arr);
return *this;
}
template <typename T>
tElemTrait<T, BinaryFile&> WriteArray2(const std::vector<T>& objects)
{
Write(objects.size());
WriteArray(objects);
return *this;
}
template <typename T>
tElemTrait<T, BinaryFile&> WriteArray2(const std::span<T>& objects)
{
Write(objects.size());
WriteArray(objects);
return *this;
}
private:
std::FILE* m_pFile;
};
+202
View File
@@ -0,0 +1,202 @@
#pragma once
#include "BinaryFile.hpp"
#include <vector>
#include <optional>
#include <stdexcept>
class MemoryFile
{
public:
typedef std::vector<unsigned char> buffer_type;
//从物理文件构造
MemoryFile(const std::filesystem::path& filename)
{
Load(filename);
}
//从缓冲区构造
MemoryFile(const buffer_type& buffer)
{
Create(buffer);
}
//从缓冲区构造
MemoryFile(buffer_type&& buffer)
{
Create(std::move(buffer));
}
//从缓冲区创建
void Create(const buffer_type& buffer)
{
m_bytes_opt = buffer;
m_file_pointer = 0;
}
//从缓冲区创建
void Create(buffer_type&& buffer)
{
m_bytes_opt = std::move(buffer);
m_file_pointer = 0;
}
//创建指定大小的文件
void Create(long size)
{
if (!m_bytes_opt.has_value())
m_bytes_opt.emplace(size);
m_bytes_opt->resize(size);
m_file_pointer = 0;
}
//读物理文件
bool Load(const std::filesystem::path& filename)
{
BinaryFile binary(filename.string().c_str(), "rb");
if (binary)
{
binary.Seek(0, SEEK_END);
auto size = binary.Tell();
limit_offset(size);
binary.Seek(0, SEEK_SET);
buffer_type buffer;
buffer.reserve(s_max_file_size);
buffer.resize(size);
binary.Read(buffer.data(), size);
m_bytes_opt.emplace(std::move(buffer));
m_file_pointer = 0;
}
return binary;
}
//写物理文件
void Dump(const std::filesystem::path& filename)
{
if (!Opened())
{
return;
}
BinaryFile file(filename, "rb");
if (!file)
return;
file.Write(m_bytes_opt->data(), m_bytes_opt->size());
}
void Close()
{
m_bytes_opt.reset();
}
bool Opened() const
{
return m_bytes_opt.has_value();
}
operator bool() const
{
return Opened();
}
MemoryFile& Seek(long offset, int mode)
{
switch (mode)
{
case SEEK_SET:
m_file_pointer = offset;
break;
case SEEK_END:
m_file_pointer = m_bytes_opt->size() + offset;
break;
case SEEK_CUR:
m_file_pointer += offset;
break;
default:
throw std::invalid_argument("Invalid seek method.");
break;
}
//Seek之后文件有可能变大
try_expand(m_file_pointer);
return *this;
}
long Tell() const
{
return m_file_pointer;
}
MemoryFile& Read(void* buffer, std::size_t size)
{
limit_offset(m_file_pointer + size);
std::memcpy(buffer, m_bytes_opt->data() + size, size);
return *this;
}
template <typename T>
std::enable_if_t<std::is_trivially_copyable_v<T>, MemoryFile&> Read(T& object)
{
Read(&object, sizeof(object));
return *this;
}
template <typename T>
std::enable_if_t<std::is_trivially_copyable_v<T>, MemoryFile&> ReadArray(std::size_t count, std::vector<T>& objects)
{
objects.resize(count);
Read(objects.data(), sizeof(T) * count);
return *this;
}
MemoryFile& Write(const void* buffer, std::size_t size)
{
//写文件有可能导致文件变大
try_expand(m_file_pointer + size);
std::memcpy(m_bytes_opt->data() + m_file_pointer, buffer, size);
return *this;
}
template <typename T>
std::enable_if_t<std::is_trivially_copyable_v<T>, MemoryFile&> Write(const T& object)
{
Write(&object, sizeof(object));
return *this;
}
template <typename T>
std::enable_if_t<std::is_trivially_copyable_v<T>, MemoryFile&> WriteArray(const std::vector<T>& objects)
{
Write(objects.data(), sizeof(T) * objects.size());
return *this;
}
private:
static constexpr long s_max_file_size = 104857600; //100MB
void limit_offset(long offset) const
{
if (offset < 0 || offset > s_max_file_size)
throw std::out_of_range("Invalid file offset.");
}
void try_expand(long size)
{
limit_offset(size);
if (static_cast<long>(m_bytes_opt->size()) < size)
m_bytes_opt->resize(size);
}
std::optional<std::vector<unsigned char>> m_bytes_opt;
long m_file_pointer = 0;
};
+186
View File
@@ -0,0 +1,186 @@
// Copyright (c) 2019, Tom Honermann
//
// This file is distributed under the MIT License. See the accompanying file
// LICENSE.txt or http://www.opensource.org/licenses/mit-license.php for terms
// and conditions.
#ifndef CHAR8_T_REMEDIATION_HPP // {
#define CHAR8_T_REMEDIATION_HPP
#include <algorithm>
#include <string>
#include <utility>
#if defined(__cpp_char8_t) // {
#if defined(__cpp_nontype_template_parameter_class) \
&& defined(__cpp_deduction_guides) // {
// Non-type template parameters with class type are supported. This enables
// defining a constexpr user-defined literal that returns a reference to a
// static buffer of type char that contains the contents of the UTF-8 literal.
namespace char8_t_remediation {
template<std::size_t N>
struct char8_t_string_literal {
static constexpr inline std::size_t size = N;
template<std::size_t... I>
constexpr char8_t_string_literal(
const char8_t (&r)[N],
std::index_sequence<I...>)
:
s{r[I]...}
{}
constexpr char8_t_string_literal(
const char8_t (&r)[N])
:
char8_t_string_literal(r, std::make_index_sequence<N>())
{}
// P0732R2 requires that operator <=> be defined for class types used as
// non-type template arguments, but gcc, as of version 9.1.0, does not yet
// implement support for operator <=>, but does provide an implementation
// of P0732R2 (that presumably relies on implicit memberwise comparison).
#if defined(__cpp_impl_three_way_comparison) // {
auto operator <=>(const char8_t_string_literal&) = default;
#endif // }
char8_t s[N];
};
template<std::size_t N>
char8_t_string_literal(const char8_t(&)[N]) -> char8_t_string_literal<N>;
template<char8_t_string_literal L, std::size_t... I>
constexpr inline const char as_char_buffer[sizeof...(I)] =
{ static_cast<char>(L.s[I])... };
template<char8_t_string_literal L, std::size_t... I>
constexpr auto& make_as_char_buffer(std::index_sequence<I...>) {
return as_char_buffer<L, I...>;
}
} // namespace char8_t_remediation
inline constexpr char operator ""_as_char(char8_t c) {
return c;
}
// gcc requires a fix for bug 88095 in order to deduce the template arguments
// for the non-type template parameter. A patch is available in
// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=88095
template<char8_t_remediation::char8_t_string_literal L>
constexpr auto& operator""_as_char() {
return char8_t_remediation::make_as_char_buffer<L>(
std::make_index_sequence<decltype(L)::size>());
}
#define U8(x) u8##x##_as_char
#else // } !defined(__cpp_nontype_template_parameter_class) ||
// !defined(__cpp_deduction_guides) {
// Non-type template parameters with class type are not supported. The
// best we can do is reinterpret_cast the UTF-8 literal as a pointer to
// const char.
inline constexpr char operator ""_as_char(char8_t c) {
return c;
}
inline const char* operator""_as_char(const char8_t *p, std::size_t) {
return reinterpret_cast<const char*>(p);
}
#define U8(x) u8##x##_as_char
#endif // }
#else // } !defined(__cpp_char8_t) {
#define U8(x) u8##x
#endif // }
// char_array provides an alternative declaration for C-style arrays that
// preserves the ability to initialize a char array with a u8 string literal.
// C++14 or later is required for index_sequence and make_index_sequence.
#if __cplusplus >= 201402L // {
template<std::size_t N>
struct char_array {
template<std::size_t P, std::size_t... I>
constexpr char_array(
const char (&r)[P],
std::index_sequence<I...>)
:
data{(I<P?r[I]:'\0')...}
{}
template<std::size_t P, typename = std::enable_if_t<(P<=N)>>
constexpr char_array(const char(&r)[P])
: char_array(r, std::make_index_sequence<N>())
{}
#if defined(__cpp_char8_t) // {
template<std::size_t P, std::size_t... I>
constexpr char_array(
const char8_t (&r)[P],
std::index_sequence<I...>)
:
data{(I<P?static_cast<char>(r[I]):'\0')...}
{}
template<std::size_t P, typename = std::enable_if_t<(P<=N)>>
constexpr char_array(const char8_t(&r)[P])
: char_array(r, std::make_index_sequence<N>())
{}
#endif // }
using const_conversion_type = const char(&)[N];
constexpr operator const_conversion_type() const {
return data;
}
using conversion_type = const char(&)[N];
constexpr operator conversion_type() {
return data;
}
char data[N];
};
#if defined(__cpp_deduction_guides) // {
template<std::size_t N>
char_array(const char(&)[N]) -> char_array<N>;
#if defined(__cpp_char8_t) // {
template<std::size_t N>
char_array(const char8_t(&)[N]) -> char_array<N>;
#endif // }
#endif // }
#endif // }
// from_u8string enables explicit conversion from std::u8string to
// std::string.
std::string from_u8string(const std::string &s) {
return s;
}
std::string from_u8string(std::string &&s) {
return std::move(s);
}
#if defined(__cpp_lib_char8_t)
std::string from_u8string(const std::u8string &s) {
return std::string(s.begin(), s.end());
}
#endif
#endif // } CHAR8_T_REMEDIATION_HPP
+26
View File
@@ -0,0 +1,26 @@
#include "common.h"
bool IsNativeChar(char32_t c)
{
return c < 0x100;
}
bool IsNormalNativeChar(char32_t c)
{
return IsNativeChar(c) && (c != 0) && (c != ' ') && (c != '~');
}
void SkipUTF8Signature(std::ifstream& stream)
{
char bom[3];
if (stream.get(bom[0]) && stream.get(bom[1]) && stream.get(bom[2]))
{
if (bom[0] == '\xEF' && bom[1] == '\xBB' && bom[2] == '\xBF')
{
return;
}
}
stream.seekg(0);
}
+30
View File
@@ -0,0 +1,30 @@
#pragma once
#include "stdinc.h"
static constexpr uint g_CharsPerLine = 64;
typedef std::uint16_t GTAChar;
struct CVector2D
{
float x;
float y;
};
struct CRect
{
CVector2D bottom_left;
CVector2D top_right;
};
struct WhmTextData
{
std::size_t hash;
std::uintptr_t offset;
};
VALIDATE_SIZE(WhmTextData, 8);
bool IsNativeChar(char32_t c);
bool IsNormalNativeChar(char32_t c);
//读取流时跳过UTF8签名
void SkipUTF8Signature(std::ifstream& stream);
+29
View File
@@ -0,0 +1,29 @@
#include "fnv_hash.h"
namespace fnv_hash
{
std::span<const uchar> get_string_span(const std::string& str)
{
return { reinterpret_cast<const uchar*>(str.c_str()), str.size() };
}
std::size_t hash_string(const std::string& str, bool path_mode)
{
return hash_seq(get_string_span(str), path_mode);
}
std::size_t hash_string(const char* str, bool path_mode)
{
return hash_seq(get_string_span(str), path_mode);
}
std::size_t hash_string(const uchar* str, bool path_mode)
{
return hash_seq(get_string_span(str), path_mode);
}
std::size_t hash_string(const GTAChar* str, bool path_mode)
{
return hash_seq(get_string_span(str), path_mode);
}
}
+71
View File
@@ -0,0 +1,71 @@
#pragma once
#include "../common/stdinc.h"
#include "common.h"
namespace fnv_hash
{
template <typename T>
std::enable_if_t<std::is_integral_v<T>, std::size_t> hash_seq(std::span<const T> seq, bool path_mode)
{
static constexpr uint64 fnv_prime = 16777619ui64;
auto real_seq = std::span(reinterpret_cast<const uchar*>(seq.data()), seq.size() * sizeof(T));
std::size_t result = 2166136261u;
for (auto element : real_seq)
{
if (path_mode)
{
//正斜杠+大写
if (element == '\\')
{
element = '/';
}
else if (element >= 'a' && element <= 'z')
{
element -= 0x20;
}
}
result ^= element;
result = static_cast<uint>((result * fnv_prime) % 4294967296ui64);
}
return result;
}
template <typename T>
std::enable_if_t<std::is_integral_v<T>, std::span<const T>> get_string_span(const T* str)
{
std::size_t size = 0;
if (str != nullptr)
{
auto c = str[size];
while (c != 0)
{
++size;
c = str[size];
}
}
return { str, size };
}
template <typename T>
std::enable_if_t<std::is_integral_v<T>, std::vector<T>> get_string_vector(const T* str)
{
auto result = ranges::to<std::vector>(get_string_span(str));
result.push_back(0);
return result;
}
//字符串哈希函数
std::size_t hash_string(const std::string& str, bool path_mode);
std::size_t hash_string(const char* str, bool path_mode);
std::size_t hash_string(const uchar* str, bool path_mode);
std::size_t hash_string(const GTAChar* str, bool path_mode);
}
+178
View File
@@ -0,0 +1,178 @@
/*
* Injectors - Useful Assembly Stuff
*
* Copyright (C) 2012-2014 LINK/2012 <dma_2012@hotmail.com>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*
*/
#pragma once
// This header is very restrict about compiler and architecture
#ifndef _MSC_VER // MSVC is much more flexible when we're talking about inline assembly
#error Cannot use this header in another compiler other than MSVC
#endif
#ifndef _M_IX86
#error Supported only in x86
#endif
//
#include "injector.hpp"
namespace injector
{
struct reg_pack
{
// The ordering is very important, don't change
// The first field is the last to be pushed and first to be poped
// PUSHFD / POPFD
uint32_t ef;
// PUSHAD/POPAD -- must be the lastest fields (because of esp)
union
{
uint32_t arr[8];
struct { uint32_t edi, esi, ebp, esp, ebx, edx, ecx, eax; };
};
enum reg_name {
reg_edi, reg_esi, reg_ebp, reg_esp, reg_ebx, reg_edx, reg_ecx, reg_eax
};
enum ef_flag {
carry_flag = 0, parity_flag = 2, adjust_flag = 4, zero_flag = 6, sign_flag = 7,
direction_flag = 10, overflow_flag = 11
};
uint32_t& operator[](size_t i)
{ return this->arr[i]; }
const uint32_t& operator[](size_t i) const
{ return this->arr[i]; }
template<uint32_t bit> // bit starts from 0, use ef_flag enum
bool flag()
{
return (this->ef & (1 << bit)) != 0;
}
bool jnb()
{
return flag<carry_flag>() == false;
}
};
// Lowest level stuff (actual assembly) goes on the following namespace
// PRIVATE! Skip this, not interesting for you.
namespace injector_asm
{
// Wrapper functor, so the assembly can use some templating
template<class T>
struct wrapper
{
static void call(reg_pack* regs)
{
T fun; fun(*regs);
}
};
// Constructs a reg_pack and calls the wrapper functor
template<class W> // where W is of type wrapper
inline void __declspec(naked) make_reg_pack_and_call()
{
_asm
{
// Construct the reg_pack structure on the stack
pushad // Pushes general purposes registers to reg_pack
add dword ptr[esp+12], 4 // Add 4 to reg_pack::esp 'cuz of our return pointer, let it be as before this func is called
pushfd // Pushes EFLAGS to reg_pack
// Call wrapper sending reg_pack as parameter
push esp
call W::call
add esp, 4
// Destructs the reg_pack from the stack
sub dword ptr[esp+12+4], 4 // Fix reg_pack::esp before popping it (doesn't make a difference though) (+4 because eflags)
popfd // Warning: Do not use any instruction that changes EFLAGS after this (-> sub affects EF!! <-)
popad
// Back to normal flow
ret
}
}
};
/*
* MakeInline
* Makes inline assembly (but not assembly, an actual functor of type FuncT) at address
*/
template<class FuncT>
void MakeInline(memory_pointer_tr at)
{
typedef injector_asm::wrapper<FuncT> functor;
if(false) functor::call(nullptr); // To instantiate the template, if not done _asm will fail
MakeCALL(at, injector_asm::make_reg_pack_and_call<functor>);
}
/*
* MakeInline
* Same as above, but it NOPs everything between at and end (exclusive), then performs MakeInline
*/
template<class FuncT>
void MakeInline(memory_pointer_tr at, memory_pointer_tr end)
{
MakeRangedNOP(at, end);
MakeInline<FuncT>(at);
}
/*
* MakeInline
* Same as above, but (at,end) are template parameters.
* On this case the functor can be passed as argument since there will be one func instance for each at,end not just for each FuncT
*/
template<uintptr_t at, uintptr_t end, class FuncT>
void MakeInline(FuncT func)
{
static std::unique_ptr<FuncT> static_func;
static_func.reset(new FuncT(std::move(func)));
// Encapsulates the call to static_func
struct Caps
{
void operator()(reg_pack& regs)
{ (*static_func)(regs); }
};
// Does the actual MakeInline
return MakeInline<Caps>(lazy_pointer<at>::get(), lazy_pointer<end>::get());
}
/*
* MakeInline
* Same as above, but (end) is calculated by the length of a call instruction
*/
template<uintptr_t at, class FuncT>
void MakeInline(FuncT func)
{
return MakeInline<at, at+5, FuncT>(func);
}
};
+127
View File
@@ -0,0 +1,127 @@
/*
* Injectors - Function Calls Using Variadic Templates
*
* Copyright (C) 2014 LINK/2012 <dma_2012@hotmail.com>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*
*/
#pragma once
#include "injector.hpp"
#include <utility>
#include <tuple>
#if __cplusplus >= 201103L || _MSC_VER >= 1800 // MSVC 2013
#else
#error "This feature is not supported on this compiler"
#endif
namespace injector
{
template<class Prototype>
struct cstd;
template<class Ret, class ...Args>
struct cstd<Ret(Args...)>
{
// Call function at @p returning @Ret with args @Args
static Ret call(memory_pointer_tr p, Args... a)
{
auto fn = (Ret(*)(Args...)) p.get<void>();
return fn(std::forward<Args>(a)...);
}
template<uintptr_t addr> // Uses lazy pointer
static Ret call(Args... a)
{
return call(lazy_pointer<addr>::get(), std::forward<Args>(a)...);
}
};
template<class Prototype>
struct stdcall;
template<class Ret, class ...Args>
struct stdcall<Ret(Args...)>
{
// Call function at @p returning @Ret with args @Args
static Ret call(memory_pointer_tr p, Args... a)
{
auto fn = (Ret(__stdcall *)(Args...)) p.get<void>();
return fn(std::forward<Args>(a)...);
}
template<uintptr_t addr> // Uses lazy pointer
static Ret call(Args... a)
{
return call(lazy_pointer<addr>::get(), std::forward<Args>(a)...);
}
};
template<class Prototype>
struct fastcall;
template<class Ret, class ...Args>
struct fastcall<Ret(Args...)>
{
// Call function at @p returning @Ret with args @Args
static Ret call(memory_pointer_tr p, Args... a)
{
auto fn = (Ret(__fastcall *)(Args...)) p.get<void>();;
return fn(std::forward<Args>(a)...);
}
template<uintptr_t addr> // Uses lazy pointer
static Ret call(Args... a)
{
return call(lazy_pointer<addr>::get(), std::forward<Args>(a)...);
}
};
template<class Prototype>
struct thiscall;
template<class Ret, class ...Args>
struct thiscall<Ret(Args...)>
{
// Call function at @p returning @Ret with args @Args
static Ret call(memory_pointer_tr p, Args... a)
{
auto fn = (Ret(__thiscall *)(Args...)) p.get<void>();
return fn(std::forward<Args>(a)...);
}
// Call function at the index @i from the vtable of the object @a[0]
template<size_t i>
static Ret vtbl(Args... a)
{
auto obj = raw_ptr(std::get<0>(std::forward_as_tuple(a...)));
auto p = raw_ptr( (*obj.template get<void**>()) [i] );
return call(p, std::forward<Args>(a)...);
}
template<uintptr_t addr> // Uses lazy pointer
static Ret call(Args... a)
{
return call(lazy_pointer<addr>::get(), std::forward<Args>(a)...);
}
};
}
+229
View File
@@ -0,0 +1,229 @@
/*
* Injectors - Base Header
*
* Copyright (C) 2012-2014 LINK/2012 <dma_2012@hotmail.com>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*
*/
#pragma once
#include <windows.h>
#include <cstdint>
#include <cstdio>
namespace injector
{
#if 1 // GVM and Address Translator, Not very interesting for the users, so skip reading those...
/*
* game_version_manager
* Detects the game, the game version and the game region
* This assumes the executable is decrypted, so, Silent's ASI Loader is recommended.
*/
#ifndef INJECTOR_OWN_GVM
#ifndef INJECTOR_GVM_DUMMY
class game_version_manager
{
public:
// Set this if you would like that MessagesBox contain PluginName as caption
const char* PluginName;
private:
char game, region, major, minor, majorRevision, minorRevision, cracker, steam;
public:
game_version_manager()
{
#ifdef INJECTOR_GVM_PLUGIN_NAME
PluginName = INJECTOR_GVM_PLUGIN_NAME;
#else
PluginName = "Unknown Plugin Name";
#endif
this->Clear();
}
// Clear any information about game version
void Clear()
{
game = region = major = minor = majorRevision = minorRevision = cracker = steam = 0;
}
// Checks if I don't know the game we are attached to
bool IsUnknown() { return game == 0; }
// Checks if this is the steam version
bool IsSteam() { return steam != 0; }
// Gets the game we are attached to (0, '3', 'V', 'S', 'I', 'E')
char GetGame() { return game; }
// Gets the region from the game we are attached to (0, 'U', 'E');
char GetRegion() { return region; }
// Get major and minor version of the game (e.g. [major = 1, minor = 0] = 1.0)
int GetMajorVersion() { return major; }
int GetMinorVersion() { return minor; }
int GetMajorRevisionVersion() { return majorRevision; }
int GetMinorRevisionVersion() { return minorRevision; }
bool IsHoodlum() { return cracker == 'H'; }
// Region conditions
bool IsUS() { return region == 'U'; }
bool IsEU() { return region == 'E'; }
// Game Conditions
bool IsIII() { return game == '3'; }
bool IsVC () { return game == 'V'; }
bool IsSA () { return game == 'S'; }
bool IsIV () { return game == 'I'; }
bool IsEFLC(){ return game == 'E'; }
// Detects game, region and version; returns false if could not detect it
bool Detect();
// Gets the game version as text, the buffer must contain at least 32 bytes of space.
char* GetVersionText(char* buffer)
{
if(this->IsUnknown())
{
strcpy(buffer, "UNKNOWN GAME");
return buffer;
}
const char* g = this->IsIII() ? "III" : this->IsVC() ? "VC" : this->IsSA() ? "SA" : this->IsIV() ? "IV" : this->IsEFLC() ? "EFLC" : "UNK";
const char* r = this->IsUS()? "US" : this->IsEU()? "EURO" : "UNK_REGION";
const char* s = this->IsSteam()? "Steam" : "";
sprintf(buffer, "GTA %s %d.%d.%d.%d %s%s", g, major, minor, majorRevision, minorRevision, r, s);
return buffer;
}
public:
// Raises a error saying that you could not detect the game version
void RaiseCouldNotDetect()
{
MessageBoxA(0,
"Could not detect the game version\nContact the mod creator!",
PluginName, MB_ICONERROR
);
}
// Raises a error saying that the exe version is incompatible (and output the exe name)
void RaiseIncompatibleVersion()
{
char buf[128], v[32];
sprintf(buf,
"An incompatible exe version has been detected! (%s)\nContact the mod creator!",
GetVersionText(v)
);
MessageBoxA(0, buf, PluginName, MB_ICONERROR);
}
};
#else // INJECTOR_GVM_DUMMY
class game_version_manager
{
public:
bool Detect() { return true; }
};
#endif // INJECTOR_GVM_DUMMY
#endif // INJECTOR_OWN_GVM
/*
* address_manager
* Address translator from 1.0 executables to other executables offsets
* Inherits from game_version_manager ;)
*/
class address_manager : public game_version_manager
{
private:
address_manager()
{
this->Detect();
}
// You could implement your translator for the address your plugin uses
// If not implemented, the translator won't translate anything, just return the samething as before
#ifdef INJECTOR_GVM_HAS_TRANSLATOR
void* translator(void* p);
#else
void* translator(void* p) { return p; }
#endif
public:
// Translates address p to the running executable pointer
void* translate(void* p)
{
return translator(p);
}
public:
// Address manager singleton
static address_manager& singleton()
{
static address_manager m;
return m;
}
// Static version of translate()
static void* translate_address(void* p)
{
return singleton().translate(p);
}
//
static void set_name(const char* modname)
{
singleton().PluginName = modname;
}
public:
// Functors for memory translation:
// Translates aslr translator
struct fn_mem_translator_aslr
{
void* operator()(void* p) const
{
static uintptr_t module = (uintptr_t)GetModuleHandle(NULL);
return (void*)((uintptr_t)(p)-(0x400000 - module));
}
};
// Translates nothing translator
struct fn_mem_translator_nop
{
void* operator()(void* p) const
{ return p; }
};
// Real translator
struct fn_mem_translator
{
void* operator()(void* p) const
{ return translate_address(p); }
};
};
#endif // #if 1
}
+203
View File
@@ -0,0 +1,203 @@
/*
* Injectors - Address Translation Management
*
* Copyright (C) 2014 LINK/2012 <dma_2012@hotmail.com>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*
*/
#pragma once
#if !defined(INJECTOR_GVM_HAS_TRANSLATOR)
#error Missing INJECTOR_GVM_HAS_TRANSLATOR on compiler definitions
#endif
/*
* This is a quick solution for address translations if you're too lazy to implement a proper address_manager::translator by yourself
* So, just call address_translator_manager::singleton().translate(p) from your address_manager::translator and that's it.
* It'll translate addresses based on 'address_translator' objects, when one gets constructed it turns into a possible translator.
* At the constructor of your derived 'address_translator' make the map object to have [addr_to_translate] = translated_addr;
* There's also the virtual method 'fallback' that will get called when the translation wasn't possible, you can do some fallback stuff here
* (such as return the pointer as is or output a error message)
*/
#include "../injector.hpp"
#include <list>
#include <map>
#include <algorithm>
namespace injector
{
/*
* address_translator
* Base for an address translator
*/
class address_translator
{
private:
bool enabled;
void add();
void remove();
protected:
friend class address_translator_manager;
std::map<memory_pointer_raw, memory_pointer_raw> map;
public:
address_translator() : enabled(true)
{
// Must have bounds filled with min ptr and max ptr to have search working properly
map.insert(std::make_pair(raw_ptr(0x00000000u), raw_ptr(0x00000000u)));
map.insert(std::make_pair(raw_ptr(0xffffffffu), raw_ptr(0xffffffffu)));
add();
}
~address_translator()
{
remove();
}
virtual void* fallback(void*) const
{
return nullptr;
}
// Enables or disables this translator
void enable(bool enable_it)
{
if(enable_it) this->enable();
else this->disable();
}
// Enables this translator
void enable()
{
this->enabled = true;
}
// Disables this translator
void disable()
{
this->enabled = false;
}
// Checks if this translator is enabled
bool is_enabled() const
{
return enabled;
}
};
/*
* address_translator_manager
* Manages the address_translator objects
*/
class address_translator_manager
{
protected:
friend class address_manager;
friend class address_translator;
std::list<const address_translator*> translators;
void add(const address_translator& t)
{
translators.push_front(&t);
}
void remove(const address_translator& t)
{
translators.remove(&t);
}
public:
// Translates the address p
void* translator(void* p);
// Singleton object
static address_translator_manager& singleton()
{
static address_translator_manager mgr;
return mgr;
}
};
inline void* address_translator_manager::translator(void* p_)
{
static const size_t max_ptr_dist = 7;
// Tries to find an address in a translator map
auto try_map = [](const std::map<memory_pointer_raw, memory_pointer_raw>& map, memory_pointer_raw p) -> memory_pointer_raw
{
memory_pointer_raw result = nullptr;
// Find first element in the map that is greater than or equal to p
auto it = map.lower_bound(p);
if(it != map.end())
{
// If it's not exactly the address, get back one position on the table
if(it->first != p) --it;
auto diff = (p - it->first).as_int(); // What's the difference between p and that address?
if(diff <= max_ptr_dist) // Could we live with this difference in hands?
result = it->second + raw_ptr(diff); // Yes, we can!
}
return result;
};
//
memory_pointer_raw result = nullptr;
// Try to find translation for this pointer
auto& mgr = address_translator_manager::singleton().translators;
for(auto it = mgr.begin(); result == nullptr && it != mgr.end(); ++it)
{
auto& t = **it;
if(t.is_enabled()) result = try_map(t.map, p_);
}
// If we couldn't translate the address, notify and try to fallback
if(result.is_null())
{
for(auto it = mgr.begin(); result == nullptr && it != mgr.end(); ++it)
{
auto& t = **it;
if(t.is_enabled()) result = t.fallback(p_);
}
}
return result.get();
}
inline void address_translator::add()
{
address_translator_manager::singleton().add(*this);
}
inline void address_translator::remove()
{
address_translator_manager::singleton().remove(*this);
}
}
+687
View File
@@ -0,0 +1,687 @@
/*
* Injectors - Classes for making your hooking life easy
*
* Copyright (C) 2013-2014 LINK/2012 <dma_2012@hotmail.com>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*
*/
#pragma once
#include "injector.hpp"
#include <cassert>
#include <functional>
#include <memory> // for std::shared_ptr
#include <list>
namespace injector
{
/*
* scoped_base
* Base for any scoped hooking type
* !!!! NOTICE !!!! --> Any derived which implements/reimplements restore() should implement a destructor calling it
*/
class scoped_base
{
public:
virtual ~scoped_base() {}
virtual void restore() = 0;
};
/*
* scoped_basic
* Base for scoped types which will need a buffer to save/restore stuff
*/
template<size_t bufsize> // TODO specialize bufsize=0 to be dynamic
class scoped_basic : public scoped_base
{
private:
uint8_t buf[bufsize];// Saved content
memory_pointer_raw addr; // Data saved from this address
size_t size; // Size saved
bool saved; // Something saved?
bool vp; // Virtual protect?
public:
static const bool is_dynamic = false;
// Restore the previosly saved data
// Problems may arise if someone else hooked the same place using the same method
virtual void restore()
{
#ifndef INJECTOR_SCOPED_NOSAVE_NORESTORE
if(this->saved)
{
WriteMemoryRaw(this->addr, this->buf, this->size, this->vp);
this->saved = false;
}
#endif
}
// Save buffer at @addr with @size and virtual protect @vp
virtual void save(memory_pointer_tr addr, size_t size, bool vp)
{
#ifndef INJECTOR_SCOPED_NOSAVE_NORESTORE
assert(size <= bufsize); // Debug Safeness
this->restore(); // Restore anything we have saved
this->saved = true; // Mark that we have data save
this->addr = addr.get<void>(); // Save address
this->size = size; // Save size
this->vp = vp; // Save virtual protect
ReadMemoryRaw(addr, buf, size, vp); // Save buffer
#endif
}
public:
// Constructor, initialises
scoped_basic() : saved(false)
{}
~scoped_basic()
{
this->restore();
}
// No copy construction, we can't do this! Sure we can move construct :)
scoped_basic(const scoped_basic&) = delete;
scoped_basic(scoped_basic&& rhs)
{
*this = std::move(rhs);
}
scoped_basic& operator=(const scoped_basic& rhs) = delete;
scoped_basic& operator=(scoped_basic&& rhs)
{
if(this->saved = rhs.saved)
{
assert(bufsize >= rhs.size);
this->addr = rhs.addr;
this->size = rhs.size;
this->vp = rhs.vp;
memcpy(buf, rhs.buf, rhs.size);
rhs.saved = false;
}
return *this;
}
};
/*
* RAII wrapper for memory writes
* Can save only basic and POD types
*/
template<size_t bufsize_ = 10>
class scoped_write : public scoped_basic<bufsize_>
{
public:
// Save buffer at @addr with @size and virtual protect @vp and then overwrite it with @value
void write(memory_pointer_tr addr, void* value, size_t size, bool vp)
{
this->save(addr, size, vp);
return WriteMemoryRaw(addr, value, size, vp);
}
// Save buffer at @addr with size sizeof(@value) and virtual protect @vp and then overwrite it with @value
template<class T>
void write(memory_pointer_tr addr, T value, bool vp = false)
{
this->save(addr, sizeof(T), vp);
return WriteMemory<T>(addr, value, vp);
}
// Constructors, move constructors, assigment operators........
scoped_write() = default;
scoped_write(const scoped_write&) = delete;
scoped_write(scoped_write&& rhs) : scoped_basic<bufsize_>(std::move(rhs)) {}
scoped_write& operator=(const scoped_write& rhs) = delete;
scoped_write& operator=(scoped_write&& rhs)
{ scoped_basic<bufsize_>::operator=(std::move(rhs)); return *this; }
};
/*
* RAII wrapper for filling
*/
template<size_t bufsize_ = 5>
class scoped_fill : public scoped_basic<bufsize_>
{
public:
// Fills memory at @addr with value @value and size @size and virtual protect @vp
void fill(memory_pointer_tr addr, uint8_t value, size_t size, bool vp)
{
this->save(addr, size, vp);
return MemoryFill(addr, value, size, vp);
}
// Constructors, move constructors, assigment operators........
scoped_fill() = default;
scoped_fill(const scoped_fill&) = delete;
scoped_fill(scoped_fill&& rhs) : scoped_basic<bufsize_>(std::move(rhs)) {}
scoped_fill& operator=(const scoped_fill& rhs) = delete;
scoped_fill& operator=(scoped_fill&& rhs)
{ scoped_basic<bufsize_>::operator=(std::move(rhs)); return *this; }
scoped_fill(memory_pointer_tr addr, uint8_t value, size_t size, bool vp)
{ fill(addr, value, vp); }
};
/*
* RAII wrapper for nopping
*/
template<size_t bufsize_>
class scoped_nop : public scoped_basic<bufsize_>
{
public:
// Makes NOP at @addr with value @value and size @size and virtual protect @vp
void make_nop(memory_pointer_tr addr, size_t size = 1, bool vp = true)
{
this->save(addr, size, vp);
return MakeNOP(addr, size, vp);
}
// Constructors, move constructors, assigment operators........
scoped_nop() = default;
scoped_nop(const scoped_nop&) = delete;
scoped_nop(scoped_nop&& rhs) : scoped_basic<bufsize_>(std::move(rhs)) {}
scoped_nop& operator=(const scoped_nop& rhs) = delete;
scoped_nop& operator=(scoped_nop&& rhs)
{ scoped_basic<bufsize_>::operator=(std::move(rhs)); return *this; }
scoped_nop(memory_pointer_tr addr, size_t size = 1, bool vp = true)
{ make_nop(addr, size, vp); }
};
/*
* RAII wrapper for MakeJMP
*/
class scoped_jmp : public scoped_basic<5>
{
public:
// Makes NOP at @addr with value @value and size @size and virtual protect @vp
memory_pointer_raw make_jmp(memory_pointer_tr at, memory_pointer_raw dest, bool vp = true)
{
this->save(at, 5, vp);
return MakeJMP(at, dest, vp);
}
// Constructors, move constructors, assigment operators........
scoped_jmp() = default;
scoped_jmp(const scoped_jmp&) = delete;
scoped_jmp(scoped_jmp&& rhs) : scoped_basic<5>(std::move(rhs)) {}
scoped_jmp& operator=(const scoped_jmp& rhs) = delete;
scoped_jmp& operator=(scoped_jmp&& rhs)
{ scoped_basic<5>::operator=(std::move(rhs)); return *this; }
scoped_jmp(memory_pointer_tr at, memory_pointer_raw dest, bool vp = true)
{ make_jmp(at, dest, vp); }
};
/*
* RAII wrapper for MakeCALL
*/
class scoped_call : public scoped_basic<5>
{
public:
// Makes NOP at @addr with value @value and size @size and virtual protect @vp
memory_pointer_raw make_call(memory_pointer_tr at, memory_pointer_raw dest, bool vp = true)
{
this->save(at, 5, vp);
return MakeCALL(at, dest, vp);
}
// Constructors, move constructors, assigment operators........
scoped_call() = default;
scoped_call(const scoped_call&) = delete;
scoped_call(scoped_call&& rhs) : scoped_basic<5>(std::move(rhs)) {}
scoped_call& operator=(const scoped_call& rhs) = delete;
scoped_call& operator=(scoped_call&& rhs)
{ scoped_basic<5>::operator=(std::move(rhs)); return *this; }
scoped_call(memory_pointer_tr at, memory_pointer_raw dest, bool vp = true)
{ make_call(at, dest, vp); }
};
#if __cplusplus >= 201103L || _MSC_VER >= 1800 // C++11 or MSVC 2013 required for variadic templates
/*
* function_hooker_manager
* Manages many function_hookers that points to the same address
* The need for this function arises because otherwise we would only be able to allow one hook per address using function_hookers
* This manager takes care of the amount of hooks placed in a particular address, calls the hooks and unhooks when necessary.
*/
template<class ToManage, class Ret, class ...Args>
class function_hooker_manager : protected scoped_call
{
private:
using func_type_raw = typename ToManage::func_type_raw;
using func_type = typename ToManage::func_type;
using functor_type = typename ToManage::functor_type;
using assoc_type = std::list<std::pair<const ToManage*, functor_type>>;
// Only construction is allowed... by myself ofcourse...
function_hooker_manager() = default;
function_hooker_manager(const function_hooker_manager&) = delete;
function_hooker_manager(function_hooker_manager&&) = delete;
//
func_type_raw original; // Pointer to the original function we've replaced
assoc_type assoc; // Association between owners of a hook and the hook (map)
bool has_hooked = false; // Is the hook already in place?
// Find assoc iterator for the content owned by 'owned'
typename assoc_type::iterator find_assoc(const ToManage& owner)
{
for(auto it = assoc.begin(); it != assoc.end(); ++it)
if(it->first == &owner) return it;
return assoc.end();
}
// Adds a new item to the association map (or override if already in the map)
void add(const ToManage& hooker, functor_type functor)
{
auto it = find_assoc(hooker);
if(it != assoc.end())
it->second = std::move(functor);
else
assoc.emplace_back(&hooker, std::move(functor));
}
public:
// Forwards the call to all the installed hooks
static Ret call_hooks(Args&... args)
{
auto& manager = *instance();
if(manager.assoc.size() == 0) // This may be uncommon but may happen (?), no hook installed
return manager.original(args...);
// Functor for the original call
func_type original = [&manager](Args... args) -> Ret {
return manager.original(args...);
};
if(manager.assoc.size() == 1)
{
// We have only one hook, just use it directly no need to go further in complexity
auto& functor = manager.assoc.begin()->second;
return functor(std::move(original), args...);
}
else
{
// Build a serie of functors which captures the previous functor sending it to the next functor,
// that's what would happen if the hooks took place independent of the template staticness (AAAAAAA)
func_type next = std::move(original);
for(auto it = manager.assoc.begin(); it != manager.assoc.end(); ++it)
{
auto& functor = it->second;
next = [functor, next](Args... args) -> Ret
{
return functor(next, args...);
};
}
return next(args...);
}
}
public:
// Installs a hook associated with the function_hooker 'hooker' which would call the specified 'functor'
// We need an auxiliar function pointer 'ptr' (to abstract calling conventions) which should forward itself to ^call_hooks
void make_call(const ToManage& hooker, functor_type functor, memory_pointer_raw ptr)
{
this->add(hooker, std::move(functor));
// Make sure we only hook this address for the manager once
if(!this->has_hooked)
{
// (the following cast is needed for __thiscall functions)
this->original = (func_type_raw) (void*) scoped_call::make_call(hooker.addr, ptr).get();
this->has_hooked = true;
}
}
// Restores the state of the call we've replaced in the game code
// All installed hooks gets uninstalled after this
void restore()
{
if(this->has_hooked)
{
this->has_hooked = false;
this->assoc.clear();
return scoped_call::restore();
}
}
// Replaces the hook associated with 'from' to be associated with 'to'
// After this call the 'from' object has no association in this manager
void replace(const ToManage& from, const ToManage& to)
{
auto it = find_assoc(from);
if(it != assoc.end())
{
auto functor = std::move(it->second);
assoc.erase(it);
this->add(to, std::move(functor));
}
}
// Removes the hook associated with the specified 'hooker'
// If the number of hooks reaches zero after the remotion, a restore will take place
void remove(const ToManage& hooker)
{
auto it = find_assoc(hooker);
if(it != assoc.end())
{
assoc.erase(it);
if(assoc.size() == 0) this->restore();
}
}
// The instance of this specific manager
// This work as a shared pointer to avoid the static destruction of the manager even when a static function_hooker
// still wants to use it.
static std::shared_ptr<function_hooker_manager> instance()
{
static auto fm_ptr = std::shared_ptr<function_hooker_manager>(new function_hooker_manager());
return fm_ptr;
}
};
/*
* function_hooker_base
* Base for any function_hooker, this class manages the relationship with the function hooker manager
*/
template<uintptr_t addr1, class FuncType, class Ret, class ...Args>
class function_hooker_base : public scoped_base
{
public:
static const uintptr_t addr = addr1;
using func_type_raw = FuncType;
using func_type = std::function<Ret(Args...)>;
using functor_type = std::function<Ret(func_type, Args&...)>;
using manager_type = function_hooker_manager<function_hooker_base, Ret, Args...>;
public:
// Constructors, move constructors, assigment operators........
function_hooker_base(const function_hooker_base&) = delete;
function_hooker_base& operator=(const function_hooker_base& rhs) = delete;
function_hooker_base() : manager(manager_type::instance())
{}
//
virtual ~function_hooker_base()
{
this->restore();
}
// The move constructor should do a replace in the manager
function_hooker_base(function_hooker_base&& rhs)
: scoped_base(std::move(rhs)), has_call(rhs.has_call),
manager(rhs.manager) // (don't move the manager!, every function_hooker should own one)
{
manager->replace(rhs, *this);
}
// The move assignment operator should also do a replace in the manager
function_hooker_base& operator=(function_hooker_base&& rhs)
{
scoped_base::operator=(std::move(rhs));
manager->replace(rhs, *this);
this->has_call = rhs.has_call;
this->manager = rhs.manager; // (don't move the manager! every function_hooker should own one)
return *this;
}
// Deriveds should implement a proper make_call (yeah it's virtual so derived-deriveds can do some fest)
virtual void make_call(functor_type functor) = 0;
// Restores the state of the call we've replaced in the game code
virtual void restore()
{
this->has_call = false;
manager->remove(*this);
}
// Checkers whether a hook is installed
bool has_hooked()
{
return this->has_call;
}
private:
bool has_call = false; // Has a hook installed?
std::shared_ptr<manager_type> manager; // **EVERY** function_hooker should have a ownership over it's manager_type
// this prevents the static destruction of the manager_type while it may be still needed.
protected: // Forwarders to the function hooker manager
void make_call(functor_type functor, memory_pointer_raw ptr)
{
this->has_call = true;
manager->make_call(*this, std::move(functor), ptr);
}
static Ret call_hooks(Args&... a)
{
return manager_type::call_hooks(a...);
}
};
/*
* function_hooker
* For standard conventions (usually __cdecl)
*/
template<uintptr_t addr1, class Prototype>
class function_hooker;
template<uintptr_t addr1, class Ret, class ...Args>
class function_hooker<addr1, Ret(Args...)>
: public function_hooker_base<addr1, Ret(*)(Args...), Ret, Args...>
{
private:
using base = function_hooker_base<addr1, Ret(*)(Args...), Ret, Args...>;
// The hook caller
static Ret call(Args... a)
{
return base::call_hooks(a...);
}
public:
// Constructors, move constructors, assigment operators........
function_hooker() = default;
function_hooker(const function_hooker&) = delete;
function_hooker(function_hooker&& rhs) : base(std::move(rhs)) {}
function_hooker& operator=(const function_hooker& rhs) = delete;
function_hooker& operator=(function_hooker&& rhs)
{ base::operator=(std::move(rhs)); return *this; }
// Makes the hook
void make_call(typename base::functor_type functor)
{
return base::make_call(std::move(functor), raw_ptr(call));
}
};
/*
* function_hooker_stdcall
* For stdcall conventions (__stdcall)
*/
template<uintptr_t addr1, class Prototype>
struct function_hooker_stdcall;
template<uintptr_t addr1, class Ret, class ...Args>
struct function_hooker_stdcall<addr1, Ret(Args...)>
: public function_hooker_base<addr1, Ret(__stdcall*)(Args...), Ret, Args...>
{
private:
using base = function_hooker_base<addr1, Ret(__stdcall*)(Args...), Ret, Args...>;
// The hook caller
static Ret __stdcall call(Args... a)
{
return base::call_hooks(a...);
}
public:
// Constructors, move constructors, assigment operators........
function_hooker_stdcall() = default;
function_hooker_stdcall(const function_hooker_stdcall&) = delete;
function_hooker_stdcall(function_hooker_stdcall&& rhs) : base(std::move(rhs)) {}
function_hooker_stdcall& operator=(const function_hooker_stdcall& rhs) = delete;
function_hooker_stdcall& operator=(function_hooker_stdcall&& rhs)
{ base::operator=(std::move(rhs)); return *this; }
// Makes the hook
void make_call(typename base::functor_type functor)
{
return base::make_call(std::move(functor), raw_ptr(call));
}
};
/*
* function_hooker_fastcall
* For fastcall conventions (__fastcall)
*/
template<uintptr_t addr1, class Prototype>
struct function_hooker_fastcall;
template<uintptr_t addr1, class Ret, class ...Args>
struct function_hooker_fastcall<addr1, Ret(Args...)>
: public function_hooker_base<addr1, Ret(__fastcall*)(Args...), Ret, Args...>
{
private:
using base = function_hooker_base<addr1, Ret(__fastcall*)(Args...), Ret, Args...>;
// The hook caller
static Ret __fastcall call(Args... a)
{
return base::call_hooks(a...);
}
public:
// Constructors, move constructors, assigment operators........
function_hooker_fastcall() = default;
function_hooker_fastcall(const function_hooker_fastcall&) = delete;
function_hooker_fastcall(function_hooker_fastcall&& rhs) : base(std::move(rhs)) {}
function_hooker_fastcall& operator=(const function_hooker_fastcall& rhs) = delete;
function_hooker_fastcall& operator=(function_hooker_fastcall&& rhs)
{ base::operator=(std::move(rhs)); return *this; }
// Makes the hook
void make_call(typename base::functor_type functor)
{
return base::make_call(std::move(functor), raw_ptr(call));
}
};
/*
* function_hooker_thiscall
* For thiscall conventions (__thiscall, class methods)
*/
template<uintptr_t addr1, class Prototype>
struct function_hooker_thiscall;
template<uintptr_t addr1, class Ret, class ...Args>
struct function_hooker_thiscall<addr1, Ret(Args...)>
: public function_hooker_base<addr1, Ret(__thiscall*)(Args...), Ret, Args...>
{
private:
using base = function_hooker_base<addr1, Ret(__thiscall*)(Args...), Ret, Args...>;
// The hook caller
static Ret __thiscall call(Args... a)
{
return base::call_hooks(a...);
}
public:
// Constructors, move constructors, assigment operators........
function_hooker_thiscall() = default;
function_hooker_thiscall(const function_hooker_thiscall&) = delete;
function_hooker_thiscall(function_hooker_thiscall&& rhs) : base(std::move(rhs)) {}
function_hooker_thiscall& operator=(const function_hooker_thiscall& rhs) = delete;
function_hooker_thiscall& operator=(function_hooker_thiscall&& rhs)
{ base::operator=(std::move(rhs)); return *this; }
// Makes the hook
void make_call(typename base::functor_type functor)
{
return base::make_call(std::move(functor), raw_ptr(call));
}
};
/******************* HELPERS ******************/
/*
* Adds a hook to be alive for the entire program lifetime
* That means the hook received will be alive until the program dies.
* Note: Parameter must be a rvalue
*/
template<class T> inline
T& add_static_hook(T&& hooker)
{
static std::list<T> a;
return *a.emplace(a.end(), std::move(hooker));
}
/*
* Makes a hook which is alive until it gets out of scope
* 'T' must be any function_hooker object
*/
template<class T, class F> inline
T make_function_hook(F functor)
{
T a;
a.make_call(std::move(functor));
return a;
}
/*
* Makes a hook which is alive for the entire lifetime of this program
* 'T' must be any function_hooker object
*/
template<class T, class F> inline
T& make_static_hook(F functor)
{
return add_static_hook(make_function_hook<T>(std::move(functor)));
}
// TODO when we have access to C++14 add a make_function_hook, make_stdcall_function_hook, and so on
// the problem behind implement it with C++11 is that lambdas cannot be generic and the first param of a hook is a functor pointing
// to the previous call pointer
#endif
}
+748
View File
@@ -0,0 +1,748 @@
/*
* Injectors - Base Header
*
* Copyright (C) 2012-2014 LINK/2012 <dma_2012@hotmail.com>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*
*/
#pragma once
#define INJECTOR_HAS_INJECTOR_HPP
#include <windows.h>
#include <cstdint>
#include <cstdio>
/*
The following macros (#define) are relevant on this header:
INJECTOR_GVM_HAS_TRANSLATOR
If defined, the user should provide their own address_manager::translator function.
That function is responssible for translating a void pointer (that mayn't be an actual pointer) into an actual address.
The meaning of that void pointer will be made by YOU when you send it to the functions that receive pointers on this library.
The default translator does nothing but returns that void pointer as the address.
INJECTOR_GVM_OWN_DETECT
If defined, the user should provide it's own game detection function thought game_version_manager::Detect
By default it provide an good detection for the Grand Theft Auto series.
INJECTOR_GVM_PLUGIN_NAME
If this is defined, it will be used as the plugin name used at error messages.
By default it will use ""Unknown Plugin Name"
INJECTOR_GVM_DUMMY
If defined, the game_version_manager will be a dummy object
By default it provides a nice gvm for Grand Theft Auto series
INJECTOR_OWN_GVM
If defined, the game_version_manager should be implemented by the user before including this library.
By default it provides a nice gvm for Grand Theft Auto series
*/
#include "gvm/gvm.hpp"
namespace injector
{
/*
* auto_pointer
* Casts itself to another pointer type in the lhs
*/
union auto_pointer
{
protected:
friend union memory_pointer_tr;
template<class T> friend union basic_memory_pointer;
void* p;
uintptr_t a;
public:
auto_pointer() : p(0) {}
auto_pointer(const auto_pointer& x) : p(x.p) {}
explicit auto_pointer(void* x) : p(x) {}
explicit auto_pointer(uint32_t x) : a(x) {}
bool is_null() const { return this->p != nullptr; }
#if __cplusplus >= 201103L || _MSC_VER >= 1800
explicit operator bool() const { return is_null(); }
#endif
auto_pointer get() const { return *this; }
template<class T> T* get() const { return (T*) this->p; }
template<class T> T* get_raw() const { return (T*) this->p; }
template<class T>
operator T*() const { return reinterpret_cast<T*>(p); }
};
/*
* basic_memory_pointer
* A memory pointer class that is capable of many operations, including address translation
* MemTranslator is the translator functor
*/
template<class MemTranslator>
union basic_memory_pointer
{
protected:
void* p;
uintptr_t a;
// Translates address p to the running executable pointer
static auto_pointer memory_translate(void* p)
{
return auto_pointer(MemTranslator()(p));
}
public:
basic_memory_pointer() : p(nullptr) {}
basic_memory_pointer(std::nullptr_t) : p(nullptr) {}
basic_memory_pointer(uintptr_t x) : a(x) {}
basic_memory_pointer(const auto_pointer& x) : p(x.p) {}
basic_memory_pointer(const basic_memory_pointer& rhs) : p(rhs.p) {}
template<class T>
basic_memory_pointer(T* x) : p((void*)x) {}
// Gets the translated pointer (plus automatic casting to lhs)
auto_pointer get() const { return memory_translate(p); }
// Gets the translated pointer (casted to T*)
template<class T> T* get() const { return get(); }
// Gets the raw pointer, without translation (casted to T*)
template<class T> T* get_raw() const { return auto_pointer(p); }
// This type can get assigned from void* and uintptr_t
basic_memory_pointer& operator=(void* x) { return p = x, *this; }
basic_memory_pointer& operator=(uintptr_t x) { return a = x, *this; }
/* Arithmetic */
basic_memory_pointer operator+(const basic_memory_pointer& rhs) const
{ return basic_memory_pointer(this->a + rhs.a); }
basic_memory_pointer operator-(const basic_memory_pointer& rhs) const
{ return basic_memory_pointer(this->a - rhs.a); }
basic_memory_pointer operator*(const basic_memory_pointer& rhs) const
{ return basic_memory_pointer(this->a * rhs.a); }
basic_memory_pointer operator/(const basic_memory_pointer& rhs) const
{ return basic_memory_pointer(this->a / rhs.a); }
/* Comparision */
bool operator==(const basic_memory_pointer& rhs) const
{ return this->a == rhs.a; }
bool operator!=(const basic_memory_pointer& rhs) const
{ return this->a != rhs.a; }
bool operator<(const basic_memory_pointer& rhs) const
{ return this->a < rhs.a; }
bool operator<=(const basic_memory_pointer& rhs) const
{ return this->a <= rhs.a; }
bool operator>(const basic_memory_pointer& rhs) const
{ return this->a > rhs.a; }
bool operator>=(const basic_memory_pointer& rhs) const
{ return this->a >=rhs.a; }
bool is_null() const { return this->p == nullptr; }
uintptr_t as_int() const { return this->a; } // does not perform translation
#if __cplusplus >= 201103L || _MSC_VER >= 1800 // MSVC 2013
/* Conversion to other types */
explicit operator uintptr_t() const
{ return this->a; } // does not perform translation
explicit operator bool() const
{ return this->p != nullptr; }
#else
//operator bool() -------------- Causes casting problems because of implicitness, use !is_null()
//{ return this->p != nullptr; }
#endif
};
// Typedefs including memory translator for the above type
typedef basic_memory_pointer<address_manager::fn_mem_translator_nop> memory_pointer;
typedef basic_memory_pointer<address_manager::fn_mem_translator_nop> memory_pointer_raw;
typedef basic_memory_pointer<address_manager::fn_mem_translator_aslr> memory_pointer_aslr;
/*
* memory_pointer_tr
* Stores a basic_memory_pointer<Tr> as a raw pointer from translated pointer
*/
union memory_pointer_tr
{
protected:
void* p;
uintptr_t a;
public:
template<class Tr>
memory_pointer_tr(const basic_memory_pointer<Tr>& ptr)
: p(ptr.get())
{} // Constructs from a basic_memory_pointer
memory_pointer_tr(const auto_pointer& ptr)
: p(ptr.p)
{} // Constructs from a auto_pointer, probably comming from basic_memory_pointer::get
memory_pointer_tr(const memory_pointer_tr& rhs)
: p(rhs.p)
{} // Constructs from my own type, copy constructor
memory_pointer_tr(uintptr_t x)
: p(memory_pointer(x).get())
{} // Constructs from a integer, translating the address
memory_pointer_tr(void* x)
: p(memory_pointer(x).get())
{} // Constructs from a void pointer, translating the address
// Just to be method-compatible with basic_memory_pointer ...
auto_pointer get() { return auto_pointer(p); }
template<class T> T* get() { return get(); }
template<class T> T* get_raw() { return get(); }
memory_pointer_tr operator+(const uintptr_t& rhs) const
{ return memory_pointer_raw(this->a + rhs); }
memory_pointer_tr operator-(const uintptr_t& rhs) const
{ return memory_pointer_raw(this->a - rhs); }
memory_pointer_tr operator*(const uintptr_t& rhs) const
{ return memory_pointer_raw(this->a * rhs); }
memory_pointer_tr operator/(const uintptr_t& rhs) const
{ return memory_pointer_raw(this->a / rhs); }
bool is_null() const { return this->p == nullptr; }
uintptr_t as_int() const { return this->a; }
#if __cplusplus >= 201103L
explicit operator uintptr_t() const
{ return this->a; }
#else
#endif
};
/*
* ProtectMemory
* Makes the address @addr have a protection of @protection
*/
inline bool ProtectMemory(memory_pointer_tr addr, size_t size, DWORD protection)
{
return VirtualProtect(addr.get(), size, protection, &protection) != 0;
}
/*
* UnprotectMemory
* Unprotect the memory at @addr with size @size so it have all accesses (execute, read and write)
* Returns the old protection to out_oldprotect
*/
inline bool UnprotectMemory(memory_pointer_tr addr, size_t size, DWORD& out_oldprotect)
{
return VirtualProtect(addr.get(), size, PAGE_EXECUTE_READWRITE, &out_oldprotect) != 0;
}
/*
* scoped_unprotect
* RAII wrapper for UnprotectMemory
* On construction unprotects the memory, on destruction reprotects the memory
*/
struct scoped_unprotect
{
memory_pointer_raw addr;
size_t size;
DWORD dwOldProtect;
bool bUnprotected;
scoped_unprotect(memory_pointer_tr addr, size_t size)
{
if(size == 0) bUnprotected = false;
else bUnprotected = UnprotectMemory(this->addr = addr.get<void>(), this->size = size, dwOldProtect);
}
~scoped_unprotect()
{
if(bUnprotected) ProtectMemory(this->addr.get(), this->size, this->dwOldProtect);
}
};
/*
* WriteMemoryRaw
* Writes into memory @addr the content of @value with a sizeof @size
* Does memory unprotection if @vp is true
*/
inline void WriteMemoryRaw(memory_pointer_tr addr, void* value, size_t size, bool vp)
{
scoped_unprotect xprotect(addr, vp? size : 0);
memcpy(addr.get(), value, size);
}
/*
* ReadMemoryRaw
* Reads the memory at @addr with a sizeof @size into address @ret
* Does memory unprotection if @vp is true
*/
inline void ReadMemoryRaw(memory_pointer_tr addr, void* ret, size_t size, bool vp)
{
scoped_unprotect xprotect(addr, vp? size : 0);
memcpy(ret, addr.get(), size);
}
/*
* MemoryFill
* Fills the memory at @addr with the byte @value doing it @size times
* Does memory unprotection if @vp is true
*/
inline void MemoryFill(memory_pointer_tr addr, uint8_t value, size_t size, bool vp)
{
scoped_unprotect xprotect(addr, vp? size : 0);
memset(addr.get(), value, size);
}
/*
* WriteObject
* Assigns the object @value into the same object type at @addr
* Does memory unprotection if @vp is true
*/
template<class T>
inline T& WriteObject(memory_pointer_tr addr, const T& value, bool vp = false)
{
scoped_unprotect xprotect(addr, vp? sizeof(value) : 0);
return (*addr.get<T>() = value);
}
/*
* ReadObject
* Assigns the object @value with the value of the same object type at @addr
* Does memory unprotection if @vp is true
*/
template<class T>
inline T& ReadObject(memory_pointer_tr addr, T& value, bool vp = false)
{
scoped_unprotect xprotect(addr, vp? sizeof(value) : 0);
return (value = *addr.get<T>());
}
/*
* WriteMemory
* Writes the object of type T into the address @addr
* Does memory unprotection if @vp is true
*/
template<class T>
inline void WriteMemory(memory_pointer_tr addr, T value, bool vp = false)
{
WriteObject(addr, value, vp);
}
/*
* ReadMemory
* Reads the object type T at address @addr
* Does memory unprotection if @vp is true
*/
template<class T>
inline T ReadMemory(memory_pointer_tr addr, bool vp = false)
{
T value;
return ReadObject(addr, value, vp);
}
/*
* AdjustPointer
* Searches in the range [@addr, @addr + @max_search] for a pointer in the range [@default_base, @default_end] and replaces
* it with the proper offset in the pointer @replacement_base.
* Does memory unprotection if @vp is true.
*/
inline memory_pointer_raw AdjustPointer(memory_pointer_tr addr,
memory_pointer_raw replacement_base, memory_pointer_tr default_base, memory_pointer_tr default_end,
size_t max_search = 8, bool vp = true)
{
scoped_unprotect xprotect(addr, vp? max_search + sizeof(void*) : 0);
for(size_t i = 0; i < max_search; ++i)
{
memory_pointer_raw ptr = ReadMemory<void*>(addr + i);
if(ptr >= default_base.get() && ptr <= default_end.get())
{
auto result = replacement_base + (ptr - default_base.get());
WriteMemory<void*>(addr + i, result.get());
return result;
}
}
return nullptr;
}
/*
* GetAbsoluteOffset
* Gets absolute address based on relative offset @rel_value from instruction that ends at @end_of_instruction
*/
inline memory_pointer_raw GetAbsoluteOffset(int rel_value, memory_pointer_tr end_of_instruction)
{
return end_of_instruction.get<char>() + rel_value;
}
/*
* GetRelativeOffset
* Gets relative offset based on absolute address @abs_value for instruction that ends at @end_of_instruction
*/
inline int GetRelativeOffset(memory_pointer_tr abs_value, memory_pointer_tr end_of_instruction)
{
return uintptr_t(abs_value.get<char>() - end_of_instruction.get<char>());
}
/*
* ReadRelativeOffset
* Reads relative offset from address @at
*/
inline memory_pointer_raw ReadRelativeOffset(memory_pointer_tr at, size_t sizeof_addr = 4, bool vp = true)
{
switch(sizeof_addr)
{
case 1: return (GetAbsoluteOffset(ReadMemory<int8_t> (at, vp), at+sizeof_addr));
case 2: return (GetAbsoluteOffset(ReadMemory<int16_t>(at, vp), at+sizeof_addr));
case 4: return (GetAbsoluteOffset(ReadMemory<int32_t>(at, vp), at+sizeof_addr));
}
return nullptr;
}
/*
* MakeRelativeOffset
* Writes relative offset into @at based on absolute destination @dest
*/
inline void MakeRelativeOffset(memory_pointer_tr at, memory_pointer_tr dest, size_t sizeof_addr = 4, bool vp = true)
{
switch(sizeof_addr)
{
case 1: WriteMemory<int8_t> (at, static_cast<int8_t> (GetRelativeOffset(dest, at+sizeof_addr)), vp);
case 2: WriteMemory<int16_t>(at, static_cast<int16_t>(GetRelativeOffset(dest, at+sizeof_addr)), vp);
case 4: WriteMemory<int32_t>(at, static_cast<int32_t>(GetRelativeOffset(dest, at+sizeof_addr)), vp);
}
}
/*
* GetBranchDestination
* Gets the destination of a branch instruction at address @at
* *** Works only with JMP and CALL for now ***
*/
inline memory_pointer_raw GetBranchDestination(memory_pointer_tr at, bool vp = true)
{
switch(ReadMemory<uint8_t>(at, vp))
{
// We need to handle other instructions (and prefixes) later...
case 0xE8: // call rel
case 0xE9: // jmp rel
return ReadRelativeOffset(at + 1, 4, vp);
case 0xFF:
switch(ReadMemory<uint8_t>(at + 1, vp))
{
case 0x15: // call dword ptr [addr]
case 0x25: // jmp dword ptr [addr]
return *(ReadMemory<uintptr_t*>(at + 2, vp));
}
break;
}
return nullptr;
}
/*
* MakeJMP
* Creates a JMP instruction at address @at that jumps into address @dest
* If there was already a branch instruction there, returns the previosly destination of the branch
*/
inline memory_pointer_raw MakeJMP(memory_pointer_tr at, memory_pointer_raw dest, bool vp = true)
{
auto p = GetBranchDestination(at, vp);
WriteMemory<uint8_t>(at, 0xE9, vp);
MakeRelativeOffset(at+1, dest, 4, vp);
return p;
}
/*
* MakeCALL
* Creates a CALL instruction at address @at that jumps into address @dest
* If there was already a branch instruction there, returns the previosly destination of the branch
*/
inline memory_pointer_raw MakeCALL(memory_pointer_tr at, memory_pointer_raw dest, bool vp = true)
{
auto p = GetBranchDestination(at, vp);
WriteMemory<uint8_t>(at, 0xE8, vp);
MakeRelativeOffset(at+1, dest, 4, vp);
return p;
}
/*
* MakeJA
* Creates a JA instruction at address @at that jumps if above into address @dest
* If there was already a branch instruction there, returns the previosly destination of the branch
*/
inline void MakeJA(memory_pointer_tr at, memory_pointer_raw dest, bool vp = true)
{
WriteMemory<uint16_t>(at, 0x87F0, vp);
MakeRelativeOffset(at+2, dest, 4, vp);
}
/*
* MakeNOP
* Creates a bunch of NOP instructions at address @at
*/
inline void MakeNOP(memory_pointer_tr at, size_t count = 1, bool vp = true)
{
MemoryFill(at, 0x90, count, vp);
}
/*
* MakeRangedNOP
* Creates a bunch of NOP instructions at address @at until address @until
*/
inline void MakeRangedNOP(memory_pointer_tr at, memory_pointer_tr until, bool vp = true)
{
return MakeNOP(at, size_t(until.get_raw<char>() - at.get_raw<char>()), vp);
}
/*
* MakeRET
* Creates a RET instruction at address @at popping @pop values from the stack
* If @pop is equal to 0 it will use the 1 byte form of the instruction
*/
inline void MakeRET(memory_pointer_tr at, uint16_t pop = 0, bool vp = true)
{
WriteMemory(at, pop? 0xC2 : 0xC3, vp);
if(pop) WriteMemory(at+1, pop, vp);
}
/*
* lazy_pointer
* Lazy pointer, where it's final value will get evaluated only once when finally needed.
*/
template<uintptr_t addr>
struct lazy_pointer
{
public:
// Returns the final raw pointer
static auto_pointer get()
{
return xget().get();
}
template<class T>
static T* get()
{
return get().get<T>();
}
private:
// Returns the final pointer
static memory_pointer_raw xget()
{
static void* ptr = nullptr;
if(!ptr) ptr = memory_pointer(addr).get();
return memory_pointer_raw(ptr);
}
};
/*
* lazy_object
* Lazy object, where it's final object will get evaluated only once when finally needed.
*/
template<uintptr_t addr, class T>
struct lazy_object
{
static T& get()
{
static T data;
static bool has_data = false;
if(!has_data)
{
ReadObject<T>(addr, data, true);
has_data = true;
}
return data;
}
};
/*
Helpers
*/
template<class T>
inline memory_pointer mem_ptr(T p)
{
return memory_pointer(p);
}
template<class T>
inline memory_pointer_raw raw_ptr(T p)
{
return memory_pointer_raw(p);
}
template<class Tr>
inline memory_pointer_raw raw_ptr(basic_memory_pointer<Tr> p)
{
return raw_ptr(p.get());
}
template<uintptr_t addr>
inline memory_pointer_raw lazy_ptr()
{
return lazy_pointer<addr>::get();
}
template<class T>
inline memory_pointer_aslr aslr_ptr(T p)
{
return memory_pointer_aslr(p);
}
#ifndef INJECTOR_GVM_OWN_DETECT // Should we implement our detection method?
// Detects game, region and version; returns false if could not detect it
inline bool game_version_manager::Detect()
{
// Cleanup data
this->Clear();
// Find NT header
uintptr_t base = (uintptr_t) GetModuleHandleA(NULL);
IMAGE_DOS_HEADER* dos = (IMAGE_DOS_HEADER*)(base);
IMAGE_NT_HEADERS* nt = (IMAGE_NT_HEADERS*)(base + dos->e_lfanew);
// Look for game and version thought the entry-point
// Thanks to Silent for many of the entry point offsets
switch (base + nt->OptionalHeader.AddressOfEntryPoint + (0x400000 - base))
{
case 0x5C1E70: // GTA III 1.0
game = '3', major = 1, minor = 0, region = 0, steam = false;
return true;
case 0x5C2130: // GTA III 1.1
game = '3', major = 1, minor = 1, region = 0, steam = false;
return true;
case 0x5C6FD0: // GTA III 1.1 (Cracked Steam Version)
case 0x9912ED: // GTA III 1.1 (Encrypted Steam Version)
game = '3', major = 1, minor = 1, region = 0, steam = true;
return true;
case 0x667BF0: // GTA VC 1.0
game = 'V', major = 1, minor = 0, region = 0, steam = false;
return true;
case 0x667C40: // GTA VC 1.1
game = 'V', major = 1, minor = 1, region = 0, steam = false;
return true;
case 0x666BA0: // GTA VC 1.1 (Cracked Steam Version)
case 0xA402ED: // GTA VC 1.1 (Encrypted Steam Version)
game = 'V', major = 1, minor = 1, region = 0, steam = true;
return true;
case 0x82457C: // GTA SA 1.0 US Cracked
case 0x824570: // GTA SA 1.0 US Compact
game = 'S', major = 1, minor = 0, region = 'U', steam = false;
cracker = injector::ReadMemory<uint8_t>(raw_ptr(0x406A20), true) == 0xE9? 'H' : 0;
return true;
case 0x8245BC: // GTA SA 1.0 EU Cracked (??????)
case 0x8245B0: // GTA SA 1.0 EU Cracked
game = 'S', major = 1, minor = 0, region = 'E', steam = false;
cracker = injector::ReadMemory<uint8_t>(raw_ptr(0x406A20), true) == 0xE9? 'H' : 0; // just to say 'securom'
return true;
case 0x8252FC: // GTA SA 1.1 US Cracked
game = 'S', major = 1, minor = 1, region = 'U', steam = false;
return true;
case 0x82533C: // GTA SA 1.1 EU Cracked
game = 'S', major = 1, minor = 1, region = 'E', steam = false;
return true;
case 0x85EC4A: // GTA SA 3.0 (Cracked Steam Version)
case 0xD3C3DB: // GTA SA 3.0 (Encrypted Steam Version)
game = 'S', major = 3, minor = 0, region = 0, steam = true;
return true;
case 0xC965AD: // GTA IV 1.0.0.4 US
game = 'I', major = 1, minor = 0, majorRevision = 0, minorRevision = 4, region = 'U', steam = false;
return true;
case 0xD0D011: // GTA IV 1.0.0.7 US
game = 'I', major = 1, minor = 0, majorRevision = 0, minorRevision = 7, region = 'U', steam = false;
return true;
case 0xD0AF06: // GTA EFLC 1.1.2.0 US
game = 'E', major = 1, minor = 1, majorRevision = 2, minorRevision = 0, region = 'U', steam = false;
return true;
default:
return false;
}
}
#endif
} // namespace
+56
View File
@@ -0,0 +1,56 @@
/*
* Injectors - Utility / Helpers
*
* Copyright (C) 2014 LINK/2012 <dma_2012@hotmail.com>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*
*/
#pragma once
namespace injector
{
template<class T, T value>
T return_value()
{
return value;
}
template<class T>
void* force_ptr(const T& fun)
{
auto ptr = fun;
return *(void**)&ptr;
}
// Helper structure to help calling back what was there before a hook
// e.g. hb.fun = MakeCALL(0x0, raw_ptr(my_hook));
template<class FuncType>
struct hook_back
{
typedef FuncType func_type;
func_type fun;
hook_back() : fun(nullptr)
{}
};
};
+39
View File
@@ -0,0 +1,39 @@
#include "module_path.h"
ModulePath::ModulePath(HMODULE module)
{
m_Module = module;
SetModule(module);
}
void ModulePath::SetModule(HMODULE module)
{
m_ModuleDir.clear();
m_Module = module;
wchar_t w_path[512];
::GetModuleFileNameW(module, w_path, 512);
path_type module_path = w_path;
m_ModuleDir = module_path.parent_path();
}
HMODULE ModulePath::GetModule() const
{
return m_Module;
}
ModulePath::path_type ModulePath::GetModuleDir() const
{
return m_ModuleDir;
}
ModulePath::path_type ModulePath::GetRelativeSub(const path_type& rest) const
{
if (m_ModuleDir.empty())
{
return {};
}
return m_ModuleDir / rest;
}
+20
View File
@@ -0,0 +1,20 @@
#pragma once
#include "stdinc.h"
class ModulePath
{
public:
typedef std::filesystem::path path_type;
ModulePath() = default;
explicit ModulePath(HMODULE module);
void SetModule(HMODULE module);
HMODULE GetModule() const;
path_type GetModuleDir() const;
path_type GetRelativeSub(const path_type& rest) const;
private:
HMODULE m_Module;
path_type m_ModuleDir;
};
+1
View File
@@ -0,0 +1 @@
#include "stdinc.h"
+50
View File
@@ -0,0 +1,50 @@
#pragma once
#define _CRT_SECURE_NO_WARNINGS
#define NOMINMAX
#pragma warning(disable:4244)
#define VALIDATE_SIZE(expr, size) static_assert(sizeof(expr) == (size), "Wrong size.")
#include <Windows.h>
#include <d3d9.h>
#include <cstdint>
#include <cstddef>
#include <cstring>
#include <cstdio>
#include <fstream>
#include <vector>
#include <filesystem>
#include <regex>
#include <functional>
#include <array>
#include <utility>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <string>
#include <iterator>
#include <algorithm>
#include <chrono>
#include <span>
#include "injector/hooking.hpp"
#include "injector/calling.hpp"
#include "injector/injector.hpp"
#include "injector/assembly.hpp"
#include "BinaryFile.hpp"
#include "MemoryFile.hpp"
//vcpkg
#include <range/v3/all.hpp>
#include <utf8cpp/utf8.h>
#include <zlib.h>
typedef unsigned char uchar;
typedef unsigned short ushort;
typedef unsigned int uint;
typedef unsigned long ulong;
typedef unsigned long long ulonglong;
typedef unsigned long long uint64;
+9
View File
@@ -0,0 +1,9 @@
cmake_minimum_required(VERSION 3.15.0)
project(gta4.chs)
file(GLOB sources "*.cpp")
add_library(gta4.chs SHARED ${sources} ${common_sources})
set_target_properties(gta4.chs PROPERTIES SUFFIX ".asi")
+176
View File
@@ -0,0 +1,176 @@
#include "batch_matching.h"
#include "gta_aslr.h"
void batch_matching::set_aslr(const gta_aslr& handler)
{
aslr_handler = handler;
}
void batch_matching::register_step(const char* pattern, std::size_t expected_size, callback_type callback, bool confirm)
{
match_step step;
step.confirm = confirm;
step.expected_size = expected_size;
step.callback = std::move(callback);
_steps.emplace(pattern, std::move(step));
}
void batch_matching::clear()
{
_steps.clear();
}
bool batch_matching::perform_search()
{
bool result = false;
auto start_time = std::chrono::steady_clock::now();
byte_pattern pattern_obj;
for (auto& step : _steps)
{
//写入缓存的数据,验证不成功时才进行搜索
pattern_obj.set_pattern(step.first.c_str());
pattern_obj.set_results(step.second.result);
//如果缓存结果个数跟要求个数不一样,也要重新搜索
if (step.second.expected_size != step.second.result.size() || !pattern_obj.validate_result())
{
result = true;
pattern_obj.search();
step.second.result = pattern_obj.get();
}
}
auto end_time = std::chrono::steady_clock::now();
_last_cost_ms = static_cast<double>(std::chrono::duration_cast<std::chrono::microseconds>(end_time - start_time).count()) / 1000.0;
return result;
}
bool batch_matching::is_all_succeed() const
{
return ranges::all_of(_steps,
[](const std::pair<std::string, match_step>& step)
{
return step.second.expected_size == step.second.result.size();
});
}
void batch_matching::run_callbacks() const
{
for (auto& step : _steps)
{
if (step.second.confirm)
{
step.second.callback(step.second.result);
}
}
}
void batch_matching::write_log(const std::filesystem::path& filename, bool invalid_only) const
{
std::FILE* out = std::fopen(filename.string().c_str(), "wb");
if (!out)
{
return;
}
std::fprintf(out, "Time Cost: %.2lf ms\n\n", _last_cost_ms);
for (auto& step : _steps)
{
if (invalid_only && step.second.expected_size != step.second.result.size())
{
continue;
}
std::fprintf(out, "Pattern: %s\n", step.first.c_str());
std::fprintf(out, "Expected: %u\n", step.second.expected_size);
std::fprintf(out, "Found: %u\n", step.second.result.size());
for (std::size_t index = 0; index < step.second.result.size(); ++index)
{
std::fprintf(out, "Address%u: 0x%08X\n", index + 1, aslr_handler.GetIdaAddr(step.second.result[index].i()));
}
std::fprintf(out, "\n");
}
std::fflush(out);
std::fclose(out);
}
void batch_matching::write_cache(const std::filesystem::path& filename) const
{
BinaryFile out(filename, "wb");
if (!out)
{
return;
}
uint step_count = _steps.size();
out.Write(step_count);
for (auto& step : _steps)
{
//写入pattern
out.WriteArray2(std::span{ step.first });
std::vector<std::intptr_t> transformed_addr(step.second.result.size());
//转换成ida地址
ranges::transform(step.second.result, transformed_addr.begin(), [this](const memory_pointer& p)
{
return aslr_handler.GetIdaAddr(p.i());
});
//写入结果
out.WriteArray2(std::span{ transformed_addr });
}
out.Close();
}
void batch_matching::load_cache(const std::filesystem::path& filename)
{
BinaryFile in(filename, "rb");
if (!in)
{
return;
}
uint step_count;
in.Read(step_count);
for (uint step_index = 0; step_index < step_count; ++step_index)
{
std::string pattern_str;
std::vector<char> pattern_bytes;
in.ReadArray2(pattern_bytes);
pattern_str.assign(pattern_bytes.begin(), pattern_bytes.end());
std::vector<std::intptr_t> transformed_addr;
in.ReadArray2(transformed_addr);
auto step_it = _steps.find(pattern_str);
//忽略没注册的pattern
if (step_it == _steps.end())
{
continue;
}
//填入储存的结果
step_it->second.result.resize(transformed_addr.size());
ranges::transform(transformed_addr, step_it->second.result.begin(), [this](std::intptr_t i)
{
return memory_pointer(aslr_handler.GetIdaAddr(i));
});
}
}
+34
View File
@@ -0,0 +1,34 @@
#pragma once
#include "../common/stdinc.h"
#include "byte_pattern.h"
#include "gta_aslr.h"
class batch_matching
{
public:
typedef std::function<void(const byte_pattern::result_type&)> callback_type;
struct match_step
{
bool confirm;
std::size_t expected_size;
callback_type callback;
byte_pattern::result_type result;
};
void set_aslr(const gta_aslr& handler);
void register_step(const char* pattern, std::size_t expected_size, callback_type callback, bool confirm = true);
void clear();
bool perform_search(); //返回是否进行过搜索
bool is_all_succeed() const;
void run_callbacks() const;
void write_log(const std::filesystem::path& filename, bool invalid_only) const;
void write_cache(const std::filesystem::path& filename) const;
void load_cache(const std::filesystem::path& filename);
private:
std::unordered_map<std::string, match_step> _steps;
double _last_cost_ms;
gta_aslr aslr_handler;
};
+383
View File
@@ -0,0 +1,383 @@
//Core code from Hooking.Patterns
//https://github.com/ThirteenAG/Hooking.Patterns
#include "byte_pattern.h"
using namespace std;
using namespace std::chrono;
using namespace std::filesystem;
memory_pointer byte_pattern::get(size_t index) const
{
if (this->_results.size() < (index + 1))
{
return nullptr;
}
else
{
return this->_results.at(index);
}
}
byte_pattern::result_type byte_pattern::get() const
{
return _results;
}
memory_pointer byte_pattern::get_first() const
{
return this->get(0);
}
byte_pattern::byte_pattern()
{
reset_module();
}
byte_pattern& byte_pattern::set_pattern(const char* pattern_literal)
{
this->_bpattern.clear();
this->_mask.clear();
this->transform_pattern(pattern_literal);
this->_pattern = pattern_literal;
this->bm_preprocess();
return *this;
}
byte_pattern& byte_pattern::set_pattern(const void* pattern_binary, size_t size)
{
this->_bpattern.clear();
this->_mask.clear();
this->_bpattern.assign(reinterpret_cast<const uint8_t*>(pattern_binary), reinterpret_cast<const uint8_t*>(pattern_binary) + size);
this->_pattern = make_bytes_literal(pattern_binary, size);
this->_mask.resize(size, 0xFF);
this->bm_preprocess();
return *this;
}
byte_pattern& byte_pattern::set_results(const result_type& results)
{
_results = results;
return *this;
}
byte_pattern& byte_pattern::reset_module()
{
static HMODULE default_module = GetModuleHandleA(nullptr);
return set_module(default_module);
}
byte_pattern& byte_pattern::set_module(memory_pointer module)
{
this->get_module_range(module);
return *this;
}
byte_pattern& byte_pattern::set_range(memory_pointer beg, memory_pointer end)
{
this->_range.first = beg;
this->_range.second = end;
return *this;
}
byte_pattern& byte_pattern::search()
{
this->bm_search();
return *this;
}
byte_pattern& byte_pattern::find_pattern(const char* pattern_literal)
{
this->set_pattern(pattern_literal).search();
return *this;
}
byte_pattern& byte_pattern::find_pattern(const void* pattern_binary, size_t size)
{
this->set_pattern(pattern_binary, size).search();
return *this;
}
std::vector<std::string> byte_pattern::split_pattern(const char* literal)
{
std::vector<std::string> result;
std::string sub_pattern;
while (true)
{
if (*literal == ' ' || *literal == 0)
{
if (!sub_pattern.empty())
{
result.push_back(sub_pattern);
}
sub_pattern.clear();
}
else
{
sub_pattern += *literal;
}
if (*literal == 0)
{
break;
}
++literal;
}
return result;
}
pair<uint8_t, uint8_t> byte_pattern::parse_sub_pattern(const std::string& sub)
{
auto digit_to_value = [](char character) {
if ('0' <= character && character <= '9') return (character - '0');
else if ('A' <= character && character <= 'F') return (character - 'A' + 10);
else if ('a' <= character && character <= 'f') return (character - 'a' + 10);
throw invalid_argument("Could not parse pattern."); };
pair<uint8_t, uint8_t> result;
if (sub.size() == 1)
{
if (sub[0] == '?')
{
result.first = 0;
result.second = 0;
}
else
{
result.first = digit_to_value(sub[0]);
result.second = 0xFF;
}
}
else if (sub.size() == 2)
{
if (sub[0] == '?' && sub[1] == '?')
{
result.first = 0;
result.second = 0;
}
else if (sub[0] == '?')
{
result.first = digit_to_value(sub[1]);
result.second = 0xF;
}
else if (sub[1] == '?')
{
result.first = (digit_to_value(sub[0]) << 4);
result.second = 0xF0;
}
else
{
result.first = ((digit_to_value(sub[0]) << 4) | digit_to_value(sub[1]));
result.second = 0xFF;
}
}
else
{
throw invalid_argument("Could not parse pattern.");
}
return result;
}
void byte_pattern::transform_pattern(const char* literal)
{
vector<string> sub_patterns;
this->_pattern = literal;
if (this->_pattern.empty())
{
return;
}
sub_patterns = split_pattern(literal);
for (auto sub : sub_patterns)
{
auto pat = parse_sub_pattern(sub);
this->_bpattern.push_back(pat.first);
this->_mask.push_back(pat.second);
}
}
void byte_pattern::get_module_range(memory_pointer module)
{
static auto getSection = [](const PIMAGE_NT_HEADERS nt_headers, unsigned section) -> PIMAGE_SECTION_HEADER
{
return reinterpret_cast<PIMAGE_SECTION_HEADER>(
reinterpret_cast<UCHAR*>(nt_headers->OptionalHeader.DataDirectory) +
nt_headers->OptionalHeader.NumberOfRvaAndSizes * sizeof(IMAGE_DATA_DIRECTORY) +
section * sizeof(IMAGE_SECTION_HEADER));
};
_range.first = module;
_range.second = 0;
auto dosHeader = module.p<IMAGE_DOS_HEADER>();
auto ntHeader = module.p<IMAGE_NT_HEADERS>(dosHeader->e_lfanew);
for (int i = 0; i < ntHeader->FileHeader.NumberOfSections; i++)
{
auto sec = getSection(ntHeader, i);
auto secSize = sec->SizeOfRawData != 0 ? sec->SizeOfRawData : sec->Misc.VirtualSize;
if (sec->Characteristics & IMAGE_SCN_MEM_EXECUTE)
_range.second = _range.first + sec->VirtualAddress + secSize;
if ((i == ntHeader->FileHeader.NumberOfSections - 1) && _range.second == 0)
_range.second = _range.first + sec->PointerToRawData + secSize;
}
}
void byte_pattern::clear()
{
this->_pattern.clear();
this->_bpattern.clear();
this->_mask.clear();
this->_results.clear();
}
bool byte_pattern::validate_result() const
{
const uint8_t* pbytes = this->_bpattern.data();
const uint8_t* pmask = this->_mask.data();
for (auto& result : _results)
{
__try
{
auto ptr = result.p<const uint8_t>();
for (size_t i = 0; i < _bpattern.size(); i++)
{
if ((pbytes[i] & pmask[i]) != (ptr[i] & pmask[i]))
{
return false;
}
}
}
__except ((GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION) ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH)
{
return false;
}
}
return true;
}
size_t byte_pattern::count() const
{
return this->_results.size();
}
bool byte_pattern::has_size(size_t expected) const
{
return (this->_results.size() == expected);
}
bool byte_pattern::empty() const
{
return this->_results.empty();
}
void byte_pattern::bm_preprocess()
{
ptrdiff_t index;
const uint8_t* pbytes = this->_bpattern.data();
const uint8_t* pmask = this->_mask.data();
auto pattern_len = static_cast<ptrdiff_t>(this->_bpattern.size());
for (uint32_t bc = 0; bc < 256; ++bc)
{
for (index = pattern_len - 1; index >= 0; --index)
{
if ((pbytes[index] & pmask[index]) == (bc & pmask[index]))
{
break;
}
}
this->_bmbc[bc] = index;
}
}
void byte_pattern::bm_search()
{
const uint8_t* pbytes = this->_bpattern.data();
const uint8_t* pmask = this->_mask.data();
auto pattern_len = static_cast<ptrdiff_t>(this->_bpattern.size());
this->_results.clear();
if (pattern_len == 0)
{
return;
}
uint8_t* range_begin = reinterpret_cast<uint8_t*>(this->_range.first);
uint8_t* range_end = reinterpret_cast<uint8_t*>(this->_range.second - pattern_len);
ptrdiff_t index;
__try
{
while (range_begin <= range_end)
{
for (index = pattern_len - 1; index >= 0; --index)
{
if ((pbytes[index] & pmask[index]) != (range_begin[index] & pmask[index]))
{
break;
}
}
if (index == -1)
{
this->_results.emplace_back(range_begin);
range_begin += pattern_len;
}
else
{
range_begin += max(index - this->_bmbc[range_begin[index]], 1);
}
}
}
__except ((GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION) ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH)
{
}
}
std::string byte_pattern::make_bytes_literal(memory_pointer pointer, std::size_t length)
{
std::string result;
for (int i = 0; i < static_cast<int>(length); i++)
{
char buffer[10];
std::sprintf(buffer, "%02X ", static_cast<int>(*pointer.p<uint8_t>(i)));
result += buffer;
}
if (!result.empty())
{
result.pop_back();
}
return result;
}
+102
View File
@@ -0,0 +1,102 @@
//Core code from Hooking.Patterns
//https://github.com/ThirteenAG/Hooking.Patterns
#pragma once
#include "../common/stdinc.h"
class memory_pointer
{
public:
memory_pointer() :_address(0) {}
memory_pointer(const void* pointer) :_address(reinterpret_cast<std::intptr_t>(pointer)) {}
explicit memory_pointer(std::intptr_t address) :_address(address) {}
template <typename T = void>
T* p(std::intptr_t offset = 0) const
{
return reinterpret_cast<T*>(i(offset));
}
std::intptr_t i(std::intptr_t offset = 0) const
{
return (_address + offset);
}
memory_pointer& operator=(const void* pointer)
{
_address = reinterpret_cast<std::intptr_t>(pointer);
return *this;
}
memory_pointer& operator=(std::intptr_t address)
{
_address = address;
return *this;
}
template <typename T>
operator T* () const
{
return p<T>();
}
operator std::intptr_t() const
{
return _address;
}
private:
std::intptr_t _address;
};
class byte_pattern
{
public:
typedef std::vector<memory_pointer> result_type;
byte_pattern();
byte_pattern& set_pattern(const char* pattern_literal);
byte_pattern& set_pattern(const void* pattern_binary, std::size_t size);
byte_pattern& set_results(const result_type& results); //直接设定结果,供验证用
byte_pattern& reset_module();
byte_pattern& set_module(memory_pointer module);
byte_pattern& set_range(memory_pointer beg, memory_pointer end);
byte_pattern& search();
byte_pattern& find_pattern(const char* pattern_literal);
byte_pattern& find_pattern(const void* pattern_binary, std::size_t size);
memory_pointer get(std::size_t index) const;
result_type get() const;
memory_pointer get_first() const;
std::size_t count() const;
bool has_size(std::size_t expected) const;
bool empty() const;
void clear();
bool validate_result() const;
private:
std::pair<std::uintptr_t, std::uintptr_t> _range;
std::vector<std::uint8_t> _bpattern;
std::vector<std::uint8_t> _mask;
result_type _results;
std::string _pattern;
std::ptrdiff_t _bmbc[256];
static std::vector<std::string> split_pattern(const char* literal);
static std::pair<uint8_t, uint8_t> parse_sub_pattern(const std::string& sub);
void transform_pattern(const char* literal);
void get_module_range(memory_pointer module);
void bm_preprocess();
void bm_search();
static std::string make_bytes_literal(memory_pointer pointer, std::size_t length);
};
+28
View File
@@ -0,0 +1,28 @@
#include "char_table.h"
void CCharTable::LoadTable(const std::filesystem::path& filename)
{
BinaryFile file(filename, "rb");
file.ReadArray2(m_Chars);
}
std::pair<uint, uint> CCharTable::GetCharPos(GTAChar chr) const
{
auto char_it = ranges::lower_bound(m_Chars, chr);
if (char_it != m_Chars.end() && *char_it == chr)
{
auto diff = char_it - m_Chars.begin();
return { diff / g_CharsPerLine,diff % g_CharsPerLine };
}
else
{
return GetCharPos(L'?');
}
}
const std::vector<char32_t>& CCharTable::GetChars() const
{
return m_Chars;
}
+14
View File
@@ -0,0 +1,14 @@
#pragma once
#include "../common/stdinc.h"
#include "../common/common.h"
class CCharTable
{
public:
void LoadTable(const std::filesystem::path& filename);
std::pair<uint, uint> GetCharPos(GTAChar chr) const;
const std::vector<char32_t>& GetChars() const;
private:
std::vector<char32_t> m_Chars;
};
+29
View File
@@ -0,0 +1,29 @@
#pragma once
#include "../common/stdinc.h"
//在没有定义的情况下,手动访问结构体成员
class class_pointer
{
public:
template <typename T>
T* get_field(std::uintptr_t offset) const
{
return reinterpret_cast<T*>(reinterpret_cast<std::intptr_t> (this) + offset);
}
//TODO: call_member_function
template <typename Ret, typename ...Arg>
Ret call_member_function(std::uintptr_t func_addr, Arg ...args)
{
return reinterpret_cast<Ret(__thiscall*)(class_pointer*, Arg...)>(func_addr)(this, std::forward<Arg>(args)...);
}
//TODO: call_virtual_function
template <typename Ret, typename ...Arg>
Ret call_virtual_function(std::size_t index, Arg ...args)
{
auto func_addr = (*get_field<std::uintptr_t*>(0))[index];
return call_member_function(func_addr, std::forward<Arg>(args)...);
}
};
+11
View File
@@ -0,0 +1,11 @@
#include "plugin.h"
BOOL WINAPI DllMain(HMODULE module, DWORD reason, LPVOID reserved)
{
if (reason == DLL_PROCESS_ATTACH)
{
return plugin.Init(module) ? TRUE : FALSE;
}
return TRUE;
}
+439
View File
@@ -0,0 +1,439 @@
#include "font.h"
#include "plugin.h"
#include "gta_string.h"
static const float fChsWidth = 32.0f;
static const float fChsWidthFix = -1.0f;
static const float fSpriteWidth = 64.0f;
static const float fSpriteHeight = 80.0f;
static const float fTextureResolution = 4096.0f;
static const float fTextureRowsCount = 51.2f;
static const float fTextureColumnsCount = 64.0f;
static const float fRatio = 4.0f;
static grcTexturePC* pChsTexture;
const GTAChar* CFont::SkipWord_Prolog(std::uintptr_t address)
{
auto ptr = reinterpret_cast<const GTAChar*>(address & 0x7FFFFFFF);
if ((address & 0x80000000) == 0)
{
ptr = SkipWord(ptr);
}
SkipSpecialPunctuationMarks(ptr);
return ptr;
}
bool CFont::IsSpecialPunctuationMark(GTAChar chr)
{
#if 0
return false;
#else
//—、。《》「」『』!,-:;?~
return
//chr == L'—' ||
chr == L'、' ||
chr == L'。' ||
//chr == L'《' ||
chr == L'》' ||
//chr == L'「' ||
chr == L'」' ||
//chr == L'『' ||
chr == L'』' ||
chr == L'!' ||
chr == L',' ||
//chr == L'-' ||
chr == L':' ||
chr == L';' ||
chr == L'?' ||
chr == L'~' ||
chr == L'…'
;
#endif
}
void CFont::SkipSpecialPunctuationMarks(const GTAChar*& str)
{
while (IsSpecialPunctuationMark(*str))
{
++str;
}
}
void CFont::AddSpecialPunctuationMarksWidth(const GTAChar*& str, float* width)
{
while (IsSpecialPunctuationMark(*str))
{
*width += GetCharacterSizeNormalDispatch(*str - 0x20);
++str;
}
}
void* __fastcall CFont::LoadTextureCB(void* pDictionary, int, uint hash)
{
void* result = plugin.game.Dictionary_grcTexturePC_GetElementByKey(pDictionary, hash);
pChsTexture = plugin.game.Dictionary_grcTexturePC_GetElementByKey(pDictionary, plugin.game.Hash_HashStringFromSeediCase("font_chs"));
return result;
}
const GTAChar* CFont::SkipWord(const GTAChar* str)
{
if (str == nullptr)
{
return str;
}
auto begin = str;
auto current = str;
while (true)
{
GTAChar chr = *current;
if (chr == ' ' || chr == '~' || chr == 0)
{
break;
}
if (!IsNativeChar(chr))
{
if (current == begin)
{
++current;
}
break;
}
else
{
++current;
}
}
SkipSpecialPunctuationMarks(current);
return current;
}
const GTAChar* CFont::SkipSpaces(const GTAChar* text)
{
if (text == nullptr)
return text;
while (*text == ' ')
{
++text;
}
return text;
}
float CFont::GetMaxWordWidth(const GTAChar* text)
{
if (text == nullptr)
return 0.0f;
float max_word_width = 0.0f;
while (*text != 0)
{
float word_width = GetStringWidthRemake(text, false);
if (word_width > max_word_width)
max_word_width = word_width;
text = SkipSpaces(SkipWord(text));
}
return max_word_width;
}
float CFont::GetStringWidthRemake(const GTAChar* str, bool get_all)
{
float current_width = 0.0f, max_width = 0.0f;
bool had_word = false;
auto render_index = plugin.game.Font_GetRenderIndex();
auto& using_details = plugin.game.game_addr.pFont_Details[render_index];
TokenStruct token_data;
GTAChar token_string[64];
if (str == nullptr)
{
return 0.0f;
}
while (true)
{
auto chr = *str;
if (chr == 0)
{
break;
}
else if (chr == ' ')
{
if (!get_all)
break;
}
else if (!IsNativeChar(chr))
{
//汉字
//有可能是英语单词+汉字,要断开
if (had_word && !get_all)
{
break;
}
}
else if (chr == '~')
{
//token
if (had_word && !get_all)
break;
//91BEC3
token_string[0] = 0;
int token_type = plugin.game.Font_ParseToken(++str, token_string, &token_data);
if (token_data.f110 == 0)
{
//91C0B4
if (token_type < 256 || token_type > 300)
{
//91C116
if (gta_string::gtaWcslen(token_string) > 0)
{
//91C122
plugin.game.Font_AddTokenStringWidth(token_string, &current_width, render_index);
had_word = true;
}
}
else
{
//91C0C3
current_width += plugin.game.game_addr.pFont_ButtonWidths[token_type - 255]
* using_details.fBlipScaleX;
had_word = true;
}
}
else
{
//91BF11
for (int token_index = 0; token_index < 4; ++token_index)
{
switch (token_data.a110[token_index])
{
case 1:
{
//91BF26
current_width += plugin.game.game_addr.pFont_ButtonWidths[token_data.f0[token_index] - 255]
* using_details.fBlipScaleX;
had_word = true;
break;
}
case 2:
{
//91BF53
plugin.game.Font_AddTokenStringWidth(token_data.f10[token_index], &current_width, render_index);
had_word = true;
break;
}
default:
{
break;
}
}
}
}
//91BF9E
if (token_type >= 1000)
{
//91BFA6
current_width += *plugin.game.game_addr.pFont_BlipWidth
* using_details.fBlipScaleX;
had_word = true;
}
//91BFD3
while (*str != '~')
{
//91BFE0
if (*str == 'n')
{
max_width = std::max(max_width, current_width);
current_width = 0.0f;
}
++str;
}
//91C013
//跳过后边的'~'
++str;
AddSpecialPunctuationMarksWidth(str, &current_width);
//处理token后立即判断分词,配合ProcessString逻辑
if (!get_all)
{
break;
}
continue;
}
//累加字符宽度
current_width += GetCharacterSizeNormalDispatch(chr - 0x20);
had_word = true;
++str;
auto old_ptr = str;
AddSpecialPunctuationMarksWidth(str, &current_width);
//解决标英交替时的宽度计算错误
if (str != old_ptr && !get_all)
{
break;
}
//计算汉字宽度之后立即判断一次分词
if (!IsNativeChar(chr) && !get_all)
{
break;
}
}
return std::max(current_width, max_width);
}
float CFont::GetCHSCharacterSizeNormal()
{
auto render_index = plugin.game.Font_GetRenderIndex();
auto& using_details = plugin.game.game_addr.pFont_Details[render_index];
auto& using_font_data = plugin.game.game_addr.pFont_Datas[using_details.nFont];
float extra_width = using_font_data.fWidthOfSpaceBetweenChars[using_details.nExtraWidthIndex];
return (((fChsWidth + fChsWidthFix + extra_width) / *plugin.game.game_addr.pFont_ResolutionX + using_details.fEdgeSize2) *
using_details.fScaleX);
}
float CFont::GetCharacterSizeNormalDispatch(GTAChar chr)
{
if (IsNativeChar(chr + 0x20))
{
return plugin.game.Font_GetCharacterSizeNormal(chr);
}
else
{
return GetCHSCharacterSizeNormal();
}
}
float CFont::GetCHSCharacterSizeDrawing(bool use_extra_width)
{
float extra_width = 0.0f;
auto render_state = plugin.game.game_addr.pFont_RenderState;
auto& using_font_data = plugin.game.game_addr.pFont_Datas[render_state->nFont];
if (use_extra_width)
{
extra_width = using_font_data.fWidthOfSpaceBetweenChars[render_state->nExtraWidthIndex];
}
return ((fChsWidth + fChsWidthFix + extra_width) / *plugin.game.game_addr.pFont_ResolutionX + render_state->fEdgeSize) *
render_state->fScaleX;
}
float CFont::GetCharacterSizeDrawingDispatch(GTAChar chr, bool use_extra_width)
{
if (IsNativeChar(chr + 0x20))
{
return plugin.game.Font_GetCharacterSizeDrawing(chr, use_extra_width);
}
else
{
return GetCHSCharacterSizeDrawing(use_extra_width);
}
}
void CFont::PrintCHSChar(float x, float y, GTAChar chr)
{
CRect screen_rect, texture_rect;
auto [row, column] = plugin.char_table.GetCharPos(chr);
auto render_state = plugin.game.game_addr.pFont_RenderState;
float texture_sprite_width = fSpriteWidth / fTextureResolution;
float screen_character_width = (fChsWidth / *plugin.game.game_addr.pFont_ResolutionX + render_state->fEdgeSize) *
render_state->fScaleX;
float screen_character_height = render_state->fScaleY * 0.06558f;
screen_rect.bottom_left.x = x;
screen_rect.bottom_left.y = y + screen_character_height;
screen_rect.top_right.x = x + screen_character_width;
screen_rect.top_right.y = y;
texture_rect.top_right.y = (row - 0.045f) * fSpriteHeight / fTextureResolution + 8.0f / fTextureResolution;
if (texture_rect.top_right.y > 1.0f)
{
texture_rect.top_right.y = 1.0f;
}
texture_rect.bottom_left.y = (row - 0.045f) * fSpriteHeight / fTextureResolution + 79.0f / fTextureResolution - 0.001f / fRatio + 0.0048f / fRatio;
texture_rect.bottom_left.x = column / fTextureColumnsCount;
texture_rect.top_right.x = column / fTextureColumnsCount + texture_sprite_width;
switch (render_state->nFont)
{
case 0:
case 1:
case 3:
plugin.game.Graphics_SetRenderState(pChsTexture);
break;
default:
break;
}
plugin.game.Font_Render2DPrimitive(&screen_rect, &texture_rect, render_state->field_18, false);
}
void CFont::PrintCharDispatch(float x, float y, GTAChar chr, bool buffered)
{
if (plugin.game.game_addr.pFont_RenderState->TokenType != 0 || IsNativeChar(chr + 0x20))
{
plugin.game.Font_PrintChar(x, y, chr, buffered);
}
else
{
if ((chr + 0x20) == 0x3000)
{
return;
}
if (y < -0.06558f || y > 1.0f)
{
return;
}
if (-(GetCHSCharacterSizeDrawing(true) / plugin.game.game_addr.pFont_RenderState->fScaleX) > x || x > 1.0f)
{
return;
}
PrintCHSChar(x, y, chr + 0x20);
}
}
+148
View File
@@ -0,0 +1,148 @@
#pragma once
#include "../common/stdinc.h"
#include "../common/common.h"
enum eTextAlignment
{
ALIGN_CENTER = 0, //居中对齐
ALIGN_LEFT = 1, //左对齐
ALIGN_RIGHT = 2, //右对齐
ALIGN_LEFT_RIGHT = 3 //多余的宽度会平分到每个空格中
};
class CFontDetails
{
public:
uint field_0;
float fScaleX;
float fScaleY;
float fBlipScaleX;
int alignment;
bool bDrawBox;
bool field_15;
bool bProportional;
bool field_17;
bool bUseUnderscore;
bool bUseColor;
bool field_1A;
char pad1[1];
uint BoxColor;
float fWrapX;
float fCentreWrapX;
uchar nFont;
uchar nExtraWidthIndex;
char pad2[2];
float fDropShadowSize;
uint DropShadowColor;
float fEdgeSize2;
float fEdgeSize;
float fLineHeight;
float fExtraSpaceWidth;
bool bIgnoreWidthLimit;
char pad3[3];
};
VALIDATE_SIZE(CFontDetails, 0x48);
class CFontInfo
{
public:
uchar iPropValues[255];
uchar iTextureMap[255];
char pad1[2];
float fUnpropValue;
float fWidthOfSpaceBetweenChars[5];
float fJapaneseSubFont1SpaceWidth;
float fJapaneseSubFont2SpaceWidth;
int iMainFontStart;
int iMainFontEnd;
int iSubFont1Start;
int iSubFont1End;
int iSubFont2Start;
int iSubFont2End;
int iCommonFontStart;
int iCommonFontEnd;
void* pTexture;
float fTextureWidth;
float fTextureHeight;
float fSpriteSize;
float field_250;
float field_254;
};
VALIDATE_SIZE(CFontInfo, 0x258);
class CFontRenderState
{
public:
uint magic;
float field_4;
float field_8;
float fScaleX;
float fScaleY;
float field_14;
uint field_18;
float field_1C;
int field_20;
bool field_24;
uchar nExtraWidthIndex;
bool bProportional;
bool field_27;
bool bUseUnderscore;
uchar nFont;
char pad1[2];
float fEdgeSize;
uint TokenType;
bool field_34;
char pad2[3];
};
VALIDATE_SIZE(CFontRenderState, 0x38);
class CFontBuffer
{
public:
CFontRenderState render_state;
GTAChar buffer[996];
};
VALIDATE_SIZE(CFontBuffer, 2048);
struct TokenStruct
{
int f0[4];
GTAChar f10[4][32];
union
{
int f110 = 0;
uchar a110[4];
};
};
VALIDATE_SIZE(TokenStruct, 0x114);
class CFont
{
public:
static void* __fastcall LoadTextureCB(void*, int, uint);
static float GetCharacterSizeNormalDispatch(GTAChar chr);
static float GetCHSCharacterSizeNormal();
static float GetCharacterSizeDrawingDispatch(GTAChar chr, bool use_extra_width);
static float GetCHSCharacterSizeDrawing(bool use_extra_width);
static void PrintCharDispatch(float x, float y, GTAChar chr, bool buffered);
static void PrintCHSChar(float x, float y, GTAChar chr);
//判断字符是否为不能放在行首的标点符号
static bool IsSpecialPunctuationMark(GTAChar chr);
//将特殊字符看作单词的一部分
static void SkipSpecialPunctuationMarks(const GTAChar*& str);
static void AddSpecialPunctuationMarksWidth(const GTAChar*& str, float* width);
static const GTAChar* SkipWord(const GTAChar* str);
static const GTAChar* SkipWord_Prolog(std::uintptr_t address);
static const GTAChar* SkipSpaces(const GTAChar* text);
static float GetMaxWordWidth(const GTAChar* text);
static float GetStringWidthRemake(const GTAChar* str, bool get_all);
};
+66
View File
@@ -0,0 +1,66 @@
#include "game.h"
#include "plugin.h"
void CGame::Graphics_SetRenderState(void* texture, int arg4)
{
injector::cstd<void(void*, int)>::call(game_addr.fnGraphics_SetRenderState, texture, arg4);
}
grcTexturePC* CGame::Dictionary_grcTexturePC_GetElementByKey(void* dictionary, uint hash)
{
return injector::thiscall<grcTexturePC* (void*, uint)>::call(game_addr.fnDictionary_GetElementByKey, dictionary, hash);
}
uint CGame::Hash_HashStringFromSeediCase(const char* str, uint hash)
{
return injector::cstd<uint(const char*, uint)>::call(game_addr.fnHash_HashStringFromSeediCase, str, hash);
}
uchar CGame::Font_GetRenderIndex()
{
return injector::cstd<uchar()>::call(game_addr.fnFont_GetRenderIndex);
}
float CGame::Font_GetCharacterSizeNormal(GTAChar chr)
{
return injector::cstd<float(GTAChar)>::call(game_addr.fnFont_GetCharacterSizeNormal, chr);
}
float CGame::Font_GetCharacterSizeDrawing(GTAChar chr, bool use_extra_width)
{
return injector::cstd<float(GTAChar, bool)>::call(game_addr.fnFont_GetCharacterSizeDrawing, chr, use_extra_width);
}
void CGame::Font_Render2DPrimitive(const CRect* screen_rect, const CRect* texture_rect, uint color, bool buffered)
{
injector::cstd<void(const CRect*, const CRect*, uint, bool)>::call(game_addr.fnFont_Render2DPrimitive, screen_rect, texture_rect, color, buffered);
}
void CGame::Font_PrintChar(float posx, float posy, GTAChar chr, bool buffered)
{
injector::cstd<void(float, float, GTAChar, bool)>::call(game_addr.fnFont_PrintChar, posx, posy, chr, buffered);
}
int CGame::Font_ParseToken(const GTAChar* text, GTAChar* text_to_show, TokenStruct* token_data)
{
return injector::cstd<int(const GTAChar*, GTAChar*, TokenStruct*)>::call(
game_addr.fnFont_ParseToken, text, text_to_show, token_data);
}
const GTAChar* CGame::Font_ProcessToken(const GTAChar* text, uint* color, bool get_color, uchar* color_code,
int* key_number, bool* is_new_line_token, GTAChar* text_to_show, TokenStruct* token_data)
{
return injector::cstd<const GTAChar* (const GTAChar*, uint*, bool, uchar*, int*, bool*, GTAChar*, TokenStruct*)>::call(
game_addr.fnFont_ProcessToken, text, color, get_color, color_code, key_number, is_new_line_token,
text_to_show, token_data);
}
void CGame::Font_AddTokenStringWidth(const GTAChar* text, float* width, int render_index)
{
return injector::cstd<void(const GTAChar*, float*, int)>::call(game_addr.fnFont_AddTokenStringWidth, text, width, render_index);
}
void CGame::MailAppendByteString(int id, const uchar* str)
{
injector::stdcall<void(int, const uchar*)>::call(game_addr.fnMailAppendByteString, id, str);
}
+61
View File
@@ -0,0 +1,61 @@
#pragma once
#include "../common/stdinc.h"
#include "font.h"
struct grcTexturePC;
class CGame
{
public:
struct
{
void* fnGraphics_SetRenderState;
void* fnDictionary_GetElementByKey;
void* fnHash_HashStringFromSeediCase;
CFontInfo* pFont_Datas;
CFontDetails* pFont_Details;
CFontRenderState* pFont_RenderState;
float* pFont_BlipWidth;
float* pFont_ResolutionX;
float* pFont_ButtonWidths;
void* fnFont_GetRenderIndex;
void* fnFont_PrintChar;
void* fnFont_GetCharacterSizeNormal;
void* fnFont_GetCharacterSizeDrawing;
void* fnFont_Render2DPrimitive;
void* fnFont_AddTokenStringWidth;
void* fnFont_ParseToken;
void* fnFont_ProcessToken;
void* fnMailAppendByteString;
char* pDLCTruncateBuffer;
} game_addr;
void Graphics_SetRenderState(void* texture, int = 1);
grcTexturePC* Dictionary_grcTexturePC_GetElementByKey(void* dictionary, uint hash);
uint Hash_HashStringFromSeediCase(const char* str, uint hash = 0);
uchar Font_GetRenderIndex();
float Font_GetCharacterSizeNormal(GTAChar chr);
float Font_GetCharacterSizeDrawing(GTAChar chr, bool use_extra_width);
void Font_Render2DPrimitive(const CRect* screen_rect, const CRect* texture_rect, uint color, bool buffered);
void Font_PrintChar(float posx, float posy, GTAChar chr, bool buffered);
//ParseToken逻辑
//1000+ BLIP
//256-300 按键类
//全部strcmp都不通过则当成单字符token,返回此字符
int Font_ParseToken(const GTAChar* text, GTAChar* text_to_show, TokenStruct* token_data);
const GTAChar* Font_ProcessToken(const GTAChar* text, uint* color, bool get_color, uchar* color_code, int* key_number, bool* is_new_line_token, GTAChar* text_to_show, TokenStruct* token_data);
void Font_AddTokenStringWidth(const GTAChar* text, float* width, int render_index);
void MailAppendByteString(int id, const uchar* str);
};
+26
View File
@@ -0,0 +1,26 @@
#include "gta_aslr.h"
void gta_aslr::SetGameBase(std::intptr_t base)
{
m_Base = base;
}
void gta_aslr::SetGameBase(HMODULE module)
{
m_Base = reinterpret_cast<std::intptr_t>(module);
}
void gta_aslr::SetIdaBase(std::intptr_t base)
{
m_IdaBase = base;
}
std::intptr_t gta_aslr::GetGameAddr(std::intptr_t ida_addr) const
{
return ida_addr + m_Base - m_IdaBase;
}
std::intptr_t gta_aslr::GetIdaAddr(std::intptr_t game_addr) const
{
return game_addr - m_Base + m_IdaBase;
}
+17
View File
@@ -0,0 +1,17 @@
#pragma once
#include "../common/stdinc.h"
class gta_aslr
{
public:
void SetGameBase(std::intptr_t base);
void SetGameBase(HMODULE module);
void SetIdaBase(std::intptr_t base);
std::intptr_t GetGameAddr(std::intptr_t ida_addr) const;
std::intptr_t GetIdaAddr(std::intptr_t game_addr) const;
private:
std::intptr_t m_Base = 0x400000;
std::intptr_t m_IdaBase = 0x400000;
};
+34
View File
@@ -0,0 +1,34 @@
#include "gta_benchmark.h"
#include "gta_string.h"
namespace gta_benchmark
{
void register_patches(batch_matching& batch_matcher)
{
//全都在使用"Benchmark%02d%02d%02d%02d%02d%02d.txt"的函数里
//Benchmark输出文字转码
batch_matcher.register_step("B8 68 2E 00 00 E8", 1, [](const byte_pattern::result_type& addresses)
{
injector::MakeCALL(addresses[0].i(0x04D9 - 6), gta_string::gtaTruncateString2);
injector::MakeCALL(addresses[0].i(0x0926 - 6), gta_string::gtaTruncateString2);
injector::MakeCALL(addresses[0].i(0x0962 - 6), gta_string::gtaTruncateString2);
injector::MakeCALL(addresses[0].i(0x099E - 6), gta_string::gtaTruncateString2);
injector::MakeCALL(addresses[0].i(0x09DA - 6), gta_string::gtaTruncateString2);
injector::MakeCALL(addresses[0].i(0x0A16 - 6), gta_string::gtaTruncateString2);
injector::MakeCALL(addresses[0].i(0x0A52 - 6), gta_string::gtaTruncateString2);
injector::MakeCALL(addresses[0].i(0x0A8E - 6), gta_string::gtaTruncateString2);
injector::MakeCALL(addresses[0].i(0x0ACA - 6), gta_string::gtaTruncateString2);
injector::MakeCALL(addresses[0].i(0x0B06 - 6), gta_string::gtaTruncateString2);
injector::MakeCALL(addresses[0].i(0x13C2 - 6), gta_string::gtaTruncateString2);
injector::MakeCALL(addresses[0].i(0x14C2 - 6), gta_string::gtaTruncateString2);
injector::MakeCALL(addresses[0].i(0x19DD - 6), gta_string::gtaTruncateString2);
injector::MakeCALL(addresses[0].i(0x1A27 - 6), gta_string::gtaTruncateString2);
injector::MakeCALL(addresses[0].i(0x1A7A - 6), gta_string::gtaTruncateString2);
injector::MakeCALL(addresses[0].i(0x1AB6 - 6), gta_string::gtaTruncateString2);
injector::MakeCALL(addresses[0].i(0x1AF2 - 6), gta_string::gtaTruncateString2);
injector::MakeCALL(addresses[0].i(0x1B2E - 6), gta_string::gtaTruncateString2);
injector::MakeCALL(addresses[0].i(0x1B63 - 6), gta_string::gtaTruncateString2);
injector::MakeCALL(addresses[0].i(0x2041 - 6), gta_string::gtaTruncateString2);
});
}
}
+7
View File
@@ -0,0 +1,7 @@
#pragma once
#include "batch_matching.h"
namespace gta_benchmark
{
void register_patches(batch_matching& batch_matcher);
}
+146
View File
@@ -0,0 +1,146 @@
#include "gta_font.h"
#include "font.h"
#include "plugin.h"
#include "gta_aslr.h"
namespace gta_font
{
static const char* __stdcall GetTextFileName(int)
{
return "chinese.gxt";
}
//922095
__declspec(naked) void ProcessToken_Epilog()
{
__asm
{
pop edi;
call plugin.game.game_addr.fnFont_ProcessToken;
or eax, 0x80000000;
push edi;
ret;
}
}
//922120
__declspec(naked) void ProcessToken_Epilog2()
{
__asm
{
and edi, 0x7FFFFFFF;
movzx eax, word ptr[edi - 4];
sub edi, 4;
ret;
}
}
//922147
__declspec(naked) void ProcessToken_Epilog3()
{
__asm
{
and edi, 0x7FFFFFFF;
mov[esp + 0x16], cl; //原代码是[esp+0x12],因为栈里多了一个返回地址所以是+0x16
test cl, cl;
ret;
}
}
void register_patches(batch_matching& batch_matcher)
{
//搜索"~%c~"找到CFont::ProcessString
//ProcessToken epilog
batch_matcher.register_step("89 AC 24 80 00 00 00 E8", 1, [](const byte_pattern::result_type& addresses)
{
plugin.game.game_addr.fnFont_ProcessToken = injector::GetBranchDestination(addresses[0].i(7)).get();
injector::MakeCALL(addresses[0].i(7), ProcessToken_Epilog);
});
//ProcessString token branch2
batch_matcher.register_step("0F B7 47 FC 83 EF 04", 1, [](const std::vector<memory_pointer>& addresses)
{
injector::MakeCALL(addresses[0].i(), ProcessToken_Epilog2);
injector::MakeNOP(addresses[0].i(5), 2);
});
//ProcessString token branch3
batch_matcher.register_step("88 4C 24 12 84 C9", 1, [](const std::vector<memory_pointer>& addresses)
{
injector::MakeCALL(addresses[0].i(), ProcessToken_Epilog3);
injector::MakeNOP(addresses[0].i(5), 1);
});
//CFont::ProcessString使用了
//跳过单词
batch_matcher.register_step("57 8B 7C 24 08 85 FF 75 04 33 C0 5F C3 56", 1, [](const byte_pattern::result_type& addresses)
{
injector::MakeJMP(addresses[0].i(), CFont::SkipWord_Prolog);
});
//ProcessString使用了
//获取字符宽度
batch_matcher.register_step("83 C0 E0 50 E8 ? ? ? ? D9 5C 24", 2, [](const byte_pattern::result_type& addresses)
{
injector::MakeCALL(addresses[0].i(4), CFont::GetCharacterSizeNormalDispatch);
injector::MakeCALL(addresses[1].i(4), CFont::GetCharacterSizeNormalDispatch);
});
//查找GetCharacterSizeNormal的引用获得
batch_matcher.register_step("6A 01 57 E8 ? ? ? ? D9 5C 24 30", 1, [](const byte_pattern::result_type& addresses)
{
injector::MakeCALL(addresses[0].i(3), CFont::GetCharacterSizeDrawingDispatch);
});
//查找GetCharacterSizeNormal的引用获得
batch_matcher.register_step("EB 12 6A 01 57 E8 ? ? ? ? D9 5C 24 24", 1, [](const byte_pattern::result_type& addresses)
{
injector::MakeCALL(addresses[0].i(5), CFont::GetCharacterSizeDrawingDispatch);
});
//RenderSingleBuffer使用了
//绘制字符
batch_matcher.register_step("F3 0F 11 0C 24 E8 ? ? ? ? 8B 35", 1, [](const byte_pattern::result_type& addresses)
{
injector::MakeCALL(addresses[0].i(5), CFont::PrintCharDispatch);
});
//另一个使用PrintChar的函数里面
batch_matcher.register_step("E8 ? ? ? ? 6A 01 57 E8 ? ? ? ? D9 5C 24 30", 1, [](const byte_pattern::result_type& addresses)
{
injector::MakeCALL(addresses[0].i(), CFont::PrintCharDispatch);
});
//搜索"font3"
//加载fonts.wtd中的font_chs
batch_matcher.register_step("8B CE 50 E8 ? ? ? ? 80 3D ? ? ? ? 6A", 2, [](const byte_pattern::result_type& addresses)
{
injector::MakeCALL(addresses[0].i(3), CFont::LoadTextureCB);
injector::MakeCALL(addresses[1].i(3), CFont::LoadTextureCB);
});
//搜索"american.gxt"
//改变GXT的文件名
batch_matcher.register_step("80 7C 24 04 00 56 8B F1 74 07", 1, [](const byte_pattern::result_type& addresses)
{
injector::MakeJMP(addresses[0].i(), GetTextFileName);
});
//ProcessString使用了
//GetStringWidth
batch_matcher.register_step("B8 B4 10 00 00", 1, [](const std::vector<memory_pointer>& addresses)
{
injector::MakeJMP(addresses[0].i(-6), CFont::GetStringWidthRemake);
});
//使用了GetStringWidth
//GetMaxWordWidth
batch_matcher.register_step("51 56 8B 74 24 0C 85 F6 75 05 D9 EE 5E 59 C3 66", 1, [](const std::vector<memory_pointer>& addresses)
{
injector::MakeJMP(addresses[0].i(), CFont::GetMaxWordWidth);
});
}
}
+7
View File
@@ -0,0 +1,7 @@
#pragma once
#include "batch_matching.h"
namespace gta_font
{
void register_patches(batch_matching& batch_matcher);
}
+102
View File
@@ -0,0 +1,102 @@
#include "gta_game.h"
#include "plugin.h"
namespace gta_game
{
void register_patches(batch_matching& batch_matcher)
{
//搜索"~%c~"找到CFont::ProcessString
//RenderSingleBuffer使用了
batch_matcher.register_step("A1 ? ? ? ? 80 7C 24 08 00", 1, [](const byte_pattern::result_type& addresses)
{
plugin.game.game_addr.fnGraphics_SetRenderState = addresses[0].p();
});
//GetCharacterSizeNormal使用了
//ButtonWidths紧跟着Font_Datas
batch_matcher.register_step("0F B6 84 08 ? ? ? ? 66 0F 6E C0", 1, [](const byte_pattern::result_type& addresses)
{
plugin.game.game_addr.pFont_Datas = *addresses[0].p<CFontInfo*>(4);
plugin.game.game_addr.pFont_ButtonWidths = reinterpret_cast<float*>(&plugin.game.game_addr.pFont_Datas[4]);
});
//GetStringWidth使用了
batch_matcher.register_step("F3 0F 59 05 ? ? ? ? 88 4C 24 12", 1, [](const byte_pattern::result_type& addresses)
{
plugin.game.game_addr.pFont_BlipWidth = *addresses[0].p<float*>(4);
});
//ProcessString使用了
batch_matcher.register_step("8D AE ? ? ? ? 32 C0", 1, [](const byte_pattern::result_type& addresses)
{
plugin.game.game_addr.pFont_Details = *addresses[0].p<CFontDetails*>(2);
});
//magic: AD 7F 33 31
batch_matcher.register_step("81 3D ? ? ? ? AD 7F 33 31", 2, [](const byte_pattern::result_type& addresses)
{
plugin.game.game_addr.pFont_RenderState = *addresses[0].p<CFontRenderState*>(2);
});
//GetCharacterSizeNormal使用了
batch_matcher.register_step("F3 0F 11 05 ? ? ? ? 66 0F 6E 84 24 AC 00 00", 1, [](const byte_pattern::result_type& addresses)
{
plugin.game.game_addr.pFont_ResolutionX = *addresses[0].p<float*>(4);
});
//ProcessString使用了
batch_matcher.register_step("A1 ? ? ? ? 83 F8 FF 75 1E", 1, [](const byte_pattern::result_type& addresses)
{
plugin.game.game_addr.fnFont_GetRenderIndex = addresses[0].p();
});
//AD 7F 33 31所在的函数(RenderSingleBuffer)使用了
batch_matcher.register_step("83 EC 30 83 3D ? ? ? ? FF", 1, [](const byte_pattern::result_type& addresses)
{
plugin.game.game_addr.fnFont_PrintChar = addresses[0].p();
});
//GetStringWidth使用了
batch_matcher.register_step("51 55 56 E8", 1, [](const byte_pattern::result_type& addresses)
{
plugin.game.game_addr.fnFont_GetCharacterSizeNormal = addresses[0].p();
});
//PrintChar使用了
batch_matcher.register_step("8A 0D ? ? ? ? 0F B6 D1", 1, [](const byte_pattern::result_type& addresses)
{
plugin.game.game_addr.fnFont_GetCharacterSizeDrawing = addresses[0].p();
});
//PrintChar使用了
batch_matcher.register_step("83 EC 10 8B 44 24 14 F3 0F 7E 00", 1, [](const byte_pattern::result_type& addresses)
{
plugin.game.game_addr.fnFont_Render2DPrimitive = addresses[0].p();
});
//"font3"附近使用了
batch_matcher.register_step("8B 54 24 08 53 56 8B 74 24 0C 80 3E 22", 1, [](const byte_pattern::result_type& addresses)
{
plugin.game.game_addr.fnHash_HashStringFromSeediCase = addresses[0].p();
});
//"font3"附近使用了
batch_matcher.register_step("53 55 56 57 8B F9 85 FF 74 3F", 1, [](const byte_pattern::result_type& addresses)
{
plugin.game.game_addr.fnDictionary_GetElementByKey = addresses[0].p();
});
//GetStringWidth使用了
batch_matcher.register_step("83 C7 02 53 57 E8", 1, [](const byte_pattern::result_type& addresses)
{
plugin.game.game_addr.fnFont_ParseToken = injector::GetBranchDestination(addresses[0].p(5)).get();
});
//GetStringWidth使用了
batch_matcher.register_step("83 EC 10 53 8B 5C 24 18 55 56", 1, [](const byte_pattern::result_type& addresses)
{
plugin.game.game_addr.fnFont_AddTokenStringWidth = addresses[0].p();
});
}
}
+7
View File
@@ -0,0 +1,7 @@
#pragma once
#include "batch_matching.h"
namespace gta_game
{
void register_patches(batch_matching& batch_matcher);
}
+74
View File
@@ -0,0 +1,74 @@
#include "gta_html.h"
#include "gta_string.h"
namespace gta_html
{
void register_patches(batch_matching& batch_matcher)
{
//替换html字符串处理过程
//Native: ADD_STRING_TO_HTML_SCRIPT_OBJECT(7EB70379)里面
batch_matcher.register_step("8B F8 8D 44 24 08 50 57 E8", 1, [](const byte_pattern::result_type& addresses)
{
injector::MakeCALL(addresses[0].i(8), gta_string::gtaTruncateString2);
});
//IDA Names: const CHtmlDataNode::`vftable'
//两个使用此虚表的函数
batch_matcher.register_step("74 0A 50 55 E8", 2, [](const byte_pattern::result_type& addresses)
{
injector::MakeCALL(addresses[0].i(4), gta_string::gtaExpandStringGxt);
injector::MakeCALL(addresses[1].i(4), gta_string::gtaExpandStringGxt);
});
//Native: GET_STRING_FROM_STRING(434534BE),调用strncpy的地方
batch_matcher.register_step("7F 4B 56 52 8D 44 24 14 50 E8", 1, [](const byte_pattern::result_type& addresses)
{
injector::MakeCALL(addresses[0].i(9), gta_string::gtaUTF8strncpy);
injector::MakeNOP(addresses[0].i(27), 5);
});
//跟上面同一个函数,调用memmove的地方
batch_matcher.register_step("03 C3 57 50 68 ? ? ? ? E8", 1, [](const byte_pattern::result_type& addresses)
{
injector::MakeCALL(addresses[0].i(9), gta_string::gtaSpecialMemmove);
injector::MakeNOP(addresses[0].i(25), 7);
});
//在调用CFont_GetMaxWordWidth之前调用的函数里面,设置相关CFont参数的
//网页邮件文字的比例值,直接用日语版的数值
batch_matcher.register_step("80 3D ? ? ? ? 6A F3 0F 10 05", 1, [](const byte_pattern::result_type& addresses)
{
//jmp short +9
injector::WriteMemory<uchar>(addresses[0].i(24), 0xEBu, true);
});
//Native: GET_WEB_PAGE_LINK_AT_POSN(C1C5B1B)的判断逻辑,跟30.0比较
batch_matcher.register_step("F3 0F 10 5A 24 72 5C", 1, [](const byte_pattern::result_type& addresses)
{
#if 1
//5D6CE0
injector::WriteMemory<uchar>(addresses[0].i(5), 0xEBu, true);
#else
static const float min_link_width = 5.0f;
injector::WriteMemory(addresses[0].i(0xCD6 - 0xCF4), &min_link_width, true);
injector::WriteMemory(addresses[0].i(0xD53 - 0xCF4), &min_link_width, true);
#endif
});
//IDA Names: const CHtmlTextFormat::`vftable'
//其中一个使用此虚表的函数
//计算超链接响应宽度的逻辑
batch_matcher.register_step("F3 0F 5C 4B 04 0F 2E C1 9F F6 C4 44 7B 27", 1, [](const byte_pattern::result_type& addresses)
{
//5D9B43
//injector::WriteMemory<uchar>(addresses[0].i(12), 0xEBu, true);
});
//batch_matcher.register_step("", 1, [](const byte_pattern::result_type& addresses)
// {
//
// });
}
}
+7
View File
@@ -0,0 +1,7 @@
#pragma once
#include "batch_matching.h"
namespace gta_html
{
void register_patches(batch_matching& batch_matcher);
}
+226
View File
@@ -0,0 +1,226 @@
#include "gta_mail_reply.h"
#include "gta_string.h"
#include "plugin.h"
namespace gta_mail_reply
{
//413332
//5E49FF
struct mr_read_eax_edx
{
void operator()(injector::reg_pack& regs) const
{
auto ptr = reinterpret_cast<char*>(regs.eax + regs.edx);
auto ptr2 = ptr;
regs.ebx = utf8::unchecked::next(ptr2);
auto offset = ptr2 - ptr;
regs.eax = regs.edx + offset;
}
};
//412A9C
struct mr_read_eax_esi
{
void operator()(injector::reg_pack& regs) const
{
auto ptr = reinterpret_cast<char*>(regs.eax + regs.esi);
auto ptr2 = ptr;
regs.edx = utf8::unchecked::next(ptr2);
auto offset = ptr2 - ptr;
regs.eax = regs.esi + offset;
}
};
//413311
struct mr_read_back_edi_eax
{
void operator()(injector::reg_pack& regs) const
{
auto pclass = reinterpret_cast<class_for_mr*>(regs.edi);
auto ptr = &pclass->f48[pclass->f448];
auto ptr2 = ptr;
regs.ebx = utf8::unchecked::prior(ptr2);
pclass->f448 -= (ptr - ptr2);
}
};
//5E49DE
struct mr_read_back_esi_ecx
{
void operator()(injector::reg_pack& regs) const
{
auto pclass = reinterpret_cast<class_for_mr*>(regs.esi);
auto ptr = &pclass->f48[pclass->f448];
auto ptr2 = ptr;
regs.ebx = utf8::unchecked::prior(ptr2);
pclass->f448 -= (ptr - ptr2);
}
};
//412A7A
struct mr_read_back_ecx_eax
{
void operator()(injector::reg_pack& regs) const
{
auto pclass = reinterpret_cast<class_for_mr*>(regs.ecx);
auto ptr = &pclass->f48[pclass->f448];
auto ptr2 = ptr;
regs.eax = utf8::unchecked::prior(ptr2);
pclass->f448 -= (ptr - ptr2);
}
};
//413523
struct mr_write_edi_ecx
{
void operator()(injector::reg_pack& regs) const
{
auto pclass = reinterpret_cast<class_for_mr*>(regs.edi);
auto ptr = &pclass->f48[pclass->f448];
auto offset = utf8::unchecked::append(regs.ebx, ptr) - ptr;
pclass->f448 += offset;
}
};
//5E4CCE
struct mr_write_esi_eax
{
void operator()(injector::reg_pack& regs) const
{
auto pclass = reinterpret_cast<class_for_mr*>(regs.esi);
auto ptr = &pclass->f48[pclass->f448];
auto offset = utf8::unchecked::append(regs.ebx, ptr) - ptr;
pclass->f448 += offset;
}
};
//5E5205
struct mr_write_ebp_esi
{
void operator()(injector::reg_pack& regs) const
{
auto ptr = reinterpret_cast<char*>(regs.esi + regs.ebp);
//对&nbsp之类字符的特殊处理,从sub_5E5250的逻辑来看,这么偷懒是可以的
//目前中文字库最小的值是0x2014
if (regs.ecx > 0x100 && regs.ecx < 0x200)
regs.ecx -= 0x100;
auto offset = utf8::unchecked::append(regs.ecx, ptr) - ptr;
regs.esi += offset;
regs.ecx = regs.edi;
}
};
//8C5AB1
struct dlc_truncate
{
void operator()(injector::reg_pack& regs) const
{
auto ptr = &plugin.game.game_addr.pDLCTruncateBuffer[regs.eax + regs.edx];
auto offset = utf8::unchecked::append(*reinterpret_cast<const GTAChar*>(regs.esi), ptr) - ptr;
regs.edx += offset - 1;
}
};
void register_patches(batch_matching& batch_matcher)
{
//Native: ADD_FIRST_N_CHARACTERS_OF_STRING_TO_HTML_SCRIPT_OBJECT(75FC34EF)里面
//邮件回复
batch_matcher.register_step("E8 ? ? ? ? 8D 44 24 08 50 56 E8", 1, [](const byte_pattern::result_type& addresses)
{
//要用的函数的地址
plugin.game.game_addr.fnMailAppendByteString = injector::GetBranchDestination(addresses[0].i()).get();
//接收宽字符,但添加的是utf8
injector::MakeCALL(addresses[0].i(11), gta_string::gtaMailAppendWideStringAsUtf8);
//去掉span标签
injector::MakeNOP(addresses[0].i(-6), 11);
injector::MakeNOP(addresses[0].i(16), 11);
});
batch_matcher.register_step("0F B6 1C 10 8D 42 01", 6, [](const byte_pattern::result_type& addresses)
{
//读utf8序列
//用到"!--"的函数
injector::MakeInline<mr_read_eax_edx>(addresses[0].i(), addresses[0].i(7));
//IDA Names: const CHtmlParser::`vftable'
//虚表的第三个函数
injector::MakeInline<mr_read_eax_edx>(addresses[4].i(), addresses[4].i(7));
});
//CHtmlParser虚表第三个函数开头调用了MailGetStringChar
//在MailGetStringChar里面
batch_matcher.register_step("0F B6 14 30 8D 46 01", 7, [](const byte_pattern::result_type& addresses)
{
//读utf8序列
injector::MakeInline<mr_read_eax_esi>(addresses[0].i(), addresses[0].i(7));
});
//在上述用到"!--"的函数里面
batch_matcher.register_step("FF 8F 48 04 00 00 8B 87 48 04 00 00 0F B6 5C 38 48", 1, [](const byte_pattern::result_type& addresses)
{
//读上一个utf8序列
injector::MakeInline<mr_read_back_edi_eax>(addresses[0].i(), addresses[0].i(17));
});
//在上述用到"!--"的函数里面
batch_matcher.register_step("FF 8E 48 04 00 00 8B 8E 48 04 00 00 0F B6 5C 31 48", 1, [](const byte_pattern::result_type& addresses)
{
//读上一个utf8序列
injector::MakeInline<mr_read_back_esi_ecx>(addresses[0].i(), addresses[0].i(17));
});
//在上述CHtmlParser虚表第三个函数里面
batch_matcher.register_step("FF 89 48 04 00 00 8B 81 48 04 00 00 0F B6 44 08 48", 1, [](const byte_pattern::result_type& addresses)
{
//读上一个utf8序列
injector::MakeInline<mr_read_back_ecx_eax>(addresses[0].i(), addresses[0].i(17));
});
//在上述用到"!--"的函数里面
batch_matcher.register_step("8D 14 39 41 89 8F 48 04 00 00 88 5A 48", 1, [](const byte_pattern::result_type& addresses)
{
//写utf8序列
injector::MakeInline<mr_write_edi_ecx>(addresses[0].i(), addresses[0].i(13));
});
//在上述CHtmlParser虚表第三个函数里面
batch_matcher.register_step("8B 86 48 04 00 00 8D 0C 06 40 89 86 48 04 00 00 88 59 48", 1, [](const byte_pattern::result_type& addresses)
{
//写utf8序列
injector::MakeInline<mr_write_esi_eax>(addresses[0].i(), addresses[0].i(19));
});
//在上述CHtmlParser虚表第三个函数调用的函数里面
batch_matcher.register_step("88 0C 2E 8B CF", 1, [](const byte_pattern::result_type& addresses)
{
//写utf8序列
injector::MakeInline<mr_write_ebp_esi>(addresses[0].i(), addresses[0].i(6));
});
//Native: CONVERT_THEN_ADD_STRING_TO_HTML_SCRIPT_OBJECT(72EC0AA6)的转换过程里面
batch_matcher.register_step("C6 84 10 ? ? ? ? 3F", 1, [](const byte_pattern::result_type& addresses)
{
plugin.game.game_addr.pDLCTruncateBuffer = *addresses[0].p<char*>(3);
//DLC不支持日语而加的转换逻辑
injector::MakeInline<dlc_truncate>(addresses[0].i(), addresses[0].i(8));
});
//Native: GET_FIRST_N_CHARACTERS_OF_STRING(108B4A25)调用strncpy的地方
batch_matcher.register_step("56 50 68 ? ? ? ? E8", 1, [](const byte_pattern::result_type& addresses)
{
injector::MakeCALL(addresses[0].i(7), gta_string::gtaUTF8strncpy);
injector::MakeNOP(addresses[0].i(24), 7);
});
//batch_matcher.register_step("", 1, [](const byte_pattern::result_type& addresses)
// {
//
// });
}
}
+29
View File
@@ -0,0 +1,29 @@
#pragma once
#include "batch_matching.h"
namespace gta_mail_reply
{
struct string_storage
{
int f0;
int f4;
uchar* f8;
int fC;
int f10;
int f14;
};
VALIDATE_SIZE(string_storage, 0x18);
//4132E0的this指针
struct class_for_mr
{
int f0;
string_storage* f4;
char f8[0x40];
uchar f48[0x400];
int f448; //0表示没有sso,转而读取f4
};
VALIDATE_SIZE(class_for_mr, 0x44C);
void register_patches(batch_matching& batch_matcher);
}
+51
View File
@@ -0,0 +1,51 @@
#include "gta_menu.h"
namespace gta_menu
{
void register_patches(batch_matching& batch_matcher)
{
//密集调用GetStringWidthJump的一个函数
//Esc菜单Header热区
batch_matcher.register_step("D9 5C 24 4C F3 0F 10 44 24 4C F3 0F 58 44 24 2C", 1, [](const byte_pattern::result_type& addresses)
{
injector::WriteMemory(addresses[0].i(0xAF4B - 0xAF62 + 1), true, true);
injector::WriteMemory(addresses[0].i(0xAF7A - 0xAF62 + 1), true, true);
injector::WriteMemory(addresses[0].i(0xAFB0 - 0xAF62 + 1), true, true);
injector::WriteMemory(addresses[0].i(0xAFE6 - 0xAF62 + 1), true, true);
injector::WriteMemory(addresses[0].i(0xB01C - 0xAF62 + 1), true, true);
injector::WriteMemory(addresses[0].i(0xB052 - 0xAF62 + 1), true, true);
injector::WriteMemory(addresses[0].i(0xB088 - 0xAF62 + 1), true, true);
});
//密集调用GetStringWidthJump的另一个函数
//Esc菜单Header间距
batch_matcher.register_step("B9 ? ? ? ? F3 0F 11 44 24 54 E8", 1, [](const byte_pattern::result_type& addresses)
{
injector::WriteMemory(addresses[0].i(0x860 - 0x867 + 1), true, true);
injector::WriteMemory(addresses[0].i(0x895 - 0x867 + 1), true, true);
injector::WriteMemory(addresses[0].i(0x8CB - 0x867 + 1), true, true);
injector::WriteMemory(addresses[0].i(0x901 - 0x867 + 1), true, true);
injector::WriteMemory(addresses[0].i(0x937 - 0x867 + 1), true, true);
injector::WriteMemory(addresses[0].i(0x96D - 0x867 + 1), true, true);
injector::WriteMemory(addresses[0].i(0x9A3 - 0x867 + 1), true, true);
});
//'Esc菜单Header热区'同一个函数里
//视频编辑器菜单Header热区
batch_matcher.register_step("6A 00 68 ? ? ? ? F3 0F 58 44 24 20 F3 0F 11 44 24 4C", 1, [](const byte_pattern::result_type& addresses)
{
injector::WriteMemory(addresses[0].i(0x595 - 0x5C4 + 1), true, true);
injector::WriteMemory(addresses[0].i(0x5C4 - 0x5C4 + 1), true, true);
injector::WriteMemory(addresses[0].i(0x5FA - 0x5C4 + 1), true, true);
injector::WriteMemory(addresses[0].i(0x630 - 0x5C4 + 1), true, true);
});
//'Esc菜单Header间距'同一个函数里
//视频编辑器菜单Header间距
batch_matcher.register_step("6A 00 68 ? ? ? ? B9 ? ? ? ? F3 0F 11 44 24 20", 1, [](const byte_pattern::result_type& addresses)
{
injector::WriteMemory(addresses[0].i(0x7E8 - 0x7E8 + 1), true, true);
injector::WriteMemory(addresses[0].i(0x81D - 0x7E8 + 1), true, true);
});
}
}
+7
View File
@@ -0,0 +1,7 @@
#pragma once
#include "batch_matching.h"
namespace gta_menu
{
void register_patches(batch_matching& batch_matcher);
}
+22
View File
@@ -0,0 +1,22 @@
#include "gta_phone.h"
#include "gta_string.h"
namespace gta_phone
{
void register_patches(batch_matching& batch_matcher)
{
//用到"Unknown1"的地方往后一个调用的函数里面
//TBoGT重玩任务选择界面
batch_matcher.register_step("6A 64 53 57 E8", 2, [](const byte_pattern::result_type& addresses)
{
injector::MakeCALL(addresses[0].i(4), gta_string::gtaExpandString3);
});
//Native: DISPLAY_TEXT_WITH_LITERAL_SUBSTRING(1FCB5241)里面第二个调用strncpy的地方
batch_matcher.register_step("56 8D 44 24 10 53 50 E8", 1, [](const byte_pattern::result_type& addresses)
{
injector::MakeCALL(addresses[0].i(7), gta_string::gtaUTF8strncpy);
injector::MakeNOP(addresses[0].i(37), 5);
});
}
}
+7
View File
@@ -0,0 +1,7 @@
#pragma once
#include "batch_matching.h"
namespace gta_phone
{
void register_patches(batch_matching& batch_matcher);
}
+37
View File
@@ -0,0 +1,37 @@
#include "gta_save.h"
#include "gta_string.h"
namespace gta_save
{
void register_patches(batch_matching& batch_matcher)
{
//在使用"MO_SLOT"的函数里面
batch_matcher.register_step("8D 84 24 4C 01 00 00 50 8D 44 24 1C 50 E8", 1, [](const byte_pattern::result_type& addresses)
{
injector::MakeCALL(addresses[0].i(13), gta_string::gtaExpandString);
});
//存档覆盖提示
batch_matcher.register_step("68 80 00 00 00 8D 44 24 50 50 68 ? ? ? ? E8", 2, [](const byte_pattern::result_type& addresses)
{
//使用"SG_AUTO_SL_OVR2"的地方往前一点
injector::MakeCALL(addresses[0].i(15), gta_string::gtaExpandString2);
//使用"SG_AUTO_SL_OVRWRT2"的地方往前一点
injector::MakeCALL(addresses[1].i(15), gta_string::gtaExpandString2);
});
//使用"MO_BENCH_TEST"的函数里
//加载黑屏右下角的任务名
batch_matcher.register_step("FF 35 ? ? ? ? E8 ? ? ? ? 83 C4 0C 50 E8", 1, [](const byte_pattern::result_type& addresses)
{
injector::MakeCALL(addresses[0].i(15), gta_string::gtaExpandString);
});
//在上方被替换掉的函数里面
batch_matcher.register_step("6A 3C 05 ? ? ? ? 50 68 ? ? ? ? E8", 1, [](const byte_pattern::result_type& addresses)
{
injector::MakeCALL(addresses[0].i(13), gta_string::gtaTruncateString);
});
}
}
+7
View File
@@ -0,0 +1,7 @@
#pragma once
#include "batch_matching.h"
namespace gta_save
{
void register_patches(batch_matching& batch_matcher);
}
+178
View File
@@ -0,0 +1,178 @@
#include "gta_string.h"
#include "plugin.h"
#include "../common/fnv_hash.h"
namespace gta_string
{
static std::unordered_map<std::size_t, std::vector<GTAChar>> truncated_text_map; //key是单字节字符串的hash, value是原始宽字符串的内容,包含结尾0
constexpr uchar pad_byte = 0xA7u; //用于填充的垃圾值
unsigned gtaWcslen(const GTAChar* str)
{
auto str2 = str;
unsigned len = 0;
while (*str2 != 0)
{
++str2;
++len;
}
return len;
}
//8C5510
uchar* gtaTruncateString(uchar* dst, const GTAChar* src, unsigned size)
{
std::size_t copied_size = 0;
if (src != nullptr)
{
if (size > 1)
{
while (copied_size < size - 1)
{
auto c = src[copied_size];
if (c == 0)
break;
//如果低字节恰好是0,就随便用一个整数填充,防止结果中出现意外的0,最好是非ASCII
//游戏也只是用结果进行字符串比较,应该没有问题
if ((c & 0xFFu) == 0)
c |= pad_byte;
dst[copied_size] = static_cast<uchar>(c);
++copied_size;
}
//将dst的hash和src的数据存入map,供gtaExpandString查找
//注意要以实际复制的长度取dst
truncated_text_map.emplace(fnv_hash::hash_seq(std::span<const uchar>(dst, copied_size), false), fnv_hash::get_string_vector(src));
}
}
dst[copied_size] = 0;
return dst;
}
//909F50
void gtaExpandString(const uchar* src, GTAChar* dst)
{
if (src == nullptr || dst == nullptr)
return;
auto src_span = fnv_hash::get_string_span(src);
auto wide_string_it = truncated_text_map.find(fnv_hash::hash_seq(src_span, false));
if (wide_string_it != truncated_text_map.end())
{
ranges::copy(wide_string_it->second, dst);
}
else
{
*ranges::copy(src_span, dst).out = 0;
}
}
void gtaExpandString2(GTAChar* dst, const uchar* src, int a8)
{
gtaExpandString(src, dst);
}
//8FAC40
void gtaExpandString3(GTAChar* dst, const uchar* src, int a8)
{
auto src_span = fnv_hash::get_string_span(src);
auto src_it = src_span.begin();
auto src_end_it = src_span.end();
while (!utf8::is_valid(src_it, src_end_it))
++src_it;
gtaExpandStringGxt(&*src_it, dst);
}
//91EBC0
void gtaTruncateString2(const GTAChar* src, uchar* dst)
{
auto src_span = fnv_hash::get_string_span(src);
*utf8::utf16to8(src_span.begin(), src_span.end(), dst) = 0;
}
//909F50
void gtaExpandStringGxt(const uchar* src, GTAChar* dst)
{
auto src_span = fnv_hash::get_string_span(src);
auto src_it = src_span.begin();
auto src_end_it = src_span.end();
if (utf8::is_valid(src_it, src_end_it))
{
*utf8::utf8to16(src_span.begin(), src_end_it, dst) = 0;
}
else
{
//遇到无效的utf8序列(如网页中未翻译的FIGS字符),则直接扩展成utf16
*ranges::copy(src_span, dst).out = 0;
}
}
//replace call at 5E7AD8
void __stdcall gtaMailAppendWideStringAsUtf8(int id, const GTAChar* str)
{
std::vector<uchar> u8_buffer;
u8_buffer.reserve(2048);
auto src_span = fnv_hash::get_string_span(str);
utf8::utf16to8(src_span.begin(), src_span.end(), std::back_inserter(u8_buffer));
u8_buffer.push_back(0);
plugin.game.MailAppendByteString(id, u8_buffer.data());
}
uchar* gtaUTF8strncpy(uchar* dest, const uchar* source, unsigned size)
{
auto dest_ptr = dest;
for (unsigned index = 0; index < size; ++index)
{
auto cp = utf8::unchecked::next(source);
if (cp == 0)
break;
dest_ptr = utf8::unchecked::append(cp, dest_ptr);
}
*dest_ptr = 0;
return dest;
}
void* gtaSpecialMemmove(uchar* dest, const uchar* source, unsigned size)
{
std::strcpy(reinterpret_cast<char*>(dest), reinterpret_cast<const char*>(source));
return dest;
}
unsigned gtaUTF8Strlen(const uchar* str)
{
if (str == nullptr)
return 0;
unsigned len = 0;
while (*str != 0)
{
utf8::unchecked::next(str);
++len;
}
return len;
}
}
+29
View File
@@ -0,0 +1,29 @@
#pragma once
#include "../common/stdinc.h"
#include "../common/common.h"
namespace gta_string
{
unsigned gtaWcslen(const GTAChar* str);
//存档标题
uchar* gtaTruncateString(uchar* dst, const GTAChar* src, unsigned size);
void gtaExpandString(const uchar* src, GTAChar* dst);
//显示存档覆盖提示时用于格式化的存档名称
void gtaExpandString2(GTAChar* dst, const uchar* src, int a8);
//TBoGT重玩任务选择界面
void gtaExpandString3(GTAChar* dst, const uchar* src, int a8);
//邮件/网页
void gtaTruncateString2(const GTAChar* src, uchar* dst);
void gtaExpandStringGxt(const uchar* src, GTAChar* dst);
//接收宽字符串,但转换成utf8
void __stdcall gtaMailAppendWideStringAsUtf8(int id, const GTAChar* str);
uchar* gtaUTF8strncpy(uchar* dest, const uchar* source, unsigned size);
void* gtaSpecialMemmove(uchar* dest, const uchar* source, unsigned size);
unsigned gtaUTF8Strlen(const uchar* str);
}
+26
View File
@@ -0,0 +1,26 @@
#include "gta_whm.h"
#include "class_pointer.hpp"
#include "plugin.h"
namespace gta_whm
{
struct html_data_node_replace_string
{
void operator()(injector::reg_pack& regs) const
{
auto p_class = reinterpret_cast<class_pointer*>(regs.ebx);
regs.ebp = reinterpret_cast<std::uintptr_t>(plugin.whm_table.GetTranslated(
*p_class->get_field<const uchar*>(0xD8)));
}
};
void register_patches(batch_matching& batch_matcher)
{
//gta_html提到的用到CHtmlDataNode虚表的函数里
//替换whm自带文本
batch_matcher.register_step("8B AB D8 00 00 00", 1, [](const byte_pattern::result_type& addresses)
{
injector::MakeInline<html_data_node_replace_string>(addresses[0].i(), addresses[0].i(6));
});
}
}
+7
View File
@@ -0,0 +1,7 @@
#pragma once
#include "batch_matching.h"
namespace gta_whm
{
void register_patches(batch_matching& batch_matcher);
}
+90
View File
@@ -0,0 +1,90 @@
#include "plugin.h"
#include "font.h"
#include "game.h"
#include "char_table.h"
#include "gta_string.h"
#include "gta_benchmark.h"
#include "gta_font.h"
#include "gta_game.h"
#include "gta_html.h"
#include "gta_menu.h"
#include "gta_phone.h"
#include "gta_save.h"
#include "gta_whm.h"
#include "gta_mail_reply.h"
CPlugin plugin;
void CPlugin::RegisterPatchSteps(batch_matching& batch_matcher)
{
gta_benchmark::register_patches(batch_matcher);
gta_font::register_patches(batch_matcher);
gta_game::register_patches(batch_matcher);
gta_html::register_patches(batch_matcher);
gta_mail_reply::register_patches(batch_matcher);
gta_menu::register_patches(batch_matcher);
gta_phone::register_patches(batch_matcher);
gta_save::register_patches(batch_matcher);
gta_whm::register_patches(batch_matcher);
}
HANDLE CPlugin::GetGameModule() const
{
return game_module_path.GetModule();
}
HANDLE CPlugin::GetPluginModule() const
{
return plugin_module_path.GetModule();
}
std::filesystem::path CPlugin::GetGameRoot() const
{
return game_module_path.GetModuleDir();
}
std::filesystem::path CPlugin::GetRedirectRoot() const
{
return plugin_module_path.GetModuleDir() / "GTA4.CHS/redirect";
}
std::filesystem::path CPlugin::GetPluginAsset(const char* rest_path) const
{
return plugin_module_path.GetModuleDir() / "GTA4.CHS" / rest_path;
}
bool CPlugin::Init(HMODULE module)
{
game_module_path.SetModule(::GetModuleHandleW(nullptr));
plugin_module_path.SetModule(module);
aslr_handler.SetGameBase(game_module_path.GetModule());
batch_matching batch_matcher;
batch_matcher.set_aslr(aslr_handler);
//必须先注册再读缓存
RegisterPatchSteps(batch_matcher);
batch_matcher.load_cache(GetPluginAsset("pattern_cache.dat"));
//验证缓存的操作放在byte_pattern中
if (batch_matcher.perform_search())
{
//如果有进行过搜索则写入,不论成功还是失败
batch_matcher.write_cache(GetPluginAsset("pattern_cache.dat"));
batch_matcher.write_log(GetPluginAsset("pattern_log.log"), false);
}
if (!batch_matcher.is_all_succeed())
{
return false;
}
batch_matcher.run_callbacks();
char_table.LoadTable(GetPluginAsset("char_table.dat"));
whm_table.LoadTable(GetPluginAsset("whm_table.dat"));
return true;
}
+33
View File
@@ -0,0 +1,33 @@
#pragma once
#include "../common/stdinc.h"
#include "../common/common.h"
#include "batch_matching.h"
#include "char_table.h"
#include "whm_table.h"
#include "game.h"
#include "../common/module_path.h"
#include "gta_aslr.h"
class CPlugin
{
public:
bool Init(HMODULE module);
HANDLE GetGameModule() const;
HANDLE GetPluginModule() const;
std::filesystem::path GetGameRoot() const;
std::filesystem::path GetRedirectRoot() const;
std::filesystem::path GetPluginAsset(const char* rest_path) const; //为了支持中文字体文件名
//保证进入构造函数之后这些对象已经初始化了
ModulePath game_module_path, plugin_module_path;
CCharTable char_table;
CWhmTable whm_table;
gta_aslr aslr_handler;
CGame game;
private:
static void RegisterPatchSteps(batch_matching& batch_matcher);
};
extern CPlugin plugin;
+40
View File
@@ -0,0 +1,40 @@
#include "whm_table.h"
#include "../common/fnv_hash.h"
void CWhmTable::LoadTable(const std::filesystem::path& filename)
{
m_offsets.clear();
m_strings.clear();
BinaryFile file(filename, "rb");
if (!file)
return;
std::vector<WhmTextData> entries;
std::vector<uchar> strings;
file.ReadArray2(entries);
file.ReadArray2(strings);
for (auto& entry : entries)
{
m_offsets.emplace(entry.hash, entry.offset); //重复的hash添加不进去
}
m_strings.swap(strings);
}
const uchar* CWhmTable::GetTranslated(const uchar* src) const
{
auto it = m_offsets.find(fnv_hash::hash_string(src, false));
if (it == m_offsets.end())
{
return src;
}
else
{
return &m_strings[it->second];
}
}
+15
View File
@@ -0,0 +1,15 @@
#pragma once
#include "../common/stdinc.h"
class CWhmTable
{
public:
void LoadTable(const std::filesystem::path& filename);
//查表,将whm的原文替换成译文
const uchar* GetTranslated(const uchar* src) const;
private:
std::unordered_map<std::size_t, std::uintptr_t> m_offsets;
std::vector<uchar> m_strings;
};
+5
View File
@@ -0,0 +1,5 @@
cmake_minimum_required(VERSION 3.15.0)
project(gxt_tool)
add_executable(gxt_tool IVText.cpp main.cpp ${common_sources})
+617
View File
@@ -0,0 +1,617 @@
#include "IVText.h"
#include "../common/fnv_hash.h"
#include "../common/module_path.h"
#include "../common/char8_t-remediation.h"
void IVText::ProcessT2B(const PathType& inFolder, const PathType& outFolder)
{
create_directories(outFolder);
LoadTexts(inFolder);
GenerateBinary(outFolder / "chinese.gxt");
}
void IVText::ProcessB2T(const PathType& inFile, const PathType& outFolder)
{
create_directories(outFolder);
LoadBinary(inFile);
GenerateTexts(outFolder);
}
void IVText::ProcessCollect(const PathType& inFolder, const PathType& outFolder)
{
std::set<char32_t> chars; //文本中出现的非原版字符集合
create_directories(outFolder);
ProcessTexts(inFolder, true, [&chars](const std::string& filename, std::ifstream& stream)
{
CollectCharsFunc(stream, chars);
});
GenerateCollection(outFolder / "characters.txt", chars);
GenerateTable(outFolder / "char_table.dat", chars);
}
bool IVText::IsNativeCharacter(char32_t character)
{
if (character > 0xFFFF)
{
std::printf("Invalid code point: %u larger than 0xFFFF.\n", static_cast<unsigned>(character));
return false;
}
return (character < 0x100 || character == L'™');
}
void IVText::ProcessTexts(const PathType& inFolder, bool recursive, const FuncType& func)
{
std::vector<std::string> filenames;
if (recursive)
{
std::filesystem::recursive_directory_iterator dir_it{ inFolder };
while (dir_it != std::filesystem::recursive_directory_iterator{})
{
PathType path = dir_it->path();
if (path.extension() == ".txt")
{
filenames.push_back(path.string());
}
++dir_it;
}
}
else
{
std::filesystem::directory_iterator dir_it{ inFolder };
while (dir_it != std::filesystem::directory_iterator{})
{
PathType path = dir_it->path();
if (path.extension() == ".txt")
{
filenames.push_back(path.string());
}
++dir_it;
}
}
for (auto& filename : filenames)
{
std::ifstream ifs(filename);
if (!ifs)
{
continue;
}
func(filename, ifs);
}
}
void IVText::LoadTextFunc(const std::string& filename, std::ifstream& stream)
{
std::regex table_regex(R"(\[([0-9a-zA-Z_]{1,7})\])");
std::regex entry_regex(R"((0[xX][0-9a-fA-F]{8})=(.*))");
std::match_results<const char*> matches;
std::string line;
auto table_iter = m_Data.end();
size_t line_no = 0;
SkipUTF8Signature(stream);
while (std::getline(stream, line))
{
++line_no;
line.erase(0, line.find_first_not_of(' '));
line.erase(line.find_last_not_of(' ') + 1);
if (line.empty())
{
continue;
}
if (line.front() == '[' && regex_match(line.c_str(), matches, table_regex))
{
table_iter = m_Data.emplace(matches.str(1), std::vector<TextEntry>()).first;
continue;
}
bool is_original = (line.front() == ';');
bool match_result;
if (is_original)
{
match_result = std::regex_match(line.c_str() + 1, matches, entry_regex);
}
else
{
match_result = std::regex_match(line.c_str(), matches, entry_regex);
}
if (match_result)
{
if (table_iter != m_Data.end())
{
auto& table_cont = table_iter->second;
auto hash_string = matches.str(1);
if (table_cont.empty() || table_cont.back().hash_string != hash_string)
{
table_cont.emplace_back();
}
auto p_entry = &table_cont.back();
p_entry->hash_string = hash_string;
auto b_string = matches.str(2);
if (is_original)
{
p_entry->original = b_string;
}
else
{
p_entry->translated = b_string;
}
if (!is_original && (ranges::count(b_string, '~') & 1) == 1)
{
std::printf(U8("%s: 第%u行的\'~\'个数不是偶数!\n"), filename.c_str(), line_no);
}
}
else
{
std::printf(U8("%s: 第%u行没有所属的表。\n"), filename.c_str(), line_no);
}
}
else
{
std::printf(U8("%s: 第%u行无法识别。\n"), filename.c_str(), line_no);
}
}
}
void IVText::CollectCharsFunc(std::ifstream& stream, std::set<char32_t>& chars)
{
std::vector<char> u8_buffer;
std::vector<char32_t> u32_buffer;
u8_buffer.assign(std::istreambuf_iterator(stream), std::istreambuf_iterator<char>());
utf8::utf8to32(u8_buffer.begin(), u8_buffer.end(), std::back_inserter(u32_buffer));
for (auto chr : u32_buffer)
{
if (!IsNativeCharacter(chr) && chr != 0x3000 && chr != 0xFEFF)
{
chars.insert(chr);
}
}
}
void IVText::LoadTexts(const PathType& inFolder)
{
ProcessTexts(inFolder, false, [this](const std::string& filename, std::ifstream& stream)
{
LoadTextFunc(filename, stream);
});
}
void IVText::GenerateBinary(const PathType& output_binary) const
{
BinaryFile file(output_binary, "wb");
std::vector<uint8_t> buffer;
long writePostion;
GXTHeader gxtHeader;
TableBlock tableBlock;
KeyBlockOthers keyBlock;
DataBlock dataBlock;
TableEntry tableEntry;
KeyEntry keyEntry;
std::vector<TableEntry> tables;
std::vector<KeyEntry> keys;
std::vector<uint16_t> datas;
if (!file)
{
std::printf(U8("创建输出文件 %s 失败。\n"), output_binary.string().c_str());
return;
}
gxtHeader.Version = 4;
gxtHeader.CharBits = 16;
file.Write(gxtHeader);
tableBlock.TABL[0] = 'T';
tableBlock.TABL[1] = 'A';
tableBlock.TABL[2] = 'B';
tableBlock.TABL[3] = 'L';
keyBlock.Body.TKEY[0] = 'T';
keyBlock.Body.TKEY[1] = 'K';
keyBlock.Body.TKEY[2] = 'E';
keyBlock.Body.TKEY[3] = 'Y';
dataBlock.TDAT[0] = 'T';
dataBlock.TDAT[1] = 'D';
dataBlock.TDAT[2] = 'A';
dataBlock.TDAT[3] = 'T';
tableBlock.Size = m_Data.size() * sizeof(TableEntry);
file.Write(tableBlock);
writePostion = 4 + 8 + tableBlock.Size;
tables.clear();
for (auto& table : m_Data)
{
keys.clear();
datas.clear();
strcpy(tableEntry.Name, table.first.c_str());
tableEntry.Offset = static_cast<int>(writePostion);
tables.push_back(tableEntry);
strcpy(keyBlock.Name, table.first.c_str());
keyBlock.Body.Size = table.second.size() * sizeof(KeyEntry);
for (auto& entry : table.second)
{
if (entry.hash_string.empty() || entry.original.empty() || entry.translated.empty())
{
std::printf(U8("遇到缺失的文本项:\nhash_string: %s\noriginal: %s\ntranslated: %s\n\n"), entry.hash_string.c_str(), entry.original.c_str(), entry.translated.c_str());
}
if (!CompareTokens(entry.original, entry.translated))
{
std::printf(U8("遇到Token与原文不一致的译文:\nhash_string: %s\noriginal: %s\ntranslated: %s\n\n"), entry.hash_string.c_str(), entry.original.c_str(), entry.translated.c_str());
}
keyEntry.Hash = std::stoul(entry.hash_string, nullptr, 16);
keyEntry.Offset = static_cast<std::int32_t>(datas.size() * 2);
auto w_string_to_write = U8ToWide(entry.translated);
ranges::copy(w_string_to_write, std::back_inserter(datas));
keys.push_back(keyEntry);
}
dataBlock.Size = static_cast<std::int32_t>(datas.size() * 2);
file.Seek(writePostion, SEEK_SET);
if (table.first == "MAIN")
{
file.Write(keyBlock.Body);
}
else
{
file.Write(keyBlock);
}
file.WriteArray(keys);
file.Write(dataBlock);
file.WriteArray(datas);
writePostion = file.Tell();
}
file.Seek(4 + 8, SEEK_SET);
file.WriteArray(tables);
}
void IVText::GenerateCollection(const PathType& outFile, const std::set<char32_t>& chars)
{
size_t count = 0;
u8StringType u8_text;
for (auto character : chars)
{
if (count == g_CharsPerLine)
{
u8_text += L'\n';
count = 0;
}
utf8::append(character, std::back_inserter(u8_text));
++count;
}
std::ofstream stream(outFile, std::ios::trunc);
std::copy_n(u8_text.c_str(), u8_text.size(), std::ostreambuf_iterator(stream));
}
void IVText::GenerateTable(const PathType& outFile, const std::set<char32_t>& chars)
{
BinaryFile stream(outFile, "wb");
stream.WriteArray2(ranges::to_vector(chars));
}
IVText::wStringType IVText::U8ToWide(const u8StringType& u8_string)
{
wStringType result;
utf8::utf8to16(u8_string.begin(), u8_string.end(), std::back_inserter(result));
result.push_back(0);
LiteralToGame(result);
return result;
}
IVText::u8StringType IVText::WideToU8(const wStringType& wide_string)
{
u8StringType result;
if (!wide_string.empty())
{
utf8::utf16to8(wide_string.begin(), wide_string.end() - 1, std::back_inserter(result));
}
return result;
}
void IVText::FixCharacters(wStringType& wtext)
{
//bad character in IV stock text: 0x85 0x92 0x94 0x96 0x97 0xA0
//bad character in EFLC stock text: 0x93
for (auto& character : wtext)
{
switch (character)
{
case 0x85:
character = L' ';
break;
case 0x92:
case 0x94:
character = L'\'';
break;
case 0x93: //EFLC
break;
case 0x96:
character = L'-';
break;
case 0x97:
case 0xA0:
character = L' ';
break;
default:
break;
}
}
}
void IVText::LiteralToGame(wStringType& wtext)
{
for (auto& character : wtext)
{
switch (character)
{
case L'™':
character = 0x99;
break;
default:
break;
}
}
}
void IVText::GameToLiteral(wStringType& wtext)
{
for (auto& character : wtext)
{
switch (character)
{
case 0x99:
character = L'™';
break;
default:
break;
}
}
}
std::set<std::string> IVText::CollectTokens(const std::string& str)
{
std::set<std::string> result;
std::vector<std::string::size_type> wave_token_indexes, html_token_indexes;
//收集token的起止点
//明显是不支持嵌套尖括号的
for (std::string::size_type index = 0; index < str.length(); ++index)
{
auto chr = str[index];
if (chr == '~')
{
wave_token_indexes.push_back(index);
}
else if (chr == '<')
{
if (html_token_indexes.empty() || html_token_indexes.back() == '>')
{
html_token_indexes.push_back(index);
}
}
else if (chr == '>')
{
if (!html_token_indexes.empty() && html_token_indexes.back() == '<')
{
html_token_indexes.push_back(index);
}
}
}
if ((wave_token_indexes.size() & 1) == 1 || (html_token_indexes.size() & 1) == 1)
{
return result;
}
//提取每个token
for (std::vector<std::string::size_type>::size_type token_index = 0; token_index < wave_token_indexes.size() / 2; ++token_index)
{
result.emplace(str, wave_token_indexes[token_index * 2], wave_token_indexes[token_index * 2 + 1] - wave_token_indexes[token_index * 2] + 1);
}
for (std::vector<std::string::size_type>::size_type token_index = 0; token_index < html_token_indexes.size() / 2; ++token_index)
{
result.emplace(str, html_token_indexes[token_index * 2], html_token_indexes[token_index * 2 + 1] - html_token_indexes[token_index * 2] + 1);
}
return result;
}
bool IVText::CompareTokens(const std::string& s1, const std::string& s2)
{
auto token1 = CollectTokens(s1);
auto token2 = CollectTokens(s2);
if (token1.size() != token2.size())
{
return false;
}
for (auto& token : token1)
{
if (!token2.contains(token))
{
return false;
}
}
return true;
}
void IVText::LoadBinary(const PathType& inFile)
{
GXTHeader gxtHeader;
TableBlock tableBlock;
KeyBlockOthers keyBlock;
DataBlock tdatHeader;
std::vector<TableEntry> tables;
std::vector<KeyEntry> keys;
std::vector<CharType> datas;
m_Data.clear();
auto tableIter = m_Data.end();
BinaryFile file(inFile, "rb");
if (!file)
{
std::printf(U8("打开输入文件 %s 失败。\n"), inFile.string().c_str());
return;
}
file.Read(gxtHeader);
file.Read(tableBlock);
file.ReadArray(tableBlock.Size / sizeof(TableEntry), tables);
for (TableEntry& table : tables)
{
tableIter = m_Data.emplace(table.Name, std::vector<TextEntry>()).first;
file.Seek(table.Offset, SEEK_SET);
if (strcmp(table.Name, "MAIN") != 0)
{
file.Read(keyBlock);
}
else
{
file.Read(keyBlock.Body);
}
file.ReadArray(keyBlock.Body.Size / sizeof(KeyEntry), keys);
file.Read(tdatHeader);
file.ReadArray(tdatHeader.Size / 2, datas);
for (auto& key : keys)
{
wStringType w_string;
TextEntry entry;
char buffer[20];
std::sprintf(buffer, "0x%08X", key.Hash);
entry.hash_string = buffer;
auto offset = key.Offset / 2;
while (datas[offset] != 0)
{
w_string.push_back(datas[offset]);
++offset;
}
w_string.push_back(0);
FixCharacters(w_string);
GameToLiteral(w_string);
entry.translated = WideToU8(w_string);
tableIter->second.emplace_back(std::move(entry));
}
}
}
void IVText::GenerateTexts(const PathType& output_texts) const
{
std::ofstream stream;
std::string line;
std::vector<char> buffer(4096);
for (auto& table : m_Data)
{
stream.open(output_texts / (table.first + ".txt"), std::ios::trunc);
if (!stream)
{
std::printf(U8("创建输出文件失败\n"));
}
stream.write("\xEF\xBB\xBF", 3);
std::sprintf(buffer.data(), "[%s]\n", table.first.c_str());
stream << buffer.data();
for (auto& entry : table.second)
{
std::sprintf(buffer.data(), "%s=%s\n", entry.hash_string.c_str(), entry.translated.c_str());
line = buffer.data();
stream << ';' << line << line << '\n';
}
stream.close();
}
}
+129
View File
@@ -0,0 +1,129 @@
#pragma once
#include "../common/stdinc.h"
#include "../common/common.h"
struct IVTextTableSorting
{
//保证'MAIN'是第一个
bool operator()(const std::string& lhs, const std::string& rhs) const
{
//确保两个'MAIN'比较结果是false
if (rhs == "MAIN")
{
return false;
}
else if (lhs == "MAIN")
{
return true;
}
else
{
return lhs < rhs;
}
}
};
struct GXTHeader
{
std::uint16_t Version; //4
std::uint16_t CharBits; //8 or 16
};
struct TableEntry
{
char Name[8];
std::int32_t Offset;
};
struct TableBlock
{
char TABL[4];
std::int32_t Size;
//TableEntry Entries[Size / 12];
};
struct KeyEntry
{
std::int32_t Offset;
std::uint32_t Hash;
};
struct KeyBlockMAIN
{
char TKEY[4];
std::int32_t Size;
};
struct KeyBlockOthers
{
char Name[8];
KeyBlockMAIN Body;
};
struct DataBlock
{
char TDAT[4];
std::int32_t Size;
//std::uint16_t Entries[Size / 2];
};
class IVText
{
public:
typedef std::filesystem::path PathType; //路径类型
typedef GTAChar CharType; //宽字符(GXT)类型
typedef std::uint32_t HashType; //GXT key类型
typedef std::string u8StringType; //转码用
typedef std::vector<GTAChar> wStringType; //GXT字符串类型(手动补0)
typedef std::function<void(const std::string&, std::ifstream&) > FuncType; //文本func类型
struct TextEntry
{
u8StringType hash_string;
u8StringType original, translated;
};
void ProcessT2B(const PathType& inFolder, const PathType& outFolder);
void ProcessB2T(const PathType& inFile, const PathType& outFolder);
void ProcessCollect(const PathType& inFolder, const PathType& outFolder);
private:
static bool IsNativeCharacter(char32_t character);
//用func处理文件夹中每个文件
static void ProcessTexts(const PathType& inFolder, bool recursive, const FuncType& func);
//func: 加载译文
void LoadTextFunc(const std::string& filename, std::ifstream& stream);
//func: 收集文本中需要做成字库的字符
static void CollectCharsFunc(std::ifstream& stream, std::set<char32_t>& chars);
//生成字库位置数据和字符集
static void GenerateCollection(const PathType& outFile, const std::set<char32_t>& chars);
static void GenerateTable(const PathType& outFile, const std::set<char32_t>& chars);
void LoadBinary(const PathType& inFile);
void LoadTexts(const PathType& inFolder);
void GenerateTexts(const PathType& output_texts) const;
void GenerateBinary(const PathType& output_binary) const;
//文本/GXT形式互转
static wStringType U8ToWide(const u8StringType& u8_string);
static u8StringType WideToU8(const wStringType& wide_string);
//修正原版GXT中的混乱字符
static void FixCharacters(wStringType& wtext);
//标准编码转到游戏编码
static void LiteralToGame(wStringType& wtext);
//游戏编码转到标准编码
static void GameToLiteral(wStringType& wtext);
//收集'~~'和'<>'形式的Token供比较
static std::set<std::string> CollectTokens(const std::string& str);
static bool CompareTokens(const std::string& s1, const std::string& s2);
std::map<std::string, std::vector<TextEntry>, IVTextTableSorting> m_Data;
};
+33
View File
@@ -0,0 +1,33 @@
#include "../common/stdinc.h"
#include "IVText.h"
int main(int argc, char** argv)
{
//GXTTool -b2t american.gxt D:/text
//GXTTool -t2b D:/text D:/binary
//GXTTool -collect D:/text D:/collection
IVText instance;
if (argc == 4)
{
if (std::strcmp(argv[1],"-b2t") == 0)
{
instance.ProcessB2T(argv[2], argv[3]);
}
else if (std::strcmp(argv[1], "-t2b") == 0)
{
instance.ProcessT2B(argv[2], argv[3]);
}
else if (std::strcmp(argv[1], "-collect") == 0)
{
instance.ProcessCollect(argv[2], argv[3]);
}
}
else
{
std::printf("打开方式不对。\n");
}
return 0;
}
+3131
View File
File diff suppressed because it is too large. Load diff
+3057
View File
File diff suppressed because it is too large. Load diff
+5
View File
@@ -0,0 +1,5 @@
cmake_minimum_required(VERSION 3.15.0)
project(whm_io)
add_executable(whm_io HtmlTextExport.cpp WhmIO.cpp ${common_sources})
+255
View File
@@ -0,0 +1,255 @@
#pragma once
#include "../common/stdinc.h"
#include "pgBase.h"
enum HtmlNodeType :uint {
Node_HtmlNode = 0,
Node_HtmlDataNode = 1,
Node_HtmlTableNode = 2,
Node_HtmlTableElementNode = 3
};
enum HtmlTag :uint {
HTMLTAG_HTML = 0,
HTMLTAG_TITLE = 1,
HTMLTAG_A = 2,
HTMLTAG_BODY = 3,
HTMLTAG_B = 4,
HTMLTAG_BR = 5,
HTMLTAG_CENTER = 6,
HTMLTAG_CODE = 7,
HTMLTAG_DL = 8,
HTMLTAG_DT = 9,
HTMLTAG_DD = 10,
HTMLTAG_DIV = 11,
HTMLTAG_EMBED = 12,
HTMLTAG_EM = 13,
HTMLTAG_HEAD = 14,
HTMLTAG_H1 = 15,
HTMLTAG_H2 = 16,
HTMLTAG_H3 = 17,
HTMLTAG_H4 = 18,
HTMLTAG_H5 = 19,
HTMLTAG_H6 = 20,
HTMLTAG_IMG = 21,
HTMLTAG_I = 22,
HTMLTAG_LINK = 23,
HTMLTAG_LI = 24,
HTMLTAG_META = 25,
HTMLTAG_OBJECT = 26,
HTMLTAG_OL = 27,
HTMLTAG_P = 28,
HTMLTAG_PARAM = 29,
HTMLTAG_SPAN = 30,
HTMLTAG_STRONG = 31,
HTMLTAG_STYLE = 32,
HTMLTAG_TABLE = 33,
HTMLTAG_TR = 34,
HTMLTAG_TH = 35,
HTMLTAG_TD = 36,
HTMLTAG_UL = 37,
HTMLTAG_TEXT = 38,
HTMLTAG_SCRIPTOBJ = 39
};
enum HtmlAttrValue :uint {
HTMLATTRVAL_LEFT = 0,
HTMLATTRVAL_RIGHT = 1,
HTMLATTRVAL_CENTER = 2,
HTMLATTRVAL_JUSTIFY = 3,
HTMLATTRVAL_TOP = 4,
HTMLATTRVAL_BOTTOM = 5,
HTMLATTRVAL_MIDDLE = 6,
HTMLATTRVAL_INHERIT = 7,
HTMLATTRVAL_XXSMALL = 8,
HTMLATTRVAL_XSMALL = 9,
HTMLATTRVAL_SMALL = 10,
HTMLATTRVAL_MEDIUM = 11,
HTMLATTRVAL_LARGE = 12,
HTMLATTRVAL_XLARGE = 13,
HTMLATTRVAL_XXLARGE = 14,
HTMLATTRVAL_BLOCK = 15,
HTMLATTRVAL_INLINE = 18,
HTMLATTRVAL_NONE = 19,
HTMLATTRVAL_SOLID = 20,
HTMLATTRVAL_UNDERLINE = 21,
HTMLATTRVAL_OVERLINE = 22,
HTMLATTRVAL_LINETHROUGH = 23,
HTMLATTRVAL_BLINK = 24,
HTMLATTRVAL_REPEAT = 25,
HTMLATTRVAL_NOREPEAT = 26,
HTMLATTRVAL_REPEATX = 27,
HTMLATTRVAL_REPEATY = 28,
HTMLATTRVAL_COLLAPSE = 29,
HTMLATTRVAL_SEPARATE = 30,
HTMLATTRVAL_UNDEFINED = 0xFFFFFFFF
};
enum CssProperty :uint {
CSS_WIDTH = 0,
CSS_HEIGHT = 1,
CSS_DISPLAY = 2,
CSS_BACKGROUND_COLOR = 3,
CSS_BACKGROUND_REPEAT = 4,
CSS_BACKGROUND_POSITION = 5,
CSS_BACKGROUND_IMAGE = 6,
CSS_COLOR = 7,
CSS_TEXT_ALIGN = 8,
CSS_TEXT_DECORATION = 9,
CSS_VERTICAL_ALIGN = 10,
CSS_FONT = 11,
CSS_FONT_SIZE = 12,
CSS_FONT_STYLE = 13,
CSS_FONT_WEIGHT = 14,
CSS_BORDER_COLLAPSE = 15,
CSS_BORDER_STYLE = 16,
CSS_BORDER_BOTTOM_STYLE = 17,
CSS_BORDER_LEFT_STYLE = 18,
CSS_BORDER_RIGHT_STYLE = 19,
CSS_BORDER_TOP_STYLE = 20,
CSS_BORDER_COLOR = 21,
CSS_BORDER_BOTTOM_COLOR = 22,
CSS_BORDER_LEFT_COLOR = 23,
CSS_BORDER_RIGHT_COLOR = 24,
CSS_BORDER_TOP_COLOR = 25,
CSS_BORDER_WIDTH = 26,
CSS_BORDER_BOTTOM_WIDTH = 27,
CSS_BORDER_LEFT_WIDTH = 28,
CSS_BORDER_RIGHT_WIDTH = 29,
CSS_BORDER_TOP_WIDTHT = 30,
CSS_MARGIN_BOTTOM = 31,
CSS_MARGIN_LEFT = 32,
CSS_MARGIN_RIGHT = 33,
CSS_MARGIN_TOP = 34,
CSS_PADDING_BOTTOM = 35,
CSS_PADDING_LEFT = 36,
CSS_PADDING_RIGHT = 37,
CSS_PADDING_TOP = 38,
CSS_UNUSED = 39
};
struct HtmlRenderState {
HtmlAttrValue eDisplay;
float fWidth;
float fHeight;
float _fC;
float _f10;
uchar _f14[4];
float _f18;
float _f1C;
uint dwBgColor;
pgPtr<void> pBackgroundImage;
uint _f28h;
uint _f28l;
HtmlAttrValue backgroundRepeat;
uint dwColor;
HtmlAttrValue eAlign;
HtmlAttrValue eValign;
HtmlAttrValue eTextDecoration;
uint _f44;
HtmlAttrValue eFontSize;
int nFontStyle;
int nFontWeight;
float _f54;
uint dwBorderBottomColor;
HtmlAttrValue eBorderBottomStyle;
float fBorderBottomWidth;
uint dwBorderLeftColor;
HtmlAttrValue eBorderLeftStyle;
float dwBorderLeftWidth;
uint dwBorderRightColor;
HtmlAttrValue eBorderRightStyle;
float fBorderRightWidth;
uint dwBorderTopColor;
HtmlAttrValue eBorderTopStyle;
float fBorderTopWidth;
float fMarginBottom;
float fMarginLeft;
float fMarginRight;
float fMarginTop;
float fPaddingBottom;
float fPaddingLeft;
float fPaddingRight;
float fPaddingTop;
float fCellPadding;
float fCellSpacing;
int nColSpan;
int nRowSpan;
bool hasBackground;
bool isLink;
uchar _BA[2];
uint dwLinkColor;
HtmlAttrValue _fC0;
};
struct CHtmlCssDeclaration {
CssProperty m_eProperty;
uint _f4; // data1
uint _f8; // data2
uint m_eDataType; // data type (0 - int, 1 - float, .., 3 - color, ..., 6 - unused)
};
struct CHtmlCssSelector {
HtmlTag m_eTag;
pgObjectArray<CHtmlCssDeclaration> m_aDeclarations;
pgPtr<CHtmlCssSelector> _fC;
};
struct CHtmlStylesheet {
DWORD _f0; // unknown (hash?)
pgObjectPtrArray<CHtmlCssSelector> _f4;
BYTE _padC[3];
BYTE _fF;
pgPtr<CHtmlStylesheet> m_pNext;
};
struct CHtmlNode
{
uint vtbl;
HtmlNodeType m_eNodeType;
pgPtr<CHtmlNode> m_pParentNode;
pgObjectPtrArray<CHtmlNode> m_children;
HtmlRenderState m_renderState;
};
struct CHtmlDataNode :CHtmlNode
{
pgString m_pData;
};
struct CHtmlElementNode :CHtmlNode
{
HtmlTag m_eHtmlTag;
pgString m_pszTagName;
pgObjectArray<char> m_nodeParam;
};
struct CHtmlTableNode :CHtmlElementNode
{
pgPtr<void> _fE8;
pgPtr<void> _fEC;
pgPtr<void> _fF0;
pgPtr<void> _fF4;
pgPtr<void> _fF8;
DWORD m_dwCellCount;
DWORD _f100;
};
struct CHtmlTableElementNode :CHtmlElementNode
{
int _fE8;
int _fEC;
};
struct CHtmlDocument
{
pgPtr<CHtmlNode> m_pRootElement;
pgPtr<CHtmlNode> m_pBody;
pgString m_pszTitle;
pgPtr<void> m_pTxd;
pgObjectPtrArray<uint> _f10;
pgObjectPtrArray<CHtmlNode> m_childNodes;
pgObjectPtrArray<CHtmlStylesheet> m_pStylesheet;
uchar pad[3];
uchar _f2B;
};
+341
View File
@@ -0,0 +1,341 @@
#include "HtmlTextExport.h"
#include "rsc_header.h"
#include "HTMLDocument.h"
#include "../common/fnv_hash.h"
#include "../common/char8_t-remediation.h"
void CHtmlTextExport::ExportHtml(const path_type& input_folder)
{
std::set<std::size_t> hashes;
std::filesystem::recursive_directory_iterator it{ input_folder };
for (; it != std::filesystem::recursive_directory_iterator{}; ++it)
{
if (!it->is_regular_file())
continue;
auto filename = it->path();
if (filename.extension() == ".whm")
{
ExportText(filename.replace_extension(".txt"), ExtractWhmStrings(it->path(), hashes));
}
}
}
void CHtmlTextExport::GenerateDataBase(const path_type& input_folder, const path_type& output_file)
{
std::vector<exported_text_entry> texts;
std::filesystem::recursive_directory_iterator it{ input_folder };
for (; it != std::filesystem::recursive_directory_iterator{}; ++it)
{
if (!it->is_regular_file())
{
continue;
}
auto filename = it->path();
if (filename.extension() == ".txt")
{
for (auto& entry : LoadText(filename))
{
texts.push_back(std::move(entry));
}
}
}
std::vector<WhmTextData> text_table;
std::vector<char> text_data;
for (auto& entry : texts)
{
WhmTextData bin_entry;
bin_entry.hash = entry.hash;
bin_entry.offset = text_data.size();
ranges::copy(entry.str, std::back_inserter(text_data));
text_data.push_back(0);
text_table.push_back(bin_entry);
}
BinaryFile out(output_file, "wb");
if (!out)
{
std::printf(U8("创建输出文件 %s 失败。\n"), output_file.string().c_str());
return;
}
out.WriteArray2(std::span{ text_table });
out.WriteArray2(std::span{ text_data });
out.Close();
}
void CHtmlTextExport::ExportText(const std::filesystem::path& filename,
const std::vector<exported_text_entry>& container)
{
if (container.empty())
{
return;
}
auto out = std::fopen(filename.string().c_str(), "w");
if (!out)
{
return;
}
std::fwrite("\xEF\xBB\xBF", 1, 3, out);
for (auto& entry : container)
{
std::fprintf(out, ";0x%08X=%s\n", entry.hash, Windows1252ToUtf8(entry.str).c_str());
std::fprintf(out, "0x%08X=\n\n", entry.hash);
}
std::fclose(out);
}
bool CHtmlTextExport::IsBlankText(const std::string& str)
{
return ranges::all_of(str, [](char chr)
{
//TODO: 全角空格之类更加特殊的字符判断
return chr == ' ' || chr == '\t';
});
}
std::vector<CHtmlTextExport::exported_text_entry> CHtmlTextExport::LoadText(const std::filesystem::path& filename)
{
std::vector<exported_text_entry> result;
std::ifstream stream(filename);
std::string line;
std::size_t line_no = 0;
std::smatch matches;
std::regex entry_regex(R"((0[xX][0-9a-fA-F]{8})=(.*))");
if (!stream)
{
std::printf(U8("打开输入文件 %s 失败。\n"), filename.string().c_str());
return result;
}
SkipUTF8Signature(stream);
while (std::getline(stream, line))
{
++line_no;
line.erase(0, line.find_first_not_of(' '));
line.erase(line.find_last_not_of(' ') + 1);
if (line.empty() || line.front() == ';')
{
continue;
}
if (std::regex_match(line, matches, entry_regex))
{
exported_text_entry entry;
entry.hash = std::stoul(matches.str(1), nullptr, 16);
entry.str = matches.str(2);
//忽略空白文本&原译一致的文本
if (!IsBlankText(entry.str) && entry.hash != fnv_hash::hash_string(entry.str, false))
{
result.emplace_back(std::move(entry));
}
}
else
{
std::printf(U8("%s: 第%u行无法识别。\n"), filename.string().c_str(), line_no);
}
}
return result;
}
std::vector<uchar> CHtmlTextExport::UnpackWhm(const path_type& input_file)
{
BinaryFile file;
std::vector<uchar> uncompressed_bytes;
file.Open(input_file, "rb");
if (file)
{
std::vector<uchar> compressed_bytes;
rsc_header header;
file.Seek(0, SEEK_END);
auto compressed_size = file.Tell() - sizeof(header);
compressed_bytes.resize(compressed_size);
file.Seek(0, SEEK_SET);
file.Read(header);
auto virtual_size = header.flags.GetVirtualSize();
auto physical_size = header.flags.GetPhysicalSize();
ulong uncompressed_size = virtual_size + physical_size;
uncompressed_bytes.resize(uncompressed_size);
file.Read(compressed_bytes.data(), compressed_size);
uncompress(uncompressed_bytes.data(), &uncompressed_size, compressed_bytes.data(), compressed_size);
}
return uncompressed_bytes;
}
void CHtmlTextExport::ExtractNodeStrings(CHtmlNode* node, std::vector<uchar>& block,
std::vector<exported_text_entry>& container, std::set<std::size_t>& hashes)
{
if (node == nullptr)
return;
for (auto& element : node->m_children.get_span(block))
{
ExtractNodeStrings(element.locate(block), block, container, hashes);
}
switch (node->m_eNodeType)
{
case Node_HtmlNode:
case Node_HtmlTableNode:
case Node_HtmlTableElementNode:
{
break;
}
case Node_HtmlDataNode:
{
auto data_node = static_cast<CHtmlDataNode*>(node);
TryAppendString(container, data_node->m_pData.locate(block), hashes);
break;
}
default:
{
throw std::invalid_argument("Unknown node type.");
}
}
}
void CHtmlTextExport::TryAppendString(std::vector<exported_text_entry>& container, char* ptr, std::set<std::size_t>& hashes)
{
//合法的文本类型:
//1) 包含EFIGS字母
//2) 非网址
//判断一个字符是不是数字
auto validate_digit_char = [](char chr)
{
auto ucr = *reinterpret_cast<uchar*>(&chr);
return
(ucr >= '0' && ucr <= '9');
};
//判断一个字符是不是英语字母
auto validate_english_char = [](char chr)
{
auto ucr = *reinterpret_cast<uchar*>(&chr);
return
(ucr >= 'a' && ucr <= 'z') ||
(ucr >= 'A' && ucr <= 'Z');
};
//判断一个字符是不是EFIGS字母
auto validate_efigs_char = [validate_english_char](char chr)
{
auto ucr = *reinterpret_cast<uchar*>(&chr);
return
validate_english_char(chr) ||
(ucr >= 0xC0);
};
//判断字符是不是游戏中url会出现的字符
auto validate_url_char = [validate_digit_char, validate_english_char](char chr)
{
auto ucr = *reinterpret_cast<uchar*>(&chr);
return
validate_english_char(chr) || validate_digit_char(chr) || ucr == '.' || ucr == '%' || ucr == '@' || ucr == '-' || ucr == '_';
};
//判断字符串是否为url
auto validate_url = [validate_url_char](std::string_view view)
{
auto validate_char_result = ranges::all_of(view, validate_url_char);
auto first_dot_pos = view.find('.');
auto last_dot_pos = view.find_last_of('.');
return
!view.empty() && //非空
validate_char_result && //所有字符合法
first_dot_pos != std::string_view::npos && //最少包含一个'.'
first_dot_pos != 0 && //第一个字符不是'.'
last_dot_pos != view.length() - 1; //最后一个字符不是'.'
};
auto validate_string = [validate_efigs_char, validate_url](std::string_view view)
{
//包含EFIGS字母且不是网址
return ranges::any_of(view, validate_efigs_char) && !validate_url(view);
};
if (ptr == nullptr)
{
return;
}
if (validate_string(std::string_view(ptr)))
{
auto hash = fnv_hash::hash_string(ptr, false);
if (hashes.insert(hash).second)
{
container.emplace_back(exported_text_entry{ hash, ptr });
}
}
}
std::vector<CHtmlTextExport::exported_text_entry> CHtmlTextExport::ExtractWhmStrings(const std::filesystem::path& filename, std::set<std::size_t>& hashes)
{
std::vector<exported_text_entry> container;
auto block = UnpackWhm(filename);
if (!block.empty())
{
auto* p_doc = reinterpret_cast<CHtmlDocument*>(block.data());
ExtractNodeStrings(p_doc->m_pBody.locate(block), block, container, hashes);
}
return container;
}
std::string CHtmlTextExport::Windows1252ToUtf8(const std::string& str)
{
std::string result;
for (auto chr : str)
{
utf8::append(*reinterpret_cast<uchar*>(&chr), std::back_inserter(result));
}
return result;
}
+32
View File
@@ -0,0 +1,32 @@
#pragma once
#include "../common/stdinc.h"
struct CHtmlNode;
class CHtmlTextExport
{
public:
typedef std::filesystem::path path_type;
struct exported_text_entry
{
uint hash;
std::string str;
};
void ExportHtml(const path_type& input_folder); //加载文件夹中所有whm文件,在原地生成供翻译的文本
void GenerateDataBase(const path_type& input_folder, const path_type& output_file);
private:
std::vector<std::vector<std::string>> m_Texts;
static std::vector<uchar> UnpackWhm(const path_type& input_file); //解包whm
static void ExtractNodeStrings(CHtmlNode* node, std::vector<uchar>& block, std::vector<exported_text_entry>& container, std::set<std::size_t>& hashes); //收集Node及其子Node的字符串
static void TryAppendString(std::vector<exported_text_entry>& container, char* ptr, std::set<std::size_t>& hashes); //排除没用的字符串
static std::vector<exported_text_entry> ExtractWhmStrings(const std::filesystem::path& filename, std::set<std::size_t>& hashes); //收集whm中所有字符串
static std::string Windows1252ToUtf8(const std::string& str); //转码
static void ExportText(const std::filesystem::path& filename, const std::vector<exported_text_entry>& container); //将whm文本输出到txt
static bool IsBlankText(const std::string& str);
static std::vector<exported_text_entry> LoadText(const std::filesystem::path& filename);
};
+25
View File
@@ -0,0 +1,25 @@
#include "HtmlTextExport.h"
int main(int argc, char* argv[])
{
CHtmlTextExport exporter;
if (argc == 3)
{
//读取翻译后文本并生成汉化补丁用数据库
CHtmlTextExport::path_type p1 = argv[1];
CHtmlTextExport::path_type p2 = argv[2];
exporter.GenerateDataBase(p1, p2);
}
else if (argc == 2)
{
//读取whm文件并在原位生成输出文本
CHtmlTextExport::path_type p1 = argv[1];
exporter.ExportHtml(p1);
}
return 0;
}
+56
View File
@@ -0,0 +1,56 @@
#pragma once
typedef unsigned short ushort;
typedef unsigned int uint;
typedef unsigned char uchar;
enum class ptr_element_type :uint
{
Cpu_Type = 5,
Gpu_Type = 6
};
template <typename T>
struct pgPtr
{
uint o : 28; //block中的位置
ptr_element_type t : 4; //资源类型
T* locate(std::vector<uchar>& block) const
{
if (block.empty() || t != ptr_element_type::Cpu_Type)
{
return nullptr;
}
else
{
return reinterpret_cast<T*>(block.data() + o);
}
}
};
//指向一个C String
struct pgString : pgPtr<char>
{
};
//对象数组
template <typename T>
struct pgObjectArray : pgPtr<T>
{
ushort count; //有效元素个数(std::vector的size)
ushort size; //占据空间个数(std::vector的capacity)
std::span<T> get_span(std::vector<uchar>& block) const
{
return { pgPtr<T>::locate(block), std::max(count,size) };
}
};
//对象指针数组
template <typename T>
struct pgObjectPtrArray : pgObjectArray<pgPtr<T>>
{
};
+83
View File
@@ -0,0 +1,83 @@
#pragma once
#include "../common/stdinc.h"
enum rsc_type :uint
{
TextureXBOX = 0x7, // xtd
ModelXBOX = 0x6D, // xdr
Generic = 0x01, // xhm / xad (Generic files as rsc?)
Bounds = 0x20, // xbd, wbd
Particles = 0x24, // xpfl
Particles2 = 0x1B, // xpfl
Texture = 0x8, // wtd
Model = 0x6E, // wdr
ModelFrag = 0x70, //wft
};
//page单位大小是2^n
struct rsc_flag
{
union
{
struct
{
uint virtual1xPageFlag : 1; //4个小页面的开关
uint virtual2xPageFlag : 1;
uint virtual4xPageFlag : 1;
uint virtual8xPageFlag : 1;
uint virtual16xPageCount : 7; //大页面的个数
uint virtual1xPageSize : 4; //用于决定单位页大小((2^virtual1xPageSize)*256)
uint physical1xPageFlag : 1;
uint physical2xPageFlag : 1;
uint physical4xPageFlag : 1;
uint physical8xPageFlag : 1;
uint physical16xPageCount : 7;
uint physical1xPageSize : 4;
uint useless : 2;
};
uint flags;
}u;
uint GetVirtualPageSize() const
{
return (1u << (u.virtual1xPageSize + 8u));
}
uint GetPhysicalPageSize() const
{
return (1u << (u.physical1xPageSize + 8u));
}
uint GetVirtualSize() const
{
return GetVirtualPageSize() * (
u.virtual1xPageFlag * 1u +
u.virtual2xPageFlag * 2u +
u.virtual4xPageFlag * 4u +
u.virtual8xPageFlag * 8u +
u.virtual16xPageCount * 16u);
}
uint GetPhysicalSize() const
{
return GetPhysicalPageSize() * (
u.physical1xPageFlag * 1u +
u.physical2xPageFlag * 2u +
u.physical4xPageFlag * 4u +
u.physical8xPageFlag * 8u +
u.physical16xPageCount * 16u);
}
};
VALIDATE_SIZE(rsc_flag, 4);
struct rsc_header
{
uint magic;
uint type;
rsc_flag flags;
};
VALIDATE_SIZE(rsc_header, 12);