teleport_move.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  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. /** Written by the camera hook and read by the physics hook. Both run on the same thread. */
  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. /**
  66. * Reads one value out of game memory without faulting on a torn pointer.
  67. * @param address Source address.
  68. * @param value Receives the value.
  69. * @return True when Windows copied the whole value.
  70. */
  71. template <typename T> [[nodiscard]] bool read_at(const std::byte* address, T& value) noexcept {
  72. if (address == nullptr) {
  73. return false;
  74. }
  75. SIZE_T read = 0;
  76. return ReadProcessMemory(GetCurrentProcess(), address, &value, sizeof value, &read) != FALSE
  77. && read == sizeof value;
  78. }
  79. /**
  80. * Writes one vector into game memory. The call applies page protection itself.
  81. * @param address Destination address.
  82. * @param value Three lanes to store.
  83. * @return True when Windows copied the whole vector.
  84. */
  85. [[nodiscard]] bool write_vector(std::byte* address,
  86. const std::array<float, kVectorLanes>& value) noexcept {
  87. if (address == nullptr) {
  88. return false;
  89. }
  90. SIZE_T written = 0;
  91. const SIZE_T size = sizeof(float) * kVectorLanes;
  92. return WriteProcessMemory(GetCurrentProcess(), address, value.data(), size, &written) != FALSE
  93. && written == size;
  94. }
  95. /**
  96. * Finds the rigid body a physics component drives.
  97. * @param component Physics component.
  98. * @return The body, or null when the chain breaks.
  99. */
  100. [[nodiscard]] std::byte* body_of(std::byte* component) noexcept {
  101. std::byte* array = nullptr;
  102. std::int32_t index = 0;
  103. if (!read_at(component + kPhysicsComponentBodyArray, array)
  104. || !read_at(component + kPhysicsComponentBodyIndex, index) || array == nullptr
  105. || index < 0) {
  106. return nullptr;
  107. }
  108. std::byte* body = nullptr;
  109. const std::size_t offset = kBodyEntryStride * static_cast<std::size_t>(index) + kBodyPointer;
  110. return read_at(array + offset, body) ? body : nullptr;
  111. }
  112. /**
  113. * Ages a pending request and drops it once nothing has taken it. A press is meant for the moment
  114. * it is made, so one that finds no player physics tick is dropped, not held for the next one.
  115. */
  116. void expire_request() noexcept {
  117. if (!g_requested.load(std::memory_order_acquire)) {
  118. return;
  119. }
  120. if (g_requestAge.fetch_add(1, std::memory_order_relaxed) + 1 >= kRequestLifetimeFrames) {
  121. g_requested.store(false, std::memory_order_release);
  122. }
  123. }
  124. /**
  125. * Runs the whole move for a component already proved to be the player's.
  126. * @param component Physics component driving the player.
  127. * @return True when the body was found and its position was written.
  128. */
  129. [[nodiscard]] bool perform_move(std::byte* component) noexcept;
  130. /** @param reason Key naming the step that stopped the move. */
  131. void report_skip(const char* reason) noexcept;
  132. /**
  133. * Starts the injected press that wakes the body.
  134. * Nothing reads the new body position until something integrates it. So the move drives the
  135. * player's own forward action, instead of writing what that action would have produced.
  136. */
  137. void begin_press() noexcept {
  138. const state::AccountState account = state::account_snapshot();
  139. const auto& binding = account.settings.keyBindings.values[kForwardAction];
  140. if (!binding.primary.has_value()) {
  141. return;
  142. }
  143. const std::uint32_t virtualKey = action_key(*binding.primary);
  144. if (virtualKey == 0) {
  145. report_skip("no_key");
  146. return;
  147. }
  148. hooks::polled_input::hold_key(virtualKey);
  149. g_pressFrames.store(kPressFrames, std::memory_order_release);
  150. }
  151. /** Releases the injected press once it has been scanned. */
  152. void end_press() noexcept {
  153. if (g_pressFrames.load(std::memory_order_acquire) == 0) {
  154. return;
  155. }
  156. if (g_pressFrames.fetch_sub(1, std::memory_order_acq_rel) <= 1) {
  157. hooks::polled_input::release_key();
  158. }
  159. }
  160. /**
  161. * Reports the gate values the sync tests before it publishes a transform.
  162. *
  163. * The move lands while moving and does nothing at rest for all three write targets, so what
  164. * changes at rest is upstream of the write. These four gates are what the sync reads first.
  165. *
  166. * @param component Physics component owning the player.
  167. * @param body Rigid body behind it.
  168. */
  169. void report_gates(const std::byte* component, const std::byte* body) noexcept {
  170. std::uint8_t suppressed = 0;
  171. std::int32_t bodyIndex = 0;
  172. std::uint32_t bodyFlags = 0;
  173. std::uint8_t motionType = 0;
  174. (void)read_at(component + kPhysicsComponentSuppress, suppressed);
  175. (void)read_at(component + kPhysicsComponentBodyIndex, bodyIndex);
  176. (void)read_at(body + kBodyFlags, bodyFlags);
  177. (void)read_at(body + kBodyMotionType, motionType);
  178. std::array<char, 160> line{};
  179. const int written = std::snprintf(line.data(),
  180. line.size(),
  181. "ev=teleport stage=gates suppress=%u index=%d "
  182. "flags=0x%08X active=%u motion=%u",
  183. static_cast<unsigned>(suppressed),
  184. static_cast<int>(bodyIndex),
  185. static_cast<unsigned>(bodyFlags),
  186. (bodyFlags & kBodyActiveBit) != 0 ? 1U : 0U,
  187. static_cast<unsigned>(motionType));
  188. if (written > 0) {
  189. core::log::write(core::log::Channel::client,
  190. core::log::Level::info,
  191. {line.data(), static_cast<std::size_t>(written)});
  192. }
  193. }
  194. /**
  195. * @param component Candidate physics component.
  196. * @return True when it drives the object the local player controls.
  197. */
  198. [[nodiscard]] bool owns_player(std::byte* component) noexcept {
  199. std::uint32_t controlled = kInvalidHandle;
  200. g_controlledHandle(&controlled);
  201. if (controlled == kInvalidHandle) {
  202. return false;
  203. }
  204. std::uint16_t owner = 0;
  205. return read_at(component + kPhysicsComponentObjectHandle, owner)
  206. && (controlled & kHandleIndexMask)
  207. == (static_cast<std::uint32_t>(owner) & kHandleIndexMask);
  208. }
  209. /** @param reason Key naming the step that stopped the move. */
  210. void report_skip(const char* reason) noexcept {
  211. std::array<char, 96> line{};
  212. const int written = std::snprintf(
  213. line.data(), line.size(), "ev=teleport stage=move result=skip reason=%s", reason);
  214. if (written > 0) {
  215. core::log::write(core::log::Channel::client,
  216. core::log::Level::warn,
  217. {line.data(), static_cast<std::size_t>(written)});
  218. }
  219. }
  220. /**
  221. * Writes one vertical velocity, leaving run momentum on the other two lanes.
  222. * @param body Rigid body to write.
  223. * @param value Vertical velocity to store.
  224. */
  225. void set_vertical_velocity(std::byte* body, float value) noexcept {
  226. std::array<float, kVectorLanes> velocity{};
  227. if (!read_at(body + kBodyVelocityX, velocity)) {
  228. return;
  229. }
  230. velocity[kVerticalLane] = value;
  231. (void)write_vector(body + kBodyVelocityX, velocity);
  232. }
  233. /**
  234. * Adds one world delta to a stored position.
  235. * @param address Vector to move.
  236. * @param delta World units per lane.
  237. * @param before Receives the value read.
  238. * @param after Receives the value written.
  239. * @return True when the new value was stored.
  240. */
  241. [[nodiscard]] bool offset_vector(std::byte* address,
  242. const std::array<float, kVectorLanes>& delta,
  243. std::array<float, kVectorLanes>& before,
  244. std::array<float, kVectorLanes>& after) noexcept {
  245. if (!read_at(address, before)) {
  246. return false;
  247. }
  248. for (std::size_t lane = 0; lane < kVectorLanes; ++lane) {
  249. after[lane] = before[lane] + delta[lane];
  250. }
  251. return write_vector(address, after);
  252. }
  253. /**
  254. * Adds the configured distance along the published forward vector.
  255. *
  256. * Only the rigid body is written. The physics component's own vector is composed against the body
  257. * orientation rather than added to it, so a world delta applied there corrupts the transform.
  258. *
  259. * @param body Rigid body being moved.
  260. * @param distance World units to travel.
  261. * @return True when the new position was stored.
  262. */
  263. [[nodiscard]] bool move_body(std::byte* body, float distance) noexcept {
  264. std::array<float, kVectorLanes> delta{};
  265. for (std::size_t lane = 0; lane < kVectorLanes; ++lane) {
  266. delta[lane] = g_forward[lane] * distance;
  267. }
  268. std::array<float, kVectorLanes> position{};
  269. std::array<float, kVectorLanes> moved{};
  270. if (!offset_vector(body + kBodyPositionX, delta, position, moved)) {
  271. report_skip("body");
  272. return false;
  273. }
  274. std::array<char, 160> line{};
  275. const int written = std::snprintf(line.data(),
  276. line.size(),
  277. "ev=teleport stage=move result=ok dist=%.1f "
  278. "from=%.1f,%.1f,%.1f to=%.1f,%.1f,%.1f",
  279. static_cast<double>(distance),
  280. static_cast<double>(position[0]),
  281. static_cast<double>(position[1]),
  282. static_cast<double>(position[2]),
  283. static_cast<double>(moved[0]),
  284. static_cast<double>(moved[1]),
  285. static_cast<double>(moved[2]));
  286. if (written > 0) {
  287. core::log::write(core::log::Channel::client,
  288. core::log::Level::info,
  289. {line.data(), static_cast<std::size_t>(written)});
  290. }
  291. return true;
  292. }
  293. /**
  294. * Runs the whole move for a component already proved to be the player's.
  295. * @param component Physics component driving the player.
  296. * @return True when the body was found and its position was written.
  297. */
  298. [[nodiscard]] bool perform_move(std::byte* component) noexcept {
  299. std::byte* const body = body_of(component);
  300. if (body == nullptr) {
  301. report_skip("no_body");
  302. return false;
  303. }
  304. report_gates(component, body);
  305. set_vertical_velocity(body, 0.0F);
  306. if (!move_body(body, client::movement::get().distance)) {
  307. return false;
  308. }
  309. begin_press();
  310. return true;
  311. }
  312. } // namespace
  313. /** Publishes the two functions the hooks call. */
  314. void publish_targets(ControlledHandle controlled, CameraSingleton singleton) noexcept {
  315. g_controlledHandle = controlled;
  316. g_cameraSingleton = singleton;
  317. }
  318. /** Drops those functions and every latched request. */
  319. void clear_targets() noexcept {
  320. g_controlledHandle = nullptr;
  321. g_cameraSingleton = nullptr;
  322. g_requested.store(false, std::memory_order_release);
  323. g_forwardValid.store(false, std::memory_order_release);
  324. g_keyDown.store(false, std::memory_order_relaxed);
  325. g_requestAge.store(0, std::memory_order_relaxed);
  326. g_active.store(false, std::memory_order_relaxed);
  327. g_playerComponent.store(nullptr, std::memory_order_relaxed);
  328. invalidate_camera_pose();
  329. }
  330. /** Publishes the frame's complete camera pose and its forward vector. */
  331. void capture_camera_pose(std::uint32_t playerIndex) noexcept {
  332. if (playerIndex == kInvalidHandle || g_cameraSingleton == nullptr) {
  333. invalidate_camera_pose();
  334. return;
  335. }
  336. std::byte* const camera = g_cameraSingleton();
  337. if (camera == nullptr) {
  338. invalidate_camera_pose();
  339. return;
  340. }
  341. const std::size_t playerOffset = kCameraBlockStride * playerIndex;
  342. CameraPose pose{};
  343. if (!read_at(camera + playerOffset + kCameraPositionX, pose.position)
  344. || !read_at(camera + playerOffset + kCameraForwardX, pose.forward)
  345. || !read_at(camera + playerOffset + kCameraUpX, pose.up)
  346. || !read_at(camera + playerOffset + kCameraHorizontalFov, pose.horizontalFov)
  347. || !read_at(camera + playerOffset + kCameraAspect, pose.aspect)) {
  348. invalidate_camera_pose();
  349. return;
  350. }
  351. AcquireSRWLockExclusive(&g_cameraPoseLock);
  352. g_cameraPose = pose;
  353. g_cameraPoseValid = true;
  354. ReleaseSRWLockExclusive(&g_cameraPoseLock);
  355. g_forward = pose.forward;
  356. g_forwardValid.store(true, std::memory_order_release);
  357. }
  358. /** Latches one teleport request if the bound key went down this frame. */
  359. void poll_request() noexcept {
  360. end_press();
  361. expire_request();
  362. const client::movement::Settings settings = client::movement::get();
  363. const bool usable = settings.enabled && settings.virtualKey != client::movement::kNoKey;
  364. g_active.store(usable, std::memory_order_relaxed);
  365. if (!usable) {
  366. g_keyDown.store(false, std::memory_order_relaxed);
  367. return;
  368. }
  369. // An open interface owns the keyboard, so the key that binds the teleport must not fire it.
  370. if (core::ui::runtime::snapshot().visible) {
  371. g_keyDown.store(false, std::memory_order_relaxed);
  372. return;
  373. }
  374. const bool down = client::input::game_focused()
  375. && (GetAsyncKeyState(static_cast<int>(settings.virtualKey)) & 0x8000) != 0;
  376. if (down && !g_keyDown.exchange(down, std::memory_order_relaxed)) {
  377. g_requestAge.store(0, std::memory_order_relaxed);
  378. g_requested.store(true, std::memory_order_release);
  379. return;
  380. }
  381. g_keyDown.store(down, std::memory_order_relaxed);
  382. }
  383. /** Moves the local player if a request is pending and this component owns them. */
  384. void apply_pending(void* component) noexcept {
  385. if (!g_active.load(std::memory_order_relaxed) || component == nullptr
  386. || g_controlledHandle == nullptr) {
  387. return;
  388. }
  389. const bool requested = g_requested.load(std::memory_order_acquire);
  390. // The ownership test runs per component, so it is paid only while a request is open or until
  391. // the player's component is known. Once it is known, an ordinary tick costs two atomic reads.
  392. if (!requested && g_playerComponent.load(std::memory_order_relaxed) != nullptr) {
  393. return;
  394. }
  395. if (!owns_player(static_cast<std::byte*>(component))) {
  396. return;
  397. }
  398. std::byte* const physics = static_cast<std::byte*>(component);
  399. g_playerComponent.store(physics, std::memory_order_relaxed);
  400. if (!requested || !g_forwardValid.load(std::memory_order_acquire)) {
  401. return;
  402. }
  403. g_requested.store(false, std::memory_order_release);
  404. (void)perform_move(physics);
  405. }
  406. /** Runs the move for a request no physics tick collected. */
  407. void force_pending() noexcept {
  408. if (!g_requested.load(std::memory_order_acquire)
  409. || !g_forwardValid.load(std::memory_order_acquire)
  410. || g_requestAge.load(std::memory_order_relaxed) < kForceAfterFrames) {
  411. return;
  412. }
  413. std::byte* const physics = g_playerComponent.load(std::memory_order_relaxed);
  414. // The cached pointer outlives a destination change, so it is proved again before use.
  415. if (physics == nullptr || g_controlledHandle == nullptr || !owns_player(physics)) {
  416. return;
  417. }
  418. g_requested.store(false, std::memory_order_release);
  419. if (!perform_move(physics)) {
  420. return;
  421. }
  422. invoke_sync(physics);
  423. core::log::write(
  424. core::log::Channel::client, core::log::Level::info, "ev=teleport stage=force result=ok");
  425. }
  426. /** Reports the physics component the local player was last seen driving. */
  427. void* local_player_component() noexcept {
  428. return g_playerComponent.load(std::memory_order_relaxed);
  429. }
  430. /** @param component Candidate physics component. @return True when the local player drives it. */
  431. bool owns_local_player(void* component) noexcept {
  432. return component != nullptr && g_controlledHandle != nullptr
  433. && owns_player(static_cast<std::byte*>(component));
  434. }
  435. /** Reports whether the native controlled-object accessor has published a local player. */
  436. bool controlled_player_present() noexcept {
  437. if (g_controlledHandle == nullptr) {
  438. return false;
  439. }
  440. std::uint32_t controlled = kInvalidHandle;
  441. g_controlledHandle(&controlled);
  442. return controlled != kInvalidHandle;
  443. }
  444. /** Reads the world position of the body a physics component drives. */
  445. bool read_position(void* component, Vector& position) noexcept {
  446. if (component == nullptr) {
  447. return false;
  448. }
  449. std::byte* const body = body_of(static_cast<std::byte*>(component));
  450. return body != nullptr && read_at(body + kBodyPositionX, position);
  451. }
  452. /** Writes the world position of the body a physics component drives. */
  453. bool write_position(void* component, const Vector& position) noexcept {
  454. if (component == nullptr) {
  455. return false;
  456. }
  457. std::byte* const body = body_of(static_cast<std::byte*>(component));
  458. return body != nullptr && write_vector(body + kBodyPositionX, position);
  459. }
  460. /** Reads the linear velocity of the body a physics component drives. */
  461. bool read_velocity(void* component, Vector& velocity) noexcept {
  462. if (component == nullptr) {
  463. return false;
  464. }
  465. std::byte* const body = body_of(static_cast<std::byte*>(component));
  466. return body != nullptr && read_at(body + kBodyVelocityX, velocity);
  467. }
  468. /** Writes the linear velocity of the body a physics component drives. */
  469. bool write_velocity(void* component, const Vector& velocity) noexcept {
  470. if (component == nullptr) {
  471. return false;
  472. }
  473. std::byte* const body = body_of(static_cast<std::byte*>(component));
  474. return body != nullptr && write_vector(body + kBodyVelocityX, velocity);
  475. }
  476. /** Reports the camera forward vector published this frame. */
  477. bool camera_forward(Vector& forward) noexcept {
  478. if (!g_forwardValid.load(std::memory_order_acquire)) {
  479. return false;
  480. }
  481. forward = g_forward;
  482. return true;
  483. }
  484. /** Copies the last complete pose published by the camera-frame hook. */
  485. bool camera_pose(CameraPose& pose) noexcept {
  486. AcquireSRWLockShared(&g_cameraPoseLock);
  487. const bool valid = g_cameraPoseValid;
  488. pose = valid ? g_cameraPose : CameraPose{};
  489. ReleaseSRWLockShared(&g_cameraPoseLock);
  490. return valid;
  491. }
  492. } // namespace sunrise::client::hooks::teleport