teleport_move.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  1. /**
  2. * The teleport itself. The camera hook publishes a forward vector and reads the bound key once a
  3. * frame. The physics hook applies the move before the sync it runs ahead of. Physics owns the
  4. * position, so writing the object placement would move the camera alone.
  5. */
  6. #include <Windows.h>
  7. #include <array>
  8. #include <atomic>
  9. #include <cstddef>
  10. #include <cstdint>
  11. #include <cstdio>
  12. #include "../../../core/logging/log.h"
  13. #include "../../../core/ui/runtime/ui_visibility_runtime.h"
  14. #include "../../../state/account/account_state.h"
  15. #include "../../../state/runtime/runtime.h"
  16. #include "../../input/window_focus.h"
  17. #include "../../movement/movement_settings_store.h"
  18. #include "../polled_input/runtime.h"
  19. #include "internal.h"
  20. #include "runtime.h"
  21. namespace sunrise::client::hooks::teleport {
  22. namespace {
  23. /**
  24. * Frames a press stays pending. Orbit and loading screens tick the camera but never the player's
  25. * physics, so a request with no limit is used up later and reads as a queued teleport.
  26. */
  27. constexpr std::uint32_t kRequestLifetimeFrames = 3;
  28. /** Frames an ordinary physics tick gets to collect a request before the forced path takes it. */
  29. constexpr std::uint32_t kForceAfterFrames = 1;
  30. /**
  31. * Frames the injected press is held. It has to survive at least one scan and one integration
  32. * step, or the move it exists to publish is never read.
  33. */
  34. constexpr std::uint32_t kPressFrames = 2;
  35. /** Authored action driven to wake the body. Forward is the gentlest one that moves it. */
  36. constexpr std::uint16_t kForwardAction =
  37. static_cast<std::uint16_t>(state::account::settings::bindings::Action::moveForward);
  38. std::atomic_bool g_requested{false};
  39. std::atomic_bool g_forwardValid{false};
  40. std::atomic_bool g_keyDown{false};
  41. std::atomic_uint32_t g_requestAge{0};
  42. /** Set while the feature is usable, so the per-tick path costs one atomic read when it is not. */
  43. std::atomic_bool g_active{false};
  44. SRWLOCK g_cameraPoseLock{SRWLOCK_INIT};
  45. CameraPose g_cameraPose{};
  46. bool g_cameraPoseValid{};
  47. /**
  48. * The player's physics component, kept from the last tick that carried it. At rest the sync stops
  49. * being called for the player at all, so the pointer is the only way back to them.
  50. */
  51. std::atomic<std::byte*> g_playerComponent{nullptr};
  52. /** Frames left before the injected press is released. */
  53. std::atomic_uint32_t g_pressFrames{0};
  54. ControlledHandle g_controlledHandle{};
  55. CameraSingleton g_cameraSingleton{};
  56. /** Camera forward vector for the next physics tick. Every access holds g_cameraPoseLock. */
  57. std::array<float, kVectorLanes> g_forward{};
  58. /** Withdraws the pose when the camera block is not readable for this frame. */
  59. void invalidate_camera_pose() noexcept {
  60. AcquireSRWLockExclusive(&g_cameraPoseLock);
  61. g_cameraPose = {};
  62. g_cameraPoseValid = false;
  63. ReleaseSRWLockExclusive(&g_cameraPoseLock);
  64. }
  65. /** @param forward Receives the published camera forward vector, copied under the pose lock. */
  66. void copy_forward(Vector& forward) noexcept {
  67. AcquireSRWLockShared(&g_cameraPoseLock);
  68. forward = g_forward;
  69. ReleaseSRWLockShared(&g_cameraPoseLock);
  70. }
  71. /**
  72. * Reads one value out of game memory without faulting on a torn pointer.
  73. * @param address Source address.
  74. * @param value Receives the value.
  75. * @return True when Windows copied the whole value.
  76. */
  77. template <typename T> [[nodiscard]] bool read_at(const std::byte* address, T& value) noexcept {
  78. if (address == nullptr) {
  79. return false;
  80. }
  81. SIZE_T read = 0;
  82. return ReadProcessMemory(GetCurrentProcess(), address, &value, sizeof value, &read) != FALSE
  83. && read == sizeof value;
  84. }
  85. /**
  86. * Writes one vector into game memory. The call applies page protection itself.
  87. * @param address Destination address.
  88. * @param value Three lanes to store.
  89. * @return True when Windows copied the whole vector.
  90. */
  91. [[nodiscard]] bool write_vector(std::byte* address,
  92. const std::array<float, kVectorLanes>& value) noexcept {
  93. if (address == nullptr) {
  94. return false;
  95. }
  96. SIZE_T written = 0;
  97. const SIZE_T size = sizeof(float) * kVectorLanes;
  98. return WriteProcessMemory(GetCurrentProcess(), address, value.data(), size, &written) != FALSE
  99. && written == size;
  100. }
  101. /**
  102. * Finds the rigid body a physics component drives.
  103. * @param component Physics component.
  104. * @return The body, or null when the chain breaks.
  105. */
  106. [[nodiscard]] std::byte* body_of(std::byte* component) noexcept {
  107. std::byte* array = nullptr;
  108. std::int32_t index = 0;
  109. if (!read_at(component + kPhysicsComponentBodyArray, array)
  110. || !read_at(component + kPhysicsComponentBodyIndex, index) || array == nullptr
  111. || index < 0) {
  112. return nullptr;
  113. }
  114. std::byte* body = nullptr;
  115. const std::size_t offset = kBodyEntryStride * static_cast<std::size_t>(index) + kBodyPointer;
  116. return read_at(array + offset, body) ? body : nullptr;
  117. }
  118. /**
  119. * Ages a pending request and drops it once nothing has taken it. A press is meant for the moment
  120. * it is made, so one that finds no player physics tick is dropped, not held for the next one.
  121. */
  122. void expire_request() noexcept {
  123. if (!g_requested.load(std::memory_order_acquire)) {
  124. return;
  125. }
  126. if (g_requestAge.fetch_add(1, std::memory_order_relaxed) + 1 >= kRequestLifetimeFrames) {
  127. g_requested.store(false, std::memory_order_release);
  128. }
  129. }
  130. /**
  131. * Runs the whole move for a component already proved to be the player's.
  132. * @param component Physics component driving the player.
  133. * @return True when the body was found and its position was written.
  134. */
  135. [[nodiscard]] bool perform_move(std::byte* component) noexcept;
  136. /** @param reason Key naming the step that stopped the move. */
  137. void report_skip(const char* reason) noexcept;
  138. /**
  139. * Starts the injected press that wakes the body.
  140. * Nothing reads the new body position until something integrates it. So the move drives the
  141. * player's own forward action, instead of writing what that action would have produced.
  142. */
  143. void begin_press() noexcept {
  144. const state::AccountState account = state::account_snapshot();
  145. const auto& binding = account.settings.keyBindings.values[kForwardAction];
  146. if (!binding.primary.has_value()) {
  147. return;
  148. }
  149. const std::uint32_t virtualKey = action_key(*binding.primary);
  150. if (virtualKey == 0) {
  151. report_skip("no_key");
  152. return;
  153. }
  154. hooks::polled_input::hold_key(virtualKey);
  155. g_pressFrames.store(kPressFrames, std::memory_order_release);
  156. }
  157. /** Releases the injected press once it has been scanned. */
  158. void end_press() noexcept {
  159. if (g_pressFrames.load(std::memory_order_acquire) == 0) {
  160. return;
  161. }
  162. if (g_pressFrames.fetch_sub(1, std::memory_order_acq_rel) <= 1) {
  163. hooks::polled_input::release_key();
  164. }
  165. }
  166. /**
  167. * @param component Candidate physics component.
  168. * @return True when it drives the object the local player controls.
  169. */
  170. [[nodiscard]] bool owns_player(std::byte* component) noexcept {
  171. std::uint32_t controlled = kInvalidHandle;
  172. g_controlledHandle(&controlled);
  173. if (controlled == kInvalidHandle) {
  174. return false;
  175. }
  176. std::uint16_t owner = 0;
  177. return read_at(component + kPhysicsComponentObjectHandle, owner)
  178. && (controlled & kHandleIndexMask)
  179. == (static_cast<std::uint32_t>(owner) & kHandleIndexMask);
  180. }
  181. /** @param reason Key naming the step that stopped the move. */
  182. void report_skip(const char* reason) noexcept {
  183. std::array<char, 96> line{};
  184. const int written = std::snprintf(
  185. line.data(), line.size(), "ev=teleport stage=move result=skip reason=%s", reason);
  186. if (written > 0) {
  187. core::log::write(core::log::Channel::client,
  188. core::log::Level::warn,
  189. {line.data(), static_cast<std::size_t>(written)});
  190. }
  191. }
  192. /**
  193. * Writes one vertical velocity, leaving run momentum on the other two lanes.
  194. * @param body Rigid body to write.
  195. * @param value Vertical velocity to store.
  196. */
  197. void set_vertical_velocity(std::byte* body, float value) noexcept {
  198. std::array<float, kVectorLanes> velocity{};
  199. if (!read_at(body + kBodyVelocityX, velocity)) {
  200. return;
  201. }
  202. velocity[kVerticalLane] = value;
  203. (void)write_vector(body + kBodyVelocityX, velocity);
  204. }
  205. /**
  206. * Adds one world delta to a stored position.
  207. * @param address Vector to move.
  208. * @param delta World units per lane.
  209. * @param before Receives the value read.
  210. * @param after Receives the value written.
  211. * @return True when the new value was stored.
  212. */
  213. [[nodiscard]] bool offset_vector(std::byte* address,
  214. const std::array<float, kVectorLanes>& delta,
  215. std::array<float, kVectorLanes>& before,
  216. std::array<float, kVectorLanes>& after) noexcept {
  217. if (!read_at(address, before)) {
  218. return false;
  219. }
  220. for (std::size_t lane = 0; lane < kVectorLanes; ++lane) {
  221. after[lane] = before[lane] + delta[lane];
  222. }
  223. return write_vector(address, after);
  224. }
  225. /**
  226. * Adds the configured distance along the published forward vector.
  227. *
  228. * Only the rigid body is written. The physics component's own vector is composed against the body
  229. * orientation rather than added to it, so a world delta applied there corrupts the transform.
  230. *
  231. * @param body Rigid body being moved.
  232. * @param distance World units to travel.
  233. * @return True when the new position was stored.
  234. */
  235. [[nodiscard]] bool move_body(std::byte* body, float distance) noexcept {
  236. Vector forward{};
  237. copy_forward(forward);
  238. std::array<float, kVectorLanes> delta{};
  239. for (std::size_t lane = 0; lane < kVectorLanes; ++lane) {
  240. delta[lane] = forward[lane] * distance;
  241. }
  242. std::array<float, kVectorLanes> position{};
  243. std::array<float, kVectorLanes> moved{};
  244. if (!offset_vector(body + kBodyPositionX, delta, position, moved)) {
  245. report_skip("body");
  246. return false;
  247. }
  248. std::array<char, 160> line{};
  249. const int written = std::snprintf(line.data(),
  250. line.size(),
  251. "ev=teleport stage=move result=ok dist=%.1f "
  252. "from=%.1f,%.1f,%.1f to=%.1f,%.1f,%.1f",
  253. static_cast<double>(distance),
  254. static_cast<double>(position[0]),
  255. static_cast<double>(position[1]),
  256. static_cast<double>(position[2]),
  257. static_cast<double>(moved[0]),
  258. static_cast<double>(moved[1]),
  259. static_cast<double>(moved[2]));
  260. if (written > 0) {
  261. core::log::write(core::log::Channel::client,
  262. core::log::Level::info,
  263. {line.data(), static_cast<std::size_t>(written)});
  264. }
  265. return true;
  266. }
  267. /**
  268. * Runs the whole move for a component already proved to be the player's.
  269. * @param component Physics component driving the player.
  270. * @return True when the body was found and its position was written.
  271. */
  272. [[nodiscard]] bool perform_move(std::byte* component) noexcept {
  273. std::byte* const body = body_of(component);
  274. if (body == nullptr) {
  275. report_skip("no_body");
  276. return false;
  277. }
  278. set_vertical_velocity(body, 0.0F);
  279. if (!move_body(body, client::movement::get().distance)) {
  280. return false;
  281. }
  282. begin_press();
  283. return true;
  284. }
  285. } // namespace
  286. /** Publishes the two functions the hooks call. */
  287. void publish_targets(ControlledHandle controlled, CameraSingleton singleton) noexcept {
  288. g_controlledHandle = controlled;
  289. g_cameraSingleton = singleton;
  290. }
  291. /** Drops those functions and every latched request. */
  292. void clear_targets() noexcept {
  293. g_controlledHandle = nullptr;
  294. g_cameraSingleton = nullptr;
  295. g_requested.store(false, std::memory_order_release);
  296. g_forwardValid.store(false, std::memory_order_release);
  297. g_keyDown.store(false, std::memory_order_relaxed);
  298. g_requestAge.store(0, std::memory_order_relaxed);
  299. g_active.store(false, std::memory_order_relaxed);
  300. g_playerComponent.store(nullptr, std::memory_order_relaxed);
  301. invalidate_camera_pose();
  302. }
  303. /** Publishes the frame's complete camera pose and its forward vector. */
  304. void capture_camera_pose(std::uint32_t playerIndex) noexcept {
  305. if (playerIndex == kInvalidHandle || g_cameraSingleton == nullptr) {
  306. invalidate_camera_pose();
  307. return;
  308. }
  309. std::byte* const camera = g_cameraSingleton();
  310. if (camera == nullptr) {
  311. invalidate_camera_pose();
  312. return;
  313. }
  314. const std::size_t playerOffset = kCameraBlockStride * playerIndex;
  315. CameraPose pose{};
  316. if (!read_at(camera + playerOffset + kCameraPositionX, pose.position)
  317. || !read_at(camera + playerOffset + kCameraForwardX, pose.forward)
  318. || !read_at(camera + playerOffset + kCameraUpX, pose.up)
  319. || !read_at(camera + playerOffset + kCameraHorizontalFov, pose.horizontalFov)
  320. || !read_at(camera + playerOffset + kCameraAspect, pose.aspect)) {
  321. invalidate_camera_pose();
  322. return;
  323. }
  324. AcquireSRWLockExclusive(&g_cameraPoseLock);
  325. g_cameraPose = pose;
  326. g_cameraPoseValid = true;
  327. g_forward = pose.forward;
  328. ReleaseSRWLockExclusive(&g_cameraPoseLock);
  329. g_forwardValid.store(true, std::memory_order_release);
  330. }
  331. /** Latches one teleport request if the bound key went down this frame. */
  332. void poll_request() noexcept {
  333. end_press();
  334. expire_request();
  335. const client::movement::Settings settings = client::movement::get();
  336. const bool usable = settings.enabled && settings.virtualKey != client::movement::kNoKey;
  337. g_active.store(usable, std::memory_order_relaxed);
  338. if (!usable) {
  339. g_keyDown.store(false, std::memory_order_relaxed);
  340. return;
  341. }
  342. // An open interface owns the keyboard, so the key that binds the teleport must not fire it.
  343. if (core::ui::runtime::snapshot().visible) {
  344. g_keyDown.store(false, std::memory_order_relaxed);
  345. return;
  346. }
  347. const bool down = client::input::game_focused()
  348. && (GetAsyncKeyState(static_cast<int>(settings.virtualKey)) & 0x8000) != 0;
  349. if (down && !g_keyDown.exchange(down, std::memory_order_relaxed)) {
  350. g_requestAge.store(0, std::memory_order_relaxed);
  351. g_requested.store(true, std::memory_order_release);
  352. return;
  353. }
  354. g_keyDown.store(down, std::memory_order_relaxed);
  355. }
  356. /** Moves the local player if a request is pending and this component owns them. */
  357. void apply_pending(void* component) noexcept {
  358. if (!g_active.load(std::memory_order_relaxed) || component == nullptr
  359. || g_controlledHandle == nullptr) {
  360. return;
  361. }
  362. const bool requested = g_requested.load(std::memory_order_acquire);
  363. // The ownership test runs per component, so it is paid only while a request is open or until
  364. // the player's component is known. Once it is known, an ordinary tick costs two atomic reads.
  365. if (!requested && g_playerComponent.load(std::memory_order_relaxed) != nullptr) {
  366. return;
  367. }
  368. if (!owns_player(static_cast<std::byte*>(component))) {
  369. return;
  370. }
  371. std::byte* const physics = static_cast<std::byte*>(component);
  372. g_playerComponent.store(physics, std::memory_order_relaxed);
  373. if (!requested || !g_forwardValid.load(std::memory_order_acquire)) {
  374. return;
  375. }
  376. g_requested.store(false, std::memory_order_release);
  377. (void)perform_move(physics);
  378. }
  379. /** Runs the move for a request no physics tick collected. */
  380. void force_pending() noexcept {
  381. if (!g_requested.load(std::memory_order_acquire)
  382. || !g_forwardValid.load(std::memory_order_acquire)
  383. || g_requestAge.load(std::memory_order_relaxed) < kForceAfterFrames) {
  384. return;
  385. }
  386. std::byte* const physics = g_playerComponent.load(std::memory_order_relaxed);
  387. // The cached pointer outlives a destination change, so it is proved again before use.
  388. if (physics == nullptr || g_controlledHandle == nullptr || !owns_player(physics)) {
  389. return;
  390. }
  391. g_requested.store(false, std::memory_order_release);
  392. if (!perform_move(physics)) {
  393. return;
  394. }
  395. invoke_sync(physics);
  396. core::log::write(
  397. core::log::Channel::client, core::log::Level::info, "ev=teleport stage=force result=ok");
  398. }
  399. /** Reports the physics component the local player was last seen driving. */
  400. void* local_player_component() noexcept {
  401. return g_playerComponent.load(std::memory_order_relaxed);
  402. }
  403. /** @param component Candidate physics component. @return True when the local player drives it. */
  404. bool owns_local_player(void* component) noexcept {
  405. return component != nullptr && g_controlledHandle != nullptr
  406. && owns_player(static_cast<std::byte*>(component));
  407. }
  408. /** Reads the world position of the body a physics component drives. */
  409. bool read_position(void* component, Vector& position) noexcept {
  410. if (component == nullptr) {
  411. return false;
  412. }
  413. std::byte* const body = body_of(static_cast<std::byte*>(component));
  414. return body != nullptr && read_at(body + kBodyPositionX, position);
  415. }
  416. /** Writes the linear velocity of the body a physics component drives. */
  417. bool write_velocity(void* component, const Vector& velocity) noexcept {
  418. if (component == nullptr) {
  419. return false;
  420. }
  421. std::byte* const body = body_of(static_cast<std::byte*>(component));
  422. return body != nullptr && write_vector(body + kBodyVelocityX, velocity);
  423. }
  424. /** Reports the camera forward vector published this frame. */
  425. bool camera_forward(Vector& forward) noexcept {
  426. if (!g_forwardValid.load(std::memory_order_acquire)) {
  427. return false;
  428. }
  429. copy_forward(forward);
  430. return true;
  431. }
  432. /** Copies the last complete pose published by the camera-frame hook. */
  433. bool camera_pose(CameraPose& pose) noexcept {
  434. AcquireSRWLockShared(&g_cameraPoseLock);
  435. const bool valid = g_cameraPoseValid;
  436. pose = valid ? g_cameraPose : CameraPose{};
  437. ReleaseSRWLockShared(&g_cameraPoseLock);
  438. return valid;
  439. }
  440. } // namespace sunrise::client::hooks::teleport