diff --git a/libultraship b/libultraship index 31584f73f0f..c7c649f9e75 160000 --- a/libultraship +++ b/libultraship @@ -1 +1 @@ -Subproject commit 31584f73f0f6fd1a768a6abe8f44582dfcacf8ba +Subproject commit c7c649f9e755faf071a4585adf4ac650e6cbb0f1 diff --git a/run-vr-benchmark-suite.ps1 b/run-vr-benchmark-suite.ps1 new file mode 100644 index 00000000000..ad66ed6616e --- /dev/null +++ b/run-vr-benchmark-suite.ps1 @@ -0,0 +1,156 @@ +param( + [ValidateRange(1, 10)] + [int]$RunsPerPreset = 3, + [string]$ReleaseDirectory = (Join-Path $PSScriptRoot 'x64\Release') +) + +$ErrorActionPreference = 'Stop' +$releaseDirectory = (Resolve-Path -LiteralPath $ReleaseDirectory).Path +$executable = Join-Path $releaseDirectory 'soh.exe' +$resultsDirectory = Join-Path $releaseDirectory 'benchmarks' + +if (-not (Test-Path -LiteralPath $executable -PathType Leaf)) { + throw "Shipwright executable not found: $executable" +} + +New-Item -ItemType Directory -Path $resultsDirectory -Force | Out-Null + +function Get-Median([double[]]$Values) { + if ($Values.Count -eq 0) { return 0.0 } + $sorted = @($Values | Sort-Object) + $middle = [math]::Floor($sorted.Count / 2) + if (($sorted.Count % 2) -eq 1) { return [double]$sorted[$middle] } + return ([double]$sorted[$middle - 1] + [double]$sorted[$middle]) / 2.0 +} + +$records = [System.Collections.Generic.List[object]]::new() +$suiteStarted = Get-Date + +Write-Host '' +Write-Host 'VR BENCHMARK SUITE' +Write-Host "Runs: $RunsPerPreset baseline + $RunsPerPreset optimized" +Write-Host 'Keep the headset worn and focused until all runs finish.' +Write-Host '' + +foreach ($preset in @('baseline', 'optimized')) { + for ($run = 1; $run -le $RunsPerPreset; $run++) { + Write-Host "[$preset $run/$RunsPerPreset] Starting Hyrule Field introduction..." + $started = Get-Date + $process = Start-Process -FilePath $executable ` + -ArgumentList '--vr-benchmark', '--benchmark-name', $preset ` + -WorkingDirectory $releaseDirectory ` + -Wait -PassThru + + $summaryFile = Get-ChildItem -LiteralPath $resultsDirectory -Filter "*_${preset}-summary.json" | + Where-Object { $_.LastWriteTime -ge $started } | + Sort-Object LastWriteTime -Descending | + Select-Object -First 1 + if ($null -eq $summaryFile) { + throw "Benchmark $preset run $run exited with code $($process.ExitCode) without producing a new summary." + } + if ($process.ExitCode -ne 0) { + Write-Warning "Benchmark $preset run $run produced a complete summary but exited with code $($process.ExitCode); keeping the result." + } + + $summary = Get-Content -LiteralPath $summaryFile.FullName -Raw | ConvertFrom-Json + $records.Add([pscustomobject]@{ + preset = $preset + run = $run + file = $summaryFile.Name + cadence_valid = [bool]$summary.cadence_valid + target_rate_frame_percent = [double]$summary.target_rate_frame_percent + average_submitted_fps = [double]$summary.average_submitted_fps + one_percent_low_submitted_fps = [double]$summary.one_percent_low_submitted_fps + frame_interval_p99_ms = [double]$summary.frame_interval_p99_ms + xr_wait_average_ms = [double]$summary.xr_wait_average_ms + xr_wait_p99_ms = [double]$summary.xr_wait_p99_ms + cpu_active_average_ms = [double]$summary.cpu_active_average_ms + cpu_active_p99_ms = [double]$summary.cpu_active_p99_ms + gpu_eyes_average_ms = [double]$summary.gpu_eyes_average_ms + gpu_eyes_p99_ms = [double]$summary.gpu_eyes_p99_ms + gpu_total_average_ms = [double]$summary.gpu_total_average_ms + gpu_total_p99_ms = [double]$summary.gpu_total_p99_ms + cpu_total_average_ms = [double]$summary.cpu_total_average_ms + cpu_total_p99_ms = [double]$summary.cpu_total_p99_ms + cpu_eyes_average_ms = [double]$summary.cpu_eyes_average_ms + cpu_eyes_p99_ms = [double]$summary.cpu_eyes_p99_ms + }) + Write-Host ("[{0} {1}/{2}] Complete: {3:N2} FPS, eye CPU {4:N2} ms, cadence {5}" -f ` + $preset, $run, $RunsPerPreset, $summary.average_submitted_fps, $summary.cpu_eyes_average_ms, ` + $(if ($summary.cadence_valid) { 'VALID' } else { 'INVALID' })) + } +} + +$aggregates = foreach ($preset in @('baseline', 'optimized')) { + $set = @($records | Where-Object preset -eq $preset) + [pscustomobject]@{ + preset = $preset + runs = $set.Count + valid_cadence_runs = @($set | Where-Object cadence_valid).Count + median_target_rate_frame_percent = Get-Median @($set.target_rate_frame_percent) + median_submitted_fps = Get-Median @($set.average_submitted_fps) + median_one_percent_low_fps = Get-Median @($set.one_percent_low_submitted_fps) + median_frame_interval_p99_ms = Get-Median @($set.frame_interval_p99_ms) + median_xr_wait_average_ms = Get-Median @($set.xr_wait_average_ms) + median_xr_wait_p99_ms = Get-Median @($set.xr_wait_p99_ms) + median_cpu_active_average_ms = Get-Median @($set.cpu_active_average_ms) + median_cpu_active_p99_ms = Get-Median @($set.cpu_active_p99_ms) + median_gpu_eyes_average_ms = Get-Median @($set.gpu_eyes_average_ms) + median_gpu_eyes_p99_ms = Get-Median @($set.gpu_eyes_p99_ms) + median_gpu_total_average_ms = Get-Median @($set.gpu_total_average_ms) + median_gpu_total_p99_ms = Get-Median @($set.gpu_total_p99_ms) + median_cpu_total_average_ms = Get-Median @($set.cpu_total_average_ms) + median_cpu_total_p99_ms = Get-Median @($set.cpu_total_p99_ms) + median_cpu_eyes_average_ms = Get-Median @($set.cpu_eyes_average_ms) + median_cpu_eyes_p99_ms = Get-Median @($set.cpu_eyes_p99_ms) + } +} + +$baseline = $aggregates | Where-Object preset -eq 'baseline' +$optimized = $aggregates | Where-Object preset -eq 'optimized' +function Percent-Change([double]$Before, [double]$After) { + if ([math]::Abs($Before) -lt 0.000001) { return 0.0 } + return (($After - $Before) / $Before) * 100.0 +} + +$comparison = [pscustomobject]@{ + submitted_fps_percent = Percent-Change $baseline.median_submitted_fps $optimized.median_submitted_fps + one_percent_low_fps_percent = Percent-Change $baseline.median_one_percent_low_fps $optimized.median_one_percent_low_fps + frame_interval_p99_percent = Percent-Change $baseline.median_frame_interval_p99_ms $optimized.median_frame_interval_p99_ms + cpu_active_average_percent = Percent-Change $baseline.median_cpu_active_average_ms $optimized.median_cpu_active_average_ms + cpu_active_p99_percent = Percent-Change $baseline.median_cpu_active_p99_ms $optimized.median_cpu_active_p99_ms + gpu_eyes_average_percent = Percent-Change $baseline.median_gpu_eyes_average_ms $optimized.median_gpu_eyes_average_ms + gpu_total_average_percent = Percent-Change $baseline.median_gpu_total_average_ms $optimized.median_gpu_total_average_ms + cpu_total_average_percent = Percent-Change $baseline.median_cpu_total_average_ms $optimized.median_cpu_total_average_ms + cpu_total_p99_percent = Percent-Change $baseline.median_cpu_total_p99_ms $optimized.median_cpu_total_p99_ms + cpu_eyes_average_percent = Percent-Change $baseline.median_cpu_eyes_average_ms $optimized.median_cpu_eyes_average_ms + cpu_eyes_p99_percent = Percent-Change $baseline.median_cpu_eyes_p99_ms $optimized.median_cpu_eyes_p99_ms +} + +$suite = [pscustomobject]@{ + started = $suiteStarted.ToString('o') + completed = (Get-Date).ToString('o') + runs_per_preset = $RunsPerPreset + runs = $records + medians = $aggregates + optimized_change_percent = $comparison +} +$timestamp = Get-Date -Format 'yyyyMMdd-HHmmss' +$suiteFile = Join-Path $resultsDirectory "suite-$timestamp-summary.json" +$suite | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath $suiteFile -Encoding UTF8 + +Write-Host '' +Write-Host 'MEDIAN RESULTS' +$aggregates | Format-Table preset, valid_cadence_runs, median_submitted_fps, median_one_percent_low_fps, ` + median_cpu_eyes_average_ms, median_cpu_eyes_p99_ms -AutoSize +Write-Host "Suite summary: $suiteFile" + +if ($aggregates.valid_cadence_runs -contains 0) { + [System.Media.SystemSounds]::Exclamation.Play() + Write-Warning 'At least one preset had no cadence-valid runs. Inspect target-rate percentages before comparing.' +} else { + 1..3 | ForEach-Object { + [System.Media.SystemSounds]::Asterisk.Play() + Start-Sleep -Milliseconds 250 + } +} diff --git a/soh/include/functions.h b/soh/include/functions.h index bd4f3795f22..04b158d448a 100644 --- a/soh/include/functions.h +++ b/soh/include/functions.h @@ -1156,6 +1156,7 @@ s32 Player_OverrideLimbDrawGameplayCommon(PlayState* play, s32 limbIndex, Gfx** s32 Player_OverrideLimbDrawGameplayDefault(PlayState* play, s32 limbIndex, Gfx** dList, Vec3f* pos, Vec3s* rot, void* data); s32 Player_OverrideLimbDrawGameplayFirstPerson(PlayState* play, s32 limbIndex, Gfx** dList, Vec3f* pos, Vec3s* rot, void* data); s32 Player_OverrideLimbDrawGameplayVRFirstPerson(PlayState* play, s32 limbIndex, Gfx** dList, Vec3f* pos, Vec3s* rot, void* data); +s32 Anchor_ApplyRemoteVrLimbPose(Player* player, s32 limbIndex); s32 Player_OverrideLimbDrawGameplayCrawling(PlayState* play, s32 limbIndex, Gfx** dList, Vec3f* pos, Vec3s* rot, void* data); u8 func_80090480(PlayState* play, ColliderQuad* collider, WeaponInfo* weaponDim, Vec3f* newTip, Vec3f* newBase); diff --git a/soh/soh/CrashHandlerExt.cpp b/soh/soh/CrashHandlerExt.cpp index b5fcd0f618f..4c2d36484e1 100644 --- a/soh/soh/CrashHandlerExt.cpp +++ b/soh/soh/CrashHandlerExt.cpp @@ -6,6 +6,9 @@ #include #include "soh/ActorDB.h" #include +#ifdef _WIN32 +#include +#endif #define WRITE_VAR_LINE(buff, len, varName, varValue) \ append_str(buff, len, varName); \ @@ -63,7 +66,7 @@ static void CrashHandler_WriteActorData(char* buffer, size_t* pos) { } } -extern "C" void CrashHandler_PrintSohData(char* buffer, size_t* pos) { +static void CrashHandler_PrintSohDataImpl(char* buffer, size_t* pos) { char intCharBuffer[16]; append_line(buffer, pos, "Build Information:"); WRITE_VAR_LINE(buffer, pos, " Game Version: ", (const char*)gBuildVersion); @@ -90,3 +93,17 @@ extern "C" void CrashHandler_PrintSohData(char* buffer, size_t* pos) { } } } + +extern "C" void CrashHandler_PrintSohData(char* buffer, size_t* pos) { +#ifdef _WIN32 + // A crash may leave gPlayState or its actor lists invalid. Never allow + // optional diagnostic collection to replace the original exception. + __try { + CrashHandler_PrintSohDataImpl(buffer, pos); + } __except (EXCEPTION_EXECUTE_HANDLER) { + append_line(buffer, pos, "Shipwright runtime data unavailable (invalid state during crash)."); + } +#else + CrashHandler_PrintSohDataImpl(buffer, pos); +#endif +} diff --git a/soh/soh/Enhancements/Items/ArrowCycle.cpp b/soh/soh/Enhancements/Items/ArrowCycle.cpp index 877de93b48c..d43166dd966 100644 --- a/soh/soh/Enhancements/Items/ArrowCycle.cpp +++ b/soh/soh/Enhancements/Items/ArrowCycle.cpp @@ -1,4 +1,5 @@ #include "soh/Enhancements/game-interactor/GameInteractor_Hooks.h" +#include "soh/Enhancements/vr-combat/VrCombat.h" #include "soh/ShipInit.hpp" extern "C" { @@ -17,6 +18,7 @@ extern PlayState* gPlayState; #define CVAR_ARROW_CYCLE_NAME CVAR_ENHANCEMENT("BowArrowCycle") #define CVAR_ARROW_CYCLE_DEFAULT 0 #define CVAR_ARROW_CYCLE_VALUE CVarGetInteger(CVAR_ARROW_CYCLE_NAME, CVAR_ARROW_CYCLE_DEFAULT) +#define CVAR_VR_ARROW_CYCLE_VALUE CVarGetInteger("gVrBowTriggerArrowCycle", 0) static const s16 sMagicArrowCosts[] = { 4, 4, 8 }; @@ -27,6 +29,8 @@ static const PlayerItemAction sArrowCycleOrder[] = { PLAYER_IA_BOW_LIGHT, }; +static int32_t sPendingMountedIconItem = ITEM_NONE; + static bool IsHoldingBow(Player* player) { return player->heldItemAction >= PLAYER_IA_BOW && player->heldItemAction <= PLAYER_IA_BOW_LIGHT; } @@ -80,12 +84,62 @@ static ArrowType GetArrowTypeForArrow(s8 itemAction) { } } +static PlayerItemAction GetItemActionForArrow(const EnArrow* arrow, const Player* player) { + switch (arrow->actor.params) { + case ARROW_FIRE: + return PLAYER_IA_BOW_FIRE; + case ARROW_ICE: + return PLAYER_IA_BOW_ICE; + case ARROW_LIGHT: + return PLAYER_IA_BOW_LIGHT; + default: + return (PlayerItemAction)player->heldItemAction; + } +} + +static void ChangeMountedArrowType(EnArrow* arrow, PlayerItemAction itemAction) { + // Mounted Link's bow state only accepts PLAYER_IA_BOW. Changing itemAction or re-running + // EnArrow_Init makes the horse action release the parented arrow and can leave Link stuck + // aiming. Change only the live projectile's elemental payload; EnArrow_Update will create + // the corresponding elemental child on its next update. + if (arrow->actor.child != NULL) { + Actor_Kill(arrow->actor.child); + arrow->actor.child = NULL; + } + + static const u32 damageFlags[] = { 0x00000020, 0x00000800, 0x00001000, 0x00002000 }; + const int index = itemAction - PLAYER_IA_BOW; + arrow->actor.params = itemAction == PLAYER_IA_BOW ? ARROW_NORMAL_HORSE : GetArrowTypeForArrow(itemAction); + arrow->collider.info.toucher.dmgFlags = damageFlags[index]; + + // Epona must keep ITEM_BOW in the temporary B slot, but the HUD texture can still show the + // selected elemental arrow. Interface_LoadItemIcon1 resolves the texture synchronously from + // buttonItems[0], so expose the display item only for that load. + sPendingMountedIconItem = GetBowItemForArrow(itemAction); +} + +static void FlushMountedBowIcon() { + if (sPendingMountedIconItem == ITEM_NONE || gPlayState == nullptr) { + return; + } + + // Run after the ordinary interface update, which restores Epona's temporary B icon during + // the frame. Load only the alternate texture, then immediately restore the required B item. + const uint8_t horseBowItem = gSaveContext.equips.buttonItems[0]; + gSaveContext.equips.buttonItems[0] = sPendingMountedIconItem; + Interface_LoadItemIcon1(gPlayState, 0); + gSaveContext.equips.buttonItems[0] = horseBowItem; + sPendingMountedIconItem = ITEM_NONE; +} + static bool CanCycleArrows() { Player* player = GET_PLAYER(gPlayState); + const bool vrPhysicalCycle = CVAR_VR_ARROW_CYCLE_VALUE && VR_IsInitialized() && VrArchery_Covers(player); return (LINK_IS_ADULT || CVarGetInteger(CVAR_CHEAT("TimelessEquipment"), 0)) && !gSaveContext.minigameState && - gPlayState->sceneNum != SCENE_SHOOTING_GALLERY && !(player->stateFlags1 & PLAYER_STATE1_ON_HORSE) && - player->rideActor == NULL && INV_CONTENT(SLOT_BOW) == ITEM_BOW && + gPlayState->sceneNum != SCENE_SHOOTING_GALLERY && + (!(player->stateFlags1 & PLAYER_STATE1_ON_HORSE) || vrPhysicalCycle) && + (player->rideActor == NULL || vrPhysicalCycle) && INV_CONTENT(SLOT_BOW) == ITEM_BOW && (INV_CONTENT(ITEM_ARROW_FIRE) == ITEM_ARROW_FIRE || INV_CONTENT(ITEM_ARROW_ICE) == ITEM_ARROW_ICE || INV_CONTENT(ITEM_ARROW_LIGHT) == ITEM_ARROW_LIGHT); } @@ -136,7 +190,7 @@ static void UpdateEquippedBow(PlayState* play, s8 arrowType) { } } -bool ArrowCycleMain() { +extern "C" bool ArrowCycleMain(void) { if (gPlayState == nullptr || !CanCycleArrows()) { return false; } @@ -152,7 +206,15 @@ bool ArrowCycleMain() { // reset magic state to IDLE before cycling to prevent error sound gSaveContext.magicState = MAGIC_STATE_IDLE; - s8 nextArrow = GetNextArrowType(player->heldItemAction); + EnArrow* enArrow = (EnArrow*)player->heldActor; + const bool mounted = (player->stateFlags1 & PLAYER_STATE1_ON_HORSE) != 0; + s8 nextArrow = GetNextArrowType(mounted ? GetItemActionForArrow(enArrow, player) : player->heldItemAction); + + if (mounted) { + ChangeMountedArrowType(enArrow, (PlayerItemAction)nextArrow); + return true; + } + player->heldItemAction = nextArrow; player->itemAction = nextArrow; Actor* arrow = player->heldActor; @@ -170,11 +232,12 @@ bool ArrowCycleMain() { } void RegisterArrowCycle() { + COND_HOOK(OnPlayDrawEnd, CVAR_VR_ARROW_CYCLE_VALUE, FlushMountedBowIcon); // suppress shield input when R is held while aiming to allow arrow cycling - COND_VB_SHOULD(VB_EXECUTE_PLAYER_ACTION_FUNC, CVAR_ARROW_CYCLE_VALUE, { + COND_VB_SHOULD(VB_EXECUTE_PLAYER_ACTION_FUNC, CVAR_ARROW_CYCLE_VALUE || CVAR_VR_ARROW_CYCLE_VALUE, { Player* player = (Player*)va_arg(args, void*); Input* input = (Input*)va_arg(args, void*); - if (IsAimingBow(player) && CHECK_BTN_ANY(input->press.button, BTN_R)) { + if (CVAR_ARROW_CYCLE_VALUE && IsAimingBow(player) && CHECK_BTN_ANY(input->press.button, BTN_R)) { if (ArrowCycleMain()) { input->cur.button &= ~BTN_R; input->press.button &= ~BTN_R; @@ -183,7 +246,7 @@ void RegisterArrowCycle() { }); // don't consume magic on draw, but check if we have enough to fire - COND_VB_SHOULD(VB_PLAYER_ARROW_MAGIC_CONSUMPTION, CVAR_ARROW_CYCLE_VALUE, { + COND_VB_SHOULD(VB_PLAYER_ARROW_MAGIC_CONSUMPTION, CVAR_ARROW_CYCLE_VALUE || CVAR_VR_ARROW_CYCLE_VALUE, { Player* player = va_arg(args, Player*); int32_t magicArrowType = va_arg(args, int32_t); int32_t* arrowType = va_arg(args, int32_t*); @@ -195,7 +258,7 @@ void RegisterArrowCycle() { } }); - COND_VB_SHOULD(VB_EN_ARROW_MAGIC_CONSUMPTION, CVAR_ARROW_CYCLE_VALUE, { + COND_VB_SHOULD(VB_EN_ARROW_MAGIC_CONSUMPTION, CVAR_ARROW_CYCLE_VALUE || CVAR_VR_ARROW_CYCLE_VALUE, { EnArrow* arrow = va_arg(args, EnArrow*); if (arrow->actor.params < ARROW_FIRE || arrow->actor.params > ARROW_LIGHT) { @@ -207,4 +270,4 @@ void RegisterArrowCycle() { }); } -static RegisterShipInitFunc initFunc(RegisterArrowCycle, { CVAR_ARROW_CYCLE_NAME }); +static RegisterShipInitFunc initFunc(RegisterArrowCycle, { CVAR_ARROW_CYCLE_NAME, "gVrBowTriggerArrowCycle" }); diff --git a/soh/soh/Enhancements/vr-combat/VrArchery.cpp b/soh/soh/Enhancements/vr-combat/VrArchery.cpp index 0b19a542506..30facb7ca2c 100644 --- a/soh/soh/Enhancements/vr-combat/VrArchery.cpp +++ b/soh/soh/Enhancements/vr-combat/VrArchery.cpp @@ -3,7 +3,10 @@ extern "C" { #include "macros.h" #include "functions.h" #include "objects/gameplay_keep/gameplay_keep.h" +#include "overlays/actors/ovl_En_Arrow/z_en_arrow.h" extern PlayState* gPlayState; +extern SaveContext gSaveContext; +bool ArrowCycleMain(void); } #include "VrCombat.h" @@ -30,14 +33,15 @@ extern PlayState* gPlayState; // hand-to-pouch gap, shot from the string hand through the pouch); both read their geometry off // the model they render, through the live hand draw matrix. // -// Deliberate fallbacks: shooting galleries, bombchu bowling and horseback keep their own -// schemes (Covers is false there), and gVrPhysArchery=0 restores the previous behavior where -// the weapon hand's trigger mirrors the item button. +// Deliberate fallbacks: gallery transitions, bombchu bowling and horseback keep their own +// schemes. Live shooting-gallery rounds use this physical interaction with their forced B-slot +// weapon, and gVrPhysArchery=0 restores the previous trigger-to-item-button behavior. namespace { bool sNocked = false; bool sPinchPrev = true; // require a fresh pinch after entry/reset +bool sCycleTriggerPrev = true; // same: entering bow mode with it held must not cycle float sDrawM = 0.0f; // current string-hand draw distance, meters // The firing release is processed by the vanilla pad path a frame AFTER the tick clears the @@ -47,6 +51,12 @@ float sDrawM = 0.0f; // current string-hand draw distance, meters float sAimLatch[6] = {}; bool sAimLatchLive = false; // a nock has produced a valid latch this draw cycle int sAimLatchTicks = 0; // >0: keep serving the latch after the nock ended +Vec3f sAimDotTarget = {}; +bool sAimDotTargetLive = false; + +constexpr int kAimDotMaxGfx = 20; +Gfx sAimDotDl[kAimDotMaxGfx]; +Vtx sAimDotVtx[4]; int StringHand() { return CVarGetInteger("gVrLeftHanded", 0) ? VR_HAND_LEFT : VR_HAND_RIGHT; @@ -135,7 +145,29 @@ bool HoldsBow(Player* player) { } bool HoldsBowNow() { - return gPlayState != NULL && HoldsBow(GET_PLAYER(gPlayState)); + if (gPlayState == NULL) { + return false; + } + // Vanilla starts both shooting galleries through ITEM_BOW. Child Link still renders and + // fires the slingshot, so the gallery's internal item action cannot identify its physical + // VR geometry: doing so puts the bow's braced nock behind the visible slingshot. Match the + // weapon model chosen by the game instead. + if (gPlayState->shootingGalleryStatus > 0) { + return LINK_IS_ADULT; + } + return HoldsBow(GET_PLAYER(gPlayState)); +} + +bool ShootingGalleryActive() { + return gPlayState != NULL && gPlayState->shootingGalleryStatus > 0; +} + +bool ShootingGalleryWeaponReady() { + if (!ShootingGalleryActive()) { + return false; + } + const uint8_t item = gSaveContext.equips.buttonItems[0]; + return item == ITEM_SLINGSHOT || item == ITEM_BOW; } // Rodrigues rotation of v about unit axis k by the angle with cosine c and sine s. @@ -226,6 +258,60 @@ bool AlignBowMatrix(float m[4][4]) { m[c][i] = cols[c][i]; } } + Player* player = gPlayState != NULL ? GET_PLAYER(gPlayState) : NULL; + if (player != NULL && (player->stateFlags1 & PLAYER_STATE1_ON_HORSE)) { + // Mounted physical bow is POSITION-ONLY after nocking. The previous minimal rotation + // still began with the controller's axes, so conflicting wrist orientations could swing + // the whole shaft sideways. Rebuild all three axes from bow-hand position, string-hand + // position and world up; no controller quaternion survives this block. + const float xLen = std::sqrt(m[0][0] * m[0][0] + m[0][1] * m[0][1] + m[0][2] * m[0][2]); + const float yLen = std::sqrt(m[1][0] * m[1][0] + m[1][1] * m[1][1] + m[1][2] * m[1][2]); + const float zLen = std::sqrt(m[2][0] * m[2][0] + m[2][1] * m[2][1] + m[2][2] * m[2][2]); + float stringPos[3], stringRot[4]; + if (xLen > 1e-6f && yLen > 1e-6f && zLen > 1e-6f && + VR_GetHandPose(StringHand(), stringPos, stringRot)) { + float x[3] = { 0.0f, 1.0f, 0.0f }; + float y[3] = {}; + for (int iter = 0; iter < 3; iter++) { + float rest[3] = { m[3][0] + x[0] * xLen * kBowNockX, + m[3][1] + x[1] * xLen * kBowNockX, + m[3][2] + x[2] * xLen * kBowNockX }; + float yNorm = 0.0f; + for (int i = 0; i < 3; i++) { + y[i] = rest[i] - stringPos[i]; + yNorm += y[i] * y[i]; + } + yNorm = std::sqrt(yNorm); + if (yNorm < 1e-4f) { + return false; + } + for (int i = 0; i < 3; i++) { + y[i] /= yNorm; + } + x[0] = -y[0] * y[1]; + x[1] = 1.0f - y[1] * y[1]; + x[2] = -y[2] * y[1]; + const float xNorm = std::sqrt(x[0] * x[0] + x[1] * x[1] + x[2] * x[2]); + if (xNorm < 1e-4f) { + return false; + } + for (int i = 0; i < 3; i++) { + x[i] /= xNorm; + } + } + float z[3] = { x[1] * y[2] - x[2] * y[1], x[2] * y[0] - x[0] * y[2], + x[0] * y[1] - x[1] * y[0] }; + const float oldCross[3] = { m[0][1] * m[1][2] - m[0][2] * m[1][1], + m[0][2] * m[1][0] - m[0][0] * m[1][2], + m[0][0] * m[1][1] - m[0][1] * m[1][0] }; + const float handedness = oldCross[0] * m[2][0] + oldCross[1] * m[2][1] + oldCross[2] * m[2][2]; + for (int i = 0; i < 3; i++) { + m[0][i] = x[i] * xLen; + m[1][i] = y[i] * yLen; + m[2][i] = z[i] * zLen * (handedness < 0.0f ? -1.0f : 1.0f); + } + } + } return true; } @@ -341,27 +427,33 @@ bool sBowFullFelt = false; // full-draw pulse already given this nock } // namespace extern "C" bool VrArchery_Covers(Player* player) { - if (!VrItemSelect_ModeActive() || !CVarGetInteger("gVrPhysArchery", 1) || player == NULL || - player->actor.category != ACTORCAT_PLAYER || gPlayState == NULL) { + const bool gallery = ShootingGalleryActive(); + const bool horseBow = player != NULL && (player->stateFlags1 & PLAYER_STATE1_ON_HORSE) && + VrItemSelect_HorseBowEnabled(); + if (!VR_IsInitialized() || (!VrItemSelect_ModeActive() && !gallery && !horseBow) || + !CVarGetInteger("gVrPhysArchery", 1) || player == NULL || player->actor.category != ACTORCAT_PLAYER || + gPlayState == NULL) { return false; } - if (!VrItemSelect_SelectionAllowed()) { + if (!gallery && !horseBow && !VrItemSelect_SelectionAllowed()) { return false; // scripted control, transitions, ocarina: no nock, no button mask } - if (gPlayState->shootingGalleryStatus != 0 || gPlayState->bombchuBowlingStatus != 0 || - (player->stateFlags1 & PLAYER_STATE1_ON_HORSE)) { - return false; // galleries, bowling and horseback keep their dedicated schemes + if (gPlayState->shootingGalleryStatus < 0 || gPlayState->bombchuBowlingStatus != 0) { + return false; // gallery transitions and bowling keep their dedicated schemes } - return (player->heldItemAction >= PLAYER_IA_BOW && player->heldItemAction <= PLAYER_IA_BOW_0E) || + return ShootingGalleryWeaponReady() || + (player->heldItemAction >= PLAYER_IA_BOW && player->heldItemAction <= PLAYER_IA_BOW_0E) || player->heldItemAction == PLAYER_IA_SLINGSHOT; } extern "C" void VrArchery_Reset(void) { sNocked = false; sPinchPrev = true; + sCycleTriggerPrev = true; sDrawM = 0.0f; sAimLatchLive = false; sAimLatchTicks = 0; + sAimDotTargetLive = false; sBowShotPower = 0.0f; sBowClick = 0; sBowFullFelt = false; @@ -376,14 +468,15 @@ extern "C" void VrArchery_Reset(void) { // broken. extern "C" linkage is load-bearing for the block-scope FrameInterpolation // declarations inside OPEN_DISPS (see VrItemSelect_Draw). extern "C" void VrArchery_DrawNockIcon(void) { + const bool gallery = ShootingGalleryWeaponReady(); if (gPlayState == NULL || !CVarGetInteger("gVrArcheryShowIcon", 0) || !CVarGetInteger("gVrPhysArchery", 1) || - !VrItemSelect_ModeActive() || sNocked) { + (!VrItemSelect_ModeActive() && !gallery) || sNocked) { return; } Player* player = GET_PLAYER(gPlayState); - if (player == NULL || + if (player == NULL || (!gallery && !((player->heldItemAction >= PLAYER_IA_BOW && player->heldItemAction <= PLAYER_IA_BOW_0E) || - player->heldItemAction == PLAYER_IA_SLINGSHOT)) { + player->heldItemAction == PLAYER_IA_SLINGSHOT))) { return; } float anchor[3]; @@ -421,19 +514,133 @@ extern "C" uint16_t VrArchery_ItemButtonMask(void) { if (!VrArchery_Covers(player)) { return 0; } + // The gallery owns a temporary B-button ammo counter and starts the forced weapon from B, + // regardless of where that item is equipped in the player's ordinary loadout. + if (ShootingGalleryActive()) { + return BTN_B; + } static const uint16_t kItemButtons[] = { BTN_B, BTN_CLEFT, BTN_CDOWN, BTN_CRIGHT, BTN_DUP, BTN_DDOWN, BTN_DLEFT, BTN_DRIGHT }; const int slot = player->heldItemButton; return (slot >= 0 && slot < (int)(sizeof(kItemButtons) / sizeof(kItemButtons[0]))) ? kItemButtons[slot] : 0; } +extern "C" bool VrArchery_GalleryOwnsWeapon(void) { + return gPlayState != NULL && ShootingGalleryActive() && VrArchery_Covers(GET_PLAYER(gPlayState)); +} + +// Optional world-space aim dot. It follows the exact physical string/pouch line used to place and +// launch the prepared projectile, and sits on the first world surface along that line. No flat-mode +// or classic-control path reaches this function because VrArchery_AimSegment requires a live VR nock. +extern "C" void VrArchery_DrawAimDot(void) { + if (gPlayState == NULL || !VR_IsInitialized() || !VR_GetFirstPerson() || VR_IsFlatScreen() || + !CVarGetInteger("gVrArcheryAimDot", 1) || !sNocked) { + return; + } + float ray[6]; + if (!VrArchery_AimSegment(ray)) { + return; + } + Vec3f start = { ray[0], ray[1], ray[2] }; + Vec3f end; + Vec3f hit = start; + CollisionPoly* poly = NULL; + s32 bgId = BGCHECK_SCENE; + bool foundHit = false; + if (HoldsBowNow() && CVarGetInteger("gVrBowDrawPower", 1)) { + // Match EnArrow's partial-draw flight instead of promising a straight-line hit. This is + // especially important on Epona, where the player's practical draw was often ~50-60%. + float norm = BowFullDrawM() > 0.01f ? sDrawM / BowFullDrawM() : 1.0f; + norm = norm > 1.0f ? 1.0f : norm; + Player* player = GET_PLAYER(gPlayState); + const float power = (player != NULL && (player->stateFlags1 & PLAYER_STATE1_ON_HORSE)) + ? 1.0f + : 0.3f + 0.7f * norm; + const float speed = 150.0f * power; + const float gravity = power < 0.99f ? -(1.0f - power) / 0.7f : 0.0f; + Vec3f pos = start; + Vec3f velocity = { ray[3] * speed, ray[4] * speed, ray[5] * speed }; + const int life = 12 + (power < 0.99f ? (int)(12.0f * ((1.0f - power) / 0.7f)) : 0); + for (int frame = 0; frame < life; frame++) { + // EnArrow applies its normal -0.4 gravity once its 12-frame full-power lifetime + // falls below 7.2. Partial shots retain their stronger release gravity instead. + const bool horseBow = player != NULL && (player->stateFlags1 & PLAYER_STATE1_ON_HORSE); + velocity.y += horseBow ? 0.0f : ((power < 0.99f) ? gravity : (frame >= 4 ? -0.4f : 0.0f)); + end = { pos.x + velocity.x, pos.y + velocity.y, pos.z + velocity.z }; + if (BgCheck_AnyLineTest3(&gPlayState->colCtx, &pos, &end, &hit, &poly, true, true, true, true, &bgId)) { + foundHit = true; + break; + } + pos = end; + } + if (!foundHit) { + hit = end; + } + } else { + end = { start.x + ray[3] * 4000.0f, start.y + ray[4] * 4000.0f, + start.z + ray[5] * 4000.0f }; + if (!BgCheck_AnyLineTest3(&gPlayState->colCtx, &start, &end, &hit, &poly, true, true, true, true, &bgId)) { + hit = end; + } + } + + const float distance = sqrtf(SQ(hit.x - start.x) + SQ(hit.y - start.y) + SQ(hit.z - start.z)); + sAimDotTarget = hit; + sAimDotTargetLive = true; + float ws = WorldScale(); + const float half = fmaxf(0.006f * ws, 0.00375f * distance); + const float scale = half / 16.0f; + const s16 p = 16; + const Vtx dot[4] = { + { { { 0, p, 0 }, 0, { 0, 0 }, { 255, 235, 70, 245 } } }, + { { { p, 0, 0 }, 0, { 0, 0 }, { 255, 235, 70, 245 } } }, + { { { -p, 0, 0 }, 0, { 0, 0 }, { 255, 235, 70, 245 } } }, + { { { 0, -p, 0 }, 0, { 0, 0 }, { 255, 235, 70, 245 } } }, + }; + for (int i = 0; i < 4; i++) { + sAimDotVtx[i] = dot[i]; + } + + FrameInterpolation_RecordOpenChild((const void*)sAimDotDl, 0); + Matrix_Translate(hit.x, hit.y, hit.z, MTXMODE_NEW); + Matrix_ReplaceRotation(&gPlayState->billboardMtxF); + Matrix_Scale(scale, scale, scale, MTXMODE_APPLY); + Mtx* dotMtx = MATRIX_NEWMTX(gPlayState->state.gfxCtx); + FrameInterpolation_RecordCloseChild(); + + Gfx* pDl = sAimDotDl; + gDPPipeSync(pDl++); + gDPSetCycleType(pDl++, G_CYC_1CYCLE); + gDPSetRenderMode(pDl++, G_RM_XLU_SURF, G_RM_XLU_SURF2); + gDPSetCombineMode(pDl++, G_CC_SHADE, G_CC_SHADE); + gSPTexture(pDl++, 0, 0, 0, G_TX_RENDERTILE, G_OFF); + gSPClearGeometryMode(pDl++, G_CULL_BOTH | G_LIGHTING | G_FOG | G_TEXTURE_GEN | G_TEXTURE_GEN_LINEAR | G_ZBUFFER); + gSPSetGeometryMode(pDl++, G_SHADE | G_SHADING_SMOOTH); + gSPMatrix(pDl++, dotMtx, G_MTX_MODELVIEW | G_MTX_LOAD | G_MTX_NOPUSH); + gSPVertex(pDl++, (uintptr_t)sAimDotVtx, 4, 0); + gSP2Triangles(pDl++, 0, 2, 1, 0, 1, 2, 3, 0); + gSPEndDisplayList(pDl++); + + OPEN_DISPS(gPlayState->state.gfxCtx); + gSPDisplayList(POLY_XLU_DISP++, sAimDotDl); + CLOSE_DISPS(gPlayState->state.gfxCtx); +} + // The string hand's pinch input loses its normal binding only when it is about to nock (near // the weapon) or currently drawn — a pinch elsewhere keeps whatever it is bound to. extern "C" bool VrArchery_PinchConsumed(int32_t vrHand, uint16_t vrBtnMask) { - if (gPlayState == NULL || vrHand != StringHand() || !(vrBtnMask & PinchMask()) || VrOcarina_InPlay()) { + if (gPlayState == NULL || VrOcarina_InPlay()) { return false; } - if (!VrArchery_Covers(GET_PLAYER(gPlayState))) { + Player* player = GET_PLAYER(gPlayState); + if (CVarGetInteger("gVrBowTriggerArrowCycle", 0) && vrHand == BowHand() && + (vrBtnMask & VR_BTN_TRIGGER) && HoldsBowNow() && VrArchery_Covers(player)) { + return true; + } + if (vrHand != StringHand() || !(vrBtnMask & PinchMask())) { + return false; + } + if (!VrArchery_Covers(player)) { return false; } return sNocked || NearBow(); @@ -571,14 +778,25 @@ extern "C" int32_t VrArchery_NockedArrowHand(void) { if (!sNocked || gPlayState == NULL || !HoldsBowNow() || !VrArchery_Covers(GET_PLAYER(gPlayState))) { return -1; } + // Horseback uses the same arrow-to-aligned-bow weld as on foot. AlignBowMatrix has already + // rebuilt the mounted bow frame from hand positions and world-up, so no controller rotation + // can leak through this weld. return BowHand(); } +extern "C" int32_t VrArchery_NockedArrowHandForActor(Actor* arrow) { + if (arrow == NULL || gPlayState == NULL) { + return -1; + } + Player* player = GET_PLAYER(gPlayState); + return player->heldActor == arrow && arrow->parent == &player->actor ? VrArchery_NockedArrowHand() : -1; +} + // Draw strength -> arrow power, the VR-bow convention: a full draw is the vanilla shot exactly; // a partial draw leaves slower and drops. Consumed once by EnArrow_Shoot at the vanilla release // that follows a firing bow release; 0 = not a physical bow shot, leave the shot vanilla. extern "C" float VrArchery_TakeBowShotPower(void) { - if (sBowShotPower <= 0.0f || sAimLatchTicks <= 0) { + if (sBowShotPower <= 0.0f) { sBowShotPower = 0.0f; return 0.0f; } @@ -587,6 +805,19 @@ extern "C" float VrArchery_TakeBowShotPower(void) { return p; } +extern "C" bool VrArchery_TakeReleasedAim(float* outPosDir6) { + if (outPosDir6 == NULL || !sAimLatchLive || sBowShotPower <= 0.0f) { + return false; + } + for (int i = 0; i < 6; i++) { + outPosDir6[i] = sAimLatch[i]; + } + // The launch path has its copy. It must not leak into a later vanilla projectile. + sAimLatchLive = false; + sAimLatchTicks = 0; + return true; +} + namespace { void ArcheryTick() { @@ -607,7 +838,7 @@ void ArcheryTick() { if (sAimLatchTicks > 0 && !sNocked) { sAimLatchTicks--; - if (sAimLatchTicks == 0) { + if (sAimLatchTicks == 0 && sBowShotPower <= 0.0f) { sAimLatchLive = false; } } @@ -617,6 +848,13 @@ void ArcheryTick() { sPinchPrev = pinch; const bool bow = HoldsBow(player); + const bool cycleHeld = bow && CVarGetInteger("gVrBowTriggerArrowCycle", 0) && + (VR_GetControllerButton(BowHand()) & VR_BTN_TRIGGER) != 0; + const bool cyclePressed = cycleHeld && !sCycleTriggerPrev; + sCycleTriggerPrev = cycleHeld; + if (cyclePressed && sNocked && ArrowCycleMain()) { + VR_TriggerHaptic(BowHand(), 0.45f, 0.0f, 25.0f); + } const float gap = CurrentDrawM(); if (gap >= 0.0f) { sDrawM = gap; @@ -682,12 +920,47 @@ void ArcheryTick() { // The nock mask drops with sNocked this tick; the vanilla button release fires the // prepared shot NEXT tick — the aim latch keeps serving the drawn pull line through // that window so the fallback ray cannot overwrite the direction. Thunk both hands. - sAimLatchTicks = 4; + // On foot the arrow detaches on the next update, but the horseback release animation + // can keep it parented for considerably longer. Preserve the exact dot/string line + // until that delayed horse arrow reaches EnArrow_Shoot; otherwise it falls back to the + // mounted animation pose and wrist orientation before velocity is calculated. + sAimLatchTicks = (player->stateFlags1 & PLAYER_STATE1_ON_HORSE) ? 30 : 4; if (bow) { // Power from draw: 30% at no draw up to the full vanilla shot at full draw. float norm = sDrawM / BowFullDrawM(); norm = norm > 1.0f ? 1.0f : norm; - sBowShotPower = CVarGetInteger("gVrBowDrawPower", 1) ? 0.3f + 0.7f * norm : 1.0f; + sBowShotPower = (player->stateFlags1 & PLAYER_STATE1_ON_HORSE) + ? 1.0f + : (CVarGetInteger("gVrBowDrawPower", 1) ? 0.3f + 0.7f * norm : 1.0f); + // The dot is what the player actually aimed at in the headset. On Epona, a trigger + // release can land between headset-rate poses and the 20 Hz game update; rebuilding + // from that update's hand sample occasionally produced a large sideways shot. Make + // the last displayed world-space dot authoritative for mounted straight-flight aim. + if ((player->stateFlags1 & PLAYER_STATE1_ON_HORSE) && sAimLatchLive && sAimDotTargetLive) { + const float dx = sAimDotTarget.x - sAimLatch[0]; + const float dy = sAimDotTarget.y - sAimLatch[1]; + const float dz = sAimDotTarget.z - sAimLatch[2]; + const float len = std::sqrt(dx * dx + dy * dy + dz * dz); + if (len > 1e-4f) { + sAimLatch[3] = dx / len; + sAimLatch[4] = dy / len; + sAimLatch[5] = dz / len; + } + } + // Commit the physical release to the prepared arrow itself. Mounted Link keeps the + // arrow parented through a longer animation, during which ordinary archery state can + // reset and the limb callback can rewrite its pose. Neither may alter this shot. + if (sAimLatchLive && player->heldActor != NULL && player->heldActor->id == ACTOR_EN_ARROW) { + EnArrow* arrow = (EnArrow*)player->heldActor; + arrow->vrPhysicalBowShot = true; + arrow->vrHorseBowShot = (player->stateFlags1 & PLAYER_STATE1_ON_HORSE) != 0; + arrow->vrBowPower = sBowShotPower; + arrow->vrBowAimOrigin = { sAimLatch[0], sAimLatch[1], sAimLatch[2] }; + arrow->vrBowAimDir = { sAimLatch[3], sAimLatch[4], sAimLatch[5] }; + // The actor owns both values now; do not leave a global release that a later + // unrelated arrow could consume after the mounted animation resets archery. + sBowShotPower = 0.0f; + } // The string slaps the bow: the bow hand takes the bigger kick. VR_TriggerHaptic(BowHand(), 0.6f + 0.4f * norm, 0.0f, 50.0f); VR_TriggerHaptic(StringHand(), 0.5f, 0.0f, 30.0f); @@ -707,6 +980,7 @@ void ArcheryTick() { void RegisterVrArchery() { COND_HOOK(OnPlayerUpdate, true, ArcheryTick); COND_HOOK(OnPlayDrawEnd, true, VrArchery_DrawNockIcon); + COND_HOOK(OnPlayDrawEnd, true, VrArchery_DrawAimDot); } static RegisterShipInitFunc initVrArchery(RegisterVrArchery); diff --git a/soh/soh/Enhancements/vr-combat/VrCarry.cpp b/soh/soh/Enhancements/vr-combat/VrCarry.cpp index ccbefd40dfa..25fa8d895a7 100644 --- a/soh/soh/Enhancements/vr-combat/VrCarry.cpp +++ b/soh/soh/Enhancements/vr-combat/VrCarry.cpp @@ -661,6 +661,17 @@ extern "C" void VrCarry_Tick(PlayState* play, Player* player) { } sDebug.gate = 0; + // Pulling a Bomb Flower replaces the rooted flower actor with a newly spawned carried body. + // Both actors are ACTOR_EN_BOMBF, and func_8002F5C4 transfers the player's parent/heldActor + // links to the new one. Keep the physical grab attached to that replacement instead of + // mistaking the actor swap for a vanilla release and abandoning hand-driven throwing. + if (sHeld != nullptr && sHeld->id == ACTOR_EN_BOMBF && player->heldActor != nullptr && + player->heldActor != sHeld && player->heldActor->id == ACTOR_EN_BOMBF && + player->heldActor->parent == &player->actor && (player->stateFlags1 & PLAYER_STATE1_CARRYING_ACTOR)) { + sHeld = player->heldActor; + sHeld->bgCheckFlags &= 0xFF00; + } + // Ours no longer (thrown by A/B, switched away, burst, exploded, scene change): forget it. if (sHeld != nullptr && (player->heldActor != sHeld || sHeld->parent != &player->actor || !(player->stateFlags1 & PLAYER_STATE1_CARRYING_ACTOR) || sHeld->update == nullptr)) { diff --git a/soh/soh/Enhancements/vr-combat/VrChest.cpp b/soh/soh/Enhancements/vr-combat/VrChest.cpp new file mode 100644 index 00000000000..78a068092a2 --- /dev/null +++ b/soh/soh/Enhancements/vr-combat/VrChest.cpp @@ -0,0 +1,751 @@ +extern "C" { +#include "z64.h" +#include "macros.h" +#include "functions.h" +#include "overlays/actors/ovl_En_Box/z_en_box.h" +extern PlayState* gPlayState; +void func_8083AE40(Player* player, s16 objectId); +} + +#include "VrCombat.h" +#include "soh/Enhancements/enhancementTypes.h" +#include "soh/Enhancements/game-interactor/GameInteractor.h" +#include "soh/Enhancements/game-interactor/GameInteractor_Hooks.h" +#include "soh/Enhancements/randomizer/draw.h" +#include "soh/OTRGlobals.h" +#include "soh/ShipInit.hpp" +#include +#include +#include +#include +#include + +// Two-handed physical treasure-chest lids. En_Box remains the authority for chest visibility, +// rewards and save flags; this module only owns the unopened lid and asks the normal player chest +// path to run after the physical motion reaches its end. +namespace { + +constexpr float kPi = 3.14159265358979323846f; +constexpr uint16_t kClosedJoint = 0x8000; +constexpr uint16_t kOpenJoint = 0x34A5; +constexpr float kPhysicalOpenRadians = 106.0f * (kPi / 180.0f); +// Once the player has clearly lifted the lid, releasing it completes the remaining travel. A +// lower balance point keeps the full gesture inside one comfortable shoulder/wrist motion. +constexpr float kCommitAngleRadians = 25.0f * (kPi / 180.0f); +constexpr float kFinishStep = 0.065f; + +struct ChestProfile { + float halfWidth; + float frontZ; + float hingeZ; + float lidY; + float lidTopY; + float hoverY; + float itemScale; + float grabReach; + float surfaceClearance; +}; + +struct ChestHandState { + EnBox* chest = nullptr; + uint32_t frame = 0; + uint32_t contactFrame = 0; + bool active = false; + bool latched = false; + uint8_t trackingMissFrames = 0; + float score = 1e30f; + float localX = 0.0f; + float localY = 0.0f; + float localZ = 0.0f; + float tangentY = 0.0f; + float tangentZ = 1.0f; + float contactAlong = 0.0f; +}; + +EnBox* sChest = nullptr; +EnBox* sOpenRequest = nullptr; +ChestHandState sHands[2]; +EnBox* sPrevHoverChest[2] = {}; +bool sGripNow[2] = {}; +uint32_t sInputFrame = UINT32_MAX; +float sStartHandAngle[2] = {}; +float sStartOpenFraction = 0.0f; +float sOpenFraction = 0.0f; +bool sOpening = false; +bool sOpenArmed = false; +bool sFinishing = false; +bool sRequestConsumed = false; +bool sSawAwardDraw = false; +bool sPreviewDone = false; +bool sAwardActive = false; +GetItemEntry sAwardEntry = GET_ITEM_NONE; +uint32_t sRevealFrame = 0; +float sFrameHandPos[2][3] = {}; +bool sFrameHandValid[2] = {}; + +struct LidMatrixRecord { + EnBox* chest = nullptr; + uint32_t frame = 0; + uint16_t joint = 0; + float m[16] = {}; +}; + +constexpr size_t kLidMatrixSlots = 32; +LidMatrixRecord sLidMatrices[kLidMatrixSlots]; + +bool IsSmall(const EnBox* chest) { + return chest->type == ENBOX_TYPE_SMALL || chest->type == ENBOX_TYPE_6 || + chest->type == ENBOX_TYPE_ROOM_CLEAR_SMALL || chest->type == ENBOX_TYPE_SWITCH_FLAG_FALL_SMALL; +} + +ChestProfile Profile(const EnBox* chest) { + // Small chests use the same model at half scale, so one calibrated large profile can be + // reduced exactly instead of maintaining age-dependent or scene-dependent dimensions. + if (IsSmall(chest)) { + return { 12.625f, -9.615f, 9.91f, 13.665f, 22.375f, 31.0f, 0.20f, 5.0f, 0.375f }; + } + // Exact object_box collision/model bounds in world units at the actor's 0.01 scale. The lid + // limb is a half-cylinder. Its real skeletal pivot is Y=27.33, Z=19.82 and its mesh + // extends 39.05 units toward local -Z, rather than rotating about the collision-box corner. + return { 25.25f, -19.23f, 19.82f, 27.33f, 44.75f, 58.0f, 0.20f, 10.0f, 0.75f }; +} + +s16 LidJoint(float fraction) { + return static_cast(static_cast(kClosedJoint) + + static_cast((static_cast(kOpenJoint) - + static_cast(kClosedJoint)) * fraction)); +} + +float LidOpenAngle(const EnBox* chest) { + if (chest == nullptr) return 0.0f; + // Derive the relative rotation from the exact skeletal joint that draws the lid. Working in + // wrapping binary-angle space preserves the -106-degree path across the signed-s16 boundary. + const uint16_t current = static_cast(chest->skelanime.jointTable[3].z); + const int16_t delta = static_cast(current - kClosedJoint); + return -static_cast(delta) * (2.0f * kPi / 65536.0f); +} + +LidMatrixRecord* FindLidMatrix(const EnBox* chest) { + if (chest == nullptr) return nullptr; + for (LidMatrixRecord& record : sLidMatrices) { + if (record.chest == chest) return &record; + } + return nullptr; +} + +// Return the exact current lid transform. The captured draw matrix may be one update old, so rotate +// its local X/Y columns by the joint delta while retaining the skeleton's real pivot and parent axes. +bool LidTransform(const EnBox* chest, float x[3], float y[3], float z[3], float origin[3]) { + LidMatrixRecord* record = FindLidMatrix(chest); + if (record == nullptr || gPlayState == nullptr || + gPlayState->state.frames - record->frame > 3) { + return false; + } + const uint16_t current = static_cast(chest->skelanime.jointTable[3].z); + const int16_t deltaJoint = static_cast(current - record->joint); + const float delta = static_cast(deltaJoint) * (2.0f * kPi / 65536.0f); + const float co = cosf(delta); + const float si = sinf(delta); + for (int component = 0; component < 3; ++component) { + const float oldX = record->m[component]; + const float oldY = record->m[4 + component]; + x[component] = oldX * co + oldY * si; + y[component] = oldY * co - oldX * si; + z[component] = record->m[8 + component]; + origin[component] = record->m[12 + component]; + } + return true; +} + +void Clear(bool keepPresentation = false) { + sHands[0] = {}; + sHands[1] = {}; + sPrevHoverChest[0] = sPrevHoverChest[1] = nullptr; + sOpening = false; + sOpenArmed = false; + sFinishing = false; + if (!keepPresentation) { + sChest = nullptr; + sOpenRequest = nullptr; + sStartHandAngle[0] = sStartHandAngle[1] = 0.0f; + sStartOpenFraction = 0.0f; + sOpenFraction = 0.0f; + sRequestConsumed = false; + sSawAwardDraw = false; + sPreviewDone = false; + sAwardActive = false; + sAwardEntry = GET_ITEM_NONE; + sRevealFrame = 0; + } +} + +void BeginInputFrame(PlayState* play) { + if (sInputFrame == play->state.frames) return; + sInputFrame = play->state.frames; + for (int hand = 0; hand < 2; ++hand) { + sPrevHoverChest[hand] = sHands[hand].active ? sHands[hand].chest : nullptr; + if (!sHands[hand].latched) { + // Retain the previous contact transform briefly; Tick may reuse it through a short + // distance/tracking miss instead of visibly dropping and reacquiring the hand. + sHands[hand].active = false; + sHands[hand].score = 1e30f; + } + sGripNow[hand] = (VR_GetControllerButton(hand) & VR_BTN_GRIP) != 0; + float quat[4]; + sFrameHandValid[hand] = VR_GetHandPose(hand, sFrameHandPos[hand], quat); + } +} + +bool Eligible(EnBox* chest, PlayState* play) { + if (chest == nullptr || play == nullptr || !CVarGetInteger("gVrPhysicalChests", 0) || + !VR_IsInitialized() || !VR_GetFirstPerson() || VR_IsFlatScreen() || + !CVarGetInteger("gVrMotionHands", 1) || play->csCtx.state != CS_STATE_IDLE || + play->transitionTrigger != TRANS_TRIGGER_OFF || chest->alpha != 255 || + Flags_GetTreasure(play, chest->dyna.actor.params & 0x1F)) { + return false; + } + if ((chest->type == ENBOX_TYPE_4 || chest->type == ENBOX_TYPE_6) && + (chest->dyna.actor.flags & ACTOR_FLAG_REACT_TO_LENS) && !play->actorCtx.lensActive) { + return false; + } + Player* player = GET_PLAYER(play); + return player != nullptr && !(player->stateFlags1 & + (PLAYER_STATE1_ON_HORSE | PLAYER_STATE1_DEAD | PLAYER_STATE1_CARRYING_ACTOR | + PLAYER_STATE1_HANGING_OFF_LEDGE | PLAYER_STATE1_CLIMBING_LEDGE | + PLAYER_STATE1_CLIMBING_LADDER | PLAYER_STATE1_IN_CUTSCENE)); +} + +void Axes(const EnBox* chest, float right[3], float back[3]) { + const float sn = Math_SinS(chest->dyna.actor.shape.rot.y); + const float cs = Math_CosS(chest->dyna.actor.shape.rot.y); + right[0] = cs; right[1] = 0.0f; right[2] = -sn; + back[0] = sn; back[1] = 0.0f; back[2] = cs; +} + +float HandLidPolar(const EnBox* chest, int hand) { + if (chest == nullptr || hand < 0 || hand > 1 || !sFrameHandValid[hand]) return 0.0f; + const ChestProfile profile = Profile(chest); + float right[3], back[3]; + Axes(chest, right, back); + const float dx = sFrameHandPos[hand][0] - chest->dyna.actor.world.pos.x; + const float dz = sFrameHandPos[hand][2] - chest->dyna.actor.world.pos.z; + const float localZ = dx * back[0] + dz * back[2]; + const float localY = sFrameHandPos[hand][1] - chest->dyna.actor.world.pos.y; + return atan2f(localY - profile.lidY, profile.hingeZ - localZ); +} + +float PositiveAngleChange(float current, float start) { + float change = current - start; + while (change > kPi) change -= 2.0f * kPi; + while (change < -kPi) change += 2.0f * kPi; + return fmaxf(0.0f, change); +} + +bool HandContact(const EnBox* chest, int hand, float* outX, float* outY, float* outZ, + float* outTangentY, float* outTangentZ, float* outContactAlong, + float* outDistance) { + float m[4][4]; + if (!VR_GetHandMatrix(hand, m)) return false; + const ChestProfile profile = Profile(chest); + float axisX[3], axisY[3], axisZ[3], origin[3]; + if (!LidTransform(chest, axisX, axisY, axisZ, origin)) return false; + const float scaleSq = axisX[0] * axisX[0] + axisX[1] * axisX[1] + axisX[2] * axisX[2]; + if (scaleSq < 0.000001f) return false; + const float modelScale = sqrtf(scaleSq); + const float len = VrHand_ChildSized() ? 548.0f : 862.0f; + float bestSq = 1e30f; + float bestX = 0.0f, bestY = 0.0f, bestZ = 0.0f; + float bestTangentX = -1.0f, bestTangentY = 0.0f; + size_t bestSegment = 0; + float bestFacetT = 0.0f; + + // The actual lid display list is authored in limb space: X runs from the hinge to the front, + // Y traces the faceted arch, and Z spans the chest width. These coordinates are transformed by + // the exact limb-3 draw matrix captured from EnBox_PostLimbDraw. + static constexpr float roofX[] = { 0.0f, 400.0f, 1352.0f, 2552.0f, 3504.0f, 3905.0f }; + static constexpr float roofY[] = { 0.0f, -1039.0f, -1742.0f, -1742.0f, -1039.0f, 0.0f }; + constexpr float kHalfWidth = 2525.0f; + + auto worldToLid = [&](float wx, float wy, float wz, float out[3]) { + const float dx = wx - origin[0]; + const float dy = wy - origin[1]; + const float dz = wz - origin[2]; + out[0] = (dx * axisX[0] + dy * axisX[1] + dz * axisX[2]) / scaleSq; + out[1] = (dx * axisY[0] + dy * axisY[1] + dz * axisY[2]) / scaleSq; + out[2] = (dx * axisZ[0] + dy * axisZ[1] + dz * axisZ[2]) / scaleSq; + }; + + float wrist[3]; + worldToLid(m[3][0], m[3][1], m[3][2], wrist); + // Only exclude the narrow seam at the hinge. The complete arched upper shell remains valid. + if (wrist[0] < 2.0f / modelScale) return false; + + auto distanceToFacet = [&](float along, size_t segment, float* closestXOut, float* closestYOut, + float* closestZOut, float* facetTOut) { + const float px = m[3][0] + m[0][0] * along; + const float py = m[3][1] + m[0][1] * along; + const float pz = m[3][2] + m[0][2] * along; + float local[3]; + worldToLid(px, py, pz, local); + const float closestZ = std::clamp(local[2], -kHalfWidth, kHalfWidth); + const float ez = local[2] - closestZ; + const float vx = roofX[segment + 1] - roofX[segment]; + const float vy = roofY[segment + 1] - roofY[segment]; + const float lengthSq = vx * vx + vy * vy; + const float t = std::clamp(((local[0] - roofX[segment]) * vx + + (local[1] - roofY[segment]) * vy) / lengthSq, + 0.0f, 1.0f); + const float closestX = roofX[segment] + vx * t; + const float closestY = roofY[segment] + vy * t; + const float ex = local[0] - closestX; + const float ey = local[1] - closestY; + *closestXOut = closestX; + *closestYOut = closestY; + *closestZOut = closestZ; + *facetTOut = t; + return ex * ex + ey * ey + ez * ez; + }; + + for (size_t segment = 0; segment < 5; ++segment) { + float low = 0.0f; + float high = len; + for (int iteration = 0; iteration < 18; ++iteration) { + const float third = (high - low) / 3.0f; + float unusedX, unusedY, unusedZ, unusedT; + const float lowDistance = distanceToFacet(low + third, segment, &unusedX, &unusedY, + &unusedZ, &unusedT); + const float highDistance = distanceToFacet(high - third, segment, &unusedX, &unusedY, + &unusedZ, &unusedT); + if (lowDistance <= highDistance) { + high -= third; + } else { + low += third; + } + } + const float along = (low + high) * 0.5f; + float closestX, closestY, closestZ, t; + const float distanceSq = + distanceToFacet(along, segment, &closestX, &closestY, &closestZ, &t); + if (distanceSq < bestSq) { + bestSq = distanceSq; + bestX = closestX; + bestY = closestY; + bestZ = closestZ; + bestSegment = segment; + bestFacetT = t; + } + } + + // Smooth the tangent across polygon joins while leaving contact on the real flat facets. + const size_t vertex0Prev = bestSegment > 0 ? bestSegment - 1 : bestSegment; + const size_t vertex1Next = bestSegment + 2 < 6 ? bestSegment + 2 : bestSegment + 1; + float tangent0X = roofX[vertex0Prev] - roofX[bestSegment + 1]; + float tangent0Y = roofY[vertex0Prev] - roofY[bestSegment + 1]; + float tangent1X = roofX[bestSegment] - roofX[vertex1Next]; + float tangent1Y = roofY[bestSegment] - roofY[vertex1Next]; + const float tangent0Length = sqrtf(tangent0X * tangent0X + tangent0Y * tangent0Y); + const float tangent1Length = sqrtf(tangent1X * tangent1X + tangent1Y * tangent1Y); + tangent0X /= tangent0Length; tangent0Y /= tangent0Length; + tangent1X /= tangent1Length; tangent1Y /= tangent1Length; + bestTangentX = tangent0X + (tangent1X - tangent0X) * bestFacetT; + bestTangentY = tangent0Y + (tangent1Y - tangent0Y) * bestFacetT; + const float tangentLength = sqrtf(bestTangentX * bestTangentX + bestTangentY * bestTangentY); + bestTangentX /= tangentLength; + bestTangentY /= tangentLength; + const float clearanceModel = profile.surfaceClearance / modelScale; + // For a hinge-directed tangent, (-tangentY, tangentX) is the roof's outward normal. + *outX = bestX - bestTangentY * clearanceModel; + *outY = bestY + bestTangentX * clearanceModel; + *outZ = bestZ; + *outTangentY = bestTangentX; + *outTangentZ = bestTangentY; + *outContactAlong = len * 0.5f; + *outDistance = sqrtf(bestSq) * modelScale; + // Once a chest owned hover on the preceding frame, allow a small release hysteresis so the + // hand does not flicker off at the joins between the half-cylinder's model facets. + const bool continuingHover = sHands[hand].chest == chest || sPrevHoverChest[hand] == chest; + return *outDistance <= profile.grabReach * (continuingHover ? 1.8f : 1.0f); +} + +GetItemEntry PreviewEntry(const EnBox* chest) { + if (sAwardActive && sAwardEntry.objectId != OBJECT_INVALID) { + return sAwardEntry; + } + if (IS_RANDO && CVarGetInteger(CVAR_RANDOMIZER_ENHANCEMENT("MysteriousShuffle"), 0)) { + return GET_ITEM_MYSTERY; + } + return chest->getItemEntry; +} + +void ItemPosition(const EnBox* chest, float out[3], float* scale) { + const ChestProfile profile = Profile(chest); + float right[3], back[3]; + Axes(chest, right, back); + float rise = 0.0f; + if (sRevealFrame != 0 && gPlayState != nullptr) { + rise = std::clamp((gPlayState->state.frames - sRevealFrame) / 18.0f, 0.0f, 1.0f); + } + const float jump = sinf(rise * kPi) * (IsSmall(chest) ? 4.0f : 8.0f); + const float insideY = IsSmall(chest) ? 11.0f : 22.0f; + const float y = insideY + (profile.hoverY - insideY) * rise + jump; + out[0] = chest->dyna.actor.world.pos.x - back[0] * (IsSmall(chest) ? 1.5f : 3.0f); + out[1] = chest->dyna.actor.world.pos.y + y; + out[2] = chest->dyna.actor.world.pos.z - back[2] * (IsSmall(chest) ? 1.5f : 3.0f); + *scale = profile.itemScale + (0.2f - profile.itemScale) * rise; +} + +void ForgetActor(Actor* actor) { + if (actor != nullptr && (actor == reinterpret_cast(sChest) || + actor == reinterpret_cast(sOpenRequest))) { + Clear(); + return; + } + for (int hand = 0; actor != nullptr && hand < 2; ++hand) { + if (actor == reinterpret_cast(sHands[hand].chest)) sHands[hand] = {}; + if (actor == reinterpret_cast(sPrevHoverChest[hand])) sPrevHoverChest[hand] = nullptr; + } + for (LidMatrixRecord& record : sLidMatrices) { + if (actor == reinterpret_cast(record.chest)) record = {}; + } +} + +int32_t CommitOpen(EnBox* chest, PlayState* play) { + sOpenFraction = 1.0f; + chest->skelanime.jointTable[3].z = static_cast(kOpenJoint); + sHands[0] = {}; + sHands[1] = {}; + sOpening = false; + sOpenArmed = false; + sFinishing = false; + sOpenRequest = chest; + sRequestConsumed = false; + sRevealFrame = play->state.frames; + Player* player = GET_PLAYER(play); + player->getItemId = -(chest->dyna.actor.params >> 5 & 0x7F); + player->interactRangeActor = &chest->dyna.actor; + player->getItemDirection = 0; + Audio_PlayActorSound2(&chest->dyna.actor, NA_SE_EV_TBOX_OPEN); + VR_TriggerHaptic(VR_HAND_LEFT, 0.75f, 0.0f, 45.0f); + VR_TriggerHaptic(VR_HAND_RIGHT, 0.75f, 0.0f, 45.0f); + return 2; +} + +} // namespace + +extern "C" void VrChest_RecordLidMatrix(EnBox* chest, const float* mf16) { + if (chest == nullptr || mf16 == nullptr || gPlayState == nullptr) return; + LidMatrixRecord* target = FindLidMatrix(chest); + if (target == nullptr) { + target = &sLidMatrices[0]; + for (LidMatrixRecord& candidate : sLidMatrices) { + if (candidate.chest == nullptr) { + target = &candidate; + break; + } + if (candidate.frame < target->frame) target = &candidate; + } + } + target->chest = chest; + target->frame = gPlayState->state.frames; + target->joint = static_cast(chest->skelanime.jointTable[3].z); + memcpy(target->m, mf16, sizeof(target->m)); +} + +extern "C" int32_t VrChest_Tick(EnBox* chest, PlayState* play) { + BeginInputFrame(play); + // Player_Update runs before this actor. If A committed the ordinary chest interaction earlier + // in this same frame, unk_1F4 is already nonzero: discard any hover/grip ownership and let + // EnBox_WaitOpen continue through its untouched native animation and reward path below. + if (chest != nullptr && chest->unk_1F4 != 0) { + if (sChest == chest && sOpenRequest == nullptr) Clear(); + return 0; + } + if (!Eligible(chest, play)) { + if (sChest == chest && sOpenRequest == nullptr) { + chest->skelanime.jointTable[3].z = static_cast(kClosedJoint); + Clear(); + } + return 0; + } + if (sChest != nullptr && sChest != chest) return 0; + + const ChestProfile profile = Profile(chest); + if (sChest == chest && sFinishing) { + sOpenFraction = fminf(1.0f, sOpenFraction + kFinishStep); + chest->skelanime.jointTable[3].z = LidJoint(sOpenFraction); + return sOpenFraction >= 0.999f ? CommitOpen(chest, play) : 1; + } + + for (int hand = 0; hand < 2; ++hand) { + float localX = 0.0f, localY = profile.lidTopY, localZ = profile.frontZ; + float tangentY = 0.0f, tangentZ = 1.0f, contactAlong = 0.0f, distance = 0.0f; + const bool near = HandContact(chest, hand, &localX, &localY, &localZ, &tangentY, &tangentZ, + &contactAlong, &distance); + if (sHands[hand].latched) { + sHands[hand].chest = chest; + sHands[hand].frame = play->state.frames; + sHands[hand].active = true; + if (!sGripNow[hand]) { + sHands[hand].latched = false; + } else if (sFrameHandValid[hand]) { + sHands[hand].trackingMissFrames = 0; + } else if (++sHands[hand].trackingMissFrames > 2) { + sHands[hand].latched = false; + } + } else if (near && (sChest == nullptr || sChest == chest) && distance < sHands[hand].score) { + ChestHandState& state = sHands[hand]; + state.chest = chest; + state.frame = play->state.frames; + state.contactFrame = play->state.frames; + state.active = true; + state.trackingMissFrames = 0; + state.score = distance; + state.localX = localX; + // Pin the selected point along the hand just above the curved roof in material + // coordinates. It stays outside the chest and follows the rotating lid. + state.localY = localY; + state.localZ = localZ; + state.tangentY = tangentY; + state.tangentZ = tangentZ; + state.contactAlong = contactAlong; + // As with shutters, grip only the surface owner resolved by the preceding completed + // frame. This avoids actor-order flicker when several chests are close together, but + // an already-held grip attaches as soon as this hover has remained stable for a frame. + if (sGripNow[hand] && sPrevHoverChest[hand] == chest && + GameInteractor_Should(VB_OPEN_CHEST, true, chest)) { + // Settle almost onto the lid when gripping, without changing the chosen contact. + const float grabClearance = profile.surfaceClearance * 0.2f; + const float clearanceChangeModel = + (profile.surfaceClearance - grabClearance) / fabsf(chest->dyna.actor.scale.x); + // Limb-space outward normal is (-tangentY, tangentX). Move back toward the facet. + state.localX += state.tangentZ * clearanceChangeModel; + state.localY -= state.tangentY * clearanceChangeModel; + sChest = chest; + state.latched = true; + VR_TriggerHaptic(hand, 0.3f, 0.0f, 25.0f); + } + } else if (sPrevHoverChest[hand] == chest && sHands[hand].chest == chest && + play->state.frames - sHands[hand].contactFrame <= 2) { + // Two-frame grace absorbs facet-edge precision and a single missing controller pose. + // Keep drawing the last exact surface transform, but do not initiate a new grab from it. + sHands[hand].frame = play->state.frames; + sHands[hand].active = true; + } else if (sHands[hand].chest == chest && + play->state.frames - sHands[hand].contactFrame > 2) { + sHands[hand] = {}; + } + } + + const bool bothHeld = sChest == chest && sHands[0].latched && sHands[1].latched && + sGripNow[0] && sGripNow[1]; + if (!bothHeld) { + if (sOpening) { + sOpening = false; + } + if (sChest == chest && sOpenArmed) { + // Past the balance/commit angle, letting go hands the remaining travel to the chest, + // just as a released physical shutter hands its remaining lift to the native action. + sHands[0] = {}; + sHands[1] = {}; + sFinishing = true; + return 1; + } + // Like an ordinary physical hinged door, a released lid stays at the furthest angle the + // player reached. Its moving front edge remains hoverable, so either hand can re-grab it + // and the second hand can join without the lid snapping shut. + if (sChest == chest && sOpenFraction > 0.0f) { + chest->skelanime.jointTable[3].z = LidJoint(sOpenFraction); + return 1; + } + if (sChest == chest && !sHands[0].latched && !sHands[1].latched && sOpenRequest == nullptr) { + Clear(); + } + const bool hoveringThis = + (sHands[0].active && sHands[0].chest == chest) || + (sHands[1].active && sHands[1].chest == chest); + return (hoveringThis || sChest == chest) ? 1 : 0; + } + + if (!sFrameHandValid[0] || !sFrameHandValid[1]) return 1; + const float handAngle[2] = { HandLidPolar(chest, 0), HandLidPolar(chest, 1) }; + if (!sOpening) { + sOpening = true; + sStartHandAngle[0] = handAngle[0]; + sStartHandAngle[1] = handAngle[1]; + sStartOpenFraction = sOpenFraction; + GetItemEntry entry = PreviewEntry(chest); + if (entry.objectId != OBJECT_INVALID) func_8083AE40(GET_PLAYER(play), entry.objectId); + if (sOpenFraction == 0.0f) Audio_PlayActorSound2(&chest->dyna.actor, NA_SE_EV_TBOX_UNLOCK); + } + // Match ordinary hinged-door control: drive the lid from the hands' real angular travel around + // its hinge. The previous fixed vertical-distance mapping rotated the lid much faster than the + // grabbed point's physical arc and made the pinned hands appear to trail or slide. + const float angularLift = + (PositiveAngleChange(handAngle[0], sStartHandAngle[0]) + + PositiveAngleChange(handAngle[1], sStartHandAngle[1])) * 0.5f; + const float targetFraction = std::clamp( + sStartOpenFraction + angularLift / kPhysicalOpenRadians, 0.0f, 1.0f); + // Never close because the hands moved down or tracking produced a short transient. Opening + // progress is monotonic, just as the ordinary VR door preserves the angle already achieved. + sOpenFraction = fmaxf(sOpenFraction, targetFraction); + sOpenArmed = sOpenArmed || sOpenFraction * kPhysicalOpenRadians >= kCommitAngleRadians; + chest->skelanime.jointTable[3].z = LidJoint(sOpenFraction); + + if (sOpenFraction >= 0.98f) { + return CommitOpen(chest, play); + } + return 1; +} + +extern "C" bool VrChest_GripConsumed(int32_t hand, uint16_t mask) { + const bool hovering = hand >= 0 && hand < 2 && gPlayState != nullptr && + sHands[hand].frame == gPlayState->state.frames && sHands[hand].active; + return (mask & VR_BTN_GRIP) && hand >= 0 && hand < 2 && + (hovering || sHands[hand].latched || sOpening || sFinishing); +} + +extern "C" bool VrChest_HoldsHand(int32_t hand) { + return hand >= 0 && hand < 2 && gPlayState != nullptr && sOpenRequest == nullptr && + sHands[hand].frame == gPlayState->state.frames && sHands[hand].active && + sHands[hand].chest != nullptr; +} + +extern "C" bool VrChest_PinnedHandMatrix(Player* player, int32_t hand, float* mf16) { + if (player == nullptr || mf16 == nullptr || hand < 0 || hand > 1 || gPlayState == nullptr || + player != GET_PLAYER(gPlayState) || !sHands[hand].active || sHands[hand].chest == nullptr || + sHands[hand].frame != gPlayState->state.frames || sOpenRequest != nullptr) { + return false; + } + const ChestHandState& state = sHands[hand]; + EnBox* handChest = state.chest; + float axisX[3], axisY[3], axisZ[3], origin[3]; + if (!LidTransform(handChest, axisX, axisY, axisZ, origin)) return false; + // The native anatomical open-hand meshes have the opposite palm-normal convention from the + // controller-side basis used here. Flip X and Z together: palm faces down without reversing + // the wrist-to-fingertip tangent or producing a negative-determinant matrix. + // Limb-space Z points opposite the actor-space width basis used by the previous placement. + // Reverse the paired width/normal signs so each anatomical mesh presents its palm to the lid + // while retaining a positive-determinant matrix. + const float palmTurn = hand == VR_HAND_LEFT ? 1.0f : -1.0f; + const float sx = sqrtf(mf16[0] * mf16[0] + mf16[1] * mf16[1] + mf16[2] * mf16[2]); + const float sy = sqrtf(mf16[4] * mf16[4] + mf16[5] * mf16[5] + mf16[6] * mf16[6]); + const float sz = sqrtf(mf16[8] * mf16[8] + mf16[9] * mf16[9] + mf16[10] * mf16[10]); + + float width[3] = { axisZ[0], axisZ[1], axisZ[2] }; + float tangent[3] = { + axisX[0] * state.tangentY + axisY[0] * state.tangentZ, + axisX[1] * state.tangentY + axisY[1] * state.tangentZ, + axisX[2] * state.tangentY + axisY[2] * state.tangentZ, + }; + const float widthLength = sqrtf(width[0] * width[0] + width[1] * width[1] + width[2] * width[2]); + const float tangentLength = + sqrtf(tangent[0] * tangent[0] + tangent[1] * tangent[1] + tangent[2] * tangent[2]); + for (int component = 0; component < 3; ++component) { + width[component] /= widthLength; + tangent[component] /= tangentLength; + } + const float normal[3] = { + width[1] * tangent[2] - width[2] * tangent[1], + width[2] * tangent[0] - width[0] * tangent[2], + width[0] * tangent[1] - width[1] * tangent[0], + }; + for (int component = 0; component < 3; ++component) { + mf16[component] = palmTurn * width[component] * sx; + mf16[4 + component] = tangent[component] * sy; + mf16[8 + component] = palmTurn * normal[component] * sz; + } + + const float px = origin[0] + axisX[0] * state.localX + axisY[0] * state.localY + axisZ[0] * state.localZ; + const float py = origin[1] + axisX[1] * state.localX + axisY[1] * state.localY + axisZ[1] * state.localZ; + const float pz = origin[2] + axisX[2] * state.localX + axisY[2] * state.localY + axisZ[2] * state.localZ; + // The contact clearance describes the gap below the palm, not the hand's centre plane. Lift + // the centre by the scaled half-thickness of the native open-hand mesh so its visible underside + // stays outside the lid. The small extra allowance prevents the smoothly blended palm plane + // from cutting a flat polygon facet near a join; gripping reduces it for weight-bearing contact. + constexpr float kPalmHalfThicknessModel = 220.0f; + const float curveSafety = state.latched ? 0.25f : 0.75f; + const float palmLift = sz * kPalmHalfThicknessModel + curveSafety; + mf16[12] = px + normal[0] * palmLift - mf16[4] * state.contactAlong; + mf16[13] = py + normal[1] * palmLift - mf16[5] * state.contactAlong; + mf16[14] = pz + normal[2] * palmLift - mf16[6] * state.contactAlong; + return true; +} + +extern "C" bool VrChest_OpenRequested(EnBox* chest) { + return chest != nullptr && chest == sOpenRequest && !sRequestConsumed; +} + +extern "C" void VrChest_ConsumeOpenRequest(EnBox* chest) { + if (chest == sOpenRequest) sRequestConsumed = true; +} + +extern "C" void VrChest_AwardStarted(EnBox* chest, const GetItemEntry* entry) { + if (chest != nullptr && chest == sChest) { + sAwardActive = true; + sSawAwardDraw = true; + if (entry != nullptr) sAwardEntry = *entry; + } +} + +extern "C" void VrChest_AwardFinished(EnBox* chest) { + if (chest != nullptr && chest == sChest) { + sAwardActive = false; + sPreviewDone = true; + Clear(); + } +} + +extern "C" bool VrChest_AwardActive() { + return sAwardActive; +} + +extern "C" bool VrChest_GetItemHoldUpPos(PlayState* play, Player* player, float* out) { + if (play == nullptr || player == nullptr || out == nullptr || sChest == nullptr || sPreviewDone || + !(player->stateFlags1 & PLAYER_STATE1_GETTING_ITEM)) { + return false; + } + float scale; + ItemPosition(sChest, out, &scale); + out[1] -= 14.0f; + sSawAwardDraw = true; + return true; +} + +extern "C" void VrChest_DrawItem(EnBox* chest, PlayState* play) { + if (chest == nullptr || play == nullptr || chest != sChest || sOpenFraction < 0.08f || sPreviewDone) return; + Player* player = GET_PLAYER(play); + if (sRequestConsumed && sRevealFrame != 0 && play->state.frames - sRevealFrame > 300) { + Clear(); + return; + } + + GetItemEntry entry = PreviewEntry(chest); + float pos[3], scale; + ItemPosition(chest, pos, &scale); + OPEN_DISPS(play->state.gfxCtx); + Matrix_Push(); + gSegments[6] = VIRTUAL_TO_PHYSICAL(player->giObjectSegment); + gSPSegment(POLY_OPA_DISP++, 0x06, (uintptr_t)player->giObjectSegment); + gSPSegment(POLY_XLU_DISP++, 0x06, (uintptr_t)player->giObjectSegment); + Matrix_Translate(pos[0], pos[1], pos[2], MTXMODE_NEW); + Matrix_RotateZYX(0, play->gameplayFrames * 1000, 0, MTXMODE_APPLY); + Matrix_Scale(scale, scale, scale, MTXMODE_APPLY); + GetItemEntry_Draw(play, entry); + Matrix_Pop(); + CLOSE_DISPS(play->state.gfxCtx); +} + +namespace { +void ReleaseFinishedPresentation() { + if (sChest == nullptr || gPlayState == nullptr || !sRequestConsumed) return; + const bool timedOut = sRevealFrame != 0 && gPlayState->state.frames - sRevealFrame > 300; + if (!sAwardActive && timedOut) Clear(); +} + +void RegisterVrChest() { + COND_HOOK(OnSceneInit, true, [](int16_t) { Clear(); }); + COND_HOOK(OnActorDestroy, true, [](void* actor) { ForgetActor(static_cast(actor)); }); + COND_HOOK(OnGameFrameUpdate, true, ReleaseFinishedPresentation); +} +static RegisterShipInitFunc initVrChest(RegisterVrChest); +} // namespace diff --git a/soh/soh/Enhancements/vr-combat/VrClimb.cpp b/soh/soh/Enhancements/vr-combat/VrClimb.cpp index 7d6ebdeb9b0..24f075257d8 100644 --- a/soh/soh/Enhancements/vr-combat/VrClimb.cpp +++ b/soh/soh/Enhancements/vr-combat/VrClimb.cpp @@ -229,7 +229,12 @@ bool CanMount(PlayState* play, Player* player, const VrClimbHit& hit) { nz = COLPOLY_GET_NORMAL(poly->normal.z); const float dist = nx * player->actor.world.pos.x + ny * player->actor.world.pos.y + nz * player->actor.world.pos.z + poly->dist; - return dist > -5.0f && dist < player->ageProperties->wallCheckRadius + kMountSlackUnits; + // Some dynamic climbable actors expose their usable face on the negative side of the authored + // polygon plane (the vine face on Dodongo's Cavern's falling stairs is one). Vanilla approaches + // these through its wall-contact result, which already knows the player's side. A hand probe has + // the polygon directly, so accept the same physical distance from either side; the player code + // records the side at mount and keeps its effective normal pointing back toward Link. + return fabsf(dist) < player->ageProperties->wallCheckRadius + kMountSlackUnits; } void EndDrive() { diff --git a/soh/soh/Enhancements/vr-combat/VrCombat.h b/soh/soh/Enhancements/vr-combat/VrCombat.h index e09fd3d98f1..204f01a60e1 100644 --- a/soh/soh/Enhancements/vr-combat/VrCombat.h +++ b/soh/soh/Enhancements/vr-combat/VrCombat.h @@ -141,6 +141,10 @@ int32_t VrCombat_ShieldBlockJudge(struct Player* player); // True when the given VR input on the given hand is DEDICATED to the selector — padmgr skips // that input's normal button binding so the opening click never leaks its bound action. bool VrItemSelect_ConsumesInput(int32_t vrHand, uint16_t vrBtnMask); +// On horseback the selector cannot open. Returns true once on each press of its configured +// input, allowing the player item layer to toggle the bow directly instead. +bool VrItemSelect_TakeHorseBowToggle(void); +bool VrItemSelect_HorseBowEnabled(void); // SELECTOR MODE (gVrItemSelect on, VR first person): the selector equips and the TRIGGER of the // hand the item ended up in uses it, replacing "press the C button you assigned it to". @@ -214,8 +218,12 @@ bool VrOcarina_InPlay(void); // the one-hand aim ray). Reset clears transient nock state. bool VrArchery_Covers(struct Player* player); uint16_t VrArchery_ItemButtonMask(void); +bool VrArchery_GalleryOwnsWeapon(void); bool VrArchery_PinchConsumed(int32_t vrHand, uint16_t vrBtnMask); bool VrArchery_AimSegment(float* outPosDir6); +// Consumes the exact two-hand line captured for a released physical bow shot. Unlike the +// render-time AimSegment window, this remains valid until the delayed arrow actually launches. +bool VrArchery_TakeReleasedAim(float* outPosDir6); void VrArchery_Reset(void); // Fairy Bow profile (geometry read off the bow model, as the slingshot's pouch is). // BowStringNock: world point the drawn bowstring's apex belongs at (string hand, capped at max @@ -232,6 +240,9 @@ bool VrArchery_BowAlignedMatrix(int32_t vrHand, float* mf16); // NockedArrowHand: the VR hand the nocked arrow is welded to (the bow hand, like the string) // while a bow nock is drawn; -1 otherwise (the arrow draws exactly as vanilla). int32_t VrArchery_NockedArrowHand(void); +// Same answer, but only when `arrow` is the exact projectile currently held by the player. +// Elemental child effects use this so an older arrow in flight is never welded to a new nock. +int32_t VrArchery_NockedArrowHandForActor(struct Actor* arrow); // Physical bottle scooping (VrBottle.cpp — selector mode): an EMPTY bottle catches by // moving its MOUTH (bottle-hand controller + grip-local offset) into a catchable's volume — no @@ -559,6 +570,106 @@ typedef struct VrBlockDebug { int32_t lastRelease; // -1 none yet, 0 grip opened, 1 pulled off, 2 Link left the grab } VrBlockDebug; void VrBlock_GetDebug(VrBlockDebug* out); + +// Physical handle doors (VrDoor.cpp, gVrPhysicalDoors). Ordinary unlocked En_Door actors only. +// A fresh normal VR grab near the handle latches one hand. Turning that hand about the door normal +// releases the latch; its horizontal position then drives the leaf around the hinge until released. +// Returns true while the module owns the actor, so EnDoor_Idle does not run the vanilla animation. +struct EnDoor; +bool VrDoor_Tick(struct EnDoor* door, struct PlayState* play); +bool VrDoor_GripConsumed(int32_t hand, uint16_t mask); +// Jabu-Jabu's unbarred radial flesh shutter reuses shutter hover/palm pinning, but opens completely +// from a single hand grip with no lift gesture. The native actor retains its opening/closing animation. +struct DoorShutter; +bool VrJabuDoor_Tick(struct DoorShutter* door, struct PlayState* play); +void VrJabuDoor_Cancel(struct DoorShutter* door, struct PlayState* play); +bool VrJabuDoor_GripConsumed(int32_t hand, uint16_t mask); +// An unlocked, fully unbarred rigid shutter can be gripped with both hands and physically lifted in VR. +// This covers Boss Doors and ordinary dungeon shutters; Jabu and special encounter blockers are excluded. +// 0 = inactive, 1 = owns the door/grips, 2 = fully raised. +int32_t VrShutter_Tick(struct DoorShutter* door, struct PlayState* play); +bool VrShutter_GripConsumed(int32_t hand, uint16_t mask); +// While hovering or latched, the hand is rendered as a bare open palm instead of its equipped item. +bool VrShutter_HoldsHand(int32_t hand); +bool VrShutter_KeepOpen(struct DoorShutter* door, struct PlayState* play); +bool VrShutter_IsPhysicalClosePending(struct DoorShutter* door); +int32_t VrShutter_GetPhysicalCloseRoom(struct DoorShutter* door, struct PlayState* play); +bool VrShutter_GetClosingRenderFlipped(const struct DoorShutter* door, bool* flipped); +// Completes a cancelled physical shutter's room rollback only after the slab reaches fully closed. +void VrShutter_FinishClose(struct DoorShutter* door, struct PlayState* play); +bool VrShutter_ConsumePhysicalClose(struct DoorShutter* door); +bool VrShutter_ConsumePreservedEntryUnlock(struct DoorShutter* door); +float VrShutter_OpenHeight(struct DoorShutter* door); +bool VrShutter_PinnedHandMatrix(struct Player* player, int32_t hand, float* mf16); +// Returns the OTR display-list path for the rigid slab selected by Door_Shutter. +const char* VrShutter_GetDisplayListPath(const struct DoorShutter* door); +bool VrShutter_RenderFlipped(const struct DoorShutter* door, const struct PlayState* play); +// Suppresses only the player's wall sweep inside the centre of a sufficiently open physical doorway. +bool VrDoor_AllowsWallPass(struct Actor* actor, const float* nextPos3, const float* prevPos3); +// Replaces the removed closed-door wall with a player-only collider along the rotated physical leaf. +void VrDoor_ConstrainPlayerToLeaf(struct Actor* actor); +// During physical-door streaming, room object banks are merged so prevRoom actors keep their assets. +bool VrDoor_KeepPreviousRoomActors(void); +// True only around the Room_RequestNewRoom call made by a physical VR doorway. +bool VrDoor_IsPhysicalRoomRequest(void); +int32_t VrDoor_EnvironmentBehaviorType2(struct PlayState* play); +// Supplies a stable virtual viewpoint for EnDoor's front/back display-list choice near the leaf. +bool VrDoor_StableFaceView(struct EnDoor* door, float* outPos3); +bool VrDoor_IsPhysicalActive(struct EnDoor* door); +// While a handle is held, pin the rendered hand to the point it took hold on the moving leaf. +// The physical controller continues to drive the door, but cannot visually stretch away from it. +bool VrDoor_PinnedHandMatrix(struct Player* player, int32_t hand, float* mf16); + +// Gerudo Fortress cell grates use their own actor but share the two-hand vertical-lift language +// of physical shutters. -1 means the original non-VR path should run; 2 commits the open state. +struct DoorGerudo; +int32_t VrGerudoDoor_Tick(struct DoorGerudo* door, struct PlayState* play); +bool VrGerudoDoor_GripConsumed(int32_t hand, uint16_t mask); +bool VrGerudoDoor_HoldsHand(int32_t hand); +bool VrGerudoDoor_PinnedHandMatrix(struct Player* player, int32_t hand, float* mf16); + +// Physical treasure chests (VrChest.cpp, gVrPhysicalChests). Both hands must grip anywhere across +// the front lip opposite the hinge and lift together; reaching the fully open angle commits the +// ordinary chest reward transaction. The stock path remains untouched outside first-person VR. +struct EnBox; +struct GetItemEntry; +// 0 = inactive, 1 = hovering/holding/physically opening, 2 = reached fully open this tick. +int32_t VrChest_Tick(struct EnBox* chest, struct PlayState* play); +// Captures the exact model matrix used to draw lid limb 3, allowing hover placement to use the +// rendered mesh rather than duplicating the chest skeleton transform. +void VrChest_RecordLidMatrix(struct EnBox* chest, const float* mf16); +bool VrChest_GripConsumed(int32_t hand, uint16_t mask); +bool VrChest_HoldsHand(int32_t hand); +bool VrChest_PinnedHandMatrix(struct Player* player, int32_t hand, float* mf16); +bool VrChest_OpenRequested(struct EnBox* chest); +void VrChest_ConsumeOpenRequest(struct EnBox* chest); +// The physical path runs the ordinary reward transaction in the background so Link retains +// locomotion. These calls keep the already-visible chest item alive for that entire transaction. +void VrChest_AwardStarted(struct EnBox* chest, const struct GetItemEntry* entry); +void VrChest_AwardFinished(struct EnBox* chest); +bool VrChest_AwardActive(void); +// Repositions the normal get-item model over the opened chest. `out` is the reference point used +// by Player_DrawGetItemImpl, so the caller's normal 14-unit vertical offset still applies. +bool VrChest_GetItemHoldUpPos(struct PlayState* play, struct Player* player, float* out); +// Draws the single item model while it is inside/rising from the chest and throughout the reward. +void VrChest_DrawItem(struct EnBox* chest, struct PlayState* play); +// Physical dungeon keys (VrKeys.cpp). Two-dimensional inventory icons on the left wrist can be +// grabbed to create a held key; compatible vanilla locks remain responsible for consuming it. +void VrKeys_Tick(struct PlayState* play, struct Player* player); +bool VrKeys_GripConsumed(int32_t hand, uint16_t mask); +bool VrKeys_HoldsHand(int32_t hand); +// True while the grabbing hand is inside this wrist key's visible card (bossKey: 0 small, 1 boss). +bool VrKeys_HudHighlighted(int32_t bossKey); +// True when the current dungeon's Boss Key is owned, for persistent wrist-HUD visibility. +// Physical spawning remains restricted to a nearby, still-locked Boss Door in VrKeys_Tick. +bool VrKeys_BossAvailable(struct PlayState* play); +void VrKeys_Reset(void); +// Returns true after the held physical key has been aligned with and pushed through this lock. +struct EnDoor; +struct DoorShutter; +bool VrKeys_TryEnDoor(struct EnDoor* door, struct PlayState* play); +bool VrKeys_TryShutter(struct DoorShutter* door, struct PlayState* play); +bool VrKeys_TryGerudoDoor(struct DoorGerudo* door, struct PlayState* play); // Small body collider (VrBody.cpp, gVrSmallBody — VR first person with roomscale). Link's body keeps // the vanilla wall radius for everything; the view (and the hands on the same anchor) is a small // circle (gVrSmallBodyRadiusCm) living inside that big circle, so it can get closer to walls than the diff --git a/soh/soh/Enhancements/vr-combat/VrDoor.cpp b/soh/soh/Enhancements/vr-combat/VrDoor.cpp new file mode 100644 index 00000000000..5055ac07f32 --- /dev/null +++ b/soh/soh/Enhancements/vr-combat/VrDoor.cpp @@ -0,0 +1,1785 @@ +extern "C" { +#include "z64.h" +#include "macros.h" +#include "functions.h" +#include "objects/gameplay_keep/gameplay_keep.h" +#include "overlays/actors/ovl_En_Door/z_en_door.h" +#include "overlays/actors/ovl_Door_Shutter/z_door_shutter.h" +extern PlayState* gPlayState; +s32 Player_HandleExitsAndVoids(PlayState* play, Player* player, CollisionPoly* poly, u32 bgId); +void VrDoor_ReleaseRetainedObjects(PlayState* play, bool keepDestination); +void VrDoor_ResetRetainedObjects(void); +} + +#include "VrCombat.h" +#include "soh/Enhancements/game-interactor/GameInteractor.h" +#include "soh/ResourceManagerHelpers.h" +#include "soh/ShipInit.hpp" +#include "soh/frame_interpolation.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// Physical ordinary doors. En_Door's skeleton offsets the rotating hierarchy by 2700 model units +// (27 world units) before applying limb 3's opening rotation. We keep all geometry in the actor's +// closed-door frame, then write the same limb rotation channel used by the stock animation. +namespace { +constexpr float kTurnDeg = 22.0f; +constexpr float kPi = 3.14159265358979323846f; +constexpr float kMaxOpenDeg = 90.0f; +constexpr float kExitDeg = 55.0f; +// Unlock the doorway early enough that a door pushed away from the player can be walked around +// before its handle leaves comfortable reach. +constexpr float kWalkThroughDeg = 25.0f; + +EnDoor* sDoor = nullptr; +EnDoor* sCandidate = nullptr; +int sHand = -1; +bool sUnlatched = false; +bool sRoomRequested = false; +bool sPassagePending = false; +bool sPassageCommitted = false; +bool sGripPrev[2] = { true, true }; +bool sGripNow[2] = { false, false }; +bool sGripFresh[2] = { false, false }; +uint32_t sInputFrame = UINT32_MAX; +float sStartQuat[4] = {}; +float sPullStartRad = 0.0f; +float sPullStartDeg = 0.0f; +bool sPullRefValid = false; +bool sOpenSoundPlayed = false; +bool sCloseSoundPlayed = false; +float sSide = 1.0f; +float sDisplaySide = 1.0f; +float sHandleSide = 1.0f; +float sKnobFace = 1.0f; +s16 sAngle = 0; +uint32_t sTickFrame = 0; +bool sNear[2] = { false, false }; +float sNearFace[2] = { 1.0f, 1.0f }; +float sNearHandleSide[2] = { 1.0f, 1.0f }; +float sGrabOffsetLocal[3] = {}; +float sPrevPlaneDistance = 1e30f; + +DoorShutter* sJabuDoor = nullptr; +DoorShutter* sJabuLatchDoor = nullptr; +bool sJabuNear[2] = { false, false }; +bool sJabuLatched[2] = { false, false }; + +DoorShutter* sShutterCandidate = nullptr; +DoorShutter* sShutterDoor = nullptr; +DoorShutter* sShutterLatchDoor = nullptr; +DoorShutter* sShutterStreamDoor = nullptr; +DoorShutter* sShutterJustClosedDoor = nullptr; +DoorShutter* sShutterClosingRenderDoor = nullptr; +DoorShutter* sShutterPreservedEntryUnlockDoor = nullptr; +bool sShutterClosingRenderFlipped = false; +bool sShutterLatched[2] = { false, false }; +bool sShutterGripNow[2] = { false, false }; +uint32_t sShutterInputFrame = UINT32_MAX; +float sShutterLatchSide[2] = {}; +struct ShutterHandState { + DoorShutter* door = nullptr; + uint32_t frame = UINT32_MAX; + bool active = false; + bool latched = false; + float score = FLT_MAX; + float localX = 0.0f; + float localY = 0.0f; + float localZ = 0.0f; + float surfaceFace = 1.0f; + float visualFace = 1.0f; +}; +ShutterHandState sShutterHandState[2]; +DoorShutter* sShutterPrevHoverDoor[2] = { nullptr, nullptr }; +float sShutterPrevHoverFace[2] = { 1.0f, 1.0f }; +float sShutterFrameHandPos[2][3] = {}; +float sShutterPrevHandPos[2][3] = {}; +bool sShutterFrameHandValid[2] = { false, false }; +bool sShutterPrevHandValid[2] = { false, false }; +float sShutterGrabFace[2] = {}; +float sShutterGrabLocal[2][2] = {}; +float sShutterStartMeanY = 0.0f; +float sShutterStartHeight = 0.0f; +float sShutterEntrySide = 1.0f; +int sShutterEntryRoom = -1; +bool sShutterRoomRequested = false; +bool sShutterFullyOpen = false; +bool sShutterLiftArmed = false; +bool sShutterCloseRollbackPending = false; +bool sShutterCloseForNextDoor = false; + +// Room streaming is identical for every physical doorway. Interaction code (turning a handle, +// lifting a slab, or touching a membrane) only drives the door's animation; this object owns the +// shared preload/commit/rollback lifecycle. +struct PhysicalDoorwayTransition { + Actor* owner = nullptr; + float entrySide = 1.0f; + int entryRoom = -1; + bool requested = false; + bool crossed = false; +}; + +PhysicalDoorwayTransition sHingeTransition; +PhysicalDoorwayTransition sShutterTransition; +bool sPhysicalRoomRequest = false; + +void SetDoorwayActorRoom(Actor* actor, int room, bool includeRelatives) { + if (actor == nullptr) return; + actor->room = room; + if (includeRelatives && actor->child != nullptr) actor->child->room = room; + if (includeRelatives && actor->parent != nullptr) actor->parent->room = room; +} + +bool BeginDoorwayTransition(PhysicalDoorwayTransition& transition, Actor* actor, PlayState* play, + float entrySide, bool includeRelatives) { + if (actor == nullptr || play == nullptr || transition.requested) { + return transition.requested && transition.owner == actor; + } + const int index = GET_TRANSITION_ACTOR_INDEX(actor); + const TransitionActorEntry* entry = &play->transiActorCtx.list[index]; + + // The invisible En_Holl behind a doorway may begin loading the same adjacent room before a VR + // hand reaches the door. Adopt that exact room pair instead of rejecting the physical touch + // merely because prevRoom is already populated. Never claim a preload belonging to another + // transition actor. + if (play->roomCtx.prevRoom.num >= 0) { + const int currentRoom = play->roomCtx.curRoom.num; + const int previousRoom = play->roomCtx.prevRoom.num; + const bool matchingPair = + (entry->sides[0].room == currentRoom && entry->sides[1].room == previousRoom) || + (entry->sides[1].room == currentRoom && entry->sides[0].room == previousRoom); + if (!matchingPair) return false; + transition.owner = actor; + transition.entrySide = entrySide; + // Room_RequestNewRoom promotes the destination to curRoom immediately and retains the + // physical origin as prevRoom. The player has not crossed this doorway yet, so prevRoom is + // the stable entry-room identity when adopting an En_Holl preload. + transition.entryRoom = previousRoom; + transition.requested = true; + transition.crossed = false; + SetDoorwayActorRoom(actor, -1, includeRelatives); + return true; + } + if (play->roomCtx.status != 0) return false; + + int destination; + if (entry->sides[0].room == play->roomCtx.curRoom.num) { + destination = entry->sides[1].room; + } else if (entry->sides[1].room == play->roomCtx.curRoom.num) { + destination = entry->sides[0].room; + } else { + destination = entry->sides[entrySide > 0.0f ? 0 : 1].room; + } + if (destination < 0 || destination == play->roomCtx.curRoom.num) { + return false; + } + // Capture the physical origin before Room_RequestNewRoom replaces curRoom with destination. + // Side-dependent shutter types use this identity for their switch/clear condition throughout + // the retained-room lifecycle. + const int entryRoom = play->roomCtx.curRoom.num; + sPhysicalRoomRequest = true; + const bool requested = Room_RequestNewRoom(play, &play->roomCtx, destination) != 0; + sPhysicalRoomRequest = false; + if (!requested) return false; + transition.owner = actor; + transition.entrySide = entrySide; + transition.entryRoom = entryRoom; + transition.requested = true; + transition.crossed = false; + SetDoorwayActorRoom(actor, -1, includeRelatives); + return true; +} + +void FinishDoorwayTransition(PhysicalDoorwayTransition& transition, PlayState* play, float currentSide, + bool includeRelatives) { + if (!transition.requested || play == nullptr || play->roomCtx.status != 0) return; + const bool keepDestination = currentSide != transition.entrySide; + transition.crossed = keepDestination; + if (play->roomCtx.prevRoom.num >= 0) { + if (!keepDestination) { + Room room = play->roomCtx.curRoom; + play->roomCtx.curRoom = play->roomCtx.prevRoom; + play->roomCtx.prevRoom = room; + } + Room_FinishRoomChange(play, &play->roomCtx); + } + VrDoor_ReleaseRetainedObjects(play, keepDestination); + if (keepDestination) Play_SetupRespawnPoint(play, RESPAWN_MODE_DOWN, 0xDFF); + SetDoorwayActorRoom(transition.owner, play->roomCtx.curRoom.num, includeRelatives); + transition = {}; +} +constexpr float kBossShutterRaisedHeight = 240.0f; +constexpr float kShutterHoverOffset = 2.0f; +constexpr float kShutterGrabClearance = 0.75f; + +struct ShutterSurfacePoint { + float x; + float y; + float z; + bool valid = false; +}; + +struct ShutterSurfaceTriangle { + ShutterSurfacePoint p[3]; +}; + +std::unordered_map> sShutterSurfaceCache; + +void AddSurfaceTriangle(std::vector& triangles, + const std::array& slots, int a, int b, int c) { + if (a < 0 || b < 0 || c < 0 || a >= static_cast(slots.size()) || + b >= static_cast(slots.size()) || c >= static_cast(slots.size()) || + !slots[a].valid || !slots[b].valid || !slots[c].valid) { + return; + } + triangles.push_back({ slots[a], slots[b], slots[c] }); +} + +void AppendDisplayListTriangles(const std::string& path, std::vector& triangles, + std::array& slots, int recursionDepth) { + if (recursionDepth > 16) return; + auto resourceManager = Ship::Context::GetRawInstance()->GetResourceManager(); + ResourceMgr_UnloadOriginalWhenAltExists(path.c_str()); + auto displayList = std::dynamic_pointer_cast(resourceManager->LoadResourceProcess(path)); + if (displayList == nullptr) return; + for (size_t i = 0; i < displayList->Instructions.size(); ++i) { + const Gfx& command = displayList->Instructions[i]; + const int8_t opcode = static_cast(command.words.w0 >> 24); + const char* resourcePath = nullptr; + const bool vertexHash = opcode == G_VTX_OTR_HASH; + const bool displayListHash = opcode == G_DL_OTR_HASH; + size_t vertexCount = 0; + size_t vertexOffset = 0; + size_t vertexSlot = 0; + const Vtx* directVertices = nullptr; + if ((vertexHash || displayListHash) && i + 1 < displayList->Instructions.size()) { + const Gfx& hashWords = displayList->Instructions[++i]; + const uint64_t hash = (static_cast(hashWords.words.w0) << 32) | hashWords.words.w1; + resourcePath = ResourceGetNameByCrc(hash); + if (vertexHash) { + vertexCount = _SHIFTR(command.words.w0, 12, 8); + vertexSlot = _SHIFTR(command.words.w0, 1, 7) - vertexCount; + // The renderer patches this field to a live vertex pointer after first use. + // Before that happens it is a byte offset into the referenced resource. + if (command.words.w1 > 0xFFFFF) { + directVertices = reinterpret_cast(command.words.w1); + } else { + vertexOffset = command.words.w1 / sizeof(Vtx); + } + } + } else if (opcode == G_VTX_OTR_FILEPATH || opcode == G_DL_OTR_FILEPATH) { + resourcePath = reinterpret_cast(command.words.w1); + if (opcode == G_VTX_OTR_FILEPATH && i + 1 < displayList->Instructions.size()) { + const Gfx& range = displayList->Instructions[++i]; + vertexCount = range.words.w0; + vertexSlot = range.words.w1 >> 16; + vertexOffset = range.words.w1 & 0xFFFF; + } + } + if (vertexHash || opcode == G_VTX_OTR_FILEPATH) { + if (directVertices != nullptr) { + for (size_t vertexIndex = 0; vertexIndex < vertexCount; ++vertexIndex) { + const Vtx& vertex = directVertices[vertexIndex]; + const size_t slot = vertexSlot + vertexIndex; + if (slot >= slots.size()) break; + slots[slot] = { static_cast(vertex.v.ob[0]), static_cast(vertex.v.ob[1]), + static_cast(vertex.v.ob[2]), true }; + } + } else if (resourcePath != nullptr) { + ResourceMgr_UnloadOriginalWhenAltExists(resourcePath); + auto vertexResource = + std::dynamic_pointer_cast(resourceManager->LoadResourceProcess(resourcePath)); + if (vertexResource == nullptr) continue; + const size_t end = vertexCount == 0 + ? vertexResource->VertexList.size() + : std::min(vertexOffset + vertexCount, vertexResource->VertexList.size()); + for (size_t vertexIndex = vertexOffset; vertexIndex < end; ++vertexIndex) { + const Vtx& vertex = vertexResource->VertexList[vertexIndex]; + const size_t slot = vertexSlot + vertexIndex - vertexOffset; + if (slot >= slots.size()) break; + slots[slot] = { static_cast(vertex.v.ob[0]), static_cast(vertex.v.ob[1]), + static_cast(vertex.v.ob[2]), true }; + } + } + } else if ((displayListHash || opcode == G_DL_OTR_FILEPATH) && resourcePath != nullptr) { + AppendDisplayListTriangles(resourcePath, triangles, slots, recursionDepth + 1); + } else if (opcode == G_TRI1_OTR) { + AddSurfaceTriangle(triangles, slots, _SHIFTR(command.words.w0, 0, 16), + _SHIFTR(command.words.w1, 16, 16), _SHIFTR(command.words.w1, 0, 16)); + } else if (opcode == G_TRI1) { + AddSurfaceTriangle(triangles, slots, _SHIFTR(command.words.w1, 16, 8) / 2, + _SHIFTR(command.words.w1, 8, 8) / 2, _SHIFTR(command.words.w1, 0, 8) / 2); + } else if (opcode == G_TRI2) { + AddSurfaceTriangle(triangles, slots, _SHIFTR(command.words.w0, 16, 8) / 2, + _SHIFTR(command.words.w0, 8, 8) / 2, _SHIFTR(command.words.w0, 0, 8) / 2); + AddSurfaceTriangle(triangles, slots, _SHIFTR(command.words.w1, 16, 8) / 2, + _SHIFTR(command.words.w1, 8, 8) / 2, _SHIFTR(command.words.w1, 0, 8) / 2); + } + } +} + +const std::vector& ShutterSurfaceTriangles(const DoorShutter* door) { + static const std::vector empty; + const char* path = VrShutter_GetDisplayListPath(door); + if (path == nullptr || path[0] == '\0') return empty; + auto resourceManager = Ship::Context::GetRawInstance()->GetResourceManager(); + // Alternate models retain the logical display-list path, so include the active asset mode in + // the cache identity. Toggling an enhancement pack must never reuse the stock model's surface. + const std::string cacheKey = std::string(resourceManager->IsAltAssetsEnabled() ? "alt:" : "base:") + path; + auto cached = sShutterSurfaceCache.find(cacheKey); + if (cached != sShutterSurfaceCache.end()) return cached->second; + + std::vector triangles; + std::array slots = {}; + AppendDisplayListTriangles(path, triangles, slots, 0); + return sShutterSurfaceCache.emplace(cacheKey, std::move(triangles)).first->second; +} + +float ShutterSurfaceDepth(const DoorShutter* door, float localX, float localY, float face, bool* found = nullptr) { + const auto& triangles = ShutterSurfaceTriangles(door); + float bestDepth = -FLT_MAX; + for (const auto& triangle : triangles) { + const float x0 = triangle.p[0].x, y0 = triangle.p[0].y; + const float x1 = triangle.p[1].x, y1 = triangle.p[1].y; + const float x2 = triangle.p[2].x, y2 = triangle.p[2].y; + const float denominator = (y1 - y2) * (x0 - x2) + (x2 - x1) * (y0 - y2); + if (fabsf(denominator) < 0.0001f) continue; + const float a = ((y1 - y2) * (localX - x2) + (x2 - x1) * (localY - y2)) / denominator; + const float b = ((y2 - y0) * (localX - x2) + (x0 - x2) * (localY - y2)) / denominator; + const float c = 1.0f - a - b; + if (a < -0.001f || b < -0.001f || c < -0.001f) continue; + const float depth = (a * triangle.p[0].z + b * triangle.p[1].z + c * triangle.p[2].z) * face; + if (depth >= 0.0f) bestDepth = fmaxf(bestDepth, depth); + } + if (found != nullptr) *found = bestDepth != -FLT_MAX; + return bestDepth != -FLT_MAX ? bestDepth : 12.0f; +} + +float ShutterHandSurfaceDepth(const DoorShutter* door, float centerX, float centerY, float face, + bool renderFlipped, float halfWidth, float halfLength) { + const float modelFace = renderFlipped ? -face : face; + const auto sampleDepth = [&](float x, float y, bool* found = nullptr) { + return ShutterSurfaceDepth(door, renderFlipped ? -x : x, y, modelFace, found); + }; + + // Constrain the entire open-hand footprint, not only its centreline. Five rows cover the wrist, + // palm and fingertips; three columns cover both outside fingers. Taking the outermost surface + // prevents any part of the planar hand pose from entering curved or decorated replacement doors. + float requiredDepth = sampleDepth(centerX, centerY); + constexpr float across[] = { -1.0f, 0.0f, 1.0f }; + constexpr float along[] = { -1.0f, -0.5f, 0.0f, 0.5f, 1.0f }; + for (float xFactor : across) { + for (float yFactor : along) { + bool found = false; + const float depth = sampleDepth(centerX + xFactor * halfWidth, + centerY + yFactor * halfLength, &found); + if (found) requiredDepth = fmaxf(requiredDepth, depth); + } + } + return requiredDepth; +} + +constexpr float kShutterReleaseLiftMeters = 0.30f; + +bool ShutterLiftEligible(const DoorShutter* door) { + return door != nullptr && door->gfxType != 3 && door->doorType != SHUTTER_PG_BARS && + door->doorType != SHUTTER_GOHMA_BLOCK && door->unlockTimer == 0 && + door->barsClosedAmount <= 0.001f; +} + +float ShutterGrabHalfWidth(const DoorShutter* door) { + if (door == nullptr) return 0.0f; + if (door->gfxType == 2) return 70.0f; // Dodongo's Cavern stone shutter + if (door->gfxType == 6 || door->gfxType == 7) return 50.0f; // Spirit and Boss shutters + // The remaining temple/Ganon shutters have a visibly broad slab as well. The former 30-unit + // half-width restricted both hands to a narrow strip around the centre; on doors such as the + // Light Trial shutter, reaching naturally for its two sides could never enter either zone. + return 50.0f; +} + +float ShutterRaisedHeight(const DoorShutter* door) { + return door != nullptr && door->doorType == SHUTTER_BOSS ? kBossShutterRaisedHeight : 200.0f; +} + +float WorldScale() { + const float ws = VR_GetWorldScale(); + return ws < 1.0f ? 35.0f : ws; +} + +float HingeOffset() { + return CVarGetFloat("gVrDoorHingeOffset", 27.0f); +} + +void Axes(const EnDoor* door, float right[3], float normal[3]) { + const float s = Math_SinS(door->actor.shape.rot.y), c = Math_CosS(door->actor.shape.rot.y); + right[0] = c; right[1] = 0.0f; right[2] = -s; + normal[0] = s; normal[1] = 0.0f; normal[2] = c; +} + +float PlayerSide(const EnDoor* door, const Player* player) { + float r[3], n[3]; Axes(door, r, n); + const float d = (player->actor.world.pos.x - door->actor.world.pos.x) * n[0] + + (player->actor.world.pos.z - door->actor.world.pos.z) * n[2]; + return d >= 0.0f ? 1.0f : -1.0f; +} + +float EyeDistanceXZ(const EnDoor* door, const PlayState* play) { + const float dx = play->view.eye.x - door->actor.world.pos.x; + const float dz = play->view.eye.z - door->actor.world.pos.z; + return sqrtf(dx * dx + dz * dz); +} + +void HandlePoint(const EnDoor* door, float side, float face, float out[3]) { + float r[3], n[3]; Axes(door, r, n); + // Match the side-specific face display list: positive calibration means the visually right + // side of the door from whichever face the player is standing on. + float localX = CVarGetFloat("gVrDoorHandleRight", 23.0f) * side; + float localZ = CVarGetFloat("gVrDoorHandleDepth", 3.0f) * face; + if (sDoor == door && sAngle != 0) { + const float a = sAngle * (2.0f * kPi / 65536.0f); + const float hingeOffset = HingeOffset(); + const float hingeX = localX >= 0.0f ? -hingeOffset : hingeOffset; + const float relX = localX - hingeX; + const float rotatedX = relX * cosf(a) + localZ * sinf(a); + localZ = -relX * sinf(a) + localZ * cosf(a); + localX = hingeX + rotatedX; + } + out[0] = door->actor.world.pos.x + r[0] * localX + n[0] * localZ; + out[1] = door->actor.world.pos.y + CVarGetFloat("gVrDoorHandleY", 38.0f); + out[2] = door->actor.world.pos.z + r[2] * localX + n[2] * localZ; +} + +bool HandPosition(int hand, float out[3]) { + float q[4]; + return VR_GetHandPose(hand, out, q); +} + +bool HandPose(int hand, float outPos[3], float outQuat[4]) { + return VR_GetHandPose(hand, outPos, outQuat); +} + +bool HandMarkerDistance(int hand, const float marker[3], float* outDistance) { + float m[4][4]; + if (!VR_GetHandMatrix(hand, m)) { + float p[3]; + if (!HandPosition(hand, p)) return false; + const float dx = p[0] - marker[0], dy = p[1] - marker[1], dz = p[2] - marker[2]; + *outDistance = sqrtf(dx * dx + dy * dy + dz * dz); + return true; + } + const float len = VrHand_ChildSized() ? 548.0f : 862.0f; + float bestSq = 1e30f; + for (int i = 0; i <= 2; ++i) { + const float x = len * 0.5f * i; + const float p[3] = { m[0][0] * x + m[3][0], m[0][1] * x + m[3][1], m[0][2] * x + m[3][2] }; + const float dx = p[0] - marker[0], dy = p[1] - marker[1], dz = p[2] - marker[2]; + bestSq = fminf(bestSq, dx * dx + dy * dy + dz * dz); + } + *outDistance = sqrtf(bestSq); + return true; +} + +float HandTurnDeg(int hand) { + float p[3], q[4]; + if (!HandPose(hand, p, q)) return 0.0f; + float dot = fabsf(q[0] * sStartQuat[0] + q[1] * sStartQuat[1] + q[2] * sStartQuat[2] + q[3] * sStartQuat[3]); + dot = fmaxf(0.0f, fminf(1.0f, dot)); + return 2.0f * acosf(dot) * (180.0f / kPi); +} + +float HandPolar(const EnDoor* door, int hand, float side) { + float p[3], right[3], normal[3]; + if (!HandPosition(hand, p)) return 0.0f; + Axes(door, right, normal); + const float handleX = CVarGetFloat("gVrDoorHandleRight", 23.0f) * side; + const float hingeOffset = HingeOffset(); + const float hingeLocal = handleX >= 0.0f ? -hingeOffset : hingeOffset; + const float hingeX = door->actor.world.pos.x + right[0] * hingeLocal; + const float hingeZ = door->actor.world.pos.z + right[2] * hingeLocal; + const float x = (p[0] - hingeX) * right[0] + (p[2] - hingeZ) * right[2]; + const float z = (p[0] - hingeX) * normal[0] + (p[2] - hingeZ) * normal[2]; + return atan2f(z, x); +} + +bool Eligible(const EnDoor* door, PlayState* play, Player* player) { + const int type = (door->actor.params >> 7) & 7; + return CVarGetInteger("gVrPhysicalDoors", 1) && VR_IsInitialized() && VR_GetFirstPerson() && + !VR_IsFlatScreen() && CVarGetInteger("gVrMotionHands", 1) && + (type == DOOR_ROOMLOAD || type == DOOR_ROOMLOAD2 || type == DOOR_ROOMLOAD7 || type == DOOR_SCENEEXIT || + type == DOOR_LOCKED) && + door->lockTimer == 0 && play->csCtx.state == CS_STATE_IDLE && + play->transitionTrigger == TRANS_TRIGGER_OFF && !(player->stateFlags1 & + (PLAYER_STATE1_ON_HORSE | PLAYER_STATE1_IN_WATER | PLAYER_STATE1_DEAD)); +} + +void Clear() { + sDoor = nullptr; sHand = -1; sUnlatched = false; sRoomRequested = false; sPassagePending = false; + sPassageCommitted = false; sAngle = 0; + sPullRefValid = false; sOpenSoundPlayed = false; sCloseSoundPlayed = false; + sPrevPlaneDistance = 1e30f; + sNear[0] = sNear[1] = false; + sHingeTransition = {}; +} + +void ClearAllDoorState() { + Clear(); + sCandidate = nullptr; + sJabuDoor = sJabuLatchDoor = nullptr; + sJabuNear[0] = sJabuNear[1] = false; + sJabuLatched[0] = sJabuLatched[1] = false; + sShutterCandidate = sShutterDoor = sShutterLatchDoor = sShutterStreamDoor = sShutterJustClosedDoor = nullptr; + sShutterClosingRenderDoor = sShutterPreservedEntryUnlockDoor = nullptr; + sShutterLatched[0] = sShutterLatched[1] = false; + sShutterHandState[0] = {}; + sShutterHandState[1] = {}; + sShutterPrevHoverDoor[0] = sShutterPrevHoverDoor[1] = nullptr; + sShutterFrameHandValid[0] = sShutterFrameHandValid[1] = false; + sShutterPrevHandValid[0] = sShutterPrevHandValid[1] = false; + sShutterRoomRequested = sShutterFullyOpen = sShutterLiftArmed = sShutterCloseRollbackPending = false; + sShutterCloseForNextDoor = false; + sShutterTransition = {}; +} + +void ForgetDestroyedDoor(Actor* actor) { + if (actor == nullptr) return; + if (actor == reinterpret_cast(sDoor)) Clear(); + if (actor == reinterpret_cast(sCandidate)) sCandidate = nullptr; + if (actor == reinterpret_cast(sJabuDoor)) sJabuDoor = nullptr; + if (actor == reinterpret_cast(sJabuLatchDoor)) sJabuLatchDoor = nullptr; + if (actor == reinterpret_cast(sShutterCandidate)) sShutterCandidate = nullptr; + if (actor == reinterpret_cast(sShutterDoor)) sShutterDoor = nullptr; + if (actor == reinterpret_cast(sShutterJustClosedDoor)) sShutterJustClosedDoor = nullptr; + if (actor == reinterpret_cast(sShutterClosingRenderDoor)) sShutterClosingRenderDoor = nullptr; + if (actor == reinterpret_cast(sShutterPreservedEntryUnlockDoor)) { + sShutterPreservedEntryUnlockDoor = nullptr; + } + for (int hand = 0; hand < 2; ++hand) { + if (actor == reinterpret_cast(sShutterHandState[hand].door)) sShutterHandState[hand] = {}; + if (actor == reinterpret_cast(sShutterPrevHoverDoor[hand])) sShutterPrevHoverDoor[hand] = nullptr; + } + if (actor == reinterpret_cast(sShutterStreamDoor)) { + sShutterStreamDoor = nullptr; + sShutterRoomRequested = false; + } + if (actor == sHingeTransition.owner) sHingeTransition = {}; + if (actor == sShutterTransition.owner) sShutterTransition = {}; + if (actor == reinterpret_cast(sShutterLatchDoor)) { + sShutterLatchDoor = nullptr; + sShutterFullyOpen = sShutterLiftArmed = sShutterCloseRollbackPending = false; + sShutterCloseForNextDoor = false; + } +} + +void CaptureGrabOffset(const EnDoor* door, int hand, float side) { + float handPos[3], handle[3], right[3], normal[3]; + if (!HandPosition(hand, handPos)) return; + HandlePoint(door, sHandleSide, sKnobFace, handle); + Axes(door, right, normal); + const float d[3] = { handPos[0] - handle[0], handPos[1] - handle[1], handPos[2] - handle[2] }; + sGrabOffsetLocal[0] = d[0] * right[0] + d[2] * right[2]; + sGrabOffsetLocal[1] = d[1]; + sGrabOffsetLocal[2] = d[0] * normal[0] + d[2] * normal[2]; +} + +void Grab(EnDoor* door, int hand, float side, float face, const float quat[4], bool preserveAngle) { + sDoor = door; sHand = hand; sSide = side; sUnlatched = false; + if (!preserveAngle) sDisplaySide = side; + sHandleSide = sNearHandleSide[hand]; + sKnobFace = face; + if (!preserveAngle) sAngle = 0; + for (int i = 0; i < 4; ++i) sStartQuat[i] = quat[i]; + sPullRefValid = false; + sCloseSoundPlayed = false; + CaptureGrabOffset(door, hand, side); + sPrevPlaneDistance = 1e30f; + VR_TriggerHaptic(hand, 0.35f, 0.0f, 25.0f); +} + +void RequestRoom(EnDoor* door, PlayState* play, Player* player); + +void AssistWalkThrough(EnDoor* door, PlayState* play, Player* player) { + float right[3], normal[3]; Axes(door, right, normal); + const float dx = player->actor.world.pos.x - door->actor.world.pos.x; + const float dz = player->actor.world.pos.z - door->actor.world.pos.z; + const float across = dx * normal[0] + dz * normal[2]; + const float lateral = dx * right[0] + dz * right[2]; + const float distance = fabsf(across); + + // Approaching the open centre starts streaming the adjacent room. Once it is ready, the local + // wall-collision aperture below lets the player cross under their own locomotion. + if (sPrevPlaneDistance < 1e20f && distance < sPrevPlaneDistance - 0.02f && distance < 36.0f && + fabsf(lateral) < 24.0f) { + sPassagePending = true; + } + if (sPassagePending && !sRoomRequested) { + RequestRoom(door, play, player); + } + if (sPassagePending && sRoomRequested && play->roomCtx.status == 0 && PlayerSide(door, player) != sSide) { + sPassageCommitted = true; + } + sPrevPlaneDistance = distance; +} + +void RequestRoom(EnDoor* door, PlayState* play, Player* player) { + sRoomRequested = BeginDoorwayTransition(sHingeTransition, &door->actor, play, sSide, true); +} + +void ResolveLoadedRooms(EnDoor* door, PlayState* play, Player* player) { + if (!sRoomRequested || play->roomCtx.status != 0) return; + FinishDoorwayTransition(sHingeTransition, play, PlayerSide(door, player), true); + sRoomRequested = false; +} + +void BeginShutterInputFrame(PlayState* play) { + if (play == nullptr || sShutterInputFrame == play->state.frames) return; + sShutterInputFrame = play->state.frames; + if (sShutterLatchDoor == nullptr) sShutterCandidate = nullptr; + for (int hand = 0; hand < 2; ++hand) { + const ShutterHandState previous = sShutterHandState[hand]; + const bool previousFrame = previous.frame != UINT32_MAX && previous.frame + 1 == play->state.frames; + sShutterPrevHoverDoor[hand] = + previousFrame && previous.active && !previous.latched ? previous.door : nullptr; + sShutterPrevHoverFace[hand] = previous.surfaceFace; + sShutterHandState[hand] = {}; + sShutterHandState[hand].frame = play->state.frames; + sShutterGripNow[hand] = (VR_GetControllerButton(hand) & VR_BTN_GRIP) != 0; + if (sShutterFrameHandValid[hand]) { + memcpy(sShutterPrevHandPos[hand], sShutterFrameHandPos[hand], sizeof(sShutterPrevHandPos[hand])); + sShutterPrevHandValid[hand] = true; + } + sShutterFrameHandValid[hand] = HandPosition(hand, sShutterFrameHandPos[hand]); + if (!sShutterPrevHandValid[hand] && sShutterFrameHandValid[hand]) { + memcpy(sShutterPrevHandPos[hand], sShutterFrameHandPos[hand], sizeof(sShutterPrevHandPos[hand])); + sShutterPrevHandValid[hand] = true; + } + } +} + +} // namespace + +extern "C" bool VrJabuDoor_Tick(DoorShutter* door, PlayState* play) { + if (door == nullptr || play == nullptr || door->gfxType != 3 || + !CVarGetInteger("gVrPhysicalDoors", 1) || !VR_IsInitialized() || !VR_GetFirstPerson() || + VR_IsFlatScreen() || !CVarGetInteger("gVrMotionHands", 1) || play->csCtx.state != CS_STATE_IDLE) { + if (sJabuDoor == door) sJabuDoor = nullptr; + if (sJabuLatchDoor == door) sJabuLatchDoor = nullptr; + sJabuNear[0] = sJabuNear[1] = false; + sJabuLatched[0] = sJabuLatched[1] = false; + return false; + } + if ((sJabuLatchDoor != nullptr && sJabuLatchDoor != door) || + (sShutterLatchDoor != nullptr && sShutterLatchDoor != door)) return false; + + // Jabu and rigid shutters share the rendered open-palm state. Initialize that state before + // either actor class writes it; otherwise an actor from the newly preloaded adjacent room can + // reset the membrane's hover later in this same update frame, before Player_Draw consumes it. + BeginShutterInputFrame(play); + + Player* player = GET_PLAYER(play); + const float s = Math_SinS(door->dyna.actor.shape.rot.y); + const float c = Math_CosS(door->dyna.actor.shape.rot.y); + const float pdx = player->actor.world.pos.x - door->dyna.actor.world.pos.x; + const float pdz = player->actor.world.pos.z - door->dyna.actor.world.pos.z; + const float entrySide = (pdx * s + pdz * c) >= 0.0f ? 1.0f : -1.0f; + + // Match ordinary physical doors: proximity owns room streaming, while physical contact alone + // owns opening. This removes loading latency from the touch without activating the membrane. + if (!sShutterTransition.requested && door->dyna.actor.xzDistToPlayer < 90.0f && + BeginDoorwayTransition(sShutterTransition, &door->dyna.actor, play, entrySide, false)) { + sShutterEntryRoom = sShutterTransition.entryRoom; + sJabuDoor = door; + sShutterStreamDoor = door; + sShutterRoomRequested = true; + sShutterEntrySide = entrySide; + } + + bool grabbed = false; + for (int hand = 0; hand < 2; ++hand) { + float handMtx[4][4]; + if (!VR_GetHandMatrix(hand, handMtx)) { + sJabuNear[hand] = false; + sJabuLatched[hand] = false; + continue; + } + const float originX = handMtx[3][0]; + const float originY = handMtx[3][1]; + const float originZ = handMtx[3][2]; + const float originDx = originX - door->dyna.actor.world.pos.x; + const float originDz = originZ - door->dyna.actor.world.pos.z; + const float originLocalX = originDx * c - originDz * s; + const float originLocalY = originY - door->dyna.actor.world.pos.y; + const float originLocalZ = originDx * s + originDz * c; + const float length = VrHand_ChildSized() ? 548.0f : 862.0f; + const float tipX = handMtx[3][0] + handMtx[0][0] * length; + const float tipY = handMtx[3][1] + handMtx[0][1] * length; + const float tipZ = handMtx[3][2] + handMtx[0][2] * length; + const float tipDx = tipX - door->dyna.actor.world.pos.x; + const float tipDz = tipZ - door->dyna.actor.world.pos.z; + const float tipLocalX = tipDx * c - tipDz * s; + const float tipLocalY = tipY - door->dyna.actor.world.pos.y; + const float tipLocalZ = tipDx * s + tipDz * c; + + // Treat the rendered hand as a continuous wrist-to-fingertip segment. The previous three + // point samples could straddle this thin plane (for example +40 and -40) without either + // point entering the 28-unit hover band, even though the visible palm crossed the flesh. + const float segmentZ = tipLocalZ - originLocalZ; + const float planeT = fabsf(segmentZ) > 0.0001f + ? fmaxf(0.0f, fminf(1.0f, -originLocalZ / segmentZ)) + : 0.5f; + float contactX = originLocalX + (tipLocalX - originLocalX) * planeT; + float contactY = originLocalY + (tipLocalY - originLocalY) * planeT; + float contactZ = originLocalZ + segmentZ * planeT; + + // If the closest point to the plane misses the round membrane, test a dense set along the + // visible mesh and retain the valid point nearest the plane. This also covers a hand lying + // almost parallel against the membrane rather than pointing through it. + // The closed iris is eight petals translated roughly 80-99 model units away from the + // centre before rotation. Its visible/contactable surface therefore spans the complete + // doorway, not merely the small central overlap where the petal tips meet. + constexpr float kMembraneRadius = 180.0f; + constexpr float kMembraneHoverDepth = 36.0f; + bool insideMembrane = false; + float closest = FLT_MAX; + for (int point = 0; point <= 10; ++point) { + const float t = point == 0 ? planeT : (point - 1) * 0.1f; + const float x = originLocalX + (tipLocalX - originLocalX) * t; + const float y = originLocalY + (tipLocalY - originLocalY) * t; + const float z = originLocalZ + segmentZ * t; + const float radialX = x / kMembraneRadius; + const float radialY = (y - 80.0f) / kMembraneRadius; + if (radialX * radialX + radialY * radialY <= 1.0f && fabsf(z) < closest) { + insideMembrane = true; + closest = fabsf(z); + contactX = x; + contactY = y; + contactZ = z; + } + } + const bool isNear = insideMembrane && fabsf(contactZ) <= kMembraneHoverDepth; + sJabuNear[hand] = isNear; + sJabuLatched[hand] = isNear && sShutterGripNow[hand]; + if (!isNear) continue; + + // Keep the contact on the player's side even after the controller penetrates the thin + // mathematical plane. Deriving the face from contactZ made the pinned hand jump through + // the membrane as soon as that value crossed zero. + const float face = entrySide; + ShutterHandState& state = sShutterHandState[hand]; + state.door = door; + state.frame = play->state.frames; + state.active = true; + state.latched = sJabuLatched[hand]; + state.score = fabsf(contactZ); + state.localX = contactX; + state.localY = contactY; + const float clearance = state.latched ? kShutterGrabClearance : kShutterHoverOffset; + const float handAxisScale = sqrtf(handMtx[0][0] * handMtx[0][0] + handMtx[0][1] * handMtx[0][1] + + handMtx[0][2] * handMtx[0][2]); + const float handHalfLength = handAxisScale * length * 0.5f; + const float radialDistance = + sqrtf(contactX * contactX + (contactY - 80.0f) * (contactY - 80.0f)) + handHalfLength; + const float radialAmount = fmaxf(0.0f, fminf(1.0f, radialDistance / kMembraneRadius)); + // The iris petals bow toward the player away from their central overlap. Follow that + // contour quadratically and use the palm's outer edge, not just its centre, so the lower + // fingers cannot disappear into the curved membrane. + const float membraneDepth = 20.0f * radialAmount * radialAmount; + state.localZ = originLocalZ + (face * (clearance + membraneDepth) - contactZ); + state.surfaceFace = face; + state.visualFace = face; + if (state.latched) grabbed = true; + } + + if (!grabbed) { + // Release a completed proximity preload if the player walks away without touching. + if (sJabuDoor == door && sJabuLatchDoor != door && door->dyna.actor.xzDistToPlayer > 130.0f && + play->roomCtx.status == 0) { + FinishDoorwayTransition(sShutterTransition, play, sShutterEntrySide, false); + sJabuDoor = nullptr; + sShutterStreamDoor = nullptr; + sShutterRoomRequested = false; + } + return false; + } + + if (!BeginDoorwayTransition(sShutterTransition, &door->dyna.actor, play, entrySide, false)) { + return false; + } + sJabuDoor = door; + sJabuLatchDoor = door; + sShutterStreamDoor = door; + sShutterRoomRequested = true; + sShutterEntrySide = entrySide; + sShutterEntryRoom = sShutterTransition.entryRoom; + for (int hand = 0; hand < 2; ++hand) { + if (sJabuLatched[hand]) VR_TriggerHaptic(hand, 0.3f, 0.0f, 25.0f); + } + // From this point the membrane uses the same open/cross/close lifecycle as every rigid shutter. + // Start the visible iris response immediately; collision passage remains gated separately on + // both completed room loading and sufficient visual retraction. + sShutterLatchDoor = door; + sShutterFullyOpen = true; + sShutterCloseRollbackPending = false; + return true; +} + +extern "C" void VrJabuDoor_Cancel(DoorShutter* door, PlayState* play) { + if (door == nullptr || play == nullptr) return; + if (sJabuDoor != door && sJabuLatchDoor != door) return; + if (sShutterTransition.owner == &door->dyna.actor && sShutterTransition.requested) { + if (play->roomCtx.status != 0) return; + FinishDoorwayTransition(sShutterTransition, play, sShutterEntrySide, false); + } + if (sShutterStreamDoor == door) { + sShutterStreamDoor = nullptr; + sShutterRoomRequested = false; + } + if (sShutterLatchDoor == door) { + sShutterLatchDoor = nullptr; + sShutterFullyOpen = false; + sShutterCloseRollbackPending = false; + sShutterCloseForNextDoor = false; + } + if (sShutterCandidate == door) sShutterCandidate = nullptr; + if (sShutterDoor == door) sShutterDoor = nullptr; + for (int hand = 0; hand < 2; ++hand) { + if (sShutterHandState[hand].door == door) sShutterHandState[hand] = {}; + } + sJabuDoor = nullptr; + sJabuLatchDoor = nullptr; + sJabuNear[0] = sJabuNear[1] = false; + sJabuLatched[0] = sJabuLatched[1] = false; +} + +extern "C" bool VrJabuDoor_GripConsumed(int32_t hand, uint16_t mask) { + return (mask & VR_BTN_GRIP) && hand >= 0 && hand < 2 && (sJabuNear[hand] || sJabuLatched[hand]); +} + +extern "C" int32_t VrShutter_Tick(DoorShutter* door, PlayState* play) { + Player* player = play != nullptr ? GET_PLAYER(play) : nullptr; + const bool ownsActivePreload = door != nullptr && door == sShutterLatchDoor && door == sShutterStreamDoor && + sShutterRoomRequested && !sShutterFullyOpen; + const bool eligible = player != nullptr && (ShutterLiftEligible(door) || ownsActivePreload) && + CVarGetInteger("gVrPhysicalDoors", 1) && + VR_IsInitialized() && VR_GetFirstPerson() && !VR_IsFlatScreen() && + CVarGetInteger("gVrMotionHands", 1) && play->csCtx.state == CS_STATE_IDLE && + play->transitionTrigger == TRANS_TRIGGER_OFF; + if (!eligible) { + if (sShutterCandidate == door) sShutterCandidate = nullptr; + if (sShutterDoor == door) sShutterDoor = nullptr; + // Door_Shutter actors update independently. An unrelated locked/barred/special shutter + // must never clear the hands attached to the active shutter merely because *it* is not + // eligible. Central dispatch made that old global cleanup run for every shutter and broke + // lifting immediately after a successful grab. + if (sShutterLatchDoor == door && !sShutterFullyOpen) { + sShutterLatchDoor = nullptr; + sShutterLatched[0] = sShutterLatched[1] = false; + sShutterHandState[0] = {}; + sShutterHandState[1] = {}; + sShutterLiftArmed = false; + } + return false; + } + // Destination room setup may try to bar its entrance as soon as it is preloaded. The player + // has not crossed yet, and this exact shutter was already valid when grabbed, so defer that + // lock-behind state until the physical close on the destination side. + if (ownsActivePreload) door->barsClosedAmount = 0.0f; + if (sShutterLatchDoor != nullptr && sShutterLatchDoor != door) { + // The room system can safely retain only the two rooms around one physical doorway. In a + // short room Link may reach the next shutter before the previous one's distance threshold. + // Ask the crossed shutter to close instead of making this new one appear permanently inert. + if (sShutterFullyOpen && door->dyna.actor.xzDistToPlayer < 100.0f) sShutterCloseForNextDoor = true; + return false; + } + + // Every shutter actor ticks independently. Sample grip edges once per game frame so a distant + // shutter cannot consume the press before the door under the player's hands sees it. + BeginShutterInputFrame(play); + + // Releasing a grabbed door before lifting it restores the room the player still occupies. + // This is a streaming operation, not a physical close, so it deliberately has no door sound. + if (sShutterRoomRequested && sShutterStreamDoor == door && !sShutterFullyOpen && + !sShutterLatched[0] && !sShutterLatched[1] && + play->roomCtx.status == 0) { + FinishDoorwayTransition(sShutterTransition, play, sShutterEntrySide, false); + sShutterRoomRequested = false; + sShutterStreamDoor = nullptr; + sShutterCandidate = nullptr; + sShutterLatchDoor = nullptr; + sShutterLiftArmed = false; + sShutterCloseForNextDoor = false; + return false; + } + + const float sn = Math_SinS(door->dyna.actor.shape.rot.y); + const float cs = Math_CosS(door->dyna.actor.shape.rot.y); + const float pdx = player->actor.world.pos.x - door->dyna.actor.world.pos.x; + const float pdz = player->actor.world.pos.z - door->dyna.actor.world.pos.z; + const float playerAcross = pdx * sn + pdz * cs; + // Use the shutter actor's own side resolver whenever it has an answer. It includes the native + // facing/distance rules and therefore reflects the actor's initialized orientation rather + // than duplicating constructor assumptions in the VR layer. + const float bodyFace = playerAcross >= 0.0f ? 1.0f : -1.0f; + + float handY[2] = {}; + bool grip[2] = {}; + const float grabHalfWidth = ShutterGrabHalfWidth(door); + for (int hand = 0; hand < 2; ++hand) { + const float* p = sShutterFrameHandPos[hand]; + if (!sShutterFrameHandValid[hand]) { + continue; + } + const float dx = p[0] - door->dyna.actor.world.pos.x; + const float dz = p[2] - door->dyna.actor.world.pos.z; + const float localX = dx * cs - dz * sn; + const float localZ = dx * sn + dz * cs; + const float localY = p[1] - door->dyna.actor.world.pos.y; + float contactX = localX, contactY = localY, contactZ = localZ; + float handHalfLength = (VrHand_ChildSized() ? 548.0f : 862.0f) * 0.005f * VrHand_ScaleFactor(); + float handMtx[4][4]; + if (VR_GetHandMatrix(hand, handMtx)) { + const float len = VrHand_ChildSized() ? 548.0f : 862.0f; + const float handScale = sqrtf(handMtx[0][0] * handMtx[0][0] + handMtx[0][1] * handMtx[0][1] + + handMtx[0][2] * handMtx[0][2]); + handHalfLength = handScale * len * 0.5f; + float best = fabsf(localZ); + for (int point = 0; point < 3; ++point) { + const float along = len * 0.5f * point; + const float px = handMtx[3][0] + handMtx[0][0] * along; + const float py = handMtx[3][1] + handMtx[0][1] * along; + const float pz = handMtx[3][2] + handMtx[0][2] * along; + const float pdx = px - door->dyna.actor.world.pos.x; + const float pdz = pz - door->dyna.actor.world.pos.z; + const float lx = pdx * cs - pdz * sn; + const float lz = pdx * sn + pdz * cs; + const float ly = py - door->dyna.actor.world.pos.y; + if (fabsf(lx) <= grabHalfWidth && ly >= 20.0f && ly <= 125.0f && fabsf(lz) < best) { + best = fabsf(lz); + contactX = lx; contactY = ly; contactZ = lz; + } + } + } + handY[hand] = p[1]; + const bool isNear = fabsf(contactX) <= grabHalfWidth && fabsf(contactZ) <= 28.0f && + contactY >= 20.0f && contactY <= 125.0f; + const float eyeDx = play->view.eye.x - door->dyna.actor.world.pos.x; + const float eyeDz = play->view.eye.z - door->dyna.actor.world.pos.z; + const float visualFace = (eyeDx * sn + eyeDz * cs) >= 0.0f ? 1.0f : -1.0f; + // On first contact, use the hand's previous-frame position relative to this exact door. + // This records the side from which the hand crossed into the hover zone before current- + // frame penetration can reverse it, and is rotationally invariant for every shutter yaw. + float hoverFace = bodyFace; + if (sShutterPrevHoverDoor[hand] == door) { + hoverFace = sShutterPrevHoverFace[hand]; + } else if (isNear) { + float approachFace = bodyFace; + float prevLocalZ = localZ; + if (sShutterPrevHandValid[hand]) { + const float prevDx = sShutterPrevHandPos[hand][0] - door->dyna.actor.world.pos.x; + const float prevDz = sShutterPrevHandPos[hand][2] - door->dyna.actor.world.pos.z; + prevLocalZ = prevDx * sn + prevDz * cs; + if (fabsf(prevLocalZ) > 0.5f) approachFace = prevLocalZ >= 0.0f ? 1.0f : -1.0f; + } + hoverFace = approachFace; + } + grip[hand] = sShutterGripNow[hand]; + if (sShutterLatchDoor == door && sShutterLatched[hand] && !grip[hand]) { + sShutterLatched[hand] = false; + } + + // A latched hand always owns its visual state. Otherwise accumulate the closest valid + // shutter for this hand; a later, distant actor may never overwrite it with "not near". + if (sShutterLatchDoor == door && sShutterLatched[hand]) { + ShutterHandState& state = sShutterHandState[hand]; + state.door = door; + state.frame = play->state.frames; + state.active = true; + state.latched = true; + state.score = 0.0f; + state.localX = sShutterGrabLocal[hand][0]; + state.localY = sShutterGrabLocal[hand][1]; + state.localZ = sShutterGrabFace[hand]; + state.surfaceFace = sShutterGrabFace[hand] >= 0.0f ? 1.0f : -1.0f; + state.visualFace = state.surfaceFace; + } else if (isNear && (sShutterLatchDoor == nullptr || sShutterLatchDoor == door) && + fabsf(contactZ) < sShutterHandState[hand].score) { + ShutterHandState& state = sShutterHandState[hand]; + state.door = door; + state.frame = play->state.frames; + state.active = true; + state.latched = false; + state.score = fabsf(contactZ); + state.localX = contactX; + state.localY = contactY; + const bool renderFlipped = VrShutter_RenderFlipped(door, play); + const float surfaceDepth = ShutterHandSurfaceDepth(door, contactX, contactY, hoverFace, + renderFlipped, handHalfLength * 0.45f, + handHalfLength); + const float surfaceZ = hoverFace * surfaceDepth; + // Preserve the measured offset from the hand transform to the sampled hand point. + // Placing the transform itself on the surface makes most of the rendered palm pass + // through the slab, especially when the closest sample is near the fingertips. + state.localZ = localZ + (surfaceZ + hoverFace * kShutterHoverOffset - contactZ); + state.surfaceFace = hoverFace; + state.visualFace = visualFace; + sShutterCandidate = door; + } + + // Grip only the owner resolved on the previous completed frame. This one-frame handover + // removes actor-order dependence when two shutters share a compact room. + if (!sShutterLatched[hand] && grip[hand] && isNear && sShutterPrevHoverDoor[hand] == door && + (sShutterLatchDoor == nullptr || sShutterLatchDoor == door)) { + sShutterLatchDoor = door; + sShutterCandidate = door; + sShutterLatched[hand] = true; + sShutterLatchSide[hand] = contactX >= 0.0f ? 1.0f : -1.0f; + // Hover just above the face, then let the palm settle slightly into it on grip so the + // contact reads as weight-bearing instead of floating or passing through the slab. + const bool renderFlipped = VrShutter_RenderFlipped(door, play); + const float surfaceDepth = ShutterHandSurfaceDepth(door, contactX, contactY, hoverFace, + renderFlipped, handHalfLength * 0.45f, + handHalfLength); + const float surfaceZ = hoverFace * surfaceDepth; + sShutterGrabFace[hand] = + localZ + (surfaceZ + hoverFace * kShutterGrabClearance - contactZ); + sShutterGrabLocal[hand][0] = localX; + sShutterGrabLocal[hand][1] = localY; + ShutterHandState& state = sShutterHandState[hand]; + state.door = door; + state.frame = play->state.frames; + state.active = true; + state.latched = true; + state.score = 0.0f; + state.localX = localX; + state.localY = localY; + state.localZ = sShutterGrabFace[hand]; + state.surfaceFace = sShutterGrabFace[hand] >= 0.0f ? 1.0f : -1.0f; + state.visualFace = state.surfaceFace; + VR_TriggerHaptic(hand, 0.3f, 0.0f, 25.0f); + } + } + + // A room preload belongs exclusively to the shutter the player actually grabbed. Proximity + // alone is not sufficient: several shutters can coexist in compact dungeon rooms and used to + // overwrite this global interaction state, producing flicker and incomplete openings. + if (sShutterLatchDoor == door && !sShutterRoomRequested && play->roomCtx.status == 0 && + play->roomCtx.prevRoom.num < 0) { + const float entrySide = playerAcross >= 0.0f ? 1.0f : -1.0f; + if (BeginDoorwayTransition(sShutterTransition, &door->dyna.actor, play, entrySide, false)) { + sShutterEntryRoom = sShutterTransition.entryRoom; + sShutterRoomRequested = true; + sShutterStreamDoor = door; + sShutterEntrySide = entrySide; + } + } + + const int transitionIndex = GET_TRANSITION_ACTOR_INDEX(&door->dyna.actor); + const TransitionActorEntry* transitionEntry = &play->transiActorCtx.list[transitionIndex]; + const int adjacentRoom = transitionEntry->sides[0].room == play->roomCtx.curRoom.num + ? transitionEntry->sides[1].room + : transitionEntry->sides[0].room; + const bool needsAdjacentRoom = adjacentRoom >= 0 && adjacentRoom != play->roomCtx.curRoom.num; + + // Any two points on the slab form a valid lift. Requiring opposite halves made the grip + // needlessly dependent on the player's hand spacing and was unlike the climbing interaction. + const bool holding = sShutterLatched[0] && sShutterLatched[1] && grip[0] && grip[1]; + if (!holding) { + // A comfortable 30 cm two-handed lift commits the interaction. Releasing either grip + // then hands control back to the native shutter action, which smoothly finishes raising + // the full-height slab instead of requiring the player to lift it over their head. + if (sShutterLiftArmed) { + door->dyna.actor.velocity.y = 1.0f; + sShutterFullyOpen = true; + sShutterLiftArmed = false; + VR_TriggerHaptic(VR_HAND_LEFT, 0.75f, 0.0f, 45.0f); + VR_TriggerHaptic(VR_HAND_RIGHT, 0.75f, 0.0f, 45.0f); + sShutterDoor = nullptr; + sShutterLatched[0] = sShutterLatched[1] = false; + return 2; + } + // Keep ownership while an abandoned preload finishes; the rollback above resolves it on + // the next tick. Otherwise another nearby shutter could inherit the wrong room request. + if (!sShutterLatched[0] && !sShutterLatched[1] && !sShutterRoomRequested) sShutterLatchDoor = nullptr; + sShutterDoor = nullptr; + return (sShutterLatched[0] || sShutterLatched[1]) ? 1 : 0; + } + + const float meanY = (handY[0] + handY[1]) * 0.5f; + // Capture the physical lift origin immediately, including while the destination room is still + // streaming. Previously sShutterDoor was deliberately cleared during loading, which discarded + // all hand travel made in that interval and made some shutters appear to stop partway open. + if (sShutterDoor != door) { + sShutterDoor = door; + sShutterStartMeanY = meanY; + sShutterStartHeight = door->dyna.actor.world.pos.y; + sShutterEntrySide = playerAcross >= 0.0f ? 1.0f : -1.0f; + sShutterLiftArmed = false; + } + + + // Never reveal an unloaded doorway. If another engine transition temporarily owns the room + // context, retain the two-hand grip and retry rather than allowing the slab to expose a void. + if (needsAdjacentRoom && (!sShutterRoomRequested || sShutterStreamDoor != door)) return 1; + + // Keep both hands attached while the destination loads, but do not begin moving the slab yet. + // Once ready, all hand travel since the initial two-hand grip is applied in one safe step. + if (sShutterRoomRequested && sShutterStreamDoor == door && play->roomCtx.status != 0) { + return 1; + } + + // Hand travel is amplified 3x below so Link can raise a full-height slab comfortably. Match + // the release threshold to 30 cm of resulting door travel, not 30 cm of controller travel. + if (meanY - sShutterStartMeanY >= WorldScale() * kShutterReleaseLiftMeters / 3.0f) { + sShutterLiftArmed = true; + } + + // The slab is taller than Link, so a comfortable full overhead lift must move the complete + // door rather than demanding several metres of real hand travel. + const float raisedHeight = ShutterRaisedHeight(door); + const float target = fmaxf(door->dyna.actor.home.pos.y, + fminf(door->dyna.actor.home.pos.y + raisedHeight, + sShutterStartHeight + (meanY - sShutterStartMeanY) * 3.0f)); + if (target > door->dyna.actor.world.pos.y && + door->dyna.actor.world.pos.y <= door->dyna.actor.home.pos.y + 1.0f) { + Audio_PlayActorSound2(&door->dyna.actor, NA_SE_EV_SLIDE_DOOR_OPEN); + } + door->dyna.actor.world.pos.y = target; + + if (target >= door->dyna.actor.home.pos.y + raisedHeight - 5.0f) { + door->dyna.actor.world.pos.y = door->dyna.actor.home.pos.y + raisedHeight; + door->dyna.actor.velocity.y = 1.0f; + sShutterFullyOpen = true; + sShutterLiftArmed = false; + VR_TriggerHaptic(VR_HAND_LEFT, 0.75f, 0.0f, 45.0f); + VR_TriggerHaptic(VR_HAND_RIGHT, 0.75f, 0.0f, 45.0f); + sShutterDoor = nullptr; + sShutterLatched[0] = sShutterLatched[1] = false; + return 2; + } + return 1; +} + +extern "C" bool VrShutter_GripConsumed(int32_t hand, uint16_t mask) { + const bool hovering = hand >= 0 && hand < 2 && gPlayState != nullptr && + sShutterHandState[hand].frame == gPlayState->state.frames && + sShutterHandState[hand].active; + return (mask & VR_BTN_GRIP) && hand >= 0 && hand < 2 && + (sShutterLatched[hand] || hovering || sShutterDoor != nullptr); +} + +extern "C" bool VrShutter_HoldsHand(int32_t hand) { + // Mesh selection and pinning consume this same resolved state; neither performs another hit test. + return hand >= 0 && hand < 2 && gPlayState != nullptr && !sShutterFullyOpen && + sShutterHandState[hand].frame == gPlayState->state.frames && sShutterHandState[hand].active; +} + +extern "C" bool VrShutter_KeepOpen(DoorShutter* door, PlayState* play) { + if (door == nullptr || play == nullptr || door != sShutterLatchDoor || !sShutterFullyOpen) return false; + Player* player = GET_PLAYER(play); + const float sn = Math_SinS(door->dyna.actor.shape.rot.y); + const float cs = Math_CosS(door->dyna.actor.shape.rot.y); + const float dx = player->actor.world.pos.x - door->dyna.actor.world.pos.x; + const float dz = player->actor.world.pos.z - door->dyna.actor.world.pos.z; + const float side = (dx * sn + dz * cs) >= 0.0f ? 1.0f : -1.0f; + if (side == sShutterEntrySide) { + if (door->dyna.actor.xzDistToPlayer < 140.0f) return true; + // The player opened the shutter but walked away on the side they started from. Let the + // native action close it first; only the closed-position callback may unload the visible + // destination room and its retained object bank. + sShutterCloseRollbackPending = true; + sShutterCandidate = nullptr; + sShutterLiftArmed = false; + sShutterHandState[0] = {}; + sShutterHandState[1] = {}; + sShutterLatched[0] = sShutterLatched[1] = false; + sShutterClosingRenderDoor = door; + sShutterClosingRenderFlipped = VrShutter_RenderFlipped(door, play); + return false; + } + if (sShutterCloseForNextDoor) { + sShutterCloseRollbackPending = true; + sShutterCandidate = nullptr; + sShutterLiftArmed = false; + sShutterHandState[0] = {}; + sShutterHandState[1] = {}; + sShutterLatched[0] = sShutterLatched[1] = false; + sShutterClosingRenderDoor = door; + sShutterClosingRenderFlipped = VrShutter_RenderFlipped(door, play); + return false; + } + if (door->dyna.actor.xzDistToPlayer < 70.0f) return true; + // Close the slab before releasing either room. FinishClose keeps whichever side Link actually + // occupies then, so turning around during the close can never expose an unloaded void. + sShutterCloseRollbackPending = true; + sShutterCandidate = nullptr; + sShutterLiftArmed = false; + sShutterHandState[0] = {}; + sShutterHandState[1] = {}; + sShutterLatched[0] = sShutterLatched[1] = false; + sShutterClosingRenderDoor = door; + sShutterClosingRenderFlipped = VrShutter_RenderFlipped(door, play); + return false; +} + +extern "C" bool VrShutter_IsPhysicalClosePending(DoorShutter* door) { + return door != nullptr && door == sShutterLatchDoor && sShutterFullyOpen && + sShutterCloseRollbackPending; +} + +extern "C" int32_t VrShutter_GetPhysicalCloseRoom(DoorShutter* door, PlayState* play) { + if (!VrShutter_IsPhysicalClosePending(door) || play == nullptr || sShutterEntryRoom < 0) return -1; + Player* player = GET_PLAYER(play); + const float sn = Math_SinS(door->dyna.actor.shape.rot.y); + const float cs = Math_CosS(door->dyna.actor.shape.rot.y); + const float dx = player->actor.world.pos.x - door->dyna.actor.world.pos.x; + const float dz = player->actor.world.pos.z - door->dyna.actor.world.pos.z; + const float closeSide = (dx * sn + dz * cs) >= 0.0f ? 1.0f : -1.0f; + if (closeSide == sShutterEntrySide) return sShutterEntryRoom; + const TransitionActorEntry* entry = + &play->transiActorCtx.list[GET_TRANSITION_ACTOR_INDEX(&door->dyna.actor)]; + return entry->sides[0].room == sShutterEntryRoom ? entry->sides[1].room : entry->sides[0].room; +} + +extern "C" bool VrShutter_GetClosingRenderFlipped(const DoorShutter* door, bool* flipped) { + if (door == nullptr || flipped == nullptr || door != sShutterClosingRenderDoor) return false; + *flipped = sShutterClosingRenderFlipped; + return true; +} + +extern "C" void VrShutter_FinishClose(DoorShutter* door, PlayState* play) { + if (door == nullptr || play == nullptr || door != sShutterLatchDoor || !sShutterCloseRollbackPending) return; + Player* player = GET_PLAYER(play); + const float sn = Math_SinS(door->dyna.actor.shape.rot.y); + const float cs = Math_CosS(door->dyna.actor.shape.rot.y); + const float dx = player->actor.world.pos.x - door->dyna.actor.world.pos.x; + const float dz = player->actor.world.pos.z - door->dyna.actor.world.pos.z; + const float closeSide = (dx * sn + dz * cs) >= 0.0f ? 1.0f : -1.0f; + int closeRoom = sShutterEntryRoom; + if (closeSide != sShutterEntrySide) { + const TransitionActorEntry* entry = + &play->transiActorCtx.list[GET_TRANSITION_ACTOR_INDEX(&door->dyna.actor)]; + closeRoom = entry->sides[0].room == sShutterEntryRoom ? entry->sides[1].room : entry->sides[0].room; + } + if (sShutterRoomRequested && play->roomCtx.status == 0 && play->roomCtx.prevRoom.num >= 0) { + FinishDoorwayTransition(sShutterTransition, play, closeSide, false); + } + // If Link backed away and the shutter returned to the side where an unlock condition had + // already made it physically usable, do not let room streaming transiently revoke that earned + // state. Crossing the doorway deliberately does not preserve it: the destination side keeps + // its native lock-behind/bar rule. + sShutterPreservedEntryUnlockDoor = closeSide == sShutterEntrySide ? door : nullptr; + door->dyna.actor.room = play->roomCtx.curRoom.num; + sShutterJustClosedDoor = door; + sShutterLatchDoor = nullptr; + sShutterCandidate = nullptr; + sShutterFullyOpen = false; + sShutterLiftArmed = false; + sShutterRoomRequested = false; + sShutterStreamDoor = nullptr; + sShutterCloseRollbackPending = false; + sShutterCloseForNextDoor = false; + sShutterClosingRenderDoor = nullptr; + if (sJabuDoor == door || sJabuLatchDoor == door) { + sJabuDoor = sJabuLatchDoor = nullptr; + sJabuNear[0] = sJabuNear[1] = false; + sJabuLatched[0] = sJabuLatched[1] = false; + } +} + +extern "C" bool VrShutter_ConsumePhysicalClose(DoorShutter* door) { + if (door == nullptr || door != sShutterJustClosedDoor) return false; + sShutterJustClosedDoor = nullptr; + return true; +} + +extern "C" bool VrShutter_ConsumePreservedEntryUnlock(DoorShutter* door) { + if (door == nullptr || door != sShutterPreservedEntryUnlockDoor) return false; + sShutterPreservedEntryUnlockDoor = nullptr; + return true; +} + +extern "C" float VrShutter_OpenHeight(DoorShutter* door) { + return door != nullptr && door == sShutterLatchDoor && sShutterFullyOpen ? ShutterRaisedHeight(door) : 200.0f; +} + +extern "C" bool VrShutter_PinnedHandMatrix(Player* player, int32_t hand, float* mf16) { + if (player == nullptr || mf16 == nullptr || hand < 0 || hand > 1 || + gPlayState == nullptr || player != GET_PLAYER(gPlayState) || sShutterFullyOpen) return false; + const ShutterHandState& state = sShutterHandState[hand]; + if (!state.active || state.frame != gPlayState->state.frames || state.door == nullptr) return false; + DoorShutter* door = state.door; + const float sn = Math_SinS(door->dyna.actor.shape.rot.y); + const float cs = Math_CosS(door->dyna.actor.shape.rot.y); + const auto placeOpenPalm = [&](float localX, float localY, float localZ, float orientationSide) { + const float sx = sqrtf(mf16[0] * mf16[0] + mf16[1] * mf16[1] + mf16[2] * mf16[2]); + const float sy = sqrtf(mf16[4] * mf16[4] + mf16[5] * mf16[5] + mf16[6] * mf16[6]); + const float sz = sqrtf(mf16[8] * mf16[8] + mf16[9] * mf16[9] + mf16[10] * mf16[10]); + // The open-hand display lists use local Y from wrist to fingertips, so map Y to world-up. + // This proper half-turn seats the controller-native hand mesh on the selected face. + const float palmTurn = hand == VR_HAND_LEFT ? 1.0f : -1.0f; + mf16[0] = orientationSide * palmTurn * cs * sx; + mf16[1] = 0.0f; + mf16[2] = -orientationSide * palmTurn * sn * sx; + mf16[4] = 0.0f; + mf16[5] = sy; + mf16[6] = 0.0f; + mf16[8] = orientationSide * palmTurn * sn * sz; + mf16[9] = 0.0f; + mf16[10] = orientationSide * palmTurn * cs * sz; + + const float halfLength = (VrHand_ChildSized() ? 548.0f : 862.0f) * 0.5f; + mf16[12] = door->dyna.actor.world.pos.x + localX * cs + localZ * sn; + mf16[13] = door->dyna.actor.world.pos.y + localY - sy * halfLength; + mf16[14] = door->dyna.actor.world.pos.z - localX * sn + localZ * cs; + }; + // Hover detection already resolved the exact door, point and faces during the actor update. + // Reusing that result guarantees the open mesh and the pinned pose cannot disagree. + const float orientationSide = state.latched ? state.surfaceFace : state.visualFace; + placeOpenPalm(state.localX, state.localY, state.localZ, orientationSide); + return true; +} + +extern "C" bool VrDoor_Tick(EnDoor* door, PlayState* play) { + Player* player = GET_PLAYER(play); + sTickFrame = play->state.frames; + // EnDoor_Tick runs once per door actor. Sample edge state only once per game frame so whichever + // door happens to update first cannot consume the fresh press before the nearby door sees it. + if (sInputFrame != sTickFrame) { + sInputFrame = sTickFrame; + sCandidate = nullptr; + for (int h = 0; h < 2; ++h) { + sGripNow[h] = (VR_GetControllerButton(h) & VR_BTN_GRIP) != 0; + sGripFresh[h] = sGripNow[h] && !sGripPrev[h]; + sGripPrev[h] = sGripNow[h]; + } + } + + if (!Eligible(door, play, player)) { + if (sDoor == door) { + // Do not discard ownership while a synchronous room request is between request and + // completion. Once ready, resolve from Link's real side before leaving physical mode. + if (sRoomRequested && play->roomCtx.status != 0) return true; + ResolveLoadedRooms(door, play, player); + Clear(); + } + if (sCandidate == door) sCandidate = nullptr; + return false; + } + if (sDoor != nullptr && sDoor != door) return false; + if (sDoor == nullptr && door->actor.xzDistToPlayer >= 70.0f && EyeDistanceXZ(door, play) >= 70.0f) return false; + + const float side = sDoor == door ? sSide : PlayerSide(door, player); + if (sDoor == nullptr) { + const int type = (door->actor.params >> 7) & 7; + // At arm's length the VR eye can see through the small clearance between the leaf and its + // frame. Preload the adjoining room as soon as a room-loading door enters interaction range + // so that clearance reveals real geometry instead of the void. Keep scene-exit doors on the + // stock transition path, and do not disturb a room transition already owned by the engine. + if (type != DOOR_SCENEEXIT && play->roomCtx.status == 0 && play->roomCtx.prevRoom.num < 0) { + sSide = side; + sDisplaySide = side; + RequestRoom(door, play, player); + if (sRoomRequested) { + sDoor = door; + } + } + } + if (sDoor == nullptr) sCandidate = door; + for (int h = 0; h < 2; ++h) { + float bestDistance = 1e30f; + for (int faceIndex = 0; faceIndex < 2; ++faceIndex) { + const float face = faceIndex == 0 ? side : -side; + // Front and back knobs share the same physical spindle and therefore the same leaf edge. + // The actor's local +X edge is the handle edge. A paired leaf is already rotated 180° + // when spawned, so this remains correct for both halves and from either room. + const float handleSide = 1.0f; + float handle[3], distance; + HandlePoint(door, handleSide, face, handle); + if (HandMarkerDistance(h, handle, &distance) && distance < bestDistance) { + bestDistance = distance; + sNearFace[h] = face; + sNearHandleSide[h] = handleSide; + } + } + sNear[h] = bestDistance / WorldScale() * 100.0f <= CVarGetFloat("gVrDoorGrabRadius", 18.0f); + } + + if (sDoor == nullptr) { + for (int h = 0; h < 2; ++h) { + float handPos[3], handQuat[4]; + if (sGripFresh[h] && sNear[h] && HandPose(h, handPos, handQuat)) { + Grab(door, h, side, sNearFace[h], handQuat, false); + break; + } + } + return sDoor == door; + } + + // Keep the display face stable while Link is within the doorway plane; update it only after his + // body is clearly on one side. The headset may cross this plane repeatedly at arm's length. + { + float right[3], normal[3]; Axes(door, right, normal); + const float dx = player->actor.world.pos.x - door->actor.world.pos.x; + const float dz = player->actor.world.pos.z - door->actor.world.pos.z; + const float across = dx * normal[0] + dz * normal[2]; + if (fabsf(across) > 8.0f) sDisplaySide = across >= 0.0f ? 1.0f : -1.0f; + } + + // Crossing is a geometric fact, not a side effect of the streaming helper. Detect it on every + // tick once the adjacent room is ready so automatic closing cannot be missed. + const int doorType = (door->actor.params >> 7) & 7; + if (doorType == DOOR_SCENEEXIT && sHand < 0 && + fabsf(sAngle * (360.0f / 65536.0f)) >= kExitDeg && PlayerSide(door, player) != sSide) { + float right[3], normal[3]; Axes(door, right, normal); + const float dx = player->actor.world.pos.x - door->actor.world.pos.x; + const float dz = player->actor.world.pos.z - door->actor.world.pos.z; + if (fabsf(dx * right[0] + dz * right[2]) < 28.0f) { + // The separate destination scene cannot coexist with this one. Hand the transition to + // the original entrance/exit logic only after Link has physically crossed the opening. + Vec3f checkPos = player->actor.world.pos; + checkPos.y = door->actor.world.pos.y + 10.0f; + CollisionPoly* groundPoly = nullptr; + BgCheck_EntityRaycastFloor1(&play->colCtx, &groundPoly, &checkPos); + if (groundPoly != nullptr && Player_HandleExitsAndVoids(play, player, groundPoly, BGCHECK_SCENE)) { + gSaveContext.entranceSpeed = 2.0f; + gSaveContext.entranceSound = NA_SE_OC_DOOR_OPEN; + door->jointTable[3].z = 0; + Clear(); + return false; + } + } + } + if (sRoomRequested && play->roomCtx.status == 0 && PlayerSide(door, player) != sSide) { + float right[3], normal[3]; Axes(door, right, normal); + const float dx = player->actor.world.pos.x - door->actor.world.pos.x; + const float dz = player->actor.world.pos.z - door->actor.world.pos.z; + if (fabsf(dx * right[0] + dz * right[2]) < 18.0f) { + sPassageCommitted = true; + } + } + + if (sHand < 0) { + // An opened physical door stays where the player left it. This both matches a real hinged + // door and leaves the doorway usable; it may be grabbed again at its moved handle. + for (int h = 0; h < 2; ++h) { + float handPos[3], handQuat[4]; + if (sGripFresh[h] && sNear[h] && HandPose(h, handPos, handQuat)) { + Grab(door, h, sSide, sNearFace[h], handQuat, true); + break; + } + } + if (sHand < 0 && fabsf(sAngle * (360.0f / 65536.0f)) >= kWalkThroughDeg) { + AssistWalkThrough(door, play, player); + } + if (sHand < 0) { + float right[3], normal[3]; Axes(door, right, normal); + const float dx = player->actor.world.pos.x - door->actor.world.pos.x; + const float dz = player->actor.world.pos.z - door->actor.world.pos.z; + const float across = fabsf(dx * normal[0] + dz * normal[2]); + const bool clearedAfterPassage = sPassageCommitted && across > 20.0f; + const bool abandonedOnOriginalSide = !sPassageCommitted && door->actor.xzDistToPlayer > 120.0f && + EyeDistanceXZ(door, play) > 120.0f; + // Close after a completed passage, or when Link changes his mind and walks away on the + // original side. ResolveLoadedRooms keeps whichever side he actually occupies. + if (clearedAfterPassage || abandonedOnOriginalSide) { + constexpr int kAutoCloseStep = 0x300; + // A proximity preload can own sDoor while the leaf is still closed. Resolving that + // unused preload is not a door action and must remain silent. + if (!sCloseSoundPlayed && (sOpenSoundPlayed || sAngle != 0)) { + Audio_PlayActorSound2(&door->actor, + (play->sceneNum == SCENE_SHADOW_TEMPLE || play->sceneNum == SCENE_BOTTOM_OF_THE_WELL || + play->sceneNum == SCENE_FIRE_TEMPLE) ? NA_SE_EV_IRON_DOOR_CLOSE : NA_SE_EV_DOOR_CLOSE); + sCloseSoundPlayed = true; + } + if (abs(sAngle) <= kAutoCloseStep) { + sAngle = 0; + door->jointTable[3].z = 0; + ResolveLoadedRooms(door, play, player); + door->actor.room = play->roomCtx.curRoom.num; + if (door->actor.child != nullptr) door->actor.child->room = play->roomCtx.curRoom.num; + if (door->actor.parent != nullptr) door->actor.parent->room = play->roomCtx.curRoom.num; + Clear(); + return false; + } + sAngle += sAngle > 0 ? -kAutoCloseStep : kAutoCloseStep; + door->jointTable[3].z = sAngle; + } + } + return true; + } + + if (!sGripNow[sHand]) { + sHand = -1; + sPrevPlaneDistance = 1e30f; + if (abs(sAngle) < 0x180) { + door->jointTable[3].z = 0; + if (sOpenSoundPlayed) { + Audio_PlayActorSound2(&door->actor, + (play->sceneNum == SCENE_SHADOW_TEMPLE || play->sceneNum == SCENE_BOTTOM_OF_THE_WELL || + play->sceneNum == SCENE_FIRE_TEMPLE) ? NA_SE_EV_IRON_DOOR_CLOSE : NA_SE_EV_DOOR_CLOSE); + } + // Keep both rooms and both sets of actors alive after passage. Closing the physical + // door is the commit point that releases the room behind the player. + ResolveLoadedRooms(door, play, player); + if (sRoomRequested) { + door->actor.room = play->roomCtx.curRoom.num; + if (door->actor.child != nullptr) door->actor.child->room = play->roomCtx.curRoom.num; + if (door->actor.parent != nullptr) door->actor.parent->room = play->roomCtx.curRoom.num; + } + Clear(); + return false; + } + door->jointTable[3].z = sAngle; + return true; + } + + if (!sUnlatched) { + if (HandTurnDeg(sHand) >= kTurnDeg) { + sUnlatched = true; + sPullStartRad = HandPolar(door, sHand, sHandleSide); + sPullStartDeg = sAngle * (360.0f / 65536.0f); + sPullRefValid = true; + VR_TriggerHaptic(sHand, 0.75f, 0.0f, 45.0f); + } + return true; + } + + if (sPullRefValid) { + float delta = HandPolar(door, sHand, sHandleSide) - sPullStartRad; + while (delta > kPi) delta -= 2.0f * kPi; + while (delta < -kPi) delta += 2.0f * kPi; + // The skeleton's hinge channel turns opposite the controller's polar motion. The gain also + // maps OoT's oversized 60-unit leaf to a comfortable real-world arm arc. + float deg = sPullStartDeg - delta * (180.0f / kPi) * CVarGetFloat("gVrDoorSwingGain", 1.75f); + deg = fmaxf(-kMaxOpenDeg, fminf(kMaxOpenDeg, deg)); + sAngle = (s16)(deg * (65536.0f / 360.0f)); + door->jointTable[3].z = sAngle; + + const float openDeg = fabsf(deg); + const int type = (door->actor.params >> 7) & 7; + if (!sOpenSoundPlayed && openDeg >= 3.0f) { + Audio_PlayActorSound2(&door->actor, + (play->sceneNum == SCENE_SHADOW_TEMPLE || play->sceneNum == SCENE_BOTTOM_OF_THE_WELL || + play->sceneNum == SCENE_FIRE_TEMPLE) ? NA_SE_EV_IRON_DOOR_OPEN : NA_SE_OC_DOOR_OPEN); + sOpenSoundPlayed = true; + } + // Stream the destination as soon as a normal physical door visibly begins to swing. The + // engine retains the old room as prevRoom, so both geometries and actor sets coexist until + // the automatic close commits the transition. + if (type != DOOR_SCENEEXIT && !sRoomRequested && openDeg >= 3.0f) { + RequestRoom(door, play, player); + } + // Scene exits stay physically open here. Their stock entrance transition is requested only + // after Link crosses the doorway plane (above), never merely because the leaf opened. + } + + return true; +} + +extern "C" bool VrDoor_GripConsumed(int32_t hand, uint16_t mask) { + if (!(mask & VR_BTN_GRIP) || hand < 0 || hand > 1 || gPlayState == nullptr) return false; + if ((uint32_t)gPlayState->state.frames - sTickFrame > 2) return false; + return (sDoor != nullptr && sHand == hand) || sNear[hand]; +} + +extern "C" bool VrDoor_KeepPreviousRoomActors(void) { + const bool ordinaryDoorStreaming = sDoor != nullptr && sRoomRequested; + const bool shutterStreaming = + (sShutterCandidate != nullptr || sShutterLatchDoor != nullptr || sJabuDoor != nullptr) && + sShutterRoomRequested; + return (ordinaryDoorStreaming || shutterStreaming) && gPlayState != nullptr && + CVarGetInteger("gVrPhysicalDoors", 1) && VR_IsInitialized() && !VR_IsFlatScreen(); +} + +extern "C" bool VrDoor_IsPhysicalRoomRequest(void) { + return sPhysicalRoomRequest && CVarGetInteger("gVrPhysicalDoors", 1) && VR_IsInitialized() && + !VR_IsFlatScreen(); +} + +extern "C" int32_t VrDoor_EnvironmentBehaviorType2(PlayState* play) { + if (play != nullptr && sRoomRequested && !sPassageCommitted && play->roomCtx.prevRoom.num >= 0 && + CVarGetInteger("gVrPhysicalDoors", 1) && VR_IsInitialized() && !VR_IsFlatScreen()) { + // Room_Request makes the preloaded destination curRoom immediately. Until Link actually + // crosses the doorway, environmental effects must still come from the room he occupies. + return play->roomCtx.prevRoom.behaviorType2; + } + if (play != nullptr && sShutterRoomRequested && !sShutterFullyOpen && play->roomCtx.prevRoom.num >= 0 && + CVarGetInteger("gVrPhysicalDoors", 1) && VR_IsInitialized() && !VR_IsFlatScreen()) { + return play->roomCtx.prevRoom.behaviorType2; + } + return play != nullptr ? play->roomCtx.curRoom.behaviorType2 : 0; +} + +extern "C" bool VrDoor_IsPhysicalActive(EnDoor* door) { + if (door == nullptr || sDoor == nullptr || !CVarGetInteger("gVrPhysicalDoors", 1) || + !VR_IsInitialized() || VR_IsFlatScreen()) { + return false; + } + return door == sDoor || sDoor->actor.child == &door->actor || sDoor->actor.parent == &door->actor; +} + +extern "C" bool VrDoor_StableFaceView(EnDoor* door, float* outPos3) { + if (door == nullptr || outPos3 == nullptr || sDoor != door) return false; + float right[3], normal[3]; Axes(door, right, normal); + outPos3[0] = door->actor.world.pos.x + normal[0] * sDisplaySide * 100.0f; + outPos3[1] = door->actor.world.pos.y + 40.0f; + outPos3[2] = door->actor.world.pos.z + normal[2] * sDisplaySide * 100.0f; + return true; +} + +extern "C" bool VrDoor_AllowsWallPass(Actor* actor, const float* nextPos3, const float* prevPos3) { + if (actor == nullptr || nextPos3 == nullptr || prevPos3 == nullptr || gPlayState == nullptr || + actor != &GET_PLAYER(gPlayState)->actor) { + return false; + } + if (sShutterLatchDoor != nullptr && sShutterFullyOpen && sShutterRoomRequested && gPlayState->roomCtx.status == 0 && + // Jabu's ownership becomes active before its ten-frame iris animation. Keep the scene wall + // solid until the membrane is substantially retracted instead of walking through its image. + (sShutterLatchDoor->gfxType != 3 || sShutterLatchDoor->jabuDoorClosedAmount <= 20)) { + const float sn = Math_SinS(sShutterLatchDoor->dyna.actor.shape.rot.y); + const float cs = Math_CosS(sShutterLatchDoor->dyna.actor.shape.rot.y); + const float* points[2] = { nextPos3, prevPos3 }; + for (int i = 0; i < 2; ++i) { + const float dx = points[i][0] - sShutterLatchDoor->dyna.actor.world.pos.x; + const float dz = points[i][2] - sShutterLatchDoor->dyna.actor.world.pos.z; + const float lateral = dx * cs - dz * sn; + const float across = dx * sn + dz * cs; + // Cover the full boss-door opening and a complete movement sweep, while remaining + // local enough that neighboring walls retain their collision. + if (fabsf(lateral) < 65.0f && fabsf(across) < 100.0f) return true; + } + } + if (sDoor == nullptr || sHand >= 0) return false; + const int type = (sDoor->actor.params >> 7) & 7; + const float requiredOpen = type == DOOR_SCENEEXIT ? kExitDeg : kWalkThroughDeg; + if ((type != DOOR_SCENEEXIT && (!sRoomRequested || gPlayState->roomCtx.status != 0)) || + fabsf(sAngle * (360.0f / 65536.0f)) < requiredOpen) return false; + float right[3], normal[3]; Axes(sDoor, right, normal); + const float* points[2] = { nextPos3, prevPos3 }; + for (int i = 0; i < 2; ++i) { + const float dx = points[i][0] - sDoor->actor.world.pos.x; + const float dz = points[i][2] - sDoor->actor.world.pos.z; + const float lateral = dx * right[0] + dz * right[2]; + const float across = dx * normal[0] + dz * normal[2]; + const float y = points[i][1] - sDoor->actor.world.pos.y; + if (fabsf(lateral) < 24.0f && fabsf(across) < 40.0f && y > -8.0f && y < 80.0f) { + return true; + } + } + return false; +} + +extern "C" void VrDoor_ConstrainPlayerToLeaf(Actor* actor) { + if (actor == nullptr || sDoor == nullptr || gPlayState == nullptr || + actor != &GET_PLAYER(gPlayState)->actor || fabsf(sAngle * (360.0f / 65536.0f)) < 3.0f) { + return; + } + const float relY = actor->world.pos.y - sDoor->actor.world.pos.y; + if (relY < -8.0f || relY > 80.0f) return; + + float right[3], normal[3]; Axes(sDoor, right, normal); + const float handleX = CVarGetFloat("gVrDoorHandleRight", 23.0f); + const float hingeOffset = HingeOffset(); + const float hingeLocal = handleX >= 0.0f ? -hingeOffset : hingeOffset; + const float leafDir = handleX >= 0.0f ? 1.0f : -1.0f; + const float a = sAngle * (2.0f * kPi / 65536.0f); + const float hx = sDoor->actor.world.pos.x + right[0] * hingeLocal; + const float hz = sDoor->actor.world.pos.z + right[2] * hingeLocal; + const float ex = hx + right[0] * (leafDir * 2.0f * hingeOffset * cosf(a)) + + normal[0] * (-leafDir * 2.0f * hingeOffset * sinf(a)); + const float ez = hz + right[2] * (leafDir * 2.0f * hingeOffset * cosf(a)) + + normal[2] * (-leafDir * 2.0f * hingeOffset * sinf(a)); + const float sx = ex - hx, sz = ez - hz; + const float lengthSq = sx * sx + sz * sz; + if (lengthSq < 0.001f) return; + float t = ((actor->world.pos.x - hx) * sx + (actor->world.pos.z - hz) * sz) / lengthSq; + t = fmaxf(0.0f, fminf(1.0f, t)); + const float cx = hx + sx * t, cz = hz + sz * t; + float dx = actor->world.pos.x - cx, dz = actor->world.pos.z - cz; + float distance = sqrtf(dx * dx + dz * dz); + constexpr float kPlayerLeafRadius = 8.0f; + if (distance >= kPlayerLeafRadius) return; + if (distance < 0.001f) { + dx = -sz; + dz = sx; + if ((actor->prevPos.x - cx) * dx + (actor->prevPos.z - cz) * dz < 0.0f) { + dx = -dx; dz = -dz; + } + distance = sqrtf(dx * dx + dz * dz); + } + const float push = (kPlayerLeafRadius - distance) / distance; + actor->world.pos.x += dx * push; + actor->world.pos.z += dz * push; +} + +extern "C" bool VrDoor_PinnedHandMatrix(Player* player, int32_t hand, float* mf16) { + if (mf16 == nullptr || hand < 0 || hand > 1 || sDoor == nullptr || sHand != hand || + gPlayState == nullptr || player != GET_PLAYER(gPlayState) || !sGripNow[hand]) { + return false; + } + float handle[3], right[3], normal[3]; + HandlePoint(sDoor, sHandleSide, sKnobFace, handle); + Axes(sDoor, right, normal); + const float a = sAngle * (2.0f * kPi / 65536.0f); + const float localX = sGrabOffsetLocal[0] * cosf(a) + sGrabOffsetLocal[2] * sinf(a); + const float localZ = -sGrabOffsetLocal[0] * sinf(a) + sGrabOffsetLocal[2] * cosf(a); + mf16[12] = handle[0] + right[0] * localX + normal[0] * localZ; + mf16[13] = handle[1] + sGrabOffsetLocal[1]; + mf16[14] = handle[2] + right[2] * localX + normal[2] * localZ; + return true; +} + +// Two miniature Deku Nuts expose the independent knob zones on the front and back faces. +extern "C" void VrDoor_DrawHandleMarker(void) { + if (gPlayState == nullptr || (sCandidate == nullptr && sDoor == nullptr) || + !CVarGetInteger("gVrPhysicalDoors", 1) || !CVarGetInteger("gVrDoorShowGrabMarkers", 1)) return; + Player* player = GET_PLAYER(gPlayState); + EnDoor* markerDoor = sDoor != nullptr ? sDoor : sCandidate; + if (player == nullptr || markerDoor->actor.xzDistToPlayer >= 70.0f) return; + const float side = sDoor != nullptr ? sSide : PlayerSide(markerDoor, player); + + OPEN_DISPS(gPlayState->state.gfxCtx); + for (int faceIndex = 0; faceIndex < 2; ++faceIndex) { + const float face = faceIndex == 0 ? side : -side; + float anchor[3]; + HandlePoint(markerDoor, 1.0f, face, anchor); + FrameInterpolation_RecordOpenChild((const void*)&sCandidate, faceIndex); + Matrix_Translate(anchor[0], anchor[1], anchor[2], MTXMODE_NEW); + Matrix_ReplaceRotation(&gPlayState->billboardMtxF); + float scale = 0.0045f; + if (sNear[0] || sNear[1]) scale *= 1.4f; + Matrix_Scale(scale, scale, scale, MTXMODE_APPLY); + POLY_OPA_DISP = Play_SetFog(gPlayState, POLY_OPA_DISP); + POLY_OPA_DISP = Gfx_SetupDL_66(POLY_OPA_DISP); + gSPSegment(POLY_OPA_DISP++, 0x08, (uintptr_t)SEGMENTED_TO_VIRTUAL(gDropDekuNutTex)); + gSPMatrix(POLY_OPA_DISP++, MATRIX_NEWMTX(gPlayState->state.gfxCtx), G_MTX_MODELVIEW | G_MTX_LOAD); + gSPDisplayList(POLY_OPA_DISP++, (Gfx*)gItemDropDL); + FrameInterpolation_RecordCloseChild(); + } + CLOSE_DISPS(gPlayState->state.gfxCtx); +} + +namespace { +void RegisterVrDoor() { + COND_HOOK(OnPlayDrawEnd, true, VrDoor_DrawHandleMarker); + COND_HOOK(OnSceneInit, true, [](int16_t) { + ClearAllDoorState(); + VrDoor_ResetRetainedObjects(); + }); + COND_HOOK(OnActorDestroy, true, [](void* actor) { ForgetDestroyedDoor(static_cast(actor)); }); +} +static RegisterShipInitFunc initVrDoor(RegisterVrDoor); +} diff --git a/soh/soh/Enhancements/vr-combat/VrGerudoDoor.cpp b/soh/soh/Enhancements/vr-combat/VrGerudoDoor.cpp new file mode 100644 index 00000000000..fd6d0ff42d7 --- /dev/null +++ b/soh/soh/Enhancements/vr-combat/VrGerudoDoor.cpp @@ -0,0 +1,285 @@ +extern "C" { +#include "z64.h" +#include "macros.h" +#include "functions.h" +#include "overlays/actors/ovl_Door_Gerudo/z_door_gerudo.h" +extern PlayState* gPlayState; +} + +#include "VrCombat.h" +#include "soh/Enhancements/game-interactor/GameInteractor.h" +#include "soh/ShipInit.hpp" +#include +#include +#include +#include +#include + +// Gerudo Fortress cell grates are not Door_Shutter actors, but physically they are the same +// interaction: two hands may grab anywhere on the unlocked slab and lift it vertically. The +// DoorGerudo actor remains responsible for the small-key cost, save switch and final open state. +namespace { + +constexpr float kHalfWidth = 52.0f; +constexpr float kGrabMinY = 22.0f; +constexpr float kGrabMaxY = 145.0f; +constexpr float kHoverDepth = 28.0f; +constexpr float kRaisedHeight = 200.0f; +constexpr float kReleaseLiftMeters = 0.30f; + +struct HandState { + DoorGerudo* door = nullptr; + uint32_t frame = 0; + bool active = false; + bool latched = false; + float score = 1e30f; + float localX = 0.0f; + float localY = 0.0f; + float localZ = 0.0f; + float face = 1.0f; +}; + +DoorGerudo* sDoor = nullptr; +HandState sHands[2]; +bool sGripNow[2] = {}; +bool sGripPrev[2] = { true, true }; +bool sGripFresh[2] = {}; +uint32_t sInputFrame = UINT32_MAX; +float sStartMeanY = 0.0f; +float sStartHeight = 0.0f; +bool sMoving = false; +bool sLiftArmed = false; +bool sSoundPlayed = false; + +float WorldScale() { + const float scale = VR_GetWorldScale(); + return scale < 1.0f ? 35.0f : scale; +} + +void Clear() { + sDoor = nullptr; + sHands[0] = {}; + sHands[1] = {}; + sMoving = false; + sLiftArmed = false; + sSoundPlayed = false; +} + +void BeginInputFrame(PlayState* play) { + if (sInputFrame == play->state.frames) return; + sInputFrame = play->state.frames; + for (int hand = 0; hand < 2; ++hand) { + sGripNow[hand] = (VR_GetControllerButton(hand) & VR_BTN_GRIP) != 0; + sGripFresh[hand] = sGripNow[hand] && !sGripPrev[hand]; + sGripPrev[hand] = sGripNow[hand]; + if (!sHands[hand].latched) sHands[hand] = {}; + } +} + +bool Eligible(DoorGerudo* door, PlayState* play) { + if (door == nullptr || play == nullptr || !CVarGetInteger("gVrPhysicalDoors", 1) || + !VR_IsInitialized() || !VR_GetFirstPerson() || VR_IsFlatScreen() || + !CVarGetInteger("gVrMotionHands", 1) || play->csCtx.state != CS_STATE_IDLE || + play->transitionTrigger != TRANS_TRIGGER_OFF || door->unk_166 != 0) { + return false; + } + Player* player = GET_PLAYER(play); + return player != nullptr && !(player->stateFlags1 & + (PLAYER_STATE1_ON_HORSE | PLAYER_STATE1_IN_WATER | PLAYER_STATE1_DEAD | + PLAYER_STATE1_IN_CUTSCENE)); +} + +bool HandContact(DoorGerudo* door, int hand, float* localX, float* localY, float* localZ, + float* handY, float* face) { + float matrix[4][4]; + if (!VR_GetHandMatrix(hand, matrix)) return false; + *handY = matrix[3][1]; + const float sn = Math_SinS(door->dyna.actor.shape.rot.y); + const float cs = Math_CosS(door->dyna.actor.shape.rot.y); + const float length = VrHand_ChildSized() ? 548.0f : 862.0f; + float best = 1e30f; + bool found = false; + for (int point = 0; point < 3; ++point) { + const float along = length * 0.5f * point; + const float px = matrix[3][0] + matrix[0][0] * along; + const float py = matrix[3][1] + matrix[0][1] * along; + const float pz = matrix[3][2] + matrix[0][2] * along; + const float dx = px - door->dyna.actor.world.pos.x; + const float dz = pz - door->dyna.actor.world.pos.z; + const float x = dx * cs - dz * sn; + const float z = dx * sn + dz * cs; + const float y = py - door->dyna.actor.world.pos.y; + if (fabsf(x) <= kHalfWidth && y >= kGrabMinY && y <= kGrabMaxY && + fabsf(z) <= kHoverDepth && fabsf(z) < best) { + best = fabsf(z); + *localX = x; + *localY = y; + *localZ = z; + *face = z >= 0.0f ? 1.0f : -1.0f; + found = true; + } + } + return found; +} + +void ForgetActor(Actor* actor) { + if (actor != nullptr && actor == reinterpret_cast(sDoor)) Clear(); +} + +} // namespace + +extern "C" int32_t VrGerudoDoor_Tick(DoorGerudo* door, PlayState* play) { + if (!Eligible(door, play)) { + if (door == sDoor) Clear(); + return -1; + } + if (sDoor != nullptr && sDoor != door) return 0; + BeginInputFrame(play); + + float handY[2] = { NAN, NAN }; + for (int hand = 0; hand < 2; ++hand) { + float x = 0.0f, y = 0.0f, z = 0.0f, face = 1.0f; + const bool near = HandContact(door, hand, &x, &y, &z, &handY[hand], &face); + if (sHands[hand].latched && sDoor == door) { + if (!std::isfinite(handY[hand])) { + sHands[hand].latched = false; + continue; + } + sHands[hand].frame = play->state.frames; + sHands[hand].active = true; + if (!sGripNow[hand]) { + sHands[hand].latched = false; + } + } else if (near && sDoor == nullptr) { + HandState& state = sHands[hand]; + state.door = door; + state.frame = play->state.frames; + state.active = true; + state.score = fabsf(z); + state.localX = x; + state.localY = y; + state.localZ = face * 3.0f; + state.face = face; + if (sGripFresh[hand]) { + sDoor = door; + state.latched = true; + VR_TriggerHaptic(hand, 0.3f, 0.0f, 25.0f); + } + } else if (near && sDoor == door && !sHands[hand].latched) { + HandState& state = sHands[hand]; + state.door = door; + state.frame = play->state.frames; + state.active = true; + state.score = fabsf(z); + state.localX = x; + state.localY = y; + state.localZ = face * 3.0f; + state.face = face; + if (sGripFresh[hand]) { + state.latched = true; + VR_TriggerHaptic(hand, 0.3f, 0.0f, 25.0f); + } + } + } + + const bool bothHeld = sDoor == door && sHands[0].latched && sHands[1].latched && + sGripNow[0] && sGripNow[1]; + if (!bothHeld) { + if (sMoving && sLiftArmed) { + door->dyna.actor.velocity.y = 1.0f; + sHands[0] = {}; + sHands[1] = {}; + sMoving = false; + sLiftArmed = false; + VR_TriggerHaptic(VR_HAND_LEFT, 0.75f, 0.0f, 45.0f); + VR_TriggerHaptic(VR_HAND_RIGHT, 0.75f, 0.0f, 45.0f); + Clear(); + return 2; + } + sMoving = false; + if (sDoor == door && !sHands[0].latched && !sHands[1].latched) Clear(); + return 1; + } + + const float meanY = (handY[0] + handY[1]) * 0.5f; + if (!sMoving) { + sMoving = true; + sStartMeanY = meanY; + sStartHeight = door->dyna.actor.world.pos.y; + } + const float handLift = std::max(0.0f, meanY - sStartMeanY); + if (handLift >= WorldScale() * kReleaseLiftMeters / 3.0f) sLiftArmed = true; + const float target = std::clamp(sStartHeight + handLift * 3.0f, door->dyna.actor.home.pos.y, + door->dyna.actor.home.pos.y + kRaisedHeight); + if (target > door->dyna.actor.world.pos.y && !sSoundPlayed) { + Audio_PlayActorSound2(&door->dyna.actor, NA_SE_EV_SLIDE_DOOR_OPEN); + sSoundPlayed = true; + } + door->dyna.actor.world.pos.y = target; + if (target >= door->dyna.actor.home.pos.y + kRaisedHeight - 5.0f) { + door->dyna.actor.world.pos.y = door->dyna.actor.home.pos.y + kRaisedHeight; + door->dyna.actor.velocity.y = 1.0f; + sHands[0] = {}; + sHands[1] = {}; + sMoving = false; + sLiftArmed = false; + VR_TriggerHaptic(VR_HAND_LEFT, 0.75f, 0.0f, 45.0f); + VR_TriggerHaptic(VR_HAND_RIGHT, 0.75f, 0.0f, 45.0f); + Clear(); + return 2; + } + return 1; +} + +extern "C" bool VrGerudoDoor_GripConsumed(int32_t hand, uint16_t mask) { + // Pad bindings are resolved before actors refresh their contact state for the new gameplay + // frame. Keep the most recent hover alive across that boundary so the grip that actually takes + // the grate cannot also leak through as B/R and draw Link's sword or shield. + const bool hovering = hand >= 0 && hand < 2 && gPlayState != nullptr && sHands[hand].active && + (uint32_t)(gPlayState->state.frames - sHands[hand].frame) <= 2; + return (mask & VR_BTN_GRIP) && hand >= 0 && hand < 2 && + (hovering || sHands[hand].latched || sMoving); +} + +extern "C" bool VrGerudoDoor_HoldsHand(int32_t hand) { + return hand >= 0 && hand < 2 && gPlayState != nullptr && sHands[hand].active && + sHands[hand].frame == gPlayState->state.frames; +} + +extern "C" bool VrGerudoDoor_PinnedHandMatrix(Player* player, int32_t hand, float* mf16) { + if (player == nullptr || mf16 == nullptr || hand < 0 || hand > 1 || gPlayState == nullptr || + player != GET_PLAYER(gPlayState)) { + return false; + } + const HandState& state = sHands[hand]; + if (!state.active || state.frame != gPlayState->state.frames || state.door == nullptr) return false; + DoorGerudo* door = state.door; + const float sn = Math_SinS(door->dyna.actor.shape.rot.y); + const float cs = Math_CosS(door->dyna.actor.shape.rot.y); + const float sx = sqrtf(mf16[0] * mf16[0] + mf16[1] * mf16[1] + mf16[2] * mf16[2]); + const float sy = sqrtf(mf16[4] * mf16[4] + mf16[5] * mf16[5] + mf16[6] * mf16[6]); + const float sz = sqrtf(mf16[8] * mf16[8] + mf16[9] * mf16[9] + mf16[10] * mf16[10]); + const float palmTurn = hand == VR_HAND_LEFT ? 1.0f : -1.0f; + mf16[0] = state.face * palmTurn * cs * sx; + mf16[1] = 0.0f; + mf16[2] = -state.face * palmTurn * sn * sx; + mf16[4] = 0.0f; + mf16[5] = sy; + mf16[6] = 0.0f; + mf16[8] = state.face * palmTurn * sn * sz; + mf16[9] = 0.0f; + mf16[10] = state.face * palmTurn * cs * sz; + const float halfLength = (VrHand_ChildSized() ? 548.0f : 862.0f) * 0.5f; + mf16[12] = door->dyna.actor.world.pos.x + state.localX * cs + state.localZ * sn; + mf16[13] = door->dyna.actor.world.pos.y + state.localY - sy * halfLength; + mf16[14] = door->dyna.actor.world.pos.z - state.localX * sn + state.localZ * cs; + return true; +} + +namespace { +void RegisterVrGerudoDoor() { + COND_HOOK(OnSceneInit, true, [](int16_t) { Clear(); }); + COND_HOOK(OnActorDestroy, true, [](void* actor) { ForgetActor(static_cast(actor)); }); +} +static RegisterShipInitFunc initVrGerudoDoor(RegisterVrGerudoDoor); +} // namespace diff --git a/soh/soh/Enhancements/vr-combat/VrGetItem.cpp b/soh/soh/Enhancements/vr-combat/VrGetItem.cpp index ae34695afed..bf08208fafa 100644 --- a/soh/soh/Enhancements/vr-combat/VrGetItem.cpp +++ b/soh/soh/Enhancements/vr-combat/VrGetItem.cpp @@ -35,6 +35,12 @@ extern "C" bool VrGetItem_HoldUpPos(PlayState* play, Player* player, const float return false; } + // A physically opened chest owns the get-item presentation: the normal item model rises from + // and remains over that chest instead of jumping from the lid to Link's raised hands. + if (VrChest_GetItemHoldUpPos(play, player, out)) { + return true; + } + // "Out" = horizontally from the eyes through the hands. With the hands (nearly) straight // overhead that direction is meaningless, so it eases into Link's facing there. float eye[3], fwd[3], up[3]; diff --git a/soh/soh/Enhancements/vr-combat/VrItemSelect.cpp b/soh/soh/Enhancements/vr-combat/VrItemSelect.cpp index 82768e13f11..ac730c00c11 100644 --- a/soh/soh/Enhancements/vr-combat/VrItemSelect.cpp +++ b/soh/soh/Enhancements/vr-combat/VrItemSelect.cpp @@ -91,8 +91,14 @@ int sRestoreItem = -1; // Selector mode last tick — the falling edge (third person, flat screen, F9) clears Link's // hands per the behavior plan; the selection fiction belongs to VR first person. bool sModeWasInPlay = false; +// Bombchu Bowling supplies its temporary item through B and may use a non-first-person camera. +// This latch is separate because the selector state resets outside VR first person. +bool sBowlingTriggerArmed[2] = { false, false }; // >0 while a textbox is up and for a few ticks after it closes (see the put-away guard). int sTextboxRecentTicks = 0; +// Transient mounted-control mode. This must never be persisted: leaving Epona, loading a +// save, or leaving selector mode always returns the selector button to its normal meaning. +bool sHorseBowEnabled = false; int SwordHand() { return CVarGetInteger("gVrLeftHanded", 0) ? VR_HAND_LEFT : VR_HAND_RIGHT; @@ -185,6 +191,23 @@ bool SwapChordHeld() { VrCarry_GripConsumed(VR_HAND_RIGHT, VR_BTN_GRIP))) { return false; } + if ((mask & VR_BTN_GRIP) && (VrDoor_GripConsumed(VR_HAND_LEFT, VR_BTN_GRIP) || + VrDoor_GripConsumed(VR_HAND_RIGHT, VR_BTN_GRIP))) { + return false; + } + // Shutter interactions also use a deliberate two-hand grip. They already consume the + // controller bindings in PadMgr; exclude them here as well so the selector's independent + // two-grip quick-swap cannot draw the sword and shield on the same press. + if ((mask & VR_BTN_GRIP) && (VrJabuDoor_GripConsumed(VR_HAND_LEFT, VR_BTN_GRIP) || + VrJabuDoor_GripConsumed(VR_HAND_RIGHT, VR_BTN_GRIP) || + VrShutter_GripConsumed(VR_HAND_LEFT, VR_BTN_GRIP) || + VrShutter_GripConsumed(VR_HAND_RIGHT, VR_BTN_GRIP))) { + return false; + } + if ((mask & VR_BTN_GRIP) && (VrKeys_GripConsumed(VR_HAND_LEFT, VR_BTN_GRIP) || + VrKeys_GripConsumed(VR_HAND_RIGHT, VR_BTN_GRIP))) { + return false; + } // And grips holding a climbable wall (or on one, about to): climbing hand over hand squeezes both. if ((mask & VR_BTN_GRIP) && (VrClimb_GripConsumed(VR_HAND_LEFT, VR_BTN_GRIP) || VrClimb_GripConsumed(VR_HAND_RIGHT, VR_BTN_GRIP))) { @@ -287,7 +310,41 @@ void QuickSwapTick() { } void ItemSelectTick() { + const bool bowlingTriggerMode = CVarGetInteger("gVrItemSelect", 1) && VR_IsInitialized() && + gPlayState != NULL && gPlayState->bombchuBowlingStatus > 0 && + !VrPause_InputMenuMode(); + Player* livePlayer = gPlayState != NULL ? GET_PLAYER(gPlayState) : NULL; + const bool horseSelectorMode = CVarGetInteger("gVrItemSelect", 1) && VR_IsInitialized() && + GameInteractor::IsSaveLoaded(true) && !VrPause_InputMenuMode() && + livePlayer != NULL && (livePlayer->stateFlags1 & PLAYER_STATE1_ON_HORSE); + for (int hand = 0; hand < 2; ++hand) { + if (!bowlingTriggerMode) { + sBowlingTriggerArmed[hand] = false; + } else if (!(VR_GetControllerButton(hand) & VR_BTN_TRIGGER)) { + sBowlingTriggerArmed[hand] = true; + } + } + // Epona has a dedicated two-state selector: the configured menu input toggles physical + // bow control instead of opening the radial item menu. Do not run the ordinary out-of-mode + // reset here: that reset used to erase sHorseBowEnabled on every mounted frame, handing the + // bow straight back to native horseback archery (button fire and animation/wrist roll). + if (horseSelectorMode) { + sModeWasInPlay = false; + CloseSelector(); + sSelection.CancelRequest(); + return; + } if (!SelectorModeInPlay()) { + // Bombchu Bowling deliberately keeps the physical Bombchu pocket alive while its + // minigame camera is outside ordinary selector mode. The normal full reset includes + // VrItemThrow_Reset(); doing that every tick pins both grip histories to "pressed" and + // makes it impossible for VrItemThrow_Tick to observe a fresh grab. + if (bowlingTriggerMode) { + sModeWasInPlay = false; + CloseSelector(); + sSelection.CancelRequest(); + return; + } if (sModeWasInPlay && gPlayState != NULL && GameInteractor::IsSaveLoaded(true)) { // Falling edge: leaving VR first person clears Link's hands (behavior plan). Player_VrModeExitClearHands(gPlayState, GET_PLAYER(gPlayState)); @@ -633,6 +690,35 @@ extern "C" bool VrItemSelect_ConsumesInput(int32_t vrHand, uint16_t vrBtnMask) { return vrHand == SelectorHand() && (vrBtnMask & SelectorMask()) != 0; } +extern "C" bool VrItemSelect_TakeHorseBowToggle(void) { + static bool sSelectorWasDown = false; + // The title-screen demo also places Link on Epona. Never treat that scripted rider as a + // playable horse state: controller activation can report a transient button edge while the + // headset wakes, and changing the demo player's equipment corrupts its scripted state. + const bool active = CVarGetInteger("gVrItemSelect", 1) && VR_IsInitialized() && gPlayState != NULL && + GameInteractor::IsSaveLoaded(true) && !VrPause_InputMenuMode() && !OcarinaInPlay(); + Player* player = active ? GET_PLAYER(gPlayState) : NULL; + const bool mounted = player != NULL && (player->stateFlags1 & PLAYER_STATE1_ON_HORSE); + const bool ownsBow = INV_CONTENT(SLOT_BOW) == ITEM_BOW && + (LINK_IS_ADULT || CVarGetInteger(CVAR_CHEAT("TimelessEquipment"), 0)); + const bool ready = mounted && ownsBow && player->heldItemAction == player->itemAction && + !(player->stateFlags1 & + (PLAYER_STATE1_IN_CUTSCENE | PLAYER_STATE1_START_CHANGING_HELD_ITEM)); + const bool down = ready && (VR_GetControllerButton(SelectorHand()) & SelectorMask()) != 0; + const bool pressed = down && !sSelectorWasDown; + sSelectorWasDown = down; + if (!mounted || !ownsBow) { + sHorseBowEnabled = false; + } else if (pressed) { + sHorseBowEnabled = !sHorseBowEnabled; + } + return pressed; +} + +extern "C" bool VrItemSelect_HorseBowEnabled(void) { + return sHorseBowEnabled; +} + extern "C" bool VrOcarina_InPlay(void) { return OcarinaInPlay(); } @@ -697,9 +783,18 @@ extern "C" void VrItemSelect_Reset(void) { // where neither the pending restore nor the tracked loadout is trustworthy anymore. sRestoreSlot = VrItemSelectionState::NoRequest; sStableSlot = VrItemSelectionState::NoRequest; + sHorseBowEnabled = false; } extern "C" uint16_t VrItemSelect_TriggerItemMask(int32_t vrHand) { + // The VR controller profile reserves both triggers before regular bindings are applied. + // Bowling's temporary Bombchu is not held by either hand, so feed its B action here even + // when the minigame camera has taken the game out of VR first-person selector mode. + if (gPlayState != NULL && CVarGetInteger("gVrItemSelect", 1) && VR_IsInitialized() && + !VrPause_InputMenuMode() && gPlayState->bombchuBowlingStatus > 0) { + Player* player = GET_PLAYER(gPlayState); + return !VrItemThrow_Active(player) && vrHand == SwordHand() && sBowlingTriggerArmed[vrHand] ? BTN_B : 0; + } if (!SelectorModeInPlay() || gPlayState == NULL || !sSelection.TriggerArmed(vrHand)) { return 0; } @@ -779,7 +874,7 @@ static void RegisterVrItemSelect() { // other message) must not strip the bottle from Link's hand. Guarded while a message is up // and for a few ticks after it closes (the button re-enable lags the close by a frame or two). COND_VB_SHOULD(VB_PUTAWAY_BECAUSE_DISABLED_ITEM_BUTTONS, CVarGetInteger("gVrItemSelect", 1), { - if (SelectorModeInPlay() && sTextboxRecentTicks > 0) { + if ((SelectorModeInPlay() && sTextboxRecentTicks > 0) || VrItemSelect_HorseBowEnabled()) { *should = false; } }); diff --git a/soh/soh/Enhancements/vr-combat/VrItemThrow.cpp b/soh/soh/Enhancements/vr-combat/VrItemThrow.cpp index e6cdd5677dc..853fd3d9fd8 100644 --- a/soh/soh/Enhancements/vr-combat/VrItemThrow.cpp +++ b/soh/soh/Enhancements/vr-combat/VrItemThrow.cpp @@ -19,6 +19,8 @@ bool sGripPrev[2] = { true, true }; // require a fresh press on entry/reset int sCarryHand = -1; // hand that grabbed the current throwable, -1 = none int sObservedItem = -1; bool sReleaseHasGrip = false; +Gfx sChuGuideDl[24]; +Vtx sChuGuideVtx[7]; // Bombchu grab transform (VrPocket::Grab). The presented chu is a real model with an // orientation; grabbing it records where it sat relative to the hand (position offset and its @@ -43,6 +45,18 @@ bool ChuCovered(Player* player) { return player->heldItemAction == PLAYER_IA_BOMBCHU && CVarGetInteger("gVrPhysBombchuDrop", 1); } +// Grabbing the tenth bowling Bombchu changes the counter from 1 to -1 immediately. Keep the +// physical adapter alive until that already-spawned final Bombchu leaves the hand; -1 forbids a +// new preview, but must not strand the carried actor. +bool BowlingChuInPlay(Player* player) { + if (!player || !ChuCovered(player) || !gPlayState || gPlayState->bombchuBowlingStatus == 0) { + return false; + } + return gPlayState->bombchuBowlingStatus > 0 || + (player->heldActor && player->heldActor->id == ACTOR_EN_BOM_CHU && + (player->stateFlags1 & PLAYER_STATE1_CARRYING_ACTOR)); +} + // Record how the presented chu sits relative to the grabbing hand, in the hand's frame. void CaptureChuGrab(int hand) { sChuGrab.Clear(); @@ -58,13 +72,27 @@ bool CarriedChuPose(int hand, float position[3], float left[3], float up[3], flo return sChuGrab.Replay(hand, position, left, up, forward); } +// Bombchu aim follows the player's view horizontally. A hand-directed crawl required awkward +// wrist gestures and often put the guide outside the player's view. +bool HeadChuForward(float forward[3]) { + float eye[3], up[3]; + VR_GetCameraPose(eye, forward, up); + const float horizontal = sqrtf(SQ(forward[0]) + SQ(forward[2])); + if (horizontal < 0.01f) return false; + forward[0] /= horizontal; + forward[1] = 0.0f; + forward[2] /= horizontal; + return true; +} + // Bombchu release intent: the chu crawls where its nose was pointing at the moment of release // (the carried model's forward, flattened to horizontal). Untracked controller or a nose // pointing straight up/down = no intent; the actor uses Link's facing when it lands. void SetChuCrawlYaw(EnBomChu* chu, int hand) { - float position[3], left[3], up[3], forward[3]; + float forward[3]; + (void)hand; chu->vrHasCrawlYaw = false; - if (!CarriedChuPose(hand, position, left, up, forward)) return; + if (!HeadChuForward(forward)) return; if (forward[0] * forward[0] + forward[2] * forward[2] < 1e-4f) return; // Same convention as Player_VrReleaseItem: rot.y = 0 is +Z, sin(rot.y) is the X component. chu->vrCrawlYaw = Math_Atan2S(forward[2], forward[0]); @@ -99,11 +127,16 @@ bool HandNearPreview(int hand) { } extern "C" bool VrItemThrow_Active(Player* player) { - return VrItemSelect_ModeActive() && CVarGetInteger("gVrPhysicalItemThrows", 1) && player && + const bool bowlingBombchu = BowlingChuInPlay(player); + const bool selectorContext = VrItemSelect_ModeActive() || + (bowlingBombchu && CVarGetInteger("gVrItemSelect", 1) && VR_IsInitialized() && + !VrPause_InputMenuMode()); + return selectorContext && CVarGetInteger("gVrPhysicalItemThrows", 1) && player && player->actor.category == ACTORCAT_PLAYER && (player->heldItemAction == PLAYER_IA_BOMB || player->heldItemAction == PLAYER_IA_DEKU_NUT || ChuCovered(player)) && - gPlayState && gPlayState->bombchuBowlingStatus == 0 && gPlayState->shootingGalleryStatus == 0 && + gPlayState && (gPlayState->bombchuBowlingStatus == 0 || bowlingBombchu) && + gPlayState->shootingGalleryStatus == 0 && !(player->stateFlags1 & (PLAYER_STATE1_ON_HORSE | PLAYER_STATE1_IN_WATER)); } @@ -124,11 +157,84 @@ extern "C" bool VrItemThrow_PreviewIsModel(void) { return player && ChuCovered(player) && VrItemThrow_PreviewPosition(position); } +Vtx ChuGuideVtx(float x, float z, u8 alpha) { + Vtx v = {}; + v.v.ob[0] = (s16)lroundf(x); + v.v.ob[2] = (s16)lroundf(z); + v.v.cn[0] = 255; + v.v.cn[1] = 210; + v.v.cn[2] = 40; + v.v.cn[3] = alpha; + return v; +} + +void DrawChuAimGuide(Player* player) { + if (!VR_IsInitialized() || !VR_GetFirstPerson() || VR_IsFlatScreen() || + !CVarGetInteger("gVrBombchuAimGuide", 1) || !player || !HasThrowable(player) || + player->heldActor->id != ACTOR_EN_BOM_CHU) return; + + float forward[3]; + if (!HeadChuForward(forward)) return; + const float right[3] = { forward[2], 0.0f, -forward[0] }; + + Vec3f floorProbe = { player->actor.world.pos.x, player->actor.world.pos.y + 100.0f, + player->actor.world.pos.z }; + CollisionPoly* floorPoly = nullptr; + s32 bgId = BGCHECK_SCENE; + const float floorY = BgCheck_EntityRaycastFloor3(&gPlayState->colCtx, &floorPoly, &bgId, &floorProbe); + if (floorY == BGCHECK_Y_MIN) return; + + const float scale = WorldScale(); + const float length = scale * 3.0f; + const float halfWidth = fmaxf(scale * 0.012f, 0.5f); + const float headWidth = halfWidth * 5.0f; + const float headLength = fmaxf(scale * 0.18f, 6.0f); + sChuGuideVtx[0] = ChuGuideVtx(-halfWidth, 0.0f, 170); + sChuGuideVtx[1] = ChuGuideVtx(halfWidth, 0.0f, 170); + sChuGuideVtx[2] = ChuGuideVtx(-halfWidth, length - headLength, 210); + sChuGuideVtx[3] = ChuGuideVtx(halfWidth, length - headLength, 210); + sChuGuideVtx[4] = ChuGuideVtx(-headWidth, length - headLength, 230); + sChuGuideVtx[5] = ChuGuideVtx(headWidth, length - headLength, 230); + sChuGuideVtx[6] = ChuGuideVtx(0.0f, length, 255); + + MtxF guide = {}; + guide.mf[0][0] = right[0]; guide.mf[0][1] = right[1]; guide.mf[0][2] = right[2]; + guide.mf[1][0] = 0.0f; guide.mf[1][1] = 1.0f; guide.mf[1][2] = 0.0f; + guide.mf[2][0] = forward[0]; guide.mf[2][1] = 0.0f; guide.mf[2][2] = forward[2]; + guide.mf[3][0] = player->actor.world.pos.x; + guide.mf[3][1] = floorY + 1.0f; + guide.mf[3][2] = player->actor.world.pos.z; + guide.mf[3][3] = 1.0f; + Matrix_Put(&guide); + Mtx* guideMtx = MATRIX_NEWMTX(gPlayState->state.gfxCtx); + + Gfx* p = sChuGuideDl; + gDPPipeSync(p++); + gDPSetCycleType(p++, G_CYC_1CYCLE); + // Always visible: the held Bombchu and nearby floor geometry must not hide the guide. + gDPSetRenderMode(p++, G_RM_XLU_SURF, G_RM_XLU_SURF2); + gDPSetCombineMode(p++, G_CC_SHADE, G_CC_SHADE); + gSPTexture(p++, 0, 0, 0, G_TX_RENDERTILE, G_OFF); + gSPClearGeometryMode(p++, G_CULL_BOTH | G_LIGHTING | G_FOG | G_TEXTURE_GEN | G_TEXTURE_GEN_LINEAR); + gSPClearGeometryMode(p++, G_ZBUFFER); + gSPSetGeometryMode(p++, G_SHADE | G_SHADING_SMOOTH); + gSPMatrix(p++, guideMtx, G_MTX_MODELVIEW | G_MTX_LOAD | G_MTX_NOPUSH); + gSPVertex(p++, (uintptr_t)&sChuGuideVtx[0], 7, 0); + gSP2Triangles(p++, 0, 1, 2, 0, 1, 3, 2, 0); + gSP1Triangle(p++, 4, 5, 6, 0); + gSPEndDisplayList(p++); + + OPEN_DISPS(gPlayState->state.gfxCtx); + gSPDisplayList(POLY_XLU_DISP++, sChuGuideDl); + CLOSE_DISPS(gPlayState->state.gfxCtx); +} + // Preview draw: the chu as it would appear when used, shrunk by gVrChuPreviewScale, sitting at // the preview point, level, nose away from the player. Own OnPlayDrawEnd hook with minimal // gates (same pattern as the bottle mouth marker). extern "C" linkage is load-bearing for the // block-scope FrameInterpolation declarations inside OPEN_DISPS (see VrItemSelect_Draw). extern "C" void VrItemThrow_DrawPreview(void) { + if (gPlayState) DrawChuAimGuide(GET_PLAYER(gPlayState)); if (!VrItemThrow_PreviewIsModel()) return; float position[3], left[3], up[3], forward[3]; if (!VrItemThrow_PreviewPosition(position) || !VrPocket::Axes(left, up, forward)) return; @@ -157,8 +263,10 @@ extern "C" void VrItemThrow_DrawPreview(void) { } extern "C" bool VrItemThrow_PreviewPosition(float* position) { - if (!gPlayState || !VrItemThrow_Active(GET_PLAYER(gPlayState)) || - !VrItemSelect_SelectionAllowed() || GET_PLAYER(gPlayState)->heldActor) { + Player* player = gPlayState ? GET_PLAYER(gPlayState) : nullptr; + const bool bowlingBombchu = player && ChuCovered(player) && gPlayState->bombchuBowlingStatus > 0; + if (!gPlayState || !VrItemThrow_Active(player) || (!VrItemSelect_SelectionAllowed() && !bowlingBombchu) || + player->heldActor) { return false; } return VrPocket::Point(position); @@ -209,7 +317,8 @@ extern "C" void VrItemThrow_UpdateCarryPose(Player* player) { } extern "C" void VrItemThrow_Tick(PlayState* play, Player* player) { - if (!VrItemThrow_Active(player) || !VrItemSelect_SelectionAllowed() || + const bool bowlingBombchu = BowlingChuInPlay(player); + if (!VrItemThrow_Active(player) || (!VrItemSelect_SelectionAllowed() && !bowlingBombchu) || play->pauseCtx.state != 0 || player->unk_6AD != 0 || player->heldItemAction != player->itemAction) { VrItemThrow_Reset(); return; diff --git a/soh/soh/Enhancements/vr-combat/VrKeys.cpp b/soh/soh/Enhancements/vr-combat/VrKeys.cpp new file mode 100644 index 00000000000..f5fc4390181 --- /dev/null +++ b/soh/soh/Enhancements/vr-combat/VrKeys.cpp @@ -0,0 +1,519 @@ +extern "C" { +#include "z64.h" +#include "macros.h" +#include "functions.h" +#include "variables.h" +#include "objects/object_gi_key/object_gi_key.h" +#include "objects/object_gi_bosskey/object_gi_bosskey.h" +#include "overlays/actors/ovl_En_Door/z_en_door.h" +#include "overlays/actors/ovl_Door_Shutter/z_door_shutter.h" +#include "overlays/actors/ovl_Door_Gerudo/z_door_gerudo.h" +extern PlayState* gPlayState; +} + +#include "VrCombat.h" +#include "VrPocket.h" +#include "soh/Enhancements/game-interactor/GameInteractor.h" +#include "soh/ShipInit.hpp" +#include "soh/frame_interpolation.h" +#include +#include + +// Phase one of physical locked doors. This exposes real inventory keys to the hands but never +// spends one; phase two will take ownership only after a compatible lock accepts the held key. +namespace { +enum class Kind { None, Small, Boss }; +Kind sHeld = Kind::None; +int sHand = -1; +bool sGripPrev[2] = { true, true }; +bool sNear[2] = { false, false }; +Kind sNearKind = Kind::None; +int sHeldInterpKey; +Actor* sInsertLock = nullptr; +bool sInsertArmed = false; +enum class InsertState { None, WaitRelease, Ready, Turning, Complete }; +InsertState sInsertState = InsertState::None; +float sInsertedPos[3] = {}, sInsertedSide[3] = {}, sInsertedUp[3] = {}, sInsertedForward[3] = {}; +float sInsertedTip[3] = {}, sInsertedLength = 0.0f; +float sInsertedCalOffset[3] = {}; +float sTurnStartQuat[4] = {}; + +float Cm(float cm) { return cm * 0.01f * VrPocket::WorldScale(); } + +void LockOffsets(Kind kind, float* horizontal, float* vertical, float* depth) { + *horizontal = CVarGetFloat(kind == Kind::Boss ? "gVrBossKeyLockOffsetX" : "gVrSmallKeyLockOffsetX", 0.0f); + *vertical = CVarGetFloat(kind == Kind::Boss ? "gVrBossKeyLockOffsetY" : "gVrSmallKeyLockOffsetY", 0.0f); + *depth = CVarGetFloat(kind == Kind::Boss ? "gVrBossKeyLockOffsetDepth" : "gVrSmallKeyLockOffsetDepth", 0.0f); +} + +bool Gate(PlayState* play, Player* player) { + return play && player && player == GET_PLAYER(play) && CVarGetInteger("gVrPhysicalKeys", 1) && + CVarGetInteger("gVrPhysicalDoors", 1) && + VR_IsInitialized() && VR_GetFirstPerson() && !VR_IsFlatScreen() && + CVarGetInteger("gVrMotionHands", 1) && play->pauseCtx.state == 0 && play->csCtx.state == CS_STATE_IDLE && + play->transitionTrigger == TRANS_TRIGGER_OFF && play->bombchuBowlingStatus == 0 && + play->shootingGalleryStatus == 0 && !(player->stateFlags1 & + (PLAYER_STATE1_ON_HORSE | PLAYER_STATE1_IN_WATER | PLAYER_STATE1_DEAD)); +} + +bool HasSmall() { + const int map = gSaveContext.mapIndex; + return map >= 0 && map < (int)ARRAY_COUNT(gSaveContext.inventory.dungeonKeys) && + // Negative is the engine's unlimited/debug-key sentinel (the HUD renders infinity). + // Treat every nonzero value as available so the visible card and its interaction agree. + gSaveContext.inventory.dungeonKeys[map] != 0; +} +bool OwnsBoss() { + const int map = gSaveContext.mapIndex; + return map >= 0 && map < (int)ARRAY_COUNT(gSaveContext.inventory.dungeonItems) && + CHECK_DUNGEON_ITEM(DUNGEON_KEY_BOSS, map); +} + +bool IsBossKeyDungeon(const PlayState* play) { + if (play == nullptr) return false; + switch (play->sceneNum) { + case SCENE_FOREST_TEMPLE: + case SCENE_FIRE_TEMPLE: + case SCENE_WATER_TEMPLE: + case SCENE_SPIRIT_TEMPLE: + case SCENE_SHADOW_TEMPLE: + case SCENE_INSIDE_GANONS_CASTLE: + case SCENE_GANONS_TOWER: + case SCENE_FOREST_TEMPLE_BOSS: + case SCENE_FIRE_TEMPLE_BOSS: + case SCENE_WATER_TEMPLE_BOSS: + case SCENE_SPIRIT_TEMPLE_BOSS: + case SCENE_SHADOW_TEMPLE_BOSS: + return true; + default: + return false; + } +} + +bool HasLockedBossDoorNearby(PlayState* play) { + if (play == nullptr || !OwnsBoss()) return false; + + const Player* player = GET_PLAYER(play); + constexpr float kAvailabilityRadius = 400.0f; + constexpr float kAvailabilityRadiusSq = kAvailabilityRadius * kAvailabilityRadius; + for (Actor* actor = play->actorCtx.actorLists[ACTORCAT_DOOR].head; actor != nullptr; actor = actor->next) { + if (actor->id != ACTOR_DOOR_SHUTTER || actor->update == nullptr) continue; + DoorShutter* door = reinterpret_cast(actor); + if (door->doorType != SHUTTER_BOSS || door->unlockTimer == 0) continue; + + const float dx = actor->world.pos.x - player->actor.world.pos.x; + const float dy = actor->world.pos.y - player->actor.world.pos.y; + const float dz = actor->world.pos.z - player->actor.world.pos.z; + if (dx * dx + dy * dy + dz * dz <= kAvailabilityRadiusSq) return true; + } + return false; +} + +bool HasUsedBossDoorLoaded(PlayState* play) { + if (play == nullptr) return false; + for (Actor* actor = play->actorCtx.actorLists[ACTORCAT_DOOR].head; actor != nullptr; actor = actor->next) { + if (actor->id != ACTOR_DOOR_SHUTTER || actor->update == nullptr) continue; + DoorShutter* door = reinterpret_cast(actor); + if (door->doorType == SHUTTER_BOSS && Flags_GetSwitch(play, actor->params & 0x3F)) return true; + } + return false; +} + +bool HandNear(int hand, const float point[3]) { + float p[3], q[4]; + if (!VR_GetHandPose(hand, p, q)) return false; + const float dx = p[0] - point[0], dy = p[1] - point[1], dz = p[2] - point[2]; + const float reach = Cm(CVarGetFloat("gVrKeyGrabRadius", 12.0f)); + return dx * dx + dy * dy + dz * dz <= reach * reach; +} + +bool Pose(Kind kind, float pos[3], float side[3], float up[3], float forward[3]) { + if (sHeld != kind) return false; + if (sInsertState != InsertState::None) { + float horizontal, vertical, depth; + LockOffsets(kind, &horizontal, &vertical, &depth); + const float liveDelta[3] = { horizontal - sInsertedCalOffset[0], vertical - sInsertedCalOffset[1], + depth - sInsertedCalOffset[2] }; + for (int i = 0; i < 3; ++i) { + pos[i] = sInsertedPos[i] + sInsertedSide[i] * liveDelta[0] + sInsertedUp[i] * liveDelta[1] + + sInsertedForward[i] * liveDelta[2]; + side[i] = sInsertedSide[i]; + up[i] = sInsertedUp[i]; forward[i] = sInsertedForward[i]; + } + if (sInsertState == InsertState::Turning || sInsertState == InsertState::Complete) { + float handPos[3], q[4]; + if (VR_GetHandPose(VR_HAND_RIGHT, handPos, q)) { + const float inv[4] = { -sTurnStartQuat[0], -sTurnStartQuat[1], -sTurnStartQuat[2], sTurnStartQuat[3] }; + const float delta[4] = { + q[3] * inv[0] + q[0] * inv[3] + q[1] * inv[2] - q[2] * inv[1], + q[3] * inv[1] - q[0] * inv[2] + q[1] * inv[3] + q[2] * inv[0], + q[3] * inv[2] + q[0] * inv[1] - q[1] * inv[0] + q[2] * inv[3], + q[3] * inv[3] - q[0] * inv[0] - q[1] * inv[1] - q[2] * inv[2], + }; + // A key can only twist around the lock barrel. Applying the controller's complete + // quaternion also pitched/yawed the seated key, making it hang crooked and pull its + // blade out of the keyhole. Extract only twist about the fixed insertion axis. + const float twistSin = delta[0] * sInsertedForward[0] + delta[1] * sInsertedForward[1] + + delta[2] * sInsertedForward[2]; + const float twist = 2.0f * atan2f(twistSin, delta[3]); + const float c = cosf(twist), s = sinf(twist); + auto rotateAboutLock = [&](const float v[3], float out[3]) { + const float dot = v[0] * sInsertedForward[0] + v[1] * sInsertedForward[1] + + v[2] * sInsertedForward[2]; + const float cross[3] = { + sInsertedForward[1] * v[2] - sInsertedForward[2] * v[1], + sInsertedForward[2] * v[0] - sInsertedForward[0] * v[2], + sInsertedForward[0] * v[1] - sInsertedForward[1] * v[0], + }; + for (int i = 0; i < 3; ++i) { + out[i] = v[i] * c + cross[i] * s + sInsertedForward[i] * dot * (1.0f - c); + } + }; + rotateAboutLock(sInsertedSide, side); + rotateAboutLock(sInsertedUp, up); + for (int i = 0; i < 3; ++i) { + forward[i] = sInsertedForward[i]; + pos[i] = sInsertedPos[i] + sInsertedSide[i] * liveDelta[0] + sInsertedUp[i] * liveDelta[1] + + sInsertedForward[i] * liveDelta[2]; + } + } + } + return true; + } + // A held key has a deliberate grip-local pose rather than preserving the floating anchor's + // world orientation. It is therefore rigidly part of the controller/closed fist and cannot + // appear to rotate independently as the wrist turns. + float handPos[3], q[4]; + if (!VR_GetHandPose(sHand, handPos, q)) return false; + const float sideLocal[3] = { 0, 1, 0 }; + const float upLocal[3] = { 0, 0, -1 }; + const float forwardLocal[3] = { -1, 0, 0 }; + VrPocket::QuatRot(q, sideLocal, side); + VrPocket::QuatRot(q, upLocal, up); + VrPocket::QuatRot(q, forwardLocal, forward); + // User calibration in controller-local space. This moves the complete grabbed model without + // changing its orientation or the independently calibrated position used after lock insertion. + const char* heldX = kind == Kind::Boss ? "gVrBossKeyHeldOffsetX" : "gVrSmallKeyHeldOffsetX"; + const char* heldY = kind == Kind::Boss ? "gVrBossKeyHeldOffsetY" : "gVrSmallKeyHeldOffsetY"; + const char* heldZ = kind == Kind::Boss ? "gVrBossKeyHeldOffsetZ" : "gVrSmallKeyHeldOffsetZ"; + const float localOffset[3] = { Cm(CVarGetFloat(heldX, 0.0f)), Cm(CVarGetFloat(heldY, 0.0f)), + -Cm(CVarGetFloat(heldZ, 0.0f)) }; + float worldOffset[3]; + VrPocket::QuatRot(q, localOffset, worldOffset); + for (int i = 0; i < 3; ++i) pos[i] = handPos[i] + worldOffset[i]; + return true; +} +void Clear() { + sHeld = Kind::None; sHand = -1; + sNear[0] = sNear[1] = false; + sNearKind = Kind::None; + sInsertLock = nullptr; sInsertArmed = false; + sInsertState = InsertState::None; +} +void Take(Kind kind, int hand) { + sHeld = kind; sHand = hand; + // Match the confirmation tick used when the Alyx-style item selector changes selection. + VR_TriggerHaptic(hand, 0.4f, 0.0f, 25.0f); +} +} // namespace + +static bool TryInsert(Actor* lock, float holeY, Kind required) { + if (lock == nullptr || sHeld != required) return false; + if (sInsertState == InsertState::Complete && sInsertLock == lock) { + Clear(); + return true; + } + if (sInsertState != InsertState::None || sHand < 0) return false; + + float keyPos[3], side[3], up[3], forward[3]; + if (!Pose(sHeld, keyPos, side, up, forward)) return false; + const float legacyScale = CVarGetFloat("gVrKeyHeldScale", 180.0f); + const float heldScale = CVarGetFloat(required == Kind::Boss ? "gVrBossKeyHeldScale" : "gVrSmallKeyHeldScale", + legacyScale) / + 100.0f; + const float modelScale = (required == Kind::Boss ? 0.018f : 0.022f) * heldScale; + // Measured from the actual OTR vertices: the controller origin is placed at the decorative + // handle and the blade tip lies roughly this far away along the corrected length axis. + const float bladeModelLength = required == Kind::Boss ? 57.0f : 59.0f; + float inward[3] = { -forward[0], -forward[1], -forward[2] }; + + const float yawSin = Math_SinS(lock->shape.rot.y), yawCos = Math_CosS(lock->shape.rot.y); + float outward[3] = { yawSin, 0.0f, yawCos }; + const float handSide = (keyPos[0] - lock->world.pos.x) * outward[0] + + (keyPos[2] - lock->world.pos.z) * outward[2]; + if (handSide < 0.0f) { + outward[0] = -outward[0]; outward[2] = -outward[2]; + } + float horizontal, vertical, depthOffset; + LockOffsets(required, &horizontal, &vertical, &depthOffset); + const float lockSide[3] = { outward[2], 0.0f, -outward[0] }; + const float hole[3] = { lock->world.pos.x + outward[0] * (5.0f + depthOffset) + lockSide[0] * horizontal, + lock->world.pos.y + holeY + vertical, + lock->world.pos.z + outward[2] * (5.0f + depthOffset) + lockSide[2] * horizontal }; + // Asset variants do not all author the blade on the same signed length axis. Select the end + // physically nearer this keyhole, then use that same end for alignment and the seated pose. + float tip[3] = { keyPos[0] + inward[0] * bladeModelLength * modelScale, + keyPos[1] + inward[1] * bladeModelLength * modelScale, + keyPos[2] + inward[2] * bladeModelLength * modelScale }; + const float otherTip[3] = { keyPos[0] - inward[0] * bladeModelLength * modelScale, + keyPos[1] - inward[1] * bladeModelLength * modelScale, + keyPos[2] - inward[2] * bladeModelLength * modelScale }; + const float tipSq = (tip[0] - hole[0]) * (tip[0] - hole[0]) + (tip[1] - hole[1]) * (tip[1] - hole[1]) + + (tip[2] - hole[2]) * (tip[2] - hole[2]); + const float otherSq = (otherTip[0] - hole[0]) * (otherTip[0] - hole[0]) + + (otherTip[1] - hole[1]) * (otherTip[1] - hole[1]) + + (otherTip[2] - hole[2]) * (otherTip[2] - hole[2]); + if (otherSq < tipSq) { + for (int i = 0; i < 3; ++i) { tip[i] = otherTip[i]; inward[i] = -inward[i]; } + } + const float delta[3] = { tip[0] - hole[0], tip[1] - hole[1], tip[2] - hole[2] }; + const float depth = delta[0] * outward[0] + delta[2] * outward[2]; + const float radialSq = delta[0] * delta[0] + delta[1] * delta[1] + delta[2] * delta[2] - depth * depth; + const float alignment = inward[0] * -outward[0] + inward[2] * -outward[2]; + + // The lock model and the door actor do not share pixel-perfect origins across every dungeon + // skin. Capture generously around the visible keyhole, but still require the blade to point + // into the door. Once captured, the exact seated transform below is authoritative. + if (radialSq > 36.0f * 36.0f || alignment < 0.15f || depth < -24.0f || depth > 48.0f) { + if (sInsertLock == lock) { sInsertLock = nullptr; sInsertArmed = false; } + return false; + } + if (sInsertLock != lock) { + sInsertLock = lock; + VR_TriggerHaptic(sHand, 0.22f, 0.0f, 22.0f); + } + // Entering the visible keyhole is the precision step. Once the rendered tip is within its + // capture volume, seat it in the canonical lock pose immediately; requiring a second hidden + // depth-plane crossing left the key crooked beside the padlock even when it visibly touched. + if (depth <= 28.0f) { + // Snap to the lock, not to the wrist pose: blade perpendicular to the door, handle plane + // vertical to the floor. This is the neutral pose from which the player releases and turns. + const float seatedForward[3] = { outward[0], 0.0f, outward[2] }; + const float seatedUp[3] = { 0.0f, 1.0f, 0.0f }; + const float seatedSide[3] = { seatedForward[2], 0.0f, -seatedForward[0] }; + for (int i = 0; i < 3; ++i) { + sInsertedPos[i] = hole[i] + seatedForward[i] * bladeModelLength * modelScale; + sInsertedTip[i] = hole[i]; + sInsertedSide[i] = seatedSide[i]; + sInsertedUp[i] = seatedUp[i]; + sInsertedForward[i] = seatedForward[i]; + } + sInsertedLength = bladeModelLength * modelScale; + sInsertedCalOffset[0] = horizontal; + sInsertedCalOffset[1] = vertical; + sInsertedCalOffset[2] = depthOffset; + sInsertState = InsertState::WaitRelease; + sInsertArmed = false; + VR_TriggerHaptic(sHand, 0.55f, 0.0f, 38.0f); + } + return false; +} + +extern "C" bool VrKeys_TryEnDoor(EnDoor* door, PlayState* play) { + return play != nullptr && door != nullptr && door->lockTimer != 0 && HasSmall() && + TryInsert(&door->actor, 50.0f, Kind::Small); +} + +extern "C" bool VrKeys_TryShutter(DoorShutter* door, PlayState* play) { + if (play == nullptr || door == nullptr || door->unlockTimer == 0) return false; + if (door->doorType == SHUTTER_BOSS) { + return OwnsBoss() && TryInsert(&door->dyna.actor, 80.0f, Kind::Boss); + } + return door->doorType == SHUTTER_KEY_LOCKED && HasSmall() && + TryInsert(&door->dyna.actor, door->gfxType == 6 ? 80.0f : 50.0f, Kind::Small); +} + +extern "C" bool VrKeys_TryGerudoDoor(DoorGerudo* door, PlayState* play) { + return play != nullptr && door != nullptr && door->unk_166 != 0 && HasSmall() && + TryInsert(&door->dyna.actor, 50.0f, Kind::Small); +} + +extern "C" void VrKeys_Reset(void) { + Clear(); sGripPrev[0] = sGripPrev[1] = true; +} + +extern "C" bool VrKeys_GripConsumed(int32_t hand, uint16_t mask) { + return (mask & VR_BTN_GRIP) && hand == VR_HAND_RIGHT && + ((sHeld != Kind::None && (sHand == hand || sInsertState != InsertState::None)) || sNear[hand]); +} + +extern "C" bool VrKeys_HoldsHand(int32_t hand) { + return sHeld != Kind::None && sHand == hand; +} + +extern "C" bool VrKeys_HudHighlighted(int32_t bossKey) { + return sNearKind == (bossKey ? Kind::Boss : Kind::Small); +} + +extern "C" bool VrKeys_BossAvailable(PlayState* play) { + // OoT retains the Boss Key inventory bit after use. For the physical wrist card, the unlocked + // boss-door switch is the consumed state: once that lock has accepted the key, hide the card. + return IsBossKeyDungeon(play) && OwnsBoss() && !HasUsedBossDoorLoaded(play); +} + +extern "C" void VrKeys_Tick(PlayState* play, Player* player) { + if (!Gate(play, player)) { + VrKeys_Reset(); + return; + } + if ((sHeld == Kind::Small && !HasSmall()) || (sHeld == Kind::Boss && !VrKeys_BossAvailable(play))) Clear(); + bool pressed[2], released[2]; + for (int h = 0; h < 2; ++h) { + const bool grip = (VR_GetControllerButton(h) & VR_BTN_GRIP) != 0; + pressed[h] = grip && !sGripPrev[h]; released[h] = !grip && sGripPrev[h]; + sGripPrev[h] = grip; sNear[h] = false; + } + sNearKind = Kind::None; + if (sInsertState != InsertState::None) { + if (sInsertState == InsertState::WaitRelease && sHand >= 0 && released[sHand]) { + sHand = -1; + sInsertState = InsertState::Ready; + } else if (sInsertState == InsertState::Ready && pressed[VR_HAND_RIGHT] && + HandNear(VR_HAND_RIGHT, sInsertedPos)) { + float p[3]; + if (VR_GetHandPose(VR_HAND_RIGHT, p, sTurnStartQuat)) { + sHand = VR_HAND_RIGHT; + sInsertState = InsertState::Turning; + VR_TriggerHaptic(sHand, 0.35f, 0.0f, 28.0f); + } + } else if (sInsertState == InsertState::Turning) { + if (released[VR_HAND_RIGHT]) { + sHand = -1; + sInsertState = InsertState::Ready; + } else { + float p[3], q[4]; + if (VR_GetHandPose(VR_HAND_RIGHT, p, q)) { + float dot = fabsf(q[0] * sTurnStartQuat[0] + q[1] * sTurnStartQuat[1] + + q[2] * sTurnStartQuat[2] + q[3] * sTurnStartQuat[3]); + dot = fmaxf(0.0f, fminf(1.0f, dot)); + if (2.0f * acosf(dot) * (180.0f / M_PI) >= 90.0f) { + sInsertState = InsertState::Complete; + } + } + } + } + return; + } + if (sHeld != Kind::None) { + if (released[sHand]) { + VR_TriggerHaptic(sHand, 0.18f, 0.0f, 18.0f); + Clear(); + } + return; + } + // Visibility and interaction must use the same ownership rules. Door proximity belongs to + // insertion, not to taking an already-visible inventory key from the wrist. + const Kind available[2] = { HasSmall() ? Kind::Small : Kind::None, + VrKeys_BossAvailable(play) ? Kind::Boss : Kind::None }; + Kind nearest = Kind::None; + float nearestDistance = 1.0e30f; + for (Kind kind : available) { + if (kind == Kind::None) continue; + // The key lives on the left wrist HUD, so the right hand takes it. Letting the wrist's own + // grip qualify would make ordinary left-grip input grab a key without reaching for it. + for (int h = VR_HAND_RIGHT; h <= VR_HAND_RIGHT; ++h) { + float distance = 0.0f; + const int element = kind == Kind::Boss ? VR_HUD_EL_PHYSICAL_BOSS_KEY : VR_HUD_EL_PHYSICAL_KEYS; + if (!VR_GetHudElementHandDistance(h, element, &distance) || + distance > CVarGetFloat("gVrKeyGrabRadius", 12.0f) * 0.01f) { + continue; + } + if (distance < nearestDistance) { + nearestDistance = distance; + nearest = kind; + } + } + } + if (nearest != Kind::None) { + sNear[VR_HAND_RIGHT] = true; + sNearKind = nearest; + if (pressed[VR_HAND_RIGHT]) Take(nearest, VR_HAND_RIGHT); + } +} + +static void DrawKey(Kind kind, const void* interpKey) { + float pos[3], side[3], up[3], forward[3]; + if (!Pose(kind, pos, side, up, forward)) return; + Vec3s rot; + VrPocket::SetRotFromAxes(&rot, side, up, forward); + GraphicsContext* gfxCtx = gPlayState->state.gfxCtx; + const float anchorScale = kind == Kind::Boss ? 0.018f : 0.022f; + // The two get-item models have very different authored proportions, so each key needs its own + // real-world calibration. Fall back to the former shared setting to preserve existing configs. + const float legacyHeldScale = CVarGetFloat("gVrKeyHeldScale", 180.0f); + const float heldScale = CVarGetFloat(kind == Kind::Boss ? "gVrBossKeyHeldScale" : "gVrSmallKeyHeldScale", + legacyHeldScale) / + 100.0f; + const float scale = anchorScale * (sHeld == kind ? heldScale : 1.0f); + OPEN_DISPS(gfxCtx); + FrameInterpolation_RecordOpenChild(interpKey, 0); + Matrix_SetTranslateRotateYXZ(pos[0], pos[1], pos[2], &rot); + Matrix_RotateX(1.57079632679f, MTXMODE_APPLY); + if (sHeld == kind) { + // Roll around the authored length axis. Different controller grips need fine calibration, + // so expose the value while the key is held. Once inserted, use the canonical quarter-turn + // instead: controller calibration must not leave the Boss Key tilted in the door's lock. + // The get-item key is authored upside-down relative to the grip basis. Preserve the + // exposed calibration while applying the required half-turn so its teeth point down. + const char* heldRoll = kind == Kind::Boss ? "gVrBossKeyRollDeg" : "gVrSmallKeyRollDeg"; + const char* insertRoll = kind == Kind::Boss ? "gVrBossKeyInsertRollDeg" : "gVrSmallKeyInsertRollDeg"; + const char* insertRotX = kind == Kind::Boss ? "gVrBossKeyInsertRotXDeg" : "gVrSmallKeyInsertRotXDeg"; + const char* insertRotZ = kind == Kind::Boss ? "gVrBossKeyInsertRotZDeg" : "gVrSmallKeyInsertRotZDeg"; + if (sInsertState != InsertState::None) { + Matrix_RotateX(CVarGetFloat(insertRotX, 0.0f) * (M_PI / 180.0f), MTXMODE_APPLY); + } + const float rollDeg = sInsertState == InsertState::None + ? CVarGetFloat(heldRoll, CVarGetFloat("gVrKeyRollDeg", -90.0f)) + 180.0f + : CVarGetFloat(insertRoll, 90.0f); + Matrix_RotateY(rollDeg * (M_PI / 180.0f), MTXMODE_APPLY); + if (sInsertState != InsertState::None) { + Matrix_RotateZ(CVarGetFloat(insertRotZ, 0.0f) * (M_PI / 180.0f), MTXMODE_APPLY); + } + // Both get-item meshes are authored diagonally in their XY plane rather than along +Y. + // Straighten their measured principal axis before applying the hand-space pose. + const float straightenDeg = kind == Kind::Boss ? 36.1f : 37.3f; + Matrix_RotateZ(straightenDeg * (M_PI / 180.0f), MTXMODE_APPLY); + } + Matrix_Scale(scale, scale, scale, MTXMODE_APPLY); + if (sHeld == kind) { + // Place the measured centre of the non-blade handle at the controller origin. Translation + // is model-space (and therefore scales with Held Key Size), leaving the decorative head + // outside the fist while the shaft and teeth extend away from it. + const float gripCenter = kind == Kind::Boss ? 15.0f : 18.0f; + Matrix_Translate(-gripCenter, -gripCenter, 0.0f, MTXMODE_APPLY); + } + MtxF cur; Matrix_Get(&cur); + Mtx* mtx = MATRIX_NEWMTX(gfxCtx); + const int weldHand = sHeld == kind ? sHand : VR_HAND_LEFT; + MtxF hand; + if (weldHand >= 0 && VR_GetHandMatrix(weldHand, hand.mf)) { + MtxF inv, local; + SkinMatrix_Invert(&hand, &inv); + SkinMatrix_MtxFMtxFMult(&inv, &cur, &local); + VR_RegisterHandChildMatrix(mtx, weldHand, &local.mf[0][0]); + } + POLY_OPA_DISP = Play_SetFog(gPlayState, POLY_OPA_DISP); + Gfx_SetupDL_25Opa(gfxCtx); + gSPMatrix(POLY_OPA_DISP++, mtx, G_MTX_NOPUSH | G_MTX_LOAD | G_MTX_MODELVIEW); + gSPDisplayList(POLY_OPA_DISP++, (Gfx*)(kind == Kind::Boss ? gGiBossKeyDL : gGiSmallKeyDL)); + if (kind == Kind::Boss) { + Gfx_SetupDL_25Xlu(gfxCtx); + gSPMatrix(POLY_XLU_DISP++, mtx, G_MTX_NOPUSH | G_MTX_LOAD | G_MTX_MODELVIEW); + gSPDisplayList(POLY_XLU_DISP++, (Gfx*)gGiBossKeyGemDL); + } + FrameInterpolation_RecordCloseChild(); + CLOSE_DISPS(gfxCtx); +} + +extern "C" void VrKeys_Draw(void) { + if (!gPlayState || !Gate(gPlayState, GET_PLAYER(gPlayState))) return; + if (sHeld == Kind::Small) DrawKey(Kind::Small, &sHeldInterpKey); + if (sHeld == Kind::Boss) DrawKey(Kind::Boss, &sHeldInterpKey); + // Availability is represented by two-dimensional wrist-HUD icons. This hook draws only the + // physical model created after the player actually takes one of those icons into their hand. +} + +namespace { +void RegisterVrKeys() { COND_HOOK(OnPlayDrawEnd, true, VrKeys_Draw); } +static RegisterShipInitFunc initVrKeys(RegisterVrKeys); +} diff --git a/soh/soh/Enhancements/vr-combat/VrSwing.cpp b/soh/soh/Enhancements/vr-combat/VrSwing.cpp index ec6befde425..f9c8a08fa87 100644 --- a/soh/soh/Enhancements/vr-combat/VrSwing.cpp +++ b/soh/soh/Enhancements/vr-combat/VrSwing.cpp @@ -1071,6 +1071,8 @@ VrBladeSample sHammerPath[16]; int sHammerPathCount = 0; float sHammerLastVel[3] = { 0.0f, 0.0f, 0.0f }; // newest sample of the previous snapshot int sPoundCooldown = 0; +Vec3f sHammerFloorProbe = {}; +bool sHammerFloorProbeValid = false; inline Vec3f ModelPt(float x, float y, float z) { Vec3f m = { x, y, z }; @@ -1155,6 +1157,13 @@ void FeedHammer(PlayState* play, Player* player) { const Vec3f rimOff = vsub(headOut0, headC0); // world: along the handle, head radius long const Vec3f axisDir = vnorm(vsub(headHi0, headLo0)); + // Lowest point of the visible/colliding drum. The player update uses last draw's live pose for + // the optional floor-only reach assist; keeping this separate from the physics capsule means + // the hammer remains exact against walls, enemies and props. + sHammerFloorProbe = headLo0.y < headHi0.y ? headLo0 : headHi0; + sHammerFloorProbe.y -= headR; + sHammerFloorProbeValid = true; + float effPosArr[3]; float effQuatArr[4]; const bool haveEff = VR_GetHandPose(hand, effPosArr, effQuatArr); @@ -1424,6 +1433,56 @@ void HammerContact(PlayState* play, Player* player, const VrContactEvent& ev) { VrCombat::Hammer_NoteImpact(approach, result, strike); } +// Accessibility/reach assist for players whose standing arm span cannot put the visible hammer on +// Link's floor. This deliberately synthesizes only a ground pound: it never enlarges the hammer's +// wall, enemy, or object collider, and still requires the normal downward pound velocity. +void HammerFloorReachAssist(PlayState* play, Player* player) { + const float reachCm = CVarGetFloat("gVrHammerPoundReach", 15.0f); + if (!sHammerFloorProbeValid || reachCm <= 0.0f || sPoundCooldown != 0 || sHammerPathCount == 0) { + return; + } + + float downwardMps = 0.0f; + for (int i = 0; i < sHammerPathCount; i++) { + downwardMps = fmaxf(downwardMps, -sHammerPath[i].midVelMps[1]); + } + const float poundSpeed = CVarGetFloat("gVrHammerPoundSpeed", 2.5f); + if (downwardMps < poundSpeed) { + return; + } + + CollisionPoly* floorPoly = NULL; + s32 floorBgId = BGCHECK_SCENE; + Vec3f rayPos = sHammerFloorProbe; + const float floorY = BgCheck_EntityRaycastFloor3(&play->colCtx, &floorPoly, &floorBgId, &rayPos); + if (floorY <= BGCHECK_Y_MIN || floorPoly == NULL || COLPOLY_GET_NORMAL(floorPoly->normal.y) < + CVarGetFloat("gVrHammerFloorNormal", 0.6f)) { + return; + } + + float worldScale = VR_GetWorldScale(); + if (worldScale < 1.0f) { + worldScale = 35.0f; + } + const float gap = sHammerFloorProbe.y - floorY; + const float reachUnits = reachCm * 0.01f * worldScale; + if (gap < 0.0f || gap > reachUnits) { + return; + } + + const float impact[3] = { sHammerFloorProbe.x, floorY, sHammerFloorProbe.z }; + Player_VrHammerImpact(play, player, impact, 1); + sPoundCooldown = 8; + const VrCombat::HammerGrip& grip = VrCombat::Hammer_GetGrip(); + float amp = fminf(0.7f + 0.06f * downwardMps, 1.0f); + float ms = fminf(70.0f + 15.0f * downwardMps, 180.0f); + VR_TriggerHaptic(SwordHand(), amp, 0.0f, ms); + if (grip.twoHand && grip.offHand >= 0) { + VR_TriggerHaptic(grip.offHand, amp, 0.0f, ms); + } + VrCombat::Hammer_NoteImpact(downwardMps, 1, 0); +} + } // namespace extern "C" bool VrCombat_MeleeCovered(Player* player) { @@ -1848,11 +1907,15 @@ void Swing_OnPlayerUpdate(PlayState* play, Player* player) { sHammerPathCount = VR_PhysGetBladePath(VR_PHYS_SLOT_WEAPON, sHammerPath, 16); } else { sHammerPathCount = 0; + sHammerFloorProbeValid = false; } if (sPoundCooldown > 0) { sPoundCooldown--; } VrCombat::Hammer_Tick(play, player); + if (hammer) { + HammerFloorReachAssist(play, player); + } // Contact events from the sim: impact SFX + sparks at the contact point (the matching // haptics already fired VR-side with zero latency). diff --git a/soh/soh/Network/Anchor/Anchor.h b/soh/soh/Network/Anchor/Anchor.h index ae79228472b..7c44979e561 100644 --- a/soh/soh/Network/Anchor/Anchor.h +++ b/soh/soh/Network/Anchor/Anchor.h @@ -58,6 +58,11 @@ typedef struct { f32 ocarinaModulator; s8 ocarinaBend; + // Optional extension carried by PLAYER_UPDATE. Older/non-VR clients omit it and retain the + // ordinary networked animation. Matrices are game-world MtxF snapshots for head/left/right. + bool vrTracked; + MtxF vrPose[3]; + // Ptr to the dummy player Player* player; } AnchorClient; diff --git a/soh/soh/Network/Anchor/DummyPlayer.cpp b/soh/soh/Network/Anchor/DummyPlayer.cpp index fae13d5849b..d8d012bdc22 100644 --- a/soh/soh/Network/Anchor/DummyPlayer.cpp +++ b/soh/soh/Network/Anchor/DummyPlayer.cpp @@ -1,5 +1,6 @@ #include "Anchor.h" #include "soh/Enhancements/nametag.h" +#include extern "C" { #include "macros.h" @@ -255,3 +256,29 @@ void DummyPlayer_Destroy(Actor* actor, PlayState* play) { // correctly. actor->id = ACTOR_PLAYER; } + +// Called from the normal Player limb renderer after it selects the dummy's ordinary full-body +// display lists. Replacing only these matrices preserves the complete torso/legs/gear while the +// remote headset and controllers drive the visible head and hands. Non-VR/older peers fall back +// to their transmitted skeletal animation because vrTracked remains false. +extern "C" s32 Anchor_ApplyRemoteVrLimbPose(Player* player, s32 limbIndex) { + if (player == nullptr || !CVarGetInteger("gVrAnchorShowTracking", 1) || Anchor::Instance == nullptr) return false; + const uint32_t clientId = Anchor::Instance->GetDummyPlayerClientId(&player->actor); + if (clientId == 0 || !Anchor::Instance->clients.contains(clientId)) return false; + AnchorClient& client = Anchor::Instance->clients[clientId]; + if (!client.vrTracked) return false; + int part = -1; + if (limbIndex == PLAYER_LIMB_HEAD) part = 0; + else if (limbIndex == PLAYER_LIMB_L_HAND) part = 1; + else if (limbIndex == PLAYER_LIMB_R_HAND) part = 2; + if (part < 0) return false; + Matrix_Put(&client.vrPose[part]); + if (part == 0) { + // The OpenXR head frame has unit axes; Link's authored head geometry expects actor scale. + Matrix_Scale(player->actor.scale.x, player->actor.scale.y, player->actor.scale.z, MTXMODE_APPLY); + Matrix_Translate(CVarGetFloat("gVrAnchorHeadOffsetX", 0.0f), + CVarGetFloat("gVrAnchorHeadOffsetY", -180.0f), + CVarGetFloat("gVrAnchorHeadOffsetZ", 0.0f), MTXMODE_APPLY); + } + return true; +} diff --git a/soh/soh/Network/Anchor/JsonConversions.hpp b/soh/soh/Network/Anchor/JsonConversions.hpp index f2720058af5..de5e9286dce 100644 --- a/soh/soh/Network/Anchor/JsonConversions.hpp +++ b/soh/soh/Network/Anchor/JsonConversions.hpp @@ -64,6 +64,8 @@ inline void from_json(const json& j, AnchorClient& client) { client.curRoomNum = j.value("curRoomNum", (s8)-1); client.entranceIndex = j.value("entranceIndex", (s32)0); client.self = j.value("self", false); + client.vrTracked = false; + for (MtxF& pose : client.vrPose) pose = MtxF{}; } inline void to_json(json& j, const Inventory& inventory) { diff --git a/soh/soh/Network/Anchor/Packets/PlayerUpdate.cpp b/soh/soh/Network/Anchor/Packets/PlayerUpdate.cpp index b43ae0a4804..9ca3513a188 100644 --- a/soh/soh/Network/Anchor/Packets/PlayerUpdate.cpp +++ b/soh/soh/Network/Anchor/Packets/PlayerUpdate.cpp @@ -1,6 +1,8 @@ #include "soh/Network/Anchor/Anchor.h" #include "soh/Network/Anchor/JsonConversions.hpp" #include +#include +#include extern "C" { #include "macros.h" @@ -68,6 +70,25 @@ void Anchor::SendPacket_PlayerUpdate() { payload["actionVar1"] = player->av1.actionVar1; payload["quiet"] = true; + // Optional VR pose extension. Hide Link Body is intentionally not transmitted: it is a local + // comfort setting, while remote clients always render a complete avatar. The server only needs + // to relay these extra JSON members; old clients safely ignore them. + const bool shareVr = CVarGetInteger("gVrAnchorShareTracking", 1) && VR_IsInitialized() && + VR_GetFirstPerson() && !VR_IsFlatScreen(); + payload["vrTracked"] = shareVr; + if (shareVr) { + MtxF pose[3] = {}; + const bool valid = VR_GetHeadMatrix(pose[0].mf) && VR_GetHandMatrix(VR_HAND_LEFT, pose[1].mf) && + VR_GetHandMatrix(VR_HAND_RIGHT, pose[2].mf); + payload["vrTracked"] = valid; + if (valid) { + for (int part = 0; part < 3; ++part) { + std::vector matrix(&pose[part].mf[0][0], &pose[part].mf[0][0] + 16); + payload["vrPose"][part] = matrix; + } + } + } + for (auto& [clientId, client] : clients) { if (client.sceneNum == gPlayState->sceneNum && client.online && client.isSaveLoaded && !client.self) { payload["targetClientId"] = clientId; @@ -113,5 +134,19 @@ void Anchor::HandlePacket_PlayerUpdate(nlohmann::json payload) { client.unk_862 = payload.value("unk_862", (s16)0); client.unk_85C = payload.value("unk_85C", (f32)0); client.actionVar1 = payload.value("actionVar1", (s8)0); + client.vrTracked = payload.value("vrTracked", false); + if (client.vrTracked && payload.contains("vrPose") && payload["vrPose"].is_array() && + payload["vrPose"].size() >= 3) { + for (int part = 0; part < 3; ++part) { + std::vector matrix = payload["vrPose"][part].get>(); + if (matrix.size() < 16) { + client.vrTracked = false; + break; + } + for (int i = 0; i < 16; ++i) (&client.vrPose[part].mf[0][0])[i] = matrix[i]; + } + } else { + client.vrTracked = false; + } } } diff --git a/soh/soh/Notification/Notification.cpp b/soh/soh/Notification/Notification.cpp index b92c7a4cc02..611ee62b9d0 100644 --- a/soh/soh/Notification/Notification.cpp +++ b/soh/soh/Notification/Notification.cpp @@ -10,6 +10,7 @@ extern "C" { } #include +#include namespace Notification { @@ -127,6 +128,7 @@ void Window::UpdateElement() { --index; } } + VR_SetNotificationsVisible(!notifications.empty() && CVarGetInteger(CVAR_SETTING("Notifications.Position"), 3) != 4); } void Emit(Options notification) { @@ -135,6 +137,7 @@ void Emit(Options notification) { notification.remainingTime = CVarGetFloat(CVAR_SETTING("Notifications.Duration"), 10.0f); } notifications.push_back(notification); + VR_SetNotificationsVisible(CVarGetInteger(CVAR_SETTING("Notifications.Position"), 3) != 4); if (!notification.mute && !CVarGetInteger(CVAR_SETTING("Notifications.Mute"), 0)) { Audio_PlaySoundGeneral(NA_SE_SY_METRONOME, &gSfxDefaultPos, 4, &gSfxDefaultFreqAndVolScale, &gSfxDefaultFreqAndVolScale, &gSfxDefaultReverb); diff --git a/soh/soh/OTRGlobals.cpp b/soh/soh/OTRGlobals.cpp index 2118aa4ddbe..ba4a7a68cda 100644 --- a/soh/soh/OTRGlobals.cpp +++ b/soh/soh/OTRGlobals.cpp @@ -12,6 +12,7 @@ #include "ResourceManagerHelpers.h" #include #include +#include #include #include #include @@ -1557,6 +1558,7 @@ bool VerifyArchiveVersion(OTRVersion version) { extern "C" void InitOTR(int argc, char* argv[]) { OTRGlobals::Instance = new OTRGlobals(); + vr_benchmark_apply_preset(); OTRGlobals::Instance->RunExtract(argc, argv); OTRGlobals::Instance->Initialize(); diff --git a/soh/soh/SohGui/SohMenuVRSettings.cpp b/soh/soh/SohGui/SohMenuVRSettings.cpp index ca48bc3abe3..eb1b5952a91 100644 --- a/soh/soh/SohGui/SohMenuVRSettings.cpp +++ b/soh/soh/SohGui/SohMenuVRSettings.cpp @@ -46,6 +46,8 @@ static const std::map vrHudLayoutOptions = { // Open state of the collapsed "Calibration (Dev)" groups (closed every launch). static bool sVrComfortCalOpen = false; static bool sVrCombatCalOpen = false; +static bool sVrSmallKeyCalOpen = false; +static bool sVrBossKeyCalOpen = false; static bool VrHudWristLayout() { return CVarGetInteger("gVrHudLayout", 0) == 0; @@ -435,11 +437,33 @@ static void VrPerformanceReadout(WidgetInfo& info) { VrFrameStats s = {}; vr_get_frame_stats(&s); +#ifdef __ANDROID__ + constexpr int singlePassDefault = 1; +#else + constexpr int singlePassDefault = 0; +#endif + const bool singlePassRequested = CVarGetInteger("gVrMultiview", singlePassDefault) != 0; + const bool singlePassActive = vr_multiview_enabled(); + if (singlePassActive) { + ImGui::TextUnformatted("Stereo renderer Single-pass"); + } else if (singlePassRequested) { + ImGui::TextUnformatted("Stereo renderer Two-pass (restart or unsupported)"); + } else { + ImGui::TextUnformatted("Stereo renderer Two-pass"); + } + const bool hiddenAreaRequested = CVarGetInteger("gVrHiddenAreaMask", 0) != 0; + if (vr_visibility_mask_enabled()) { + ImGui::TextUnformatted("Hidden-area mask Active"); + } else if (hiddenAreaRequested) { + ImGui::TextUnformatted("Hidden-area mask Restart or unsupported"); + } else { + ImGui::TextUnformatted("Hidden-area mask Off"); + } ImGui::Text("XR frames submitted %6.1f Hz", s.frame_hz); ImGui::Text("Stereo pairs rendered %6.1f Hz", s.eye_hz); ImGui::Separator(); ImGui::Text("XR wait (headroom) %6.2f ms", s.wait_ms); - ImGui::Text("Both eye passes %6.2f ms", s.eyes_ms); + ImGui::Text("Stereo eye rendering %6.2f ms", s.eyes_ms); ImGui::Text("HUD quad pass %6.2f ms", s.hud_ms); ImGui::Text("Companion window %6.2f ms", s.desktop_ms); ImGui::Text("Whole frame %6.2f ms", s.frame_ms); @@ -655,6 +679,10 @@ static void VrHudProfileEditor(int child) { VrHudSaveSoon(); } for (const auto& f : kVrHudElementFields) { + if ((d.id == VR_HUD_EL_PHYSICAL_KEYS || d.id == VR_HUD_EL_PHYSICAL_BOSS_KEY) && + strcmp(f.field, "X") == 0) { + continue; + } VrHudElementCVar(name, sizeof(name), child, d.key, f.field); VrHudSliderRow(f.label, name, VrHudElementDefault(d, child, f.field), f.min, f.max, f.fmt, nullptr); } @@ -1635,7 +1663,207 @@ void SohMenu::AddMenuVRSettings() { .Tooltip("When you get an item and Link holds it up, it sits this much further " "out from your hands (away from you), so it isn't right on top of " "your head. It still follows your hands.")); + AddWidget(gameplayPath, "Bombchus", WIDGET_SEPARATOR_TEXT); + AddWidget(gameplayPath, "Bombchu Floor Aim Arrow", WIDGET_CVAR_CHECKBOX) + .CVar("gVrBombchuAimGuide") + .Options(CheckboxOptions() + .DefaultValue(true) + .Tooltip("Shows an always-visible yellow arrow on the floor while holding a physical " + "bombchu. The arrow follows your horizontal view direction and shows where " + "the bombchu will crawl after release.")); + AddWidget(gameplayPath, "Physical Bombchu Fuse: %.1f s", WIDGET_CVAR_SLIDER_FLOAT) + .CVar("gVrBombchuFuseSeconds") + .Options(FloatSliderOptions() + .Min(6.0f) + .Max(20.0f) + .DefaultValue(8.0f) + .Step(0.5f) + .Format("%.1f") + .Tooltip("Fuse duration for bombchus grabbed through the physical VR interaction. " + "Defaults to eight seconds; six seconds is the original duration. This does not affect button-used " + "bombchus or non-VR gameplay.")); + AddWidget(gameplayPath, "Fairy Bow", WIDGET_SEPARATOR_TEXT); + AddWidget(gameplayPath, "Bow-Hand Trigger Cycles Arrows", WIDGET_CVAR_CHECKBOX) + .CVar("gVrBowTriggerArrowCycle") + .Options(CheckboxOptions().DefaultValue(false).Tooltip( + "While a physical bow arrow is nocked, press the bow-hand trigger to cycle through " + "normal, fire, ice and light arrows. Types you do not own or cannot afford are skipped. " + "Works on foot and on Epona, and does not change non-VR controls.")); AddWidget(gameplayPath, "Climbing", WIDGET_SEPARATOR_TEXT); + AddWidget(gameplayPath, "Physical Doors", WIDGET_CVAR_CHECKBOX) + .CVar("gVrPhysicalDoors") + .Options(CheckboxOptions().DefaultValue(true).Tooltip( + "Ordinary unlocked hinged doors can be opened by grabbing the handle, turning it, then " + "pushing or pulling the leaf around its hinge. Locked and special doors retain their " + "original controls. VR only.")); + AddWidget(gameplayPath, "Physical Chests", WIDGET_CVAR_CHECKBOX) + .CVar("gVrPhysicalChests") + .Options(CheckboxOptions().DefaultValue(false).Tooltip( + "First-person VR only: place both hands anywhere on an unopened chest lid, hold both grips, " + "and lift to open it. The item rises from the opened chest before its normal message and fanfare.")); + AddWidget(gameplayPath, "Show Door Grab Markers", WIDGET_CVAR_CHECKBOX) + .CVar("gVrDoorShowGrabMarkers") + .PreFunc([](WidgetInfo& info) { info.isHidden = !CVarGetInteger("gVrPhysicalDoors", 1); }) + .Options(CheckboxOptions().DefaultValue(true).Tooltip( + "Shows miniature Deku Nuts at the two physical door-knob grab zones. Hiding them does not disable grabbing.")); + AddWidget(gameplayPath, "Door Handle Right Offset: %.1f", WIDGET_CVAR_SLIDER_FLOAT) + .CVar("gVrDoorHandleRight") + .PreFunc([](WidgetInfo& info) { info.isHidden = !CVarGetInteger("gVrPhysicalDoors", 1); }) + .Options(FloatSliderOptions().Min(0.0f).Max(40.0f).DefaultValue(23.0f).Step(0.5f).Format("%.1f") + .Tooltip("Development calibration: distance from the centre toward the visible right-hand side.")); + AddWidget(gameplayPath, "Door Handle Height: %.1f", WIDGET_CVAR_SLIDER_FLOAT) + .CVar("gVrDoorHandleY") + .PreFunc([](WidgetInfo& info) { info.isHidden = !CVarGetInteger("gVrPhysicalDoors", 1); }) + .Options(FloatSliderOptions().Min(10.0f).Max(80.0f).DefaultValue(38.0f).Step(0.5f).Format("%.1f") + .Tooltip("Development calibration: moves the Deku Nut grab point vertically.")); + AddWidget(gameplayPath, "Door Handle Surface Offset: %.1f", WIDGET_CVAR_SLIDER_FLOAT) + .CVar("gVrDoorHandleDepth") + .PreFunc([](WidgetInfo& info) { info.isHidden = !CVarGetInteger("gVrPhysicalDoors", 1); }) + .Options(FloatSliderOptions().Min(0.0f).Max(15.0f).DefaultValue(3.0f).Step(0.5f).Format("%.1f") + .Tooltip("Development calibration: moves the marker outward from each face of the door.")); + AddWidget(gameplayPath, "Door Hinge Offset: %.1f", WIDGET_CVAR_SLIDER_FLOAT) + .CVar("gVrDoorHingeOffset") + .PreFunc([](WidgetInfo& info) { info.isHidden = !CVarGetInteger("gVrPhysicalDoors", 1); }) + .Options(FloatSliderOptions().Min(20.0f).Max(40.0f).DefaultValue(27.0f).Step(0.25f).Format("%.2f") + .Tooltip("Aligns handle markers and collision with the rendered door's skeletal hinge while it rotates.")); + AddWidget(gameplayPath, "Door Grab Radius: %.0f cm", WIDGET_CVAR_SLIDER_FLOAT) + .CVar("gVrDoorGrabRadius") + .PreFunc([](WidgetInfo& info) { info.isHidden = !CVarGetInteger("gVrPhysicalDoors", 1); }) + .Options(FloatSliderOptions().Min(5.0f).Max(35.0f).DefaultValue(18.0f).Step(1.0f).Format("%.0f cm") + .Tooltip("Development calibration: hand distance from the Deku Nut that accepts a fresh grab.")); + AddWidget(gameplayPath, "Door Swing Amount: %.2fx", WIDGET_CVAR_SLIDER_FLOAT) + .CVar("gVrDoorSwingGain") + .PreFunc([](WidgetInfo& info) { info.isHidden = !CVarGetInteger("gVrPhysicalDoors", 1); }) + .Options(FloatSliderOptions().Min(0.75f).Max(3.0f).DefaultValue(1.75f).Step(0.05f).Format("%.2fx") + .Tooltip("Development calibration: how far the door swings for the physical hand arc.")); + AddWidget(gameplayPath, "Share VR Tracking with Anchor", WIDGET_CVAR_CHECKBOX) + .CVar("gVrAnchorShareTracking") + .Options(CheckboxOptions().DefaultValue(true).Tooltip( + "Sends headset and controller poses in Anchor player updates. Hide Link Body is never shared; " + "other players continue to see your complete Link avatar.")); + AddWidget(gameplayPath, "Show Anchor Players' VR Tracking", WIDGET_CVAR_CHECKBOX) + .CVar("gVrAnchorShowTracking") + .Options(CheckboxOptions().DefaultValue(true).Tooltip( + "Uses VR tracking included by compatible Anchor peers to pose their visible head and hands. " + "Peers without this extension retain normal networked animations.")); + AddWidget(gameplayPath, "Physical Dungeon Keys", WIDGET_CVAR_CHECKBOX) + .CVar("gVrPhysicalKeys") + .Options(CheckboxOptions().DefaultValue(true).Tooltip( + "Adds Small Key and Boss Key icons beneath the left-hand HUD. Reach to an icon and squeeze " + "grip to create its physical key; releasing returns it unless a compatible lock consumes it.")); + AddWidget(gameplayPath, "Key Grab Radius: %.0f cm", WIDGET_CVAR_SLIDER_FLOAT) + .CVar("gVrKeyGrabRadius") + .PreFunc([](WidgetInfo& info) { info.isHidden = !CVarGetInteger("gVrPhysicalKeys", 1); }) + .Options(FloatSliderOptions().Min(5.0f).Max(30.0f).DefaultValue(12.0f).Step(1.0f).Format("%.0f cm") + .Tooltip("How close the grabbing controller must be to a visible wrist key icon.")); + AddWidget(gameplayPath, "Key Cards Horizontal Offset: %.0f", WIDGET_CVAR_SLIDER_FLOAT) + .CVar("gVrPhysicalKeysOffsetX") + .PreFunc([](WidgetInfo& info) { info.isHidden = !CVarGetInteger("gVrPhysicalKeys", 1); }) + .Options(FloatSliderOptions().Min(-100.0f).Max(100.0f).DefaultValue(0.0f).Step(1.0f).Format("%.0f") + .Tooltip("Moves both key cards together. At zero, the gap between them is aligned with " + "the centre of the main left-wrist HUD card.")); + const size_t smallKeyCalBegin = + vrBeginCollapsed(gameplayPath, "Small Key Calibration##SmallKeyCal", &sVrSmallKeyCalOpen); + AddWidget(gameplayPath, "Held Size: %.0f%%##SmallKey", WIDGET_CVAR_SLIDER_FLOAT) + .CVar("gVrSmallKeyHeldScale") + .PreFunc([](WidgetInfo& info) { info.isHidden = !CVarGetInteger("gVrPhysicalKeys", 1); }) + .Options(FloatSliderOptions().Min(100.0f).Max(5000.0f).DefaultValue(180.0f).Step(25.0f).Format("%.0f%%") + .Tooltip("Size of the physical Small Key after taking it from the wrist icon.")); + AddWidget(gameplayPath, "Held Roll: %.0f deg##SmallKey", WIDGET_CVAR_SLIDER_FLOAT) + .CVar("gVrSmallKeyRollDeg") + .PreFunc([](WidgetInfo& info) { info.isHidden = !CVarGetInteger("gVrPhysicalKeys", 1); }) + .Options(FloatSliderOptions().Min(-180.0f).Max(180.0f).DefaultValue(-90.0f).Step(5.0f).Format("%.0f deg") + .Tooltip("Rolls the held Small Key around its shaft.")); + AddWidget(gameplayPath, "Held Horizontal Position: %.1f cm##SmallKey", WIDGET_CVAR_SLIDER_FLOAT) + .CVar("gVrSmallKeyHeldOffsetX") + .PreFunc([](WidgetInfo& info) { info.isHidden = !CVarGetInteger("gVrPhysicalKeys", 1); }) + .Options(FloatSliderOptions().Min(-30.0f).Max(30.0f).DefaultValue(0.0f).Step(0.5f).Format("%.1f cm")); + AddWidget(gameplayPath, "Held Vertical Position: %.1f cm##SmallKey", WIDGET_CVAR_SLIDER_FLOAT) + .CVar("gVrSmallKeyHeldOffsetY") + .PreFunc([](WidgetInfo& info) { info.isHidden = !CVarGetInteger("gVrPhysicalKeys", 1); }) + .Options(FloatSliderOptions().Min(-30.0f).Max(30.0f).DefaultValue(0.0f).Step(0.5f).Format("%.1f cm")); + AddWidget(gameplayPath, "Held Forward Position: %.1f cm##SmallKey", WIDGET_CVAR_SLIDER_FLOAT) + .CVar("gVrSmallKeyHeldOffsetZ") + .PreFunc([](WidgetInfo& info) { info.isHidden = !CVarGetInteger("gVrPhysicalKeys", 1); }) + .Options(FloatSliderOptions().Min(-30.0f).Max(30.0f).DefaultValue(0.0f).Step(0.5f).Format("%.1f cm")); + AddWidget(gameplayPath, "Lock Rotation Y: %.0f deg##SmallKey", WIDGET_CVAR_SLIDER_FLOAT) + .CVar("gVrSmallKeyInsertRollDeg") + .PreFunc([](WidgetInfo& info) { info.isHidden = !CVarGetInteger("gVrPhysicalKeys", 1); }) + .Options(FloatSliderOptions().Min(-180.0f).Max(180.0f).DefaultValue(90.0f).Step(5.0f).Format("%.0f deg") + .Tooltip("Rotates an inserted Small Key around its Y axis.")); + AddWidget(gameplayPath, "Lock Rotation X: %.0f deg##SmallKey", WIDGET_CVAR_SLIDER_FLOAT) + .CVar("gVrSmallKeyInsertRotXDeg") + .PreFunc([](WidgetInfo& info) { info.isHidden = !CVarGetInteger("gVrPhysicalKeys", 1); }) + .Options(FloatSliderOptions().Min(-180.0f).Max(180.0f).DefaultValue(0.0f).Step(5.0f).Format("%.0f deg")); + AddWidget(gameplayPath, "Lock Rotation Z: %.0f deg##SmallKey", WIDGET_CVAR_SLIDER_FLOAT) + .CVar("gVrSmallKeyInsertRotZDeg") + .PreFunc([](WidgetInfo& info) { info.isHidden = !CVarGetInteger("gVrPhysicalKeys", 1); }) + .Options(FloatSliderOptions().Min(-180.0f).Max(180.0f).DefaultValue(0.0f).Step(5.0f).Format("%.0f deg")); + AddWidget(gameplayPath, "Lock Horizontal Position: %.1f##SmallKey", WIDGET_CVAR_SLIDER_FLOAT) + .CVar("gVrSmallKeyLockOffsetX") + .PreFunc([](WidgetInfo& info) { info.isHidden = !CVarGetInteger("gVrPhysicalKeys", 1); }) + .Options(FloatSliderOptions().Min(-50.0f).Max(50.0f).DefaultValue(0.0f).Step(0.5f).Format("%.1f")); + AddWidget(gameplayPath, "Lock Vertical Position: %.1f##SmallKey", WIDGET_CVAR_SLIDER_FLOAT) + .CVar("gVrSmallKeyLockOffsetY") + .PreFunc([](WidgetInfo& info) { info.isHidden = !CVarGetInteger("gVrPhysicalKeys", 1); }) + .Options(FloatSliderOptions().Min(-50.0f).Max(50.0f).DefaultValue(0.0f).Step(0.5f).Format("%.1f")); + AddWidget(gameplayPath, "Lock Insertion Depth: %.1f##SmallKey", WIDGET_CVAR_SLIDER_FLOAT) + .CVar("gVrSmallKeyLockOffsetDepth") + .PreFunc([](WidgetInfo& info) { info.isHidden = !CVarGetInteger("gVrPhysicalKeys", 1); }) + .Options(FloatSliderOptions().Min(-50.0f).Max(50.0f).DefaultValue(0.0f).Step(0.5f).Format("%.1f")); + vrEndCollapsed(gameplayPath, smallKeyCalBegin, &sVrSmallKeyCalOpen); + + const size_t bossKeyCalBegin = + vrBeginCollapsed(gameplayPath, "Boss Key Calibration##BossKeyCal", &sVrBossKeyCalOpen); + AddWidget(gameplayPath, "Held Size: %.0f%%##BossKey", WIDGET_CVAR_SLIDER_FLOAT) + .CVar("gVrBossKeyHeldScale") + .PreFunc([](WidgetInfo& info) { info.isHidden = !CVarGetInteger("gVrPhysicalKeys", 1); }) + .Options(FloatSliderOptions().Min(100.0f).Max(5000.0f).DefaultValue(180.0f).Step(25.0f).Format("%.0f%%") + .Tooltip("Size of the physical Boss Key after taking it from the wrist icon.")); + AddWidget(gameplayPath, "Held Roll: %.0f deg##BossKey", WIDGET_CVAR_SLIDER_FLOAT) + .CVar("gVrBossKeyRollDeg") + .PreFunc([](WidgetInfo& info) { info.isHidden = !CVarGetInteger("gVrPhysicalKeys", 1); }) + .Options(FloatSliderOptions().Min(-180.0f).Max(180.0f).DefaultValue(-90.0f).Step(5.0f).Format("%.0f deg") + .Tooltip("Rolls the held Boss Key around its shaft.")); + AddWidget(gameplayPath, "Held Horizontal Position: %.1f cm##BossKey", WIDGET_CVAR_SLIDER_FLOAT) + .CVar("gVrBossKeyHeldOffsetX") + .PreFunc([](WidgetInfo& info) { info.isHidden = !CVarGetInteger("gVrPhysicalKeys", 1); }) + .Options(FloatSliderOptions().Min(-30.0f).Max(30.0f).DefaultValue(0.0f).Step(0.5f).Format("%.1f cm")); + AddWidget(gameplayPath, "Held Vertical Position: %.1f cm##BossKey", WIDGET_CVAR_SLIDER_FLOAT) + .CVar("gVrBossKeyHeldOffsetY") + .PreFunc([](WidgetInfo& info) { info.isHidden = !CVarGetInteger("gVrPhysicalKeys", 1); }) + .Options(FloatSliderOptions().Min(-30.0f).Max(30.0f).DefaultValue(0.0f).Step(0.5f).Format("%.1f cm")); + AddWidget(gameplayPath, "Held Forward Position: %.1f cm##BossKey", WIDGET_CVAR_SLIDER_FLOAT) + .CVar("gVrBossKeyHeldOffsetZ") + .PreFunc([](WidgetInfo& info) { info.isHidden = !CVarGetInteger("gVrPhysicalKeys", 1); }) + .Options(FloatSliderOptions().Min(-30.0f).Max(30.0f).DefaultValue(0.0f).Step(0.5f).Format("%.1f cm")); + AddWidget(gameplayPath, "Lock Rotation Y: %.0f deg##BossKey", WIDGET_CVAR_SLIDER_FLOAT) + .CVar("gVrBossKeyInsertRollDeg") + .PreFunc([](WidgetInfo& info) { info.isHidden = !CVarGetInteger("gVrPhysicalKeys", 1); }) + .Options(FloatSliderOptions().Min(-180.0f).Max(180.0f).DefaultValue(90.0f).Step(5.0f).Format("%.0f deg") + .Tooltip("Rotates only an inserted Boss Key around its shaft. Set it so the key's flat plane " + "forms a 90-degree angle with the flat lock face.")); + AddWidget(gameplayPath, "Lock Rotation X: %.0f deg##BossKey", WIDGET_CVAR_SLIDER_FLOAT) + .CVar("gVrBossKeyInsertRotXDeg") + .PreFunc([](WidgetInfo& info) { info.isHidden = !CVarGetInteger("gVrPhysicalKeys", 1); }) + .Options(FloatSliderOptions().Min(-180.0f).Max(180.0f).DefaultValue(0.0f).Step(5.0f).Format("%.0f deg")); + AddWidget(gameplayPath, "Lock Rotation Z: %.0f deg##BossKey", WIDGET_CVAR_SLIDER_FLOAT) + .CVar("gVrBossKeyInsertRotZDeg") + .PreFunc([](WidgetInfo& info) { info.isHidden = !CVarGetInteger("gVrPhysicalKeys", 1); }) + .Options(FloatSliderOptions().Min(-180.0f).Max(180.0f).DefaultValue(0.0f).Step(5.0f).Format("%.0f deg")); + AddWidget(gameplayPath, "Lock Horizontal Position: %.1f##BossKey", WIDGET_CVAR_SLIDER_FLOAT) + .CVar("gVrBossKeyLockOffsetX") + .PreFunc([](WidgetInfo& info) { info.isHidden = !CVarGetInteger("gVrPhysicalKeys", 1); }) + .Options(FloatSliderOptions().Min(-50.0f).Max(50.0f).DefaultValue(0.0f).Step(0.5f).Format("%.1f")); + AddWidget(gameplayPath, "Lock Vertical Position: %.1f##BossKey", WIDGET_CVAR_SLIDER_FLOAT) + .CVar("gVrBossKeyLockOffsetY") + .PreFunc([](WidgetInfo& info) { info.isHidden = !CVarGetInteger("gVrPhysicalKeys", 1); }) + .Options(FloatSliderOptions().Min(-50.0f).Max(50.0f).DefaultValue(0.0f).Step(0.5f).Format("%.1f")); + AddWidget(gameplayPath, "Lock Insertion Depth: %.1f##BossKey", WIDGET_CVAR_SLIDER_FLOAT) + .CVar("gVrBossKeyLockOffsetDepth") + .PreFunc([](WidgetInfo& info) { info.isHidden = !CVarGetInteger("gVrPhysicalKeys", 1); }) + .Options(FloatSliderOptions().Min(-50.0f).Max(50.0f).DefaultValue(0.0f).Step(0.5f).Format("%.1f")); + vrEndCollapsed(gameplayPath, bossKeyCalBegin, &sVrBossKeyCalOpen); AddWidget(gameplayPath, "Physical Climbing", WIDGET_CVAR_CHECKBOX) .CVar("gVrPhysClimb") .Options(CheckboxOptions() @@ -1675,6 +1903,38 @@ void SohMenu::AddMenuVRSettings() { "speed readout below. Arrow color previews the swing tiers: green = too slow to " "count, yellow = normal hit, red = strong hit.")); + AddWidget(physPath, "Megaton Hammer", WIDGET_SEPARATOR_TEXT); + AddWidget(physPath, "Physical Hammer", WIDGET_CVAR_CHECKBOX) + .CVar("gVrPhysHammer") + .Options(CheckboxOptions() + .DefaultValue(true) + .Tooltip("The hammer swings with your arms and has real weight: the head trails your " + "hands and carries through, and it stops dead on walls, floors and bodies. " + "One-handed it is slow and droops; squeeze grip with your other hand on the " + "handle to hold it with both for control and power. Disable for the base game's " + "button swings.")); + AddWidget(physPath, "Hammer Ground-Pound Reach: %.0f cm", WIDGET_CVAR_SLIDER_FLOAT) + .CVar("gVrHammerPoundReach") + .Options(FloatSliderOptions() + .Min(0.0f) + .Max(60.0f) + .DefaultValue(15.0f) + .Step(1.0f) + .Format("%.0f") + .Tooltip("Extra floor-only reach for a downward ground-pound swing. This helps players whose " + "standing arm reach cannot put the hammer on the floor. Zero requires exact physical " + "contact; enemy, wall, and object collision are never extended.")); + AddWidget(physPath, "Hammer Ground-Pound Speed: %.1f m/s", WIDGET_CVAR_SLIDER_FLOAT) + .CVar("gVrHammerPoundSpeed") + .Options(FloatSliderOptions() + .Min(0.5f) + .Max(8.0f) + .DefaultValue(2.5f) + .Step(0.1f) + .Format("%.1f") + .Tooltip("How fast the head must move downward for a ground pound. This speed is required " + "for both exact floor contact and the optional reach assist.")); + const size_t combatCalBegin = vrBeginCollapsed(physPath, "Calibration (Dev)##CombatCal", &sVrCombatCalOpen); AddWidget(physPath, "Sword Swing Speeds", WIDGET_SEPARATOR_TEXT); @@ -2669,8 +2929,8 @@ void SohMenu::AddMenuVRSettings() { AddWidget(perfPath, "Render Cost", WIDGET_SEPARATOR_TEXT); AddWidget(perfPath, "The game's display list is walked once per eye, every frame (once for both " - "with Single-Pass Stereo on Quest). At 120 Hz that is 240 full traversals a " - "second on one thread, plus the HUD. These " + "when Single-Pass Stereo is supported and enabled). At 120 Hz that is 240 " + "full traversals a second on one thread, plus the HUD. These " "settings trade world-update rate for headroom; head tracking always stays " "at the headset's full rate because skipped frames are reprojected by the " "compositor.", @@ -2732,15 +2992,36 @@ void SohMenu::AddMenuVRSettings() { .Tooltip("Multiplier on the runtime's recommended per-eye resolution. This is " "the GPU-side knob. Applied when the OpenXR session is created, so " "it takes effect on the next restart.")); -#ifdef __ANDROID__ AddWidget(perfPath, "Single-Pass Stereo", WIDGET_CVAR_CHECKBOX) .CVar("gVrMultiview") .Options(CheckboxOptions() +#ifdef __ANDROID__ .DefaultValue(true) +#else + .DefaultValue(false) +#endif .Tooltip("Walk the game's display list once per frame and let the GPU draw both " - "eyes from it (OpenGL ES multiview), instead of once per eye. Roughly " - "halves the render thread's work. Takes effect the next time the game " - "starts. Turn off if the image looks wrong in one eye.")); + "eyes from it, instead of once per eye. This can substantially reduce " + "CPU render-thread work without lowering image quality. Supported on " + "OpenGL ES multiview and compatible PC DirectX 11 hardware; unsupported " + "systems automatically keep the normal two-pass renderer. Takes effect " + "the next time VR starts. Turn off if the image looks wrong in one eye.")); +#ifndef __ANDROID__ + AddWidget(perfPath, "D3D11 State Cache", WIDGET_CVAR_CHECKBOX) + .CVar("gVrD3D11StateCache") + .Options(CheckboxOptions().DefaultValue(true).Tooltip( + "Reuse immutable DirectX 11 depth-stencil and rasterizer states instead of recreating them when " + "render modes repeat. This reduces render-thread and driver work without changing image quality. " + "Turn off only for performance comparisons or troubleshooting; takes effect immediately.")); + AddWidget(perfPath, "Hidden-Area Mask", WIDGET_CVAR_CHECKBOX) + .CVar("gVrHiddenAreaMask") + .Options(CheckboxOptions().DefaultValue(false).Tooltip( + "Use the OpenXR runtime's lens-hidden mesh to skip pixels that cannot be seen through the headset " + "lenses. This preserves the visible image and can reduce GPU work. Currently supported by the " + "DirectX 11 VR renderer; unsupported runtimes automatically render the complete eye image. Takes " + "effect the next time the game starts. Frames copied to the desktop companion render a complete " + "left eye; a higher Companion Window Divisor leaves more headset-only frames available for this " + "optimization.")); #endif AddWidget(perfPath, "Distance-Based Actor Culling", WIDGET_CVAR_CHECKBOX) .CVar("gVrActorCullDistance") @@ -2758,6 +3039,12 @@ void SohMenu::AddMenuVRSettings() { "run at once (cheaper), but enemies and objects far off to your sides " "pause sooner than in vanilla. Default on for Quest, off on PC.")); + AddWidget(perfPath, "Display-List Processing Cache", WIDGET_CVAR_CHECKBOX) + .CVar("gVrInterpreterCache") + .Options(CheckboxOptions().DefaultValue(true).Tooltip( + "Caches immutable geometry resource lookups and repeated shader metadata throughout VR. " + "Improves CPU performance without reducing visual quality. Disable only for compatibility testing.")); + perfPath.column = SECTION_COLUMN_2; AddWidget(perfPath, "Live Frame Cost", WIDGET_SEPARATOR_TEXT); AddWidget(perfPath, "VRPerformanceReadout", WIDGET_CUSTOM).CustomFunction(VrPerformanceReadout).HideInSearch(true); @@ -2895,17 +3182,7 @@ void SohMenu::AddMenuVRSettings() { "Grip closed at that moment = caught into the hand; grip open = it " "vanishes and the pocket shows it again.")); AddWidget(devPath, "VrBoomerangReadout", WIDGET_CUSTOM).CustomFunction(VrBoomerangReadout).HideInSearch(true); - AddWidget(devPath, "Megaton Hammer", WIDGET_SEPARATOR_TEXT); - AddWidget(devPath, "Physical Hammer", WIDGET_CVAR_CHECKBOX) - .CVar("gVrPhysHammer") - .Options(CheckboxOptions() - .DefaultValue(true) - .Tooltip("The hammer swings with your arms and has real weight: the head trails your " - "hands and carries through, and it stops dead on walls, floors and bodies. " - "One-handed it is slow and droops; squeeze grip with your other hand on the " - "handle to hold it with both for control and power. Slam the head into the " - "floor hard enough for the ground pound. Disable for the base game's button " - "swings.")); + AddWidget(devPath, "Megaton Hammer (Advanced)", WIDGET_SEPARATOR_TEXT); AddWidget(devPath, "Hammer One-Hand Torque: %.0f", WIDGET_CVAR_SLIDER_FLOAT) .CVar("gVrHammer1HAccel") .Options(FloatSliderOptions() @@ -3015,17 +3292,6 @@ void SohMenu::AddMenuVRSettings() { .Step(0.1f) .Format("%.1f") .Tooltip("Head speed for the heavy blow (the base game's jump-attack hammer damage).")); - AddWidget(devPath, "Hammer Ground Pound Speed: %.1f m/s", WIDGET_CVAR_SLIDER_FLOAT) - .CVar("gVrHammerPoundSpeed") - .Options(FloatSliderOptions() - .Min(0.5f) - .Max(8.0f) - .DefaultValue(2.5f) - .Step(0.1f) - .Format("%.1f") - .Tooltip("How fast the head must be moving INTO a floor for the ground pound " - "(shockwave, quake, and the thump that flips Tektites and stuns scrubs). " - "The same speed into a wall gives the base game's wall strike.")); AddWidget(devPath, "VrHammerReadout", WIDGET_CUSTOM).CustomFunction(VrHammerReadout).HideInSearch(true); AddWidget(devPath, "Carrying", WIDGET_SEPARATOR_TEXT); AddWidget(devPath, "Physical Carrying", WIDGET_CVAR_CHECKBOX) @@ -3312,8 +3578,7 @@ void SohMenu::AddMenuVRSettings() { "hand to the weapon and squeeze its trigger to nock, pull back to " "draw, release to fire along the line between your hands. Releasing " "with almost no draw cancels the shot and keeps the ammo. Disable " - "for the classic scheme (weapon-hand trigger draws and fires). " - "Shooting galleries and horseback keep their own controls.")); + "for the classic scheme (weapon-hand trigger draws and fires).")); AddWidget(devPath, "Slingshot Nock Reach: %.0f cm", WIDGET_CVAR_SLIDER_FLOAT) .CVar("gVrArcheryNockRadius") .Options(FloatSliderOptions() @@ -3338,6 +3603,12 @@ void SohMenu::AddMenuVRSettings() { .Options(CheckboxOptions().DefaultValue(false).Tooltip( "Shows a small Deku Nut where the string is nocked on the bow and slingshot, so you " "can see where to pinch. Off by default: the string itself is the target.")); + AddWidget(devPath, "Archery Aim Dot", WIDGET_CVAR_CHECKBOX) + .CVar("gVrArcheryAimDot") + .Options(CheckboxOptions().DefaultValue(true).Tooltip( + "Shows a small yellow dot where the physically aimed bow or slingshot shot line meets " + "the world. It appears only while the string or pouch is nocked, and can be disabled " + "without changing projectile aim.")); AddWidget(devPath, "Nock Icon Size: %.0f%%", WIDGET_CVAR_SLIDER_FLOAT) .CVar("gVrArcheryIconScale") .PreFunc([](WidgetInfo& info) { info.isHidden = !CVarGetInteger("gVrArcheryShowIcon", 0); }) diff --git a/soh/soh/z_scene_otr.cpp b/soh/soh/z_scene_otr.cpp index dabfc003986..f494ccdf046 100644 --- a/soh/soh/z_scene_otr.cpp +++ b/soh/soh/z_scene_otr.cpp @@ -6,8 +6,16 @@ #include "soh/resource/type/CollisionHeader.h" #include "soh/resource/type/Cutscene.h" #include +#include +#include #include #include +#include +#include +#include +#ifdef _WIN32 +#include +#endif #include "soh/resource/type/scenecommand/SetCameraSettings.h" #include "soh/resource/type/scenecommand/SetCutscenes.h" #include "soh/resource/type/scenecommand/SetStartPositionList.h" @@ -22,6 +30,7 @@ #include "soh/resource/type/scenecommand/SetLightList.h" #include "soh/resource/type/scenecommand/SetPathways.h" #include "soh/resource/type/scenecommand/SetTransitionActorList.h" +#include "soh/Enhancements/vr-combat/VrCombat.h" #include "soh/resource/type/scenecommand/SetSkyboxSettings.h" #include "soh/resource/type/scenecommand/SetSkyboxModifier.h" #include "soh/resource/type/scenecommand/SetTimeSettings.h" @@ -30,10 +39,40 @@ #include "soh/resource/type/scenecommand/SetEchoSettings.h" #include "soh/resource/type/scenecommand/SetAlternateHeaders.h" #include +#include +#include extern Ship::IResource* OTRPlay_LoadFile(PlayState* play, const char* fileName); extern "C" s32 Object_Spawn(ObjectContext* objectCtx, s16 objectId); extern "C" RomFile sNaviMsgFiles[]; + +static std::vector sVrDoorOriginalObjects; +static std::vector sVrDoorDestinationObjects; +static std::shared_future> sRoomLoadFuture; + +extern "C" void VrDoor_ResetRetainedObjects(void) { + sVrDoorOriginalObjects.clear(); + sVrDoorDestinationObjects.clear(); +} + +extern "C" void VrDoor_ReleaseRetainedObjects(PlayState* play, bool keepDestination) { + if (play == nullptr) return; + const std::vector& keep = keepDestination ? sVrDoorDestinationObjects : sVrDoorOriginalObjects; + if (keep.empty()) return; + s32 lastUsed = play->objectCtx.unk_09 - 1; + for (s32 i = play->objectCtx.unk_09; i < play->objectCtx.num; ++i) { + const s16 id = play->objectCtx.status[i].id; + const s16 absoluteId = id < 0 ? -id : id; + if (std::find(keep.begin(), keep.end(), absoluteId) == keep.end()) { + play->objectCtx.status[i].id = OBJECT_INVALID; + } else { + lastUsed = i; + } + } + play->objectCtx.num = std::max(play->objectCtx.unk_09, lastUsed + 1); + Actor_KillAllWithMissingObject(play, &play->actorCtx); + VrDoor_ResetRetainedObjects(); +} s32 OTRScene_ExecuteCommands(PlayState* play, SOH::Scene* scene); bool Scene_CommandSpawnList(PlayState* play, SOH::ISceneCommand* cmd) { @@ -152,6 +191,39 @@ bool Scene_CommandObjectList(PlayState* play, SOH::ISceneCommand* cmd) { k = 0; i = play->objectCtx.unk_09; + if (VrDoor_KeepPreviousRoomActors()) { + // Normal room streaming replaces this list and kills actors whose object disappears. A + // physical open doorway intentionally keeps both rooms live, so retain the old banks and + // append only objects the destination room does not already share. + if (sVrDoorOriginalObjects.empty()) { + for (s32 existing = play->objectCtx.unk_09; existing < play->objectCtx.num; ++existing) { + const s16 id = play->objectCtx.status[existing].id; + if (id != OBJECT_INVALID) sVrDoorOriginalObjects.push_back(id < 0 ? -id : id); + } + } + sVrDoorDestinationObjects.assign(cmdObj->objects.begin(), cmdObj->objects.end()); + i = play->objectCtx.num; + for (k = 0; k < cmdObj->objects.size(); ++k) { + const s16 wanted = cmdObj->objects[k]; + bool present = false; + for (s32 existing = play->objectCtx.unk_09; existing < play->objectCtx.num; ++existing) { + const s16 loaded = play->objectCtx.status[existing].id; + if (loaded == wanted || loaded == -wanted) { + present = true; + break; + } + } + if (!present) { + s32 slot = play->objectCtx.unk_09; + while (slot < play->objectCtx.num && play->objectCtx.status[slot].id != OBJECT_INVALID) ++slot; + if (slot >= play->objectCtx.num) slot = i++; + if (slot < OBJECT_EXCHANGE_BANK_MAX - 1) OTRfunc_800982FC(&play->objectCtx, slot, wanted); + } + } + play->objectCtx.num = std::min(i, OBJECT_EXCHANGE_BANK_MAX - 1); + return false; + } + // Loop until a mismatch in the object lists // Then clear all object ids past that in the context object list and kill actors for those objects for (i = play->objectCtx.unk_09, k = 0; i < play->objectCtx.num; i++, k++) { @@ -465,8 +537,24 @@ s32 OTRScene_ExecuteCommands(PlayState* play, SOH::Scene* scene) { extern "C" s32 OTRfunc_800973FC(PlayState* play, RoomContext* roomCtx) { if (roomCtx->status == 1) { - // if (!osRecvMesg(&roomCtx->loadQueue, NULL, OS_MESG_NOBLOCK)) { - if (1) { + // Poll instead of waiting on the game thread so physical-door preloading cannot turn + // background resource work into a dropped frame. + const bool asyncReady = sRoomLoadFuture.valid() && + sRoomLoadFuture.wait_for(std::chrono::seconds(0)) == std::future_status::ready; + if (roomCtx->roomToLoad != nullptr || asyncReady) { + auto roomData = roomCtx->roomToLoad != nullptr + ? std::shared_ptr() + : std::static_pointer_cast(sRoomLoadFuture.get()); + if (sRoomLoadFuture.valid()) sRoomLoadFuture = {}; + if (roomData == nullptr) { + if (roomCtx->roomToLoad == nullptr) { + roomCtx->status = 0; + SPDLOG_ERROR("Failed to load room {0:#x}", roomCtx->curRoom.num); + return 0; + } + } else { + roomCtx->roomToLoad = roomData.get(); + } roomCtx->status = 0; roomCtx->curRoom.segment = roomCtx->unk_34; gSegments[3] = VIRTUAL_TO_PHYSICAL(roomCtx->unk_34); @@ -509,10 +597,44 @@ extern "C" s32 OTRRoom_RequestNewRoom(PlayState* play, RoomContext* roomCtx, s32 // DmaMgr_SendRequest2(&roomCtx->dmaRequest, roomCtx->unk_34, play->roomList[roomNum].vromStart, size, 0, //&roomCtx->loadQueue, NULL, __FILE__, __LINE__); - auto roomData = std::static_pointer_cast( - ResourceMgr_GetResourceByNameHandlingMQ(play->roomList[roomNum].fileName)); - roomCtx->status = 1; - roomCtx->roomToLoad = roomData.get(); + if (!VrDoor_IsPhysicalRoomRequest()) { + auto roomData = std::static_pointer_cast( + ResourceMgr_GetResourceByNameHandlingMQ(play->roomList[roomNum].fileName)); + roomCtx->roomToLoad = roomData.get(); + roomCtx->activeBufPage ^= 1; + SPDLOG_INFO("Room Init - curRoom.num: {0:#x}", roomCtx->curRoom.num); + return 1; + } + + std::string roomPath = play->roomList[roomNum].fileName; + if (roomPath.starts_with("__OTR__")) roomPath.erase(0, 7); + if (ResourceMgr_IsGameMasterQuest()) { + const size_t pos = roomPath.find("/nonmq/"); + if (pos != std::string::npos) roomPath.replace(pos, 7, "/mq/"); + } + auto resourceManager = Ship::Context::GetRawInstance()->GetResourceManager(); + // Use a dedicated low-priority worker. The shared resource pool runs at normal priority, + // which can starve the latency-sensitive VR game/render thread during proximity preloads. + sRoomLoadFuture = std::async(std::launch::async, [resourceManager, roomPath]() { +#ifdef _WIN32 + SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL); +#endif + // Every room-local O2R resource shares the room header's path prefix. Cold rooms used + // to resolve all of these resources in a burst, causing the one-time VR frame drop; + // revisits were smooth only because that burst had populated the cache. Warm the same + // set incrementally and yield between files so frame production retains CPU time. + auto files = resourceManager->GetArchiveManager()->ListFiles(roomPath + "*"); + std::shared_ptr roomData; + for (const std::string& file : *files) { + auto resource = resourceManager->LoadResourceProcess(file); + if (file == roomPath) roomData = resource; + std::this_thread::sleep_for(std::chrono::milliseconds(2)); + } + // A custom archive may not expose related assets under the conventional prefix. + if (roomData == nullptr) roomData = resourceManager->LoadResourceProcess(roomPath); + return roomData; + }).share(); + roomCtx->roomToLoad = nullptr; roomCtx->activeBufPage ^= 1; diff --git a/soh/src/code/graph.c b/soh/src/code/graph.c index 56d6dd905f7..2e7c2e39b7e 100644 --- a/soh/src/code/graph.c +++ b/soh/src/code/graph.c @@ -366,6 +366,11 @@ void Graph_Update(GraphicsContext* gfxCtx, GameState* gameState) { VR_SetTextDisplayList(gfxCtx->overlayBuffer, 0.0f, 0.0f, 1.0f, 1.0f); VR_SetTextPanelLayout(CVarGetFloat("gVrTitleLogoWidth", 1.8f), CVarGetFloat("gVrTitleLogoDistance", 2.2f), CVarGetFloat("gVrTitleLogoHeight", 0.0f)); + } else if (VrChest_AwardActive()) { + // With locomotion retained, the player naturally looks down at the open chest. Keep + // its reward text below the item/read line instead of at ordinary dialogue height. + VR_SetTextPanelLayout(CVarGetFloat("gVrTextWidth", 0.9f), CVarGetFloat("gVrTextDistance", 1.4f), + CVarGetFloat("gVrTextHeight", -0.15f) - 0.20f); } else { VR_SetTextPanelLayout(0.0f, 0.0f, 0.0f); } diff --git a/soh/src/code/main.c b/soh/src/code/main.c index 7a555dbc37f..ef0654aeac0 100644 --- a/soh/src/code/main.c +++ b/soh/src/code/main.c @@ -7,6 +7,7 @@ #include "vt.h" #include "stdio.h" #include +#include #include #include "soh/OTRGlobals.h" #include "soh/CrashHandlerExt.h" @@ -45,12 +46,15 @@ void Main_LogSystemHeap(void) { #ifdef _WIN32 int SDL_main(int argc, char* argv[]) { + vr_benchmark_configure(argc, argv); AllocConsole(); (void)freopen("CONIN$", "r", stdin); (void)freopen("CONOUT$", "w", stdout); (void)freopen("CONOUT$", "w", stderr); #ifndef _DEBUG - ShowWindow(GetConsoleWindow(), SW_HIDE); + if (!vr_benchmark_is_enabled()) { + ShowWindow(GetConsoleWindow(), SW_HIDE); + } #endif // Allow non-ascii characters for Windows setlocale(LC_ALL, ".UTF8"); @@ -61,6 +65,10 @@ __attribute__((visibility("default"))) int SDL_main(int argc, char* argv[]) { #else //_WIN32 int main(int argc, char* argv[]) { #endif +#ifndef _WIN32 + vr_benchmark_configure(argc, argv); +#endif + vr_benchmark_remove_arguments(&argc, argv); GameConsole_Init(); InitOTR(argc, argv); // TODO: Was moved to below InitOTR because it requires window to be setup. But will be late to catch crashes. diff --git a/soh/src/code/padmgr.c b/soh/src/code/padmgr.c index 174521a011b..d5750dbf67e 100644 --- a/soh/src/code/padmgr.c +++ b/soh/src/code/padmgr.c @@ -452,6 +452,11 @@ void PadMgr_HandleRetraceMsg(PadMgr* padMgr) { VrHammer_GripConsumed(vrHandIdx, sVrBtnMasks[vrBtnIdx]) || VrBlock_GripConsumed(vrHandIdx, sVrBtnMasks[vrBtnIdx]) || VrCarry_GripConsumed(vrHandIdx, sVrBtnMasks[vrBtnIdx]) || + VrDoor_GripConsumed(vrHandIdx, sVrBtnMasks[vrBtnIdx]) || + VrJabuDoor_GripConsumed(vrHandIdx, sVrBtnMasks[vrBtnIdx]) || + VrShutter_GripConsumed(vrHandIdx, sVrBtnMasks[vrBtnIdx]) || + VrGerudoDoor_GripConsumed(vrHandIdx, sVrBtnMasks[vrBtnIdx]) || + VrChest_GripConsumed(vrHandIdx, sVrBtnMasks[vrBtnIdx]) || VrClimb_GripConsumed(vrHandIdx, sVrBtnMasks[vrBtnIdx]) || VrArchery_PinchConsumed(vrHandIdx, sVrBtnMasks[vrBtnIdx]) || VrCombat_AimTriggerConsumed(vrHandIdx, sVrBtnMasks[vrBtnIdx])) { @@ -466,6 +471,12 @@ void PadMgr_HandleRetraceMsg(PadMgr* padMgr) { sVrBindSelDefaults[vrHandIdx][vrBtnIdx])) : CVarGetInteger(sVrBindCvars[vrHandIdx][vrBtnIdx], sVrBindDefaults[vrHandIdx][vrBtnIdx]); + // Physical archery exclusively owns the gallery's forced B-slot weapon: + // no face button or ordinary binding may also invoke stock shooting. + // VrArchery_ItemButtonMask injects B below only for a physical nock. + if (VrArchery_GalleryOwnsWeapon()) { + mapped &= ~BTN_B; + } // Mask to the real pad bits (drops the PC-only modifier bits if selected). vrPad->button |= (u16)(mapped & 0xFFFF); } diff --git a/soh/src/code/z_actor.c b/soh/src/code/z_actor.c index 0a43d0a1267..fed80fb5ea3 100644 --- a/soh/src/code/z_actor.c +++ b/soh/src/code/z_actor.c @@ -1764,6 +1764,12 @@ void Actor_UpdateBgCheckInfo(PlayState* play, Actor* actor, f32 wallCheckHeight, } } + // SOH [VR] The physical doorway aperture removes the original closed-plane response, then this + // restores solidity at the door leaf's actual rotated position so Link must walk around it. + if (actor->category == ACTORCAT_PLAYER) { + VrDoor_ConstrainPlayerToLeaf(actor); + } + sp64.x = actor->world.pos.x; sp64.z = actor->world.pos.z; @@ -3228,7 +3234,8 @@ void Actor_DrawAll(PlayState* play, ActorContext* actorCtx) { // #endregion if ((actor->flags & ACTOR_FLAG_REACT_TO_LENS) && ((play->roomCtx.curRoom.lensMode == LENS_MODE_HIDE_ACTORS) || play->actorCtx.lensActive || - (actor->room != play->roomCtx.curRoom.num))) { + ((actor->room != play->roomCtx.curRoom.num) && + !(VrDoor_KeepPreviousRoomActors() && actor->room == play->roomCtx.prevRoom.num)))) { assert(invisibleActorCounter < INVISIBLE_ACTOR_MAX); invisibleActors[invisibleActorCounter] = actor; invisibleActorCounter++; diff --git a/soh/src/code/z_bgcheck.c b/soh/src/code/z_bgcheck.c index 7339ef9d636..96245ba29e3 100644 --- a/soh/src/code/z_bgcheck.c +++ b/soh/src/code/z_bgcheck.c @@ -4,6 +4,7 @@ #include "soh/OTRGlobals.h" #include "soh/ResourceManagerHelpers.h" #include "soh/Enhancements/game-interactor/GameInteractor_Hooks.h" +#include "soh/Enhancements/vr-combat/VrCombat.h" #include #define SS_NULL 0xFFFF @@ -1902,6 +1903,12 @@ s32 BgCheck_CheckWallImpl(CollisionContext* colCtx, u16 xpFlags, Vec3f* posResul *outPoly = NULL; lookupTbl = colCtx->lookupTbl; *posResult = *posNext; + // SOH [VR] Physical doors: the original scripted animation bypasses the doorway boundary for + // Link. When the player has physically opened and released that door, omit wall response only + // inside its central aperture so both stick walking and roomscale can cross naturally. + if (VrDoor_AllowsWallPass(actor, &posNext->x, &posPrev->x)) { + return false; + } dx = posNext->x - posPrev->x; dy = posNext->y - posPrev->y; dz = posNext->z - posPrev->z; diff --git a/soh/src/code/z_parameter.c b/soh/src/code/z_parameter.c index 50e39247f39..196ec1c41f7 100644 --- a/soh/src/code/z_parameter.c +++ b/soh/src/code/z_parameter.c @@ -22,6 +22,7 @@ #include "soh/ResourceManagerHelpers.h" #include "soh/Enhancements/gameplaystats.h" #include "soh/ObjectExtension/ActorMaximumHealth.h" +#include "soh/Enhancements/vr-combat/VrCombat.h" #include "message_data_static.h" #include // SOH [VR] HUD element markers @@ -5351,16 +5352,38 @@ void Interface_Draw(PlayState* play) { PosY_SKC = PosY_SKC_ori; PosX_SKC = PosX_SKC_ori; } - // Small Key Icon - Interface_VrHudGroup(play, VR_HUD_EL_KEYS, interfaceCtx->magicAlpha); // SOH [VR] + const s32 physicalKeys = VR_IsInitialized() && CVarGetInteger("gVrPhysicalKeys", 1); + // In VR the Small Key is a full 32x32 item icon, matching the Boss Key. + // Its enlarged counter is overlaid in the lower-right so it does not + // widen the measured card or push the two key cards off-centre. + Interface_VrHudGroup(play, physicalKeys ? VR_HUD_EL_PHYSICAL_KEYS : VR_HUD_EL_KEYS, + interfaceCtx->magicAlpha); // SOH [VR] gDPPipeSync(OVERLAY_DISP++); - - gDPSetPrimColor(OVERLAY_DISP++, 0, 0, keyCountColor.r, keyCountColor.g, keyCountColor.b, - interfaceCtx->magicAlpha); - gDPSetEnvColor(OVERLAY_DISP++, 0, 0, 20, - 255); // We reset this here so it match user color :) - OVERLAY_DISP = Gfx_TextureIA8(OVERLAY_DISP, gSmallKeyCounterIconTex, 16, 16, PosX_SKC, - PosY_SKC, 16, 16, 1 << 10, 1 << 10); + if (physicalKeys) { + PosX_SKC = 26; + PosY_SKC = 184; + gDPSetCombineMode(OVERLAY_DISP++, G_CC_MODULATERGBA_PRIM, G_CC_MODULATERGBA_PRIM); + const s32 keyHighlighted = VrKeys_HudHighlighted(0); + gDPSetPrimColor(OVERLAY_DISP++, 0, 0, keyHighlighted ? 255 : 165, + keyHighlighted ? 255 : 165, keyHighlighted ? 255 : 165, + keyHighlighted ? interfaceCtx->magicAlpha + : interfaceCtx->magicAlpha * 185 / 255); + // Dungeon inventory icons are authored at 24x24 (unlike ordinary + // 32x32 item icons). Loading 32x32 read past the vanilla resource + // and appeared corrupted; some HD replacements happened to mask it. + gDPLoadTextureBlock(OVERLAY_DISP++, gItemIcons[ITEM_KEY_SMALL], G_IM_FMT_RGBA, + G_IM_SIZ_32b, 24, 24, 0, G_TX_NOMIRROR | G_TX_CLAMP, + G_TX_NOMIRROR | G_TX_CLAMP, 5, 5, G_TX_NOLOD, G_TX_NOLOD); + gSPWideTextureRectangle(OVERLAY_DISP++, PosX_SKC << 2, PosY_SKC << 2, + (PosX_SKC + 32) << 2, (PosY_SKC + 32) << 2, + G_TX_RENDERTILE, 0, 0, (24 << 10) / 32, (24 << 10) / 32); + } else { + gDPSetPrimColor(OVERLAY_DISP++, 0, 0, keyCountColor.r, keyCountColor.g, + keyCountColor.b, interfaceCtx->magicAlpha); + gDPSetEnvColor(OVERLAY_DISP++, 0, 0, 20, 255); + OVERLAY_DISP = Gfx_TextureIA8(OVERLAY_DISP, gSmallKeyCounterIconTex, 16, 16, + PosX_SKC, PosY_SKC, 16, 16, 1 << 10, 1 << 10); + } // Small Key Counter gDPPipeSync(OVERLAY_DISP++); @@ -5376,17 +5399,23 @@ void Interface_Draw(PlayState* play) { interfaceCtx->counterDigits[3] -= 10; } - svar3 = 16; + svar3 = physicalKeys ? 22 : 16; if (interfaceCtx->counterDigits[2] != 0) { OVERLAY_DISP = Gfx_TextureI8( OVERLAY_DISP, ((u8*)((u8*)digitTextures[interfaceCtx->counterDigits[2]])), 8, 16, - PosX_SKC + 16, PosY_SKC, 8, 16, 1 << 10, 1 << 10); - svar3 = 24; + PosX_SKC + (physicalKeys ? 12 : 16), PosY_SKC + (physicalKeys ? 12 : 0), + physicalKeys ? 10 : 8, physicalKeys ? 20 : 16, + physicalKeys ? (8 << 10) / 10 : 1 << 10, + physicalKeys ? (16 << 10) / 20 : 1 << 10); + svar3 = physicalKeys ? 22 : 24; } OVERLAY_DISP = Gfx_TextureI8(OVERLAY_DISP, ((u8*)digitTextures[interfaceCtx->counterDigits[3]]), 8, 16, - PosX_SKC + svar3, PosY_SKC, 8, 16, 1 << 10, 1 << 10); + PosX_SKC + svar3, PosY_SKC + (physicalKeys ? 12 : 0), + physicalKeys ? 10 : 8, physicalKeys ? 20 : 16, + physicalKeys ? (8 << 10) / 10 : 1 << 10, + physicalKeys ? (16 << 10) / 20 : 1 << 10); } break; default: @@ -5394,6 +5423,25 @@ void Interface_Draw(PlayState* play) { } } + // SOH [VR] Boss Key is a separate wrist-HUD element so its visible icon is also its + // exact physical grab target. The wrist packer places it beside the Small Key card. + if (VR_IsInitialized() && CVarGetInteger("gVrPhysicalKeys", 1) && + VrKeys_BossAvailable(play)) { + Interface_VrHudGroup(play, VR_HUD_EL_PHYSICAL_BOSS_KEY, interfaceCtx->magicAlpha); + gDPPipeSync(OVERLAY_DISP++); + gDPSetCombineMode(OVERLAY_DISP++, G_CC_MODULATERGBA_PRIM, G_CC_MODULATERGBA_PRIM); + const s32 bossKeyHighlighted = VrKeys_HudHighlighted(1); + gDPSetPrimColor(OVERLAY_DISP++, 0, 0, bossKeyHighlighted ? 255 : 165, + bossKeyHighlighted ? 255 : 165, bossKeyHighlighted ? 255 : 165, + bossKeyHighlighted ? interfaceCtx->magicAlpha + : interfaceCtx->magicAlpha * 185 / 255); + gDPLoadTextureBlock(OVERLAY_DISP++, gItemIcons[ITEM_KEY_BOSS], G_IM_FMT_RGBA, G_IM_SIZ_32b, + 24, 24, 0, G_TX_NOMIRROR | G_TX_CLAMP, G_TX_NOMIRROR | G_TX_CLAMP, + 5, 5, G_TX_NOLOD, G_TX_NOLOD); + gSPWideTextureRectangle(OVERLAY_DISP++, 72 << 2, 184 << 2, 104 << 2, 216 << 2, + G_TX_RENDERTILE, 0, 0, (24 << 10) / 32, (24 << 10) / 32); + } + if (GameInteractor_Should(VB_RENDER_RUPEE_COUNTER, true)) { // Rupee Counter Interface_VrHudGroup(play, VR_HUD_EL_RUPEES, interfaceCtx->magicAlpha); // SOH [VR] diff --git a/soh/src/code/z_play.c b/soh/src/code/z_play.c index 91255a94f2f..b090a4dd0f6 100644 --- a/soh/src/code/z_play.c +++ b/soh/src/code/z_play.c @@ -38,6 +38,10 @@ Input* D_8012D1F8 = NULL; PlayState* gPlayState; s16 firstInit = 0; +// Scene setup completes before the Player actor has a usable entrance yaw. Latch the request here +// and consume it from the first valid first-person draw, where Link's final spawn facing is known. +static bool sVrSceneHeadingPending = false; + void Play_SpawnScene(PlayState* play, s32 sceneId, s32 spawn); // This macro prints the number "1" with a file and line number if R_ENABLE_PLAY_LOGS is enabled. @@ -1415,13 +1419,18 @@ void Play_Draw(PlayState* play) { // animated head bone (actor.focus.pos) which carries the up/down bob and sway. The body // mesh still animates visually; the camera stays smooth (VR comfort: no uninitiated // vertical motion). Tune eye height with gVrHeadHeightOffset. - // Heading recenter: capture the HMD->world yaw offset when first-person turns on, and - // whenever the player requests a manual recenter (set gVrRecenterHeading 1 in console). + // Heading alignment runs when first-person turns on, after a scene spawn, or whenever + // the player requests a manual recenter (set gVrRecenterHeading 1 in console). // Also re-zero roomscale here so the player's current physical position maps to Link's // current body — must run before we read the roomscale origin for the anchor below. - if (!sVrFirstPersonWasActive || CVarGetInteger("gVrRecenterHeading", 0)) { + if (!sVrFirstPersonWasActive || sVrSceneHeadingPending || + CVarGetInteger("gVrRecenterHeading", 0)) { VR_RecenterHeading(vrPlayer->actor.shape.rot.y); + // Rotate the world about the physical head so forward matches the entrance yaw. + // This is one-shot; ordinary HMD free look remains untouched afterward. + VR_RequestFaceYaw(vrPlayer->actor.shape.rot.y); VR_ResetRoomscale(); + sVrSceneHeadingPending = false; CVarSetInteger("gVrRecenterHeading", 0); } sVrFirstPersonWasActive = true; @@ -2041,6 +2050,9 @@ void Play_SpawnScene(PlayState* play, s32 sceneId, s32 spawn) { CVarClear(CVAR_GENERAL("BetterDebugWarpScreenMQModeScene")); } + // VR may remain first-person throughout loading, so explicitly arm a heading correction for + // the first frame after the new Player receives this spawn's entrance rotation. + sVrSceneHeadingPending = true; OTRPlay_SpawnScene(play, sceneId, spawn); } diff --git a/soh/src/code/z_player_lib.c b/soh/src/code/z_player_lib.c index 5fce13e0906..a018d17f008 100644 --- a/soh/src/code/z_player_lib.c +++ b/soh/src/code/z_player_lib.c @@ -940,7 +940,7 @@ s32 Player_GetEnvironmentalHazard(PlayState* play) { TextTriggerEntry* triggerEntry; s32 envHazard; - if (play->roomCtx.curRoom.behaviorType2 == ROOM_BEHAVIOR_TYPE2_3) { // Room is hot + if (VrDoor_EnvironmentBehaviorType2(play) == ROOM_BEHAVIOR_TYPE2_3) { // Room is hot envHazard = PLAYER_ENV_HAZARD_HOTROOM - 1; } else if ((this->underwaterTimer > 80) && ((this->currentBoots == PLAYER_BOOTS_IRON) || (this->underwaterTimer >= 300))) { // Deep underwater @@ -1474,6 +1474,10 @@ s32 Player_OverrideLimbDrawGameplayDefault(PlayState* play, s32 limbIndex, Gfx** *dList = NULL; } + // Anchor VR extension: dummy players stay on this normal full-body path, but their transmitted + // headset/controller matrices replace the head and hand limb poses when available. + Anchor_ApplyRemoteVrLimbPose(this, limbIndex); + return false; } @@ -1568,7 +1572,9 @@ s32 Player_VrWeldMtxToHand(PlayState* play, const void* mtx, s32 vrHand, const f MtxF vrLocal; MtxF vrCur; - if (!(VR_IsInitialized() && VR_GetFirstPerson()) || (vrHand != VR_HAND_LEFT && vrHand != VR_HAND_RIGHT) || + Player* player = GET_PLAYER(play); + if (!(VR_IsInitialized() && (VR_GetFirstPerson() || VrArchery_Covers(player))) || + (vrHand != VR_HAND_LEFT && vrHand != VR_HAND_RIGHT) || (sVrHandLimbFrame[vrHand] != (s32)play->state.frames)) { return false; } @@ -1630,6 +1636,20 @@ s32 Player_OverrideLimbDrawGameplayVRFirstPerson(PlayState* play, s32 limbIndex, // dominant hand (VrHookshot_RightLimbHand swaps the limbs); L_HAND takes the other. s32 rightLimbVr = VrHookshot_RightLimbHand(this); s32 vrHand = (limbIndex == PLAYER_LIMB_R_HAND) ? rightLimbVr : (rightLimbVr ^ 1); + s32 vrShutterPalm = VrShutter_HoldsHand(vrHand); + s32 vrGerudoDoorPalm = VrGerudoDoor_HoldsHand(vrHand); + s32 vrChestPalm = VrChest_HoldsHand(vrHand); + // A physical dungeon key is held in a visibly closed fist. The shutter open-palm model + // is chosen below only after that exact shutter state successfully supplies the pin. + if (VrKeys_HoldsHand(vrHand)) { + if (limbIndex == PLAYER_LIMB_L_HAND) { + *dList = ResourceMgr_LoadGfxByName( + gPlayerLeftHandClosedDLs[gSaveContext.linkAge + sDListsLodOffset]); + } else { + *dList = ResourceMgr_LoadGfxByName( + sPlayerRightHandClosedDLs[gSaveContext.linkAge + sDListsLodOffset]); + } + } // Default (right-handed) maps each controller to Link's OPPOSITE-side hand model; the // reflection that flips a mesh's handedness is per hand because it also mirrors held // items' face designs — the sword survives that, but the shield's crest reads as @@ -1659,7 +1679,28 @@ s32 Player_OverrideLimbDrawGameplayVRFirstPerson(PlayState* play, s32 limbIndex, // never substituted with the live controller. // A hand latched on a silver boulder rides it the same way (VrCarry). s32 vrPinned = VrBlock_PinnedHandMatrix(this, vrHand, &handMtx.mf[0][0]) || - VrCarry_PinnedHandMatrix(this, vrHand, &handMtx.mf[0][0]); + VrCarry_PinnedHandMatrix(this, vrHand, &handMtx.mf[0][0]) || + VrDoor_PinnedHandMatrix(this, vrHand, &handMtx.mf[0][0]); + s32 vrChestPinned = !vrPinned && vrChestPalm && + VrChest_PinnedHandMatrix(this, vrHand, &handMtx.mf[0][0]); + vrPinned = vrPinned || vrChestPinned; + s32 vrGerudoDoorPinned = !vrPinned && vrGerudoDoorPalm && + VrGerudoDoor_PinnedHandMatrix(this, vrHand, &handMtx.mf[0][0]); + vrPinned = vrPinned || vrGerudoDoorPinned; + s32 vrShutterPinned = !vrPinned && vrShutterPalm && + VrShutter_PinnedHandMatrix(this, vrHand, &handMtx.mf[0][0]); + vrPinned = vrPinned || vrShutterPinned; + if (vrChestPinned || vrGerudoDoorPinned || vrShutterPinned) { + // Physical surface poses rebuild a positive-determinant matrix, so draw the + // native anatomical mesh for the controller with normal culling. + if (vrHand == VR_HAND_LEFT) { + *dList = ResourceMgr_LoadGfxByName( + gPlayerLeftHandOpenDLs[gSaveContext.linkAge + sDListsLodOffset]); + } else { + *dList = ResourceMgr_LoadGfxByName( + sPlayerRightHandOpenDLs[gSaveContext.linkAge + sDListsLodOffset]); + } + } s32 vrBowAligned = !vrPinned && VrArchery_BowAlignedMatrix(vrHand, &handMtx.mf[0][0]); // SOH [VR] Climbing (VrClimb): a holding hand is drawn on the surface where it took // hold — a fixed offset from the controller, still live (welded as a child below). @@ -1695,7 +1736,7 @@ s32 Player_OverrideLimbDrawGameplayVRFirstPerson(PlayState* play, s32 limbIndex, } pos->x = pos->y = pos->z = 0.0f; rot->x = rot->y = rot->z = 0; - if (mirror) { + if (mirror && !vrShutterPinned) { // The reflection flips triangle winding; invert back-face culling so the hand + held // item don't render inside-out. Cleared on the next limb (top of this function). OPEN_DISPS(play->state.gfxCtx); @@ -2041,7 +2082,8 @@ Vec3f sLeftRightFootLimbModelFootPos[] = { // is the exception: it rides the dominant hand (VrHookshot_RightLimbHand), and aims from there. // Returns true when it overrode the actor's transform. static s32 Player_VrAimHeldProjectile(Player* this, Actor* heldActor) { - if (!(VR_IsInitialized() && VR_GetFirstPerson() && CVarGetInteger("gVrMotionHands", 1) && + if (!(VR_IsInitialized() && (VR_GetFirstPerson() || VrArchery_Covers(this)) && + CVarGetInteger("gVrMotionHands", 1) && CVarGetInteger("gVrWeaponAim", 1))) { return false; } @@ -2260,7 +2302,15 @@ void Player_PostLimbDrawGameplay(PlayState* play, s32 limbIndex, Gfx** dList, Ve Matrix_Push(); Matrix_Translate(stringData->pos.x, stringData->pos.y, stringData->pos.z, MTXMODE_APPLY); - if ((this->stateFlags1 & PLAYER_STATE1_READY_TO_FIRE) && (this->unk_860 >= 0) && (this->unk_834 <= 10)) { + // The gallery's stock aim state keeps the band visually pulled before physical + // archery has nocked it. Its real touch target is still the braced pouch, producing + // two different apparent nock points. Leave the gallery slingshot braced until the + // physical pouch transform below takes ownership. + s32 vrPhysicalGallerySling = stringData == &sBowStringData[1] && play->shootingGalleryStatus > 0 && + VrArchery_Covers(this); + + if (!vrPhysicalGallerySling && (this->stateFlags1 & PLAYER_STATE1_READY_TO_FIRE) && + (this->unk_860 >= 0) && (this->unk_834 <= 10)) { Vec3f sp90; f32 distXYZ; @@ -2336,7 +2386,7 @@ void Player_PostLimbDrawGameplay(PlayState* play, s32 limbIndex, Gfx** dList, Ve vrStringDone = true; } if (!vrStringDone) { - Matrix_Scale(1.0f, this->unk_858, 1.0f, MTXMODE_APPLY); + Matrix_Scale(1.0f, vrPhysicalGallerySling ? 0.0f : this->unk_858, 1.0f, MTXMODE_APPLY); if (!LINK_IS_ADULT) { Matrix_RotateZ(this->unk_858 * -0.2f, MTXMODE_APPLY); diff --git a/soh/src/overlays/actors/ovl_Arrow_Fire/z_arrow_fire.c b/soh/src/overlays/actors/ovl_Arrow_Fire/z_arrow_fire.c index 50736695001..0ca909938b5 100644 --- a/soh/src/overlays/actors/ovl_Arrow_Fire/z_arrow_fire.c +++ b/soh/src/overlays/actors/ovl_Arrow_Fire/z_arrow_fire.c @@ -6,6 +6,7 @@ #include "z_arrow_fire.h" #include "overlays/actors/ovl_En_Arrow/z_en_arrow.h" +#include "soh/Enhancements/vr-combat/VrCombat.h" #define FLAGS (ACTOR_FLAG_UPDATE_CULLING_DISABLED | ACTOR_FLAG_UPDATE_DURING_OCARINA) @@ -216,6 +217,12 @@ void ArrowFire_Draw(Actor* thisx, PlayState* play2) { Matrix_RotateX(tranform->shape.rot.x * (M_PI / 0x8000), MTXMODE_APPLY); Matrix_RotateZ(tranform->shape.rot.z * (M_PI / 0x8000), MTXMODE_APPLY); Matrix_Scale(0.01f, 0.01f, 0.01f, MTXMODE_APPLY); + if (VrArchery_NockedArrowHandForActor(&arrow->actor) >= 0) { + f32 vrScale = VrHand_ScaleFactor(); + Matrix_Translate(-1.0f, 0.0f, -1003.0f, MTXMODE_APPLY); + Matrix_Scale(vrScale, vrScale, vrScale, MTXMODE_APPLY); + Matrix_Translate(1.0f, 0.0f, 1003.0f, MTXMODE_APPLY); + } // Draw red effect over the screen when arrow hits if (this->unk_15C > 0) { @@ -240,7 +247,11 @@ void ArrowFire_Draw(Actor* thisx, PlayState* play2) { } Matrix_Scale(this->radius * 0.2f, this->unk_158 * 4.0f, this->radius * 0.2f, MTXMODE_APPLY); Matrix_Translate(0.0f, -700.0f, 0.0f, MTXMODE_APPLY); + s32 vrWeldHand = VrArchery_NockedArrowHandForActor(&arrow->actor); + s32 previousWeldHand = gVrMtxWeldHand; + gVrMtxWeldHand = vrWeldHand; gSPMatrix(POLY_XLU_DISP++, MATRIX_NEWMTX(play->state.gfxCtx), G_MTX_NOPUSH | G_MTX_LOAD | G_MTX_MODELVIEW); + gVrMtxWeldHand = previousWeldHand; gSPDisplayList(POLY_XLU_DISP++, sMaterialDL); gSPDisplayList(POLY_XLU_DISP++, Gfx_TwoTexScrollEx(play->state.gfxCtx, 0, 255 - (stateFrames * 2) % 256, 0, 64, 32, 1, 255 - stateFrames % 256, diff --git a/soh/src/overlays/actors/ovl_Arrow_Ice/z_arrow_ice.c b/soh/src/overlays/actors/ovl_Arrow_Ice/z_arrow_ice.c index 42fe9d3d9db..7986f34d58d 100644 --- a/soh/src/overlays/actors/ovl_Arrow_Ice/z_arrow_ice.c +++ b/soh/src/overlays/actors/ovl_Arrow_Ice/z_arrow_ice.c @@ -7,6 +7,7 @@ #include "z_arrow_ice.h" #include "overlays/actors/ovl_En_Arrow/z_en_arrow.h" +#include "soh/Enhancements/vr-combat/VrCombat.h" #define FLAGS (ACTOR_FLAG_UPDATE_CULLING_DISABLED | ACTOR_FLAG_UPDATE_DURING_OCARINA) @@ -214,6 +215,12 @@ void ArrowIce_Draw(Actor* thisx, PlayState* play) { Matrix_RotateX(tranform->shape.rot.x * (M_PI / 0x8000), MTXMODE_APPLY); Matrix_RotateZ(tranform->shape.rot.z * (M_PI / 0x8000), MTXMODE_APPLY); Matrix_Scale(0.01f, 0.01f, 0.01f, MTXMODE_APPLY); + if (VrArchery_NockedArrowHandForActor(&arrow->actor) >= 0) { + f32 vrScale = VrHand_ScaleFactor(); + Matrix_Translate(-1.0f, 0.0f, -1003.0f, MTXMODE_APPLY); + Matrix_Scale(vrScale, vrScale, vrScale, MTXMODE_APPLY); + Matrix_Translate(1.0f, 0.0f, 1003.0f, MTXMODE_APPLY); + } // Draw blue effect over the screen when arrow hits if (this->unk_164 > 0) { @@ -238,7 +245,11 @@ void ArrowIce_Draw(Actor* thisx, PlayState* play) { } Matrix_Scale(this->radius * 0.2f, this->unk_160 * 3.0f, this->radius * 0.2f, MTXMODE_APPLY); Matrix_Translate(0.0f, -700.0f, 0.0f, MTXMODE_APPLY); + s32 vrWeldHand = VrArchery_NockedArrowHandForActor(&arrow->actor); + s32 previousWeldHand = gVrMtxWeldHand; + gVrMtxWeldHand = vrWeldHand; gSPMatrix(POLY_XLU_DISP++, MATRIX_NEWMTX(play->state.gfxCtx), G_MTX_NOPUSH | G_MTX_LOAD | G_MTX_MODELVIEW); + gVrMtxWeldHand = previousWeldHand; gSPDisplayList(POLY_XLU_DISP++, sMaterialDL); gSPDisplayList(POLY_XLU_DISP++, Gfx_TwoTexScrollEx(play->state.gfxCtx, 0, 511 - (stateFrames * 5) % 512, 0, 128, 32, 1, 511 - (stateFrames * 10) % 512, diff --git a/soh/src/overlays/actors/ovl_Arrow_Light/z_arrow_light.c b/soh/src/overlays/actors/ovl_Arrow_Light/z_arrow_light.c index 406aebc1dcb..b40fd0457b1 100644 --- a/soh/src/overlays/actors/ovl_Arrow_Light/z_arrow_light.c +++ b/soh/src/overlays/actors/ovl_Arrow_Light/z_arrow_light.c @@ -7,6 +7,7 @@ #include "z_arrow_light.h" #include "overlays/actors/ovl_En_Arrow/z_en_arrow.h" +#include "soh/Enhancements/vr-combat/VrCombat.h" #define FLAGS (ACTOR_FLAG_UPDATE_CULLING_DISABLED | ACTOR_FLAG_UPDATE_DURING_OCARINA) @@ -212,6 +213,12 @@ void ArrowLight_Draw(Actor* thisx, PlayState* play) { Matrix_RotateX(tranform->shape.rot.x * (M_PI / 0x8000), MTXMODE_APPLY); Matrix_RotateZ(tranform->shape.rot.z * (M_PI / 0x8000), MTXMODE_APPLY); Matrix_Scale(0.01f, 0.01f, 0.01f, MTXMODE_APPLY); + if (VrArchery_NockedArrowHandForActor(&arrow->actor) >= 0) { + f32 vrScale = VrHand_ScaleFactor(); + Matrix_Translate(-1.0f, 0.0f, -1003.0f, MTXMODE_APPLY); + Matrix_Scale(vrScale, vrScale, vrScale, MTXMODE_APPLY); + Matrix_Translate(1.0f, 0.0f, 1003.0f, MTXMODE_APPLY); + } // Draw yellow effect over the screen when arrow hits if (this->unk_164 > 0) { @@ -236,7 +243,11 @@ void ArrowLight_Draw(Actor* thisx, PlayState* play) { } Matrix_Scale(this->radius * 0.2f, this->unk_160 * 4.0f, this->radius * 0.2f, MTXMODE_APPLY); Matrix_Translate(0.0f, -700.0f, 0.0f, MTXMODE_APPLY); + s32 vrWeldHand = VrArchery_NockedArrowHandForActor(&arrow->actor); + s32 previousWeldHand = gVrMtxWeldHand; + gVrMtxWeldHand = vrWeldHand; gSPMatrix(POLY_XLU_DISP++, MATRIX_NEWMTX(play->state.gfxCtx), G_MTX_NOPUSH | G_MTX_LOAD | G_MTX_MODELVIEW); + gVrMtxWeldHand = previousWeldHand; gSPDisplayList(POLY_XLU_DISP++, sMaterialDL); gSPDisplayList(POLY_XLU_DISP++, Gfx_TwoTexScrollEx(play->state.gfxCtx, 0, 511 - (stateFrames * 5) % 512, 0, 4, 32, 1, 511 - (stateFrames * 10) % 512, diff --git a/soh/src/overlays/actors/ovl_Door_Gerudo/z_door_gerudo.c b/soh/src/overlays/actors/ovl_Door_Gerudo/z_door_gerudo.c index 29eccfdd7a3..6eb28705379 100644 --- a/soh/src/overlays/actors/ovl_Door_Gerudo/z_door_gerudo.c +++ b/soh/src/overlays/actors/ovl_Door_Gerudo/z_door_gerudo.c @@ -7,6 +7,7 @@ #include "z_door_gerudo.h" #include "objects/object_door_gerudo/object_door_gerudo.h" #include "soh/Enhancements/game-interactor/GameInteractor_Hooks.h" +#include "soh/Enhancements/vr-combat/VrCombat.h" #define FLAGS 0 @@ -99,6 +100,12 @@ s32 func_80994750(DoorGerudo* this, PlayState* play) { } void func_8099485C(DoorGerudo* this, PlayState* play) { + // SOH [VR] The Gerudo grate uses a distinct actor, so explicitly offer its padlock to the + // physical small-key system once the carpenter's guard requirement has been satisfied. + if (this->unk_164 == 0 && Flags_GetCollectible(play, (this->dyna.actor.params >> 8) & 0x1F) && + VrKeys_TryGerudoDoor(this, play)) { + this->unk_164 = 1; + } if (this->unk_164 != 0) { this->actionFunc = func_8099496C; gSaveContext.inventory.dungeonKeys[gSaveContext.mapIndex] -= 1; @@ -126,10 +133,22 @@ void func_8099485C(DoorGerudo* this, PlayState* play) { } void func_8099496C(DoorGerudo* this, PlayState* play) { - if (DECR(this->unk_166) == 0) { - Audio_PlayActorSound2(&this->dyna.actor, NA_SE_EV_SLIDE_DOOR_OPEN); - this->actionFunc = func_809949C8; + if (this->unk_166 != 0) { + this->unk_166--; + return; + } + + // In first-person VR the unlocked grate waits for two physical hands. Outside that mode the + // negative return preserves the original automatic sliding animation exactly. + s32 vrDoor = VrGerudoDoor_Tick(this, play); + if (vrDoor >= 0) { + if (vrDoor == 2) { + this->actionFunc = func_809949C8; + } + return; } + Audio_PlayActorSound2(&this->dyna.actor, NA_SE_EV_SLIDE_DOOR_OPEN); + this->actionFunc = func_809949C8; } void func_809949C8(DoorGerudo* this, PlayState* play) { diff --git a/soh/src/overlays/actors/ovl_Door_Shutter/z_door_shutter.c b/soh/src/overlays/actors/ovl_Door_Shutter/z_door_shutter.c index cefffeea818..62d919bad2e 100644 --- a/soh/src/overlays/actors/ovl_Door_Shutter/z_door_shutter.c +++ b/soh/src/overlays/actors/ovl_Door_Shutter/z_door_shutter.c @@ -5,6 +5,7 @@ */ #include "z_door_shutter.h" +#include "soh/Enhancements/vr-combat/VrCombat.h" // SOH [VR] #include "overlays/actors/ovl_Boss_Goma/z_boss_goma.h" #include "objects/object_gnd/object_gnd.h" @@ -24,6 +25,7 @@ #include "objects/object_demo_kekkai/object_demo_kekkai.h" #include "objects/object_ouke_haka/object_ouke_haka.h" #include "soh/Enhancements/game-interactor/GameInteractor_Hooks.h" +#include #define FLAGS ACTOR_FLAG_UPDATE_CULLING_DISABLED @@ -43,6 +45,7 @@ void DoorShutter_Open(DoorShutter* this, PlayState* play); void DoorShutter_Unbar(DoorShutter* this, PlayState* play); void DoorShutter_Close(DoorShutter* this, PlayState* play); void DoorShutter_JabuDoorClose(DoorShutter* this, PlayState* play); +s32 DoorShutter_UpdateBarsClosed(DoorShutter* this, PlayState* play, f32 arg2); void DoorShutter_WaitPlayerSurprised(DoorShutter* this, PlayState* play); void DoorShutter_GohmaBlockFall(DoorShutter* this, PlayState* play); void DoorShutter_GohmaBlockBounce(DoorShutter* this, PlayState* play); @@ -119,6 +122,26 @@ static ShutterInfo sShutterInfo[] = { { object_ouke_haka_DL_0000C0, gDoorMetalBarsDL, 130, 12, 20, 15 }, }; +const char* VrShutter_GetDisplayListPath(const DoorShutter* door) { + if (door == NULL || door->gfxType >= ARRAY_COUNT(sShutterInfo)) { + return NULL; + } + return (const char*)sShutterInfo[door->gfxType].a; +} + +bool VrShutter_RenderFlipped(const DoorShutter* door, const PlayState* play) { + if (door == NULL || play == NULL || door->gfxType >= ARRAY_COUNT(sShutterInfo) || + sShutterInfo[door->gfxType].b == NULL) { + return false; + } + TransitionActorEntry* entry = &play->transiActorCtx.list[(u16)door->dyna.actor.params >> 0xA]; + if (play->roomCtx.prevRoom.num >= 0 || entry->sides[0].room == entry->sides[1].room) { + s32 yaw = Math_Vec3f_Yaw(&play->view.eye, &door->dyna.actor.world.pos); + return ABS((s16)(door->dyna.actor.shape.rot.y - yaw)) < 0x4000; + } + return door->dyna.actor.room == entry->sides[0].room; +} + static s8 D_80998224[] = { -1, -1, -1, -1, 0, 6, 1, -1, 0, -1, -1, -1, }; @@ -187,6 +210,43 @@ void DoorShutter_SetupAction(DoorShutter* this, DoorShutterActionFunc actionFunc this->actionTimer = 0; } +// Resolve only the immutable visual assigned to a physical room side. Unlike SetupDoor this does +// not change the action, bars, or unlock state, so it is safe to run while a fully raised VR door +// selects the material it will retain throughout its descent. +u8 DoorShutter_GetGfxTypeForRoom(DoorShutter* this, PlayState* play, s8 room) { + TransitionActorEntry* transitionEntry = &play->transiActorCtx.list[(u16)this->dyna.actor.params >> 0xA]; + s8 frontRoom = transitionEntry->sides[0].room; + s32 doorType = this->doorType; + ShutterObjectInfo* objectInfo = &sObjectInfo[this->styleType]; + + if (doorType != SHUTTER_KEY_LOCKED) { + if (frontRoom == transitionEntry->sides[1].room) { + // Same-room transitions have no persistent room-side identity. Preserve the initialized + // material instead of allowing player/head orientation to rewrite it during gameplay. + return this->gfxType; + } + if (frontRoom == room) { + if (doorType == SHUTTER_FRONT_SWITCH_BACK_CLEAR) { + doorType = SHUTTER_FRONT_CLEAR; + } else { + doorType = (doorType == SHUTTER_BOSS) ? SHUTTER_BACK_LOCKED : SHUTTER; + } + } + } + return (doorType == SHUTTER) ? objectInfo->index1 : objectInfo->index2; +} + +void DoorShutter_CacheSideGfxTypes(DoorShutter* this, PlayState* play) { + TransitionActorEntry* transitionEntry = &play->transiActorCtx.list[(u16)this->dyna.actor.params >> 0xA]; + + // Both display lists live in the already-loaded shutter object. Cache their stable room-side + // mapping once; no streaming, camera, or condition state may rewrite this mapping afterward. + this->gfxType = sObjectInfo[this->styleType].index1; + this->vrGfxTypeBySide[0] = DoorShutter_GetGfxTypeForRoom(this, play, transitionEntry->sides[0].room); + this->vrGfxTypeBySide[1] = DoorShutter_GetGfxTypeForRoom(this, play, transitionEntry->sides[1].room); + this->vrGfxCacheValid = 1; +} + s32 DoorShutter_SetupDoor(DoorShutter* this, PlayState* play) { TransitionActorEntry* transitionEntry = &play->transiActorCtx.list[(u16)this->dyna.actor.params >> 0xA]; s8 frontRoom = transitionEntry->sides[0].room; @@ -242,6 +302,7 @@ void DoorShutter_Init(Actor* thisx, PlayState* play2) { Actor_ProcessInitChain(&this->dyna.actor, sInitChain); this->dyna.actor.home.pos.z = this->dyna.actor.shape.yOffset; DynaPolyActor_Init(&this->dyna, DPM_UNK); + this->vrGfxCacheValid = 0; this->doorType = (this->dyna.actor.params >> 6) & 0xF; phi_a3 = D_80998224[this->doorType]; if (phi_a3 < 0) { @@ -320,6 +381,7 @@ void DoorShutter_SetupType(DoorShutter* this, PlayState* play) { this->unk_164 = 7; } } else { + DoorShutter_CacheSideGfxTypes(this, play); DoorShutter_SetupDoor(this, play); } } @@ -367,6 +429,10 @@ s32 DoorShutter_GetPlayerSide(DoorShutter* this, PlayState* play) { } void DoorShutter_WaitClear(DoorShutter* this, PlayState* play) { + // Usually setup enters this action with the bars already fully closed. A physical VR close + // deliberately resets them to zero so this same native step function visibly lowers the bars + // after the door has covered the doorway instead of making them pop into existence. + DoorShutter_UpdateBarsClosed(this, play, 1.0f); if (Flags_GetClear(play, this->dyna.actor.room) || Flags_GetTempClear(play, this->dyna.actor.room)) { Flags_SetClear(play, this->dyna.actor.room); DoorShutter_SetupAction(this, DoorShutter_Unbar); @@ -383,9 +449,35 @@ void DoorShutter_WaitClear(DoorShutter* this, PlayState* play) { } void DoorShutter_Unopenable(DoorShutter* this, PlayState* play) { + // Closed rigid shutters are handled centrally in DoorShutter_Update. Keeping physical-door + // dispatch here made behavior depend on which vanilla action happened to own an identical + // unbarred model. } void DoorShutter_Idle(DoorShutter* this, PlayState* play) { + s32 vrKeyOpen = VrKeys_TryShutter(this, play); + if (vrKeyOpen) { + // A physical key turn unlocks the shutter; it does not also activate it. In particular, + // the Boss Key must remove the padlock and leave the boss door closed until the player + // deliberately uses the now-unlocked door through its normal interaction path. + if (this->unlockTimer != 0) { + Flags_SetSwitch(play, this->dyna.actor.params & 0x3F); + if (this->doorType != SHUTTER_BOSS) { + if (GameInteractor_Should(VB_CONSUME_SMALL_KEY, true, this)) { + gSaveContext.inventory.dungeonKeys[gSaveContext.mapIndex]--; + } + Audio_PlayActorSound2(&this->dyna.actor, NA_SE_EV_CHAIN_KEY_UNLOCK); + GameInteractor_ExecuteOnDungeonKeyUsedHooks(gSaveContext.mapIndex); + } else { + Audio_PlayActorSound2(&this->dyna.actor, NA_SE_EV_CHAIN_KEY_UNLOCK_B); + } + this->unlockTimer = 0; + } + this->unk_164 = 0; + GET_PLAYER(play)->doorTimer = 0; + GET_PLAYER(play)->doorActor = NULL; + return; + } if (this->unk_164 != 0) { DoorShutter_SetupAction(this, DoorShutter_Open); this->dyna.actor.velocity.y = 0.0f; @@ -400,6 +492,12 @@ void DoorShutter_Idle(DoorShutter* this, PlayState* play) { } } } else { + // In first-person VR the flesh membrane is exclusively physical: native body proximity + // must not expose the ordinary sliding-door interaction when neither hand touched it. + if (this->gfxType == 3 && CVarGetInteger("gVrPhysicalDoors", 1) && VR_IsInitialized() && + VR_GetFirstPerson() && !VR_IsFlatScreen() && CVarGetInteger("gVrMotionHands", 1)) { + return; + } s32 doorDirection = DoorShutter_GetPlayerSide(this, play); if (doorDirection != 0) { @@ -437,8 +535,12 @@ void DoorShutter_InitOpeningDoorCam(DoorShutter* this, PlayState* play) { DoorShutter_SetupAction(this, DoorShutter_Open); this->gfxType = sp38; this->barsClosedAmount = 0.0f; - Camera_ChangeDoorCam(play->cameraPtrs[CAM_ID_MAIN], &this->dyna.actor, player->cv.slidingDoorBgCamIndex, 0.0f, - 12, sp34, 10); + // A forced third-person door camera rotates the world around a first-person VR player. + // Keep the stock camera transition everywhere except active first-person VR. + if (!(VR_IsInitialized() && VR_GetFirstPerson() && !VR_IsFlatScreen())) { + Camera_ChangeDoorCam(play->cameraPtrs[CAM_ID_MAIN], &this->dyna.actor, + player->cv.slidingDoorBgCamIndex, 0.0f, 12, sp34, 10); + } } } @@ -449,7 +551,8 @@ s32 DoorShutter_UpdateOpening(DoorShutter* this, PlayState* play) { DoorShutter_InitOpeningDoorCam(this, play); } Math_StepToF(&this->dyna.actor.velocity.y, 15.0f, 3.0f); - if (Math_StepToF(&this->dyna.actor.world.pos.y, this->dyna.actor.home.pos.y + 200.0f, + if (Math_StepToF(&this->dyna.actor.world.pos.y, + this->dyna.actor.home.pos.y + VrShutter_OpenHeight(this), this->dyna.actor.velocity.y)) { return true; } @@ -488,6 +591,11 @@ s32 DoorShutter_UpdateBarsClosed(DoorShutter* this, PlayState* play, f32 arg2) { } void DoorShutter_BarAndWaitSwitchFlag(DoorShutter* this, PlayState* play) { + // A switch may re-bar the membrane while its touch-triggered room preload is in flight. + // Cancel that latch as soon as loading permits; it must require a new touch after unbarring. + if (this->gfxType == 3) { + VrJabuDoor_Cancel(this, play); + } if (DoorShutter_UpdateBarsClosed(this, play, 1.0f)) { if (Flags_GetSwitch(play, this->dyna.actor.params & 0x3F)) { DoorShutter_SetupAction(this, DoorShutter_Unbar); @@ -512,9 +620,37 @@ void DoorShutter_UnbarredCheckSwitchFlag(DoorShutter* this, PlayState* play) { } void DoorShutter_Open(DoorShutter* this, PlayState* play) { - if (DECR(this->unlockTimer) == 0 && play->roomCtx.status == 0 && DoorShutter_UpdateOpening(this, play) != 0) { + // A touched Jabu membrane can visibly retract while its destination room finishes loading. + // Wall passage is still denied by VrDoor_AllowsWallPass until that load completes. + if (DECR(this->unlockTimer) == 0 && (play->roomCtx.status == 0 || this->gfxType == 3) && + DoorShutter_UpdateOpening(this, play) != 0) { + if (VrShutter_KeepOpen(this, play)) { + return; + } if (((this->doorType == SHUTTER_BOSS) ? 20.0f : 50.0f) < this->dyna.actor.xzDistToPlayer) { - if (DoorShutter_SetupDoor(this, play)) { + // Native setup selects the eventual closed-side model and bars immediately. Preserve + // the open-side visuals throughout a physical VR close, then apply the resolved native + // state only after the shutter has completely covered the doorway. + s32 vrPhysicalClosing = VrShutter_IsPhysicalClosePending(this); + f32 vrOpenBarsClosedAmount = this->barsClosedAmount; + if (vrPhysicalClosing) { + s32 vrCloseRoom = VrShutter_GetPhysicalCloseRoom(this, play); + if (vrCloseRoom >= 0) { + // The slab is fully raised and outside the doorway here. Select the stable + // material belonging to the side on which it will close, before any part of + // the door becomes visible, then never alter it during the descent. + TransitionActorEntry* vrEntry = + &play->transiActorCtx.list[(u16)this->dyna.actor.params >> 0xA]; + if (this->vrGfxCacheValid && vrCloseRoom == vrEntry->sides[0].room) { + this->gfxType = this->vrGfxTypeBySide[0]; + } else if (this->vrGfxCacheValid && vrCloseRoom == vrEntry->sides[1].room) { + this->gfxType = this->vrGfxTypeBySide[1]; + } else { + this->gfxType = DoorShutter_GetGfxTypeForRoom(this, play, vrCloseRoom); + } + } + this->barsClosedAmount = vrOpenBarsClosedAmount; + } else if (DoorShutter_SetupDoor(this, play)) { this->dyna.actor.velocity.y = 30.0f; } if (this->gfxType != 3) { @@ -557,8 +693,12 @@ void DoorShutter_Unbar(DoorShutter* this, PlayState* play) { void DoorShutter_SetupClosed(DoorShutter* this, PlayState* play) { Player* player = GET_PLAYER(play); s8 room = this->dyna.actor.room; + bool vrPhysicalClose = VrShutter_ConsumePhysicalClose(this); - if (this->dyna.actor.room >= 0) { + // VrShutter_FinishClose already committed the retained room pair and assigned this actor to + // the room Link occupies. Running the stock room swap a second time can reverse that result, + // making SetupDoor resolve the opposite texture and even the opposite lock condition. + if (!vrPhysicalClose && this->dyna.actor.room >= 0) { Vec3f vec; Actor_WorldToActorCoords(&this->dyna.actor, &vec, &player->actor.world.pos); @@ -576,9 +716,65 @@ void DoorShutter_SetupClosed(DoorShutter* this, PlayState* play) { } this->unk_164 = 0; this->dyna.actor.velocity.y = 0.0f; - if (DoorShutter_SetupDoor(this, play) && !(player->stateFlags1 & PLAYER_STATE1_CARRYING_ACTOR)) { - DoorShutter_SetupAction(this, DoorShutter_WaitPlayerSurprised); - Player_SetCsActionWithHaltedActors(play, NULL, 2); + bool vrGanonStairRoom = false; + if (vrPhysicalClose && play->sceneNum == SCENE_GANONS_TOWER) { + // The ascent stair landings have no encounter of their own and therefore need not carry a + // room-clear flag. Side-dependent shutter setup otherwise mistakes that missing flag for + // an uncleared fight and recreates bars behind Link after leaving a completed battle room. + // Preserve lock-behind behavior only when the destination actually contains a live enemy. + vrGanonStairRoom = true; + Actor* enemy = play->actorCtx.actorLists[ACTORCAT_ENEMY].head; + while (enemy != NULL) { + if (enemy->update != NULL && + (enemy->room == play->roomCtx.curRoom.num || enemy->room < 0)) { + vrGanonStairRoom = false; + break; + } + enemy = enemy->next; + } + } + if (vrPhysicalClose) { + // Room ownership and the player's final side are now settled, so native setup can make the + // authoritative decision for every door type. The only exception remains empty Ganon stair + // landings, whose intended open state has no corresponding room-clear flag. + if (vrGanonStairRoom) { + this->barsClosedAmount = 0.0f; + DoorShutter_SetupAction(this, DoorShutter_Idle); + return; + } + s32 vrPreserveEntryUnlock = VrShutter_ConsumePreservedEntryUnlock(this); + u8 vrClosedGfxType = this->gfxType; + DoorShutter_SetupDoor(this, play); + // Lock resolution is live, but material resolution was completed while the slab was fully + // raised. Never allow SetupDoor or a later room-state change to rewrite the visible side. + this->gfxType = vrClosedGfxType; + if (vrPreserveEntryUnlock) { + // The source side was already unbarred when VR accepted the grab. A retained-room + // transition must not make that same side demand its condition for a second time. + DoorShutter_SetupAction(this, DoorShutter_Idle); + } + // SetupDoor selects the correct action and front/back display list. If it requires bars, + // begin from zero so that action performs the native falling animation; otherwise this + // simply preserves the unbarred state it selected. + this->barsClosedAmount = 0.0f; + return; + } + s32 vrSetupBarred = DoorShutter_SetupDoor(this, play); + if (vrSetupBarred) { + const bool vrPhysicalFirstPerson = CVarGetInteger("gVrPhysicalDoors", 1) && VR_IsInitialized() && + VR_GetFirstPerson() && !VR_IsFlatScreen() && + CVarGetInteger("gVrMotionHands", 1); + if (vrPhysicalFirstPerson) { + // Native third-person traversal briefly locks Link into a surprised animation when a + // shutter bars behind him. In physical first-person VR the player already walked the + // doorway manually; preserve SetupDoor's live lock state and falling-bar action, but + // never seize locomotion or insert the delayed surprise state. + return; + } + if (!(player->stateFlags1 & PLAYER_STATE1_CARRYING_ACTOR)) { + DoorShutter_SetupAction(this, DoorShutter_WaitPlayerSurprised); + Player_SetCsActionWithHaltedActors(play, NULL, 2); + } } } @@ -600,12 +796,15 @@ void DoorShutter_Close(DoorShutter* this, PlayState* play) { Quake_SetQuakeValues(quakeId, 2, 0, 0, 0); Quake_SetCountdown(quakeId, 10); Rumble_Request(this->dyna.actor.xyzDistToPlayerSq, 0xB4, 0x14, 0x64); + // A cancelled physical lift keeps both rooms resident until the slab hides the doorway. + VrShutter_FinishClose(this, play); DoorShutter_SetupClosed(this, play); } } void DoorShutter_JabuDoorClose(DoorShutter* this, PlayState* play) { if (Math_StepToS(&this->jabuDoorClosedAmount, 0x64, 0xA)) { + VrShutter_FinishClose(this, play); DoorShutter_SetupClosed(this, play); } } @@ -663,6 +862,41 @@ void DoorShutter_Update(Actor* thisx, PlayState* play) { if (!(player->stateFlags1 & (PLAYER_STATE1_TALKING | PLAYER_STATE1_DEAD | PLAYER_STATE1_GETTING_ITEM | PLAYER_STATE1_IN_ITEM_CS)) || (this->actionFunc == DoorShutter_SetupType)) { + // Route every stationary shutter through one physical-door gate. Previously only Idle + // and one specially patched Unopenable path called it, so visually identical doors could + // behave differently solely because a puzzle left them in another vanilla action. + // Continue dispatching while a physically held shutter is above its closed position. + // Restricting this to home.pos.y disconnected the lift after its very first movement frame. + const s32 vrInteractable = this->actionFunc != DoorShutter_SetupType && + this->actionFunc != DoorShutter_Open && this->actionFunc != DoorShutter_Close && + this->actionFunc != DoorShutter_JabuDoorClose && + this->actionFunc != DoorShutter_GohmaBlockFall && + this->actionFunc != DoorShutter_GohmaBlockBounce && + this->actionFunc != DoorShutter_PhantomGanonBarsRaise; + if (vrInteractable) { + // Jabu membranes can be left in several native stationary actions depending on the + // transition side and puzzle type. Dispatch physical hover/grab centrally whenever the + // visible web is fully retracted instead of relying on DoorShutter_Idle alone. + if (this->gfxType == 3 && this->barsClosedAmount <= 0.001f && VrJabuDoor_Tick(this, play)) { + if (GameInteractor_Should(VB_JABU_PREVENT_RUTO_REENTER_BIGOCTO, true, player, + &this->dyna.actor)) { + this->unk_164 = 1; + this->dyna.actor.velocity.y = 0.0f; + DoorShutter_SetupAction(this, DoorShutter_Open); + } else { + VrJabuDoor_Cancel(this, play); + } + return; + } + s32 vrDoor = VrShutter_Tick(this, play); + if (vrDoor == 2) { + DoorShutter_SetupAction(this, DoorShutter_Open); + return; + } + if (vrDoor == 1) { + return; + } + } this->actionFunc(this, play); } } @@ -698,6 +932,12 @@ s32 DoorShutter_ShouldDraw(DoorShutter* this, PlayState* play) { s32 phi_a1; s32 phi_a0; + // In first-person VR the headset may face across the door plane while Link's body still faces + // the previous direction. The original third-person side test interprets that disagreement as + // room-transition culling and makes a nearby shutter flicker or vanish. + if (VR_IsInitialized() && VR_GetFirstPerson() && !VR_IsFlatScreen()) { + return true; + } if (Player_InCsMode(play)) { return true; } @@ -751,8 +991,13 @@ void DoorShutter_Draw(Actor* thisx, PlayState* play) { } else { if (sp70->b != NULL) { TransitionActorEntry* transitionEntry = &play->transiActorCtx.list[(u16)this->dyna.actor.params >> 0xA]; + bool vrClosingFlipped; - if (play->roomCtx.prevRoom.num >= 0 || + if (VrShutter_GetClosingRenderFlipped(this, &vrClosingFlipped)) { + if (vrClosingFlipped) { + Matrix_RotateY(M_PI, MTXMODE_APPLY); + } + } else if (play->roomCtx.prevRoom.num >= 0 || transitionEntry->sides[0].room == transitionEntry->sides[1].room) { s32 yaw = Math_Vec3f_Yaw(&play->view.eye, &this->dyna.actor.world.pos); diff --git a/soh/src/overlays/actors/ovl_Door_Shutter/z_door_shutter.h b/soh/src/overlays/actors/ovl_Door_Shutter/z_door_shutter.h index b30706c7831..81fc3b73ccf 100644 --- a/soh/src/overlays/actors/ovl_Door_Shutter/z_door_shutter.h +++ b/soh/src/overlays/actors/ovl_Door_Shutter/z_door_shutter.h @@ -56,6 +56,10 @@ typedef struct DoorShutter { /* 0x016F */ s8 actionTimer; /* 0x0170 */ f32 barsClosedAmount; /* 0x0174 */ DoorShutterActionFunc actionFunc; -} DoorShutter; // size = 0x0178 + // VR keeps both immutable room-side visuals resolved for the actor's full lifetime. Resource + // packs may replace either underlying display list, but gameplay never remaps the materials. + /* 0x0178 */ u8 vrGfxTypeBySide[2]; + /* 0x017A */ u8 vrGfxCacheValid; +} DoorShutter; // size = 0x017C #endif diff --git a/soh/src/overlays/actors/ovl_En_Arrow/z_en_arrow.c b/soh/src/overlays/actors/ovl_En_Arrow/z_en_arrow.c index a95038ef154..21f2ae2a179 100644 --- a/soh/src/overlays/actors/ovl_En_Arrow/z_en_arrow.c +++ b/soh/src/overlays/actors/ovl_En_Arrow/z_en_arrow.c @@ -89,6 +89,11 @@ void EnArrow_Init(Actor* thisx, PlayState* play) { this->vrDeferredMagicCost = 0; this->vrPhysicalThrow = false; this->vrLaunchVelocity = (Vec3f){ 0.0f, 0.0f, 0.0f }; + this->vrPhysicalBowShot = false; + this->vrHorseBowShot = false; + this->vrBowPower = 0.0f; + this->vrBowAimOrigin = (Vec3f){ 0.0f, 0.0f, 0.0f }; + this->vrBowAimDir = (Vec3f){ 0.0f, 0.0f, 0.0f }; if (CVarGetInteger(CVAR_COSMETIC("Arrows.NormalPrimary.Changed"), 0)) { blureNormal.altEnvColor = @@ -219,6 +224,32 @@ void EnArrow_Shoot(EnArrow* this, PlayState* play) { return; } + // SOH [VR] Mounted Link's draw path can rewrite the held horse arrow after the player + // limb callback applied physical aim. At detachment, restore the same latched two-hand + // line used by the aim dot before Actor_SetProjectileSpeed turns rotation into velocity. + // Outside a physical release AimSegment is false, leaving every vanilla shot untouched. + { + float vrAim[6]; + if (this->vrPhysicalBowShot) { + vrAim[0] = this->vrBowAimOrigin.x; + vrAim[1] = this->vrBowAimOrigin.y; + vrAim[2] = this->vrBowAimOrigin.z; + vrAim[3] = this->vrBowAimDir.x; + vrAim[4] = this->vrBowAimDir.y; + vrAim[5] = this->vrBowAimDir.z; + } + if (this->vrPhysicalBowShot || VrArchery_TakeReleasedAim(vrAim)) { + Vec3f origin = { vrAim[0], vrAim[1], vrAim[2] }; + Vec3f target = { origin.x + vrAim[3] * 100.0f, origin.y + vrAim[4] * 100.0f, + origin.z + vrAim[5] * 100.0f }; + this->actor.world.pos = origin; + this->actor.world.rot.x = Math_Vec3f_Pitch(&origin, &target); + this->actor.world.rot.y = Math_Vec3f_Yaw(&origin, &target); + this->actor.world.rot.z = 0; + this->actor.shape.rot = this->actor.world.rot; + } + } + switch (this->actor.params) { case ARROW_SEED: Player_PlaySfx(&player->actor, NA_SE_IT_SLING_SHOT); @@ -252,13 +283,14 @@ void EnArrow_Shoot(EnArrow* this, PlayState* play) { // vanilla shot; a partial draw leaves slower, falls from the start, and lives longer // so a weak arrow drops to the ground instead of vanishing mid-air. { - f32 vrPower = VrArchery_TakeBowShotPower(); + f32 vrPower = this->vrPhysicalBowShot ? this->vrBowPower : VrArchery_TakeBowShotPower(); if (vrPower > 0.0f && vrPower < 0.99f) { f32 vrWeak = (1.0f - vrPower) / 0.7f; Actor_SetProjectileSpeed(&this->actor, 150.0f * vrPower); this->timer = 12 + (s32)(12.0f * vrWeak); this->actor.gravity = -1.0f * vrWeak; } + this->vrPhysicalBowShot = false; } } // SOH [VR] Physical nuts retain vanilla impact/stun logic, but launch from @@ -336,7 +368,11 @@ void EnArrow_Fly(EnArrow* this, PlayState* play) { if (this->timer < 7.2000003f) { // SOH [VR] Keep a weak physical-bow shot's stronger fall (vanilla arrows reach here at 0). - if (!((this->actor.params < ARROW_SEED) && (this->actor.gravity < -0.4f))) { + if (this->vrHorseBowShot) { + // VR horseback uses a world-space aim dot: keep its physical arrow on that exact + // line for the whole flight. On-foot and every non-VR arrow retain vanilla drop. + this->actor.gravity = 0.0f; + } else if (!((this->actor.params < ARROW_SEED) && (this->actor.gravity < -0.4f))) { this->actor.gravity = -0.4f; } } diff --git a/soh/src/overlays/actors/ovl_En_Arrow/z_en_arrow.h b/soh/src/overlays/actors/ovl_En_Arrow/z_en_arrow.h index 9657d0e28a9..b435db4999b 100644 --- a/soh/src/overlays/actors/ovl_En_Arrow/z_en_arrow.h +++ b/soh/src/overlays/actors/ovl_En_Arrow/z_en_arrow.h @@ -27,6 +27,13 @@ typedef struct EnArrow { s16 vrDeferredMagicCost; u8 vrPhysicalThrow; Vec3f vrLaunchVelocity; + // Physical-bow release data belongs to this arrow, not to the player's later animation + // state. Horseback can keep a released arrow parented for several updates before launch. + u8 vrPhysicalBowShot; + u8 vrHorseBowShot; + f32 vrBowPower; + Vec3f vrBowAimOrigin; + Vec3f vrBowAimDir; } EnArrow; // size = 0x0260 typedef enum { diff --git a/soh/src/overlays/actors/ovl_En_Box/z_en_box.c b/soh/src/overlays/actors/ovl_En_Box/z_en_box.c index 9b341f462a4..e2c37db0b6c 100644 --- a/soh/src/overlays/actors/ovl_En_Box/z_en_box.c +++ b/soh/src/overlays/actors/ovl_En_Box/z_en_box.c @@ -6,6 +6,7 @@ #include "soh/ResourceManagerHelpers.h" #include "soh/Enhancements/game-interactor/GameInteractor_Hooks.h" #include "soh/Enhancements/randomizer/item_category_adj.h" +#include "soh/Enhancements/vr-combat/VrCombat.h" #define FLAGS 0 @@ -419,6 +420,26 @@ void EnBox_WaitOpen(EnBox* this, PlayState* play) { this->alpha = 255; this->movementFlags |= ENBOX_MOVE_IMMOBILE; + + // SOH [VR] The physical two-hand path owns the unopened lid. It deliberately commits the + // treasure flag only at the fully-open angle, then leaves the actor in the same finished-open + // state as the stock animation. Player_ActionHandler_2 still performs the reward transaction. + s32 vrChest = VrChest_Tick(this, play); + if (vrChest != 0) { + if (vrChest == 2) { + linkAge = gSaveContext.linkAge; + anim = sAnimations[linkAge]; + frameCount = Animation_GetLastFrame(anim); + Animation_Change(&this->skelanime, anim, 1.5f, frameCount, frameCount, ANIMMODE_ONCE, 0.0f); + this->unk_1F4 = this->getItemEntry.gi >= 0 ? 1 : -1; + this->unk_1B0 = 0.0f; + EnBox_SetupAction(this, EnBox_Open); + Flags_SetTreasure(play, this->dyna.actor.params & 0x1F); + gSaveContext.ship.stats.count[COUNT_CHESTS_OPENED]++; + } + return; + } + if (this->unk_1F4 != 0) { // unk_1F4 is modified by player code linkAge = gSaveContext.linkAge; anim = sAnimations[(this->unk_1F4 < 0 ? 2 : 0) + linkAge]; @@ -650,6 +671,9 @@ void EnBox_PostLimbDraw(PlayState* play, s32 limbIndex, Gfx** dList, Vec3s* rot, gSPMatrix((*gfx)++, MATRIX_NEWMTX(play->state.gfxCtx), G_MTX_NOPUSH | G_MTX_LOAD | G_MTX_MODELVIEW); gSPDisplayList((*gfx)++, this->boxBodyDL); } else if (limbIndex == 3) { + MtxF lidMtx; + Matrix_Get(&lidMtx); + VrChest_RecordLidMatrix(this, &lidMtx.mf[0][0]); gSPMatrix((*gfx)++, MATRIX_NEWMTX(play->state.gfxCtx), G_MTX_NOPUSH | G_MTX_LOAD | G_MTX_MODELVIEW); gSPDisplayList((*gfx)++, this->boxLidDL); } @@ -734,4 +758,6 @@ void EnBox_Draw(Actor* thisx, PlayState* play) { } CLOSE_DISPS(play->state.gfxCtx); + + VrChest_DrawItem(this, play); } diff --git a/soh/src/overlays/actors/ovl_En_Door/z_en_door.c b/soh/src/overlays/actors/ovl_En_Door/z_en_door.c index 60a08afbc9e..d7cceda6dc2 100644 --- a/soh/src/overlays/actors/ovl_En_Door/z_en_door.c +++ b/soh/src/overlays/actors/ovl_En_Door/z_en_door.c @@ -12,6 +12,7 @@ #include "objects/object_haka_door/object_haka_door.h" #include "soh/ResourceManagerHelpers.h" #include "soh/Enhancements/game-interactor/GameInteractor_Hooks.h" +#include "soh/Enhancements/vr-combat/VrCombat.h" #define FLAGS ACTOR_FLAG_UPDATE_CULLING_DISABLED @@ -72,6 +73,7 @@ static AnimationHeader* D_809FCECC[] = { &gDoorAdultOpeningLeftAnim, &gDoorChild static u8 sDoorAnimOpenFrames[] = { 25, 25, 25, 25 }; static u8 sDoorAnimCloseFrames[] = { 60, 70, 60, 70 }; +static s32 sVrDoorSecondFacePass = false; static Gfx* D_809FCEE4[5][2] = { { gDoorLeftDL, gDoorRightDL }, @@ -198,6 +200,26 @@ void EnDoor_Idle(EnDoor* this, PlayState* play) { s16 phi_v0; doorType = this->actor.params >> 7 & 7; + if (VrKeys_TryEnDoor(this, play)) { + // Physical key use removes the lock but deliberately leaves the door leaf closed. The + // now-unlocked DOOR_LOCKED actor becomes eligible for VrDoor_Tick below, so opening it is + // a separate handle grab rather than an automatic consequence of turning the key. + if (this->lockTimer != 0) { + if (GameInteractor_Should(VB_CONSUME_SMALL_KEY, true, this)) { + gSaveContext.inventory.dungeonKeys[gSaveContext.mapIndex]--; + Flags_SetSwitch(play, this->actor.params & 0x3F); + } + Audio_PlayActorSound2(&this->actor, NA_SE_EV_CHAIN_KEY_UNLOCK); + GameInteractor_ExecuteOnDungeonKeyUsedHooks(gSaveContext.mapIndex); + this->lockTimer = 0; + this->playerIsOpening = 0; + } + } + // SOH [VR] An ordinary unlocked handle door may be owned directly by a motion hand. Locked, + // checkable, ajar and non-VR doors fall straight through to the original behavior. + if (VrDoor_Tick(this, play)) { + return; + } Actor_WorldToActorCoords(&this->actor, &playerPosRelToDoor, &player->actor.world.pos); if (this->playerIsOpening != 0) { this->actionFunc = EnDoor_Open; @@ -326,9 +348,15 @@ s32 EnDoor_OverrideLimbDraw(PlayState* play, s32 limbIndex, Gfx** dList, Vec3f* transitionEntry = &play->transiActorCtx.list[(u16)this->actor.params >> 0xA]; rot->z += this->actor.world.rot.y; if ((play->roomCtx.prevRoom.num >= 0) || (transitionEntry->sides[0].room == transitionEntry->sides[1].room)) { + Vec3f vrFaceEye = play->view.eye; + VrDoor_StableFaceView(this, &vrFaceEye.x); phi_v0_2 = ((this->actor.shape.rot.y + this->skelAnime.jointTable[3].z) + rot->z) - - Math_Vec3f_Yaw(&play->view.eye, &this->actor.world.pos); - *dList = (ABS(phi_v0_2) < 0x4000) ? temp_a2[0] : temp_a2[1]; + Math_Vec3f_Yaw(&vrFaceEye, &this->actor.world.pos); + s32 faceIndex = (ABS(phi_v0_2) < 0x4000) ? 0 : 1; + if (sVrDoorSecondFacePass && VrDoor_IsPhysicalActive(this)) { + faceIndex ^= 1; + } + *dList = temp_a2[faceIndex]; } else { phi_v0 = this->unk_192; if (transitionEntry->sides[0].room != this->actor.room) { @@ -348,6 +376,14 @@ void EnDoor_Draw(Actor* thisx, PlayState* play) { Gfx_SetupDL_25Opa(play->state.gfxCtx); SkelAnime_DrawSkeletonOpa(play, &this->skelAnime, EnDoor_OverrideLimbDraw, NULL, &this->actor); + // SOH [VR] The original renderer submits only the door face selected for a third-person + // camera. At arm's length in VR that selection can clip away half the opened leaf, so an + // active physical door submits the complementary face as a second pass. + if (VrDoor_IsPhysicalActive(this)) { + sVrDoorSecondFacePass = true; + SkelAnime_DrawSkeletonOpa(play, &this->skelAnime, EnDoor_OverrideLimbDraw, NULL, &this->actor); + sVrDoorSecondFacePass = false; + } if (this->actor.world.rot.y != 0) { if (this->actor.world.rot.y > 0) { gSPDisplayList(POLY_OPA_DISP++, gDoorRightDL); diff --git a/soh/src/overlays/actors/ovl_En_Mag/z_en_mag.c b/soh/src/overlays/actors/ovl_En_Mag/z_en_mag.c index ee8b2270b08..4aa68201781 100644 --- a/soh/src/overlays/actors/ovl_En_Mag/z_en_mag.c +++ b/soh/src/overlays/actors/ovl_En_Mag/z_en_mag.c @@ -5,6 +5,7 @@ */ #include "z_en_mag.h" +#include #include "objects/object_mag/object_mag.h" #include #include "soh/ResourceManagerHelpers.h" @@ -63,6 +64,8 @@ void EnMag_Init(Actor* thisx, PlayState* play) { EnMag* this = (EnMag*)thisx; bool isMQ = ResourceMgr_IsGameMasterQuest(); + vr_benchmark_title_intro_begin(); + YREG(1) = 63; YREG(3) = 80; YREG(4) = 255; @@ -323,6 +326,7 @@ void EnMag_Update(Actor* thisx, PlayState* play) { } } else if (this->globalState == MAG_STATE_DISPLAY) { if (Flags_GetEnv(play, 4)) { + vr_benchmark_title_intro_end(); this->globalState = MAG_STATE_FADE_OUT; } } diff --git a/soh/src/overlays/actors/ovl_player_actor/z_player.c b/soh/src/overlays/actors/ovl_player_actor/z_player.c index c580a14824d..b0bef9dfade 100644 --- a/soh/src/overlays/actors/ovl_player_actor/z_player.c +++ b/soh/src/overlays/actors/ovl_player_actor/z_player.c @@ -320,6 +320,8 @@ void Player_Action_8084E368(Player* this, PlayState* play); void Player_Action_8084E3C4(Player* this, PlayState* play); void Player_Action_8084E604(Player* this, PlayState* play); void Player_Action_8084E6D4(Player* this, PlayState* play); +void Player_VrChestStartAward(PlayState* play, Player* this, EnBox* chest, GetItemEntry* entry); +void Player_VrChestAwardUpdate(PlayState* play, Player* this); void Player_Action_8084E9AC(Player* this, PlayState* play); void Player_Action_8084EAC0(Player* this, PlayState* play); void Player_Action_SwingBottle(Player* this, PlayState* play); @@ -2697,6 +2699,34 @@ void Player_StartChangingHeldItem(Player* this, PlayState* play) { } void Player_UpdateItems(Player* this, PlayState* play) { + // Tick even while dismounted so the transient horse mode is cleared immediately. + const bool horseBowTogglePressed = VrItemSelect_TakeHorseBowToggle(); + // SOH [VR] The item compass cannot be used on Epona. Its button becomes an explicit bow + // toggle there: one persistent mode equips the horse's B-slot bow and routes it through + // the same physical nock/pull/release path used on foot; the other puts it away and returns + // the hands to horse control. The selector edge itself must never be interpreted as firing. + if ((this->actor.category == ACTORCAT_PLAYER) && (this->stateFlags1 & PLAYER_STATE1_ON_HORSE) && + this->heldItemAction == this->itemAction && + !(this->stateFlags1 & (PLAYER_STATE1_IN_CUTSCENE | PLAYER_STATE1_START_CHANGING_HELD_ITEM)) && + horseBowTogglePressed) { + Player_VrSelectItem(play, this, VrItemSelect_HorseBowEnabled() ? 0 : -1); + // Do not let this same controller edge fall through to ordinary item processing and + // become an immediate bow use. StartChangingHeldItem will run on the next update. + sUseHeldItem = sHeldItemButtonIsHeldDown = false; + VrArchery_Reset(); + return; + } + // SOH [VR] Bombchu Bowling owns the B slot for the whole round. Selector mode normally + // forbids buttons from changing held equipment, so passively put the forced minigame item + // in Link's hand as soon as ordinary item-changing state permits it. This uses the passive + // selector transition so no actor or fuse exists until the player grips the VR preview. + if (VR_IsInitialized() && CVarGetInteger("gVrItemSelect", 1) && play->bombchuBowlingStatus > 0 && + this->actor.category == ACTORCAT_PLAYER && this->heldItemAction != PLAYER_IA_BOMBCHU && + this->heldItemAction == this->itemAction && this->csAction == 0 && + !(this->stateFlags1 & (PLAYER_STATE1_CARRYING_ACTOR | PLAYER_STATE1_IN_CUTSCENE | + PLAYER_STATE1_START_CHANGING_HELD_ITEM))) { + Player_VrSelectItem(play, this, 0); + } // SOH [VR] Selection is an explicit request, not an item-button press. Resolve it // before the upper action can interpret a release as firing the old item. if (VrItemSelect_ModeActive() && this->actor.category == ACTORCAT_PLAYER && @@ -2719,6 +2749,8 @@ void Player_UpdateItems(Player* this, PlayState* play) { VrLens_Tick(play, this); // SOH [VR] Physical masks: pocket / hand; on and off at the face (currentMask stays vanilla's). VrMask_Tick(play, this); + // SOH [VR] Physical dungeon keys: pull the current dungeon's key from the left wrist HUD. + VrKeys_Tick(play, this); // SOH [VR] Bottle pour gesture (inverted + three shakes) commits contents through the // item button's own use path from this same boundary. VrBottle_Tick(play, this); @@ -3073,8 +3105,10 @@ s32 func_80834EB8(Player* this, PlayState* play) { // aim with the HAND in VR, so the standstill first-person aim stance is pointless — every // aim takes the Z-target-style path instead (upper body aims, legs keep walking; the // kinematic stick movement stays live because the main action remains locomotion). - // Shooting galleries keep their own stock aiming mode. - if (VR_IsInitialized() && VR_GetFirstPerson() && (play->shootingGalleryStatus == 0)) { + // Physical archery uses the same free motion-hand posture in shooting galleries as it does + // everywhere else; only the gallery's ammo, targets and scoring remain special. + if ((VR_IsInitialized() && VR_GetFirstPerson() && (play->shootingGalleryStatus == 0)) || + VrArchery_Covers(this)) { return 1; } if ((this->unk_6AD == 0) || (this->unk_6AD == 2)) { @@ -3287,7 +3321,7 @@ s32 func_808353D8(Player* this, PlayState* play) { // path lowers the bow here, and the lower-animation window ate the next press — the // "fires once then goes dead" bug. if (Player_IsZTargeting(this) || (this->unk_6AD != 0) || (this->stateFlags1 & PLAYER_STATE1_FIRST_PERSON) || - (VR_IsInitialized() && VR_GetFirstPerson())) { + (VR_IsInitialized() && VR_GetFirstPerson()) || VrArchery_Covers(this)) { if (this->unk_834 == 0) { this->unk_834++; } @@ -3715,27 +3749,51 @@ int32_t Player_VrSelectItem(PlayState* play, Player* this, int32_t slot) { s8 itemAction; Actor* held; bool explosive; + bool underwaterHookshotTransition; + bool bowlingBombchu; + bool horseBowToggle; - if (!VrItemSelect_SelectionAllowed() || this->actor.category != ACTORCAT_PLAYER || - slot < -1 || slot > 3 || gSaveContext.health == 0 || this->csAction != 0 || - play->shootingGalleryStatus != 0 || play->bombchuBowlingStatus != 0 || - play->activeCamera != CAM_ID_MAIN || gSaveContext.minigameState == 1 || + if (slot < -1 || slot > 3) { + return false; + } + + // The mounted HUD presents the bow on B without replacing the save file's real B item + // (normally the sword). Resolve this VR-only passive request explicitly; asking the ordinary + // button resolver for slot 0 would select the sword and fail the horse-bow classification. + horseBowToggle = VR_IsInitialized() && CVarGetInteger("gVrItemSelect", 1) && + (this->stateFlags1 & PLAYER_STATE1_ON_HORSE) && (slot == -1 || slot == 0); + item = slot < 0 ? ITEM_NONE : horseBowToggle ? ITEM_BOW : Player_GetItemOnButton(play, slot); + itemAction = Player_ItemToItemAction(item); + bowlingBombchu = play->bombchuBowlingStatus > 0 && slot == 0 && itemAction == PLAYER_IA_BOMBCHU; + underwaterHookshotTransition = + (this->stateFlags1 & PLAYER_STATE1_IN_WATER) && (this->currentBoots == PLAYER_BOOTS_IRON) && + (this->actor.bgCheckFlags & BGCHECKFLAG_GROUND) && + ((itemAction == PLAYER_IA_HOOKSHOT) || (itemAction == PLAYER_IA_LONGSHOT) || + ((itemAction == PLAYER_IA_NONE) && Player_HoldsHookshot(this))); + + if ((!VrItemSelect_SelectionAllowed() && !bowlingBombchu && !horseBowToggle) || + this->actor.category != ACTORCAT_PLAYER || + gSaveContext.health == 0 || this->csAction != 0 || + play->shootingGalleryStatus != 0 || (play->bombchuBowlingStatus != 0 && !bowlingBombchu) || + (!bowlingBombchu && + (play->activeCamera != CAM_ID_MAIN || gSaveContext.minigameState == 1)) || play->pauseCtx.state != 0 || this->unk_6AD != 0 || - (this->stateFlags1 & (PLAYER_STATE1_START_CHANGING_HELD_ITEM | PLAYER_STATE1_IN_WATER | - PLAYER_STATE1_ON_HORSE | PLAYER_STATE1_DEAD | PLAYER_STATE1_CLIMBING_LADDER | - PLAYER_STATE1_CLIMBING_LEDGE | PLAYER_STATE1_HANGING_OFF_LEDGE)) || - (this->stateFlags3 & PLAYER_STATE3_FLYING_WITH_HOOKSHOT) || this->actor.parent != NULL || + (this->stateFlags1 & (PLAYER_STATE1_START_CHANGING_HELD_ITEM | PLAYER_STATE1_DEAD | + PLAYER_STATE1_CLIMBING_LADDER | PLAYER_STATE1_CLIMBING_LEDGE | + PLAYER_STATE1_HANGING_OFF_LEDGE)) || + ((this->stateFlags1 & PLAYER_STATE1_IN_WATER) && !underwaterHookshotTransition) || + (this->stateFlags3 & PLAYER_STATE3_FLYING_WITH_HOOKSHOT) || + (this->actor.parent != NULL && !horseBowToggle) || this->heldItemAction != this->itemAction || this->upperActionFunc == Player_UpperAction_ChangeHeldItem) { return false; } - item = slot < 0 ? ITEM_NONE : Player_GetItemOnButton(play, slot); // Disabled/empty buttons must not become a way around vanilla restrictions. - if (slot >= 0 && (item >= ITEM_NONE_FE || item != VrItemSelect_PendingItem())) { + if (slot >= 0 && + (item >= ITEM_NONE_FE || (!bowlingBombchu && !horseBowToggle && item != VrItemSelect_PendingItem()))) { return 2; } - itemAction = Player_ItemToItemAction(item); if (itemAction < PLAYER_IA_NONE || itemAction >= PLAYER_IA_MAX) { return 2; } @@ -3900,6 +3958,13 @@ bool Player_VrGrabItem(PlayState* play, Player* this) { } } if (this->heldActor == NULL) return false; + if (this->heldActor->id == ACTOR_EN_BOM_CHU) { + // SOH [VR] The physical interaction is slower than a button press: allow a longer fuse + // only for Bombchus committed through this VR grab path. Six seconds (120 ticks) is + // vanilla; ordinary button use and all non-VR gameplay never pass through this code. + const f32 fuseSeconds = CLAMP(CVarGetFloat("gVrBombchuFuseSeconds", 8.0f), 6.0f, 20.0f); + ((EnBomChu*)this->heldActor)->timer = (s16)(fuseSeconds * 20.0f + 0.5f); + } this->heldItemId = selectedItem; // explosive initialization may clear it while detaching Player_SetUpperActionFunc(this, Player_UpperAction_CarryActor); LinkAnimation_PlayLoop(play, &this->upperSkelAnime, &gPlayerAnim_link_normal_carryB_wait); @@ -8070,11 +8135,15 @@ s32 Player_ActionHandler_2(Player* this, PlayState* play) { this->getItemId = GI_NONE; this->getItemEntry = (GetItemEntry)GET_ITEM_NONE; } - } else if (CHECK_BTN_ALL(sControlInput->press.button, BTN_A) && + } else if (((CHECK_BTN_ALL(sControlInput->press.button, BTN_A) && + !(interactedActor->id == ACTOR_EN_BOX && VrChest_AwardActive())) || + (interactedActor->id == ACTOR_EN_BOX && VrChest_OpenRequested((EnBox*)interactedActor))) && !(this->stateFlags1 & PLAYER_STATE1_CARRYING_ACTOR) && !(this->stateFlags2 & PLAYER_STATE2_UNDERWATER)) { if (this->getItemId != GI_NONE) { if (GameInteractor_Should(VB_OPEN_CHEST, true, interactedActor)) { + s32 vrPhysicalChest = + interactedActor->id == ACTOR_EN_BOX && VrChest_OpenRequested((EnBox*)interactedActor); GetItemEntry giEntry; if (this->getItemEntry.objectId == OBJECT_INVALID) { giEntry = ItemTable_Retrieve(-this->getItemId); @@ -8090,7 +8159,20 @@ s32 Player_ActionHandler_2(Player* this, PlayState* play) { } } - if (GameInteractor_Should(VB_GIVE_ITEM_FROM_CHEST, true, chest)) { + s32 giveChestItem = GameInteractor_Should(VB_GIVE_ITEM_FROM_CHEST, true, chest); + if (vrPhysicalChest) { + // The physical lid already supplied the animation and presentation. Run + // the exact stock reward/message state machine alongside Link's current + // action instead of replacing locomotion with the get-item cutscene. + VrChest_ConsumeOpenRequest(chest); + func_8083AE40(this, giEntry.objectId); + if (giveChestItem) { + Player_VrChestStartAward(play, this, chest, &giEntry); + } + return 1; + } + + if (giveChestItem) { Player_SetupWaitForPutAway(play, this, func_8083A434); } this->stateFlags1 |= @@ -8515,6 +8597,9 @@ void func_8084BEE4(Player* this); // (func_8083F360) holds him at ageProperties->unk_3C (15); here the arms set it. < 0 = not climbing // by hand. static f32 sVrClimbWallDist = -1.0f; +// +1 when Link holds the authored front of the polygon, -1 when a two-sided/dynamic climbable is +// approached from its back. All physical-climb plane math uses an effective normal toward Link. +static f32 sVrClimbWallSide = 1.0f; // How far toward the wall the view was last allowed to run ahead of the body between ticks // (Player_VrClimbPublishLimits). < 0 = no limit published yet: the view follows the hand fully. static f32 sVrClimbViewIn = -1.0f; @@ -8527,9 +8612,9 @@ static s32 Player_VrClimbWallNormal(Player* this, f32 n[3]) { if (poly == NULL) { return false; } - n[0] = COLPOLY_GET_NORMAL(poly->normal.x); + n[0] = COLPOLY_GET_NORMAL(poly->normal.x) * sVrClimbWallSide; n[1] = 0.0f; - n[2] = COLPOLY_GET_NORMAL(poly->normal.z); + n[2] = COLPOLY_GET_NORMAL(poly->normal.z) * sVrClimbWallSide; len = sqrtf(SQ(n[0]) + SQ(n[2])); if (len < 0.001f) { return false; @@ -8546,8 +8631,9 @@ static f32 Player_VrClimbPlaneDist(Player* this, f32 x, f32 y, f32 z) { if (poly == NULL) { return 0.0f; } - return (COLPOLY_GET_NORMAL(poly->normal.x) * x) + (COLPOLY_GET_NORMAL(poly->normal.y) * y) + - (COLPOLY_GET_NORMAL(poly->normal.z) * z) + poly->dist; + return ((COLPOLY_GET_NORMAL(poly->normal.x) * x) + (COLPOLY_GET_NORMAL(poly->normal.y) * y) + + (COLPOLY_GET_NORMAL(poly->normal.z) * z) + poly->dist) * + sVrClimbWallSide; } static f32 Player_VrClimbBodyDist(Player* this) { @@ -8583,6 +8669,58 @@ static s32 Player_VrClimbGlue(PlayState* play, Player* this, f32 dist) { s16 yaw = this->yaw; u32 wallFlags = sTouchedWallFlags; + if (sVrClimbWallSide < 0.0f) { + CollisionPoly* poly; + s32 hitBgId; + Vec3f start; + Vec3f end; + Vec3f hit; + f32 outward[3]; + f32 len; + + if (!Player_VrClimbWallNormal(this, outward)) { + return false; + } + // Search from just behind Link toward the wall. Back-side climbables must be tested as + // two-sided: their authored front face points through the wall, away from the player. + start.x = this->actor.world.pos.x + outward[0] * 20.0f; + start.y = this->actor.world.pos.y + 26.0f; + start.z = this->actor.world.pos.z + outward[2] * 20.0f; + end.x = this->actor.world.pos.x - outward[0] * (dist + 35.0f); + end.y = start.y; + end.z = this->actor.world.pos.z - outward[2] * (dist + 35.0f); + if (BgCheck_EntityLineTest1(&play->colCtx, &start, &end, &hit, &poly, true, false, false, false, + &hitBgId)) { + s32 flags = func_80041DB8(&play->colCtx, poly, hitBgId); + if ((flags & 8) || (flags & 2) || func_80041E4C(&play->colCtx, poly, hitBgId)) { + this->actor.wallPoly = poly; + this->actor.wallBgId = hitBgId; + this->actor.bgCheckFlags |= 0x200; + sTouchedWallFlags = flags; + outward[0] = -COLPOLY_GET_NORMAL(poly->normal.x); + outward[2] = -COLPOLY_GET_NORMAL(poly->normal.z); + len = sqrtf(SQ(outward[0]) + SQ(outward[2])); + if (len > 0.001f) { + outward[0] /= len; + outward[2] /= len; + this->actor.wallYaw = Math_Atan2S(outward[2], outward[0]); + this->actor.shape.rot.y = this->yaw = this->actor.wallYaw + 0x8000; + this->actor.world.pos.x = hit.x + outward[0] * dist; + this->actor.world.pos.z = hit.z + outward[2] * dist; + return true; + } + } + } + this->actor.world.pos = pos; + this->actor.wallPoly = wallPoly; + this->actor.wallBgId = wallBgId; + this->actor.wallYaw = wallYaw; + this->actor.shape.rot.y = shapeYaw; + this->yaw = yaw; + sTouchedWallFlags = wallFlags; + return false; + } + if (func_8083F360(play, this, 26.0f, dist, dist + 35.0f, -20.0f) && ((sTouchedWallFlags & 8) || (sTouchedWallFlags & 2) || func_80041E4C(&play->colCtx, this->actor.wallPoly, this->actor.wallBgId))) { @@ -8641,9 +8779,15 @@ static void Player_VrClimbMount(PlayState* play, Player* this, VrClimbHit* hit) f32 headFwd = CVarGetFloat("gVrHeadOffsetForward", 0.0f); f32 headSide = CVarGetFloat("gVrHeadOffsetSide", 0.0f); + sVrClimbWallSide = (((COLPOLY_GET_NORMAL(poly->normal.x) * this->actor.world.pos.x) + + (COLPOLY_GET_NORMAL(poly->normal.y) * this->actor.world.pos.y) + + (COLPOLY_GET_NORMAL(poly->normal.z) * this->actor.world.pos.z) + poly->dist) < 0.0f) + ? -1.0f + : 1.0f; this->actor.wallPoly = poly; this->actor.wallBgId = hit->bgId; - this->actor.wallYaw = Math_Atan2S(poly->normal.z, poly->normal.x); + this->actor.wallYaw = Math_Atan2S(poly->normal.z * sVrClimbWallSide, + poly->normal.x * sVrClimbWallSide); this->actor.bgCheckFlags |= BGCHECKFLAG_PLAYER_WALL_INTERACT; sTouchedWallFlags = wallFlags; @@ -8713,6 +8857,10 @@ static void Player_VrClimbPlaceFromAbove(PlayState* play, Player* this, Collisio this->stateFlags1 &= ~(PLAYER_STATE1_IN_WATER | PLAYER_STATE1_HANGING_OFF_LEDGE); this->av1.actionVar1 = (wallFlags & 8) ? 2 : 0; this->av2.actionVar2 = 0; + sVrClimbWallSide = ((COLPOLY_GET_NORMAL(poly->normal.x) * outX) + + (COLPOLY_GET_NORMAL(poly->normal.z) * outZ)) < 0.0f + ? -1.0f + : 1.0f; this->actor.wallPoly = poly; this->actor.wallBgId = bgId; this->actor.wallYaw = Math_Atan2S(outZ, outX); @@ -13968,6 +14116,10 @@ void Player_Update(Actor* thisx, PlayState* play) { Player_UpdateCommon(this, play, &sp44); } + // A physically opened chest keeps the normal player action alive. Its get-item transaction + // advances here independently, so the textbox/fanfare does not freeze locomotion. + Player_VrChestAwardUpdate(play, this); + MREG(52) = this->actor.world.pos.x; MREG(53) = this->actor.world.pos.y; MREG(54) = this->actor.world.pos.z; @@ -14205,9 +14357,14 @@ void Player_Draw(Actor* thisx, PlayState* play2) { func_8002EBCC(&this->actor, play, 0); func_8002ED80(&this->actor, play, 0); - if (VR_IsInitialized() && VR_GetFirstPerson()) { + if ((this == GET_PLAYER(play)) && VR_IsInitialized() && (VR_GetFirstPerson() || VrArchery_Covers(this))) { // SOH [VR] The camera sits at Link's head, so draw the full body but cull the head + // hat (the game's projected-Z test uses the third-person matrix and doesn't apply). + // Physical shooting galleries keep their fixed camera, but still need this override + // so the visible slingshot/bow and its pouch share the controller-space grab anchor. + // Anchor dummy players deliberately stay on the normal full-body renderer: local + // Hide Link Body and first-person head culling are comfort settings for this player, + // never visibility instructions sent to other clients. overrideLimbDraw = Player_OverrideLimbDrawGameplayVRFirstPerson; } else if (this->unk_6AD != 0) { Vec3f projectedHeadPos; @@ -15890,6 +16047,50 @@ s32 func_8084DFF4(PlayState* play, Player* this) { return 0; } +// The stock reward processor stores its phase in the active Player action. Physical chests must +// not replace that action, so preserve the locomotion action's variable and lend the processor a +// dedicated phase only for the duration of this call. This deliberately reuses func_8084DFF4 in +// full, retaining randomizer delivery, pending flags, equip prompts, ice traps, special messages, +// and fanfare behavior without duplicating any of those rules. +static s32 sVrChestAwardPhase = -1; +static EnBox* sVrChestAwardChest = NULL; + +void Player_VrChestStartAward(PlayState* play, Player* this, EnBox* chest, GetItemEntry* entry) { + if (play == NULL || this == NULL || chest == NULL || entry == NULL) { + return; + } + + sVrChestAwardPhase = 0; + sVrChestAwardChest = chest; + this->getItemEntry = *entry; + this->getItemId = ABS(entry->getItemId); + this->getItemEntry.getItemId = ABS(this->getItemEntry.getItemId); + this->unk_862 = 0; // VrChest_DrawItem remains the only visible copy. + VrChest_AwardStarted(chest, entry); +} + +void Player_VrChestAwardUpdate(PlayState* play, Player* this) { + s32 savedActionVar; + s32 finished; + + if (sVrChestAwardPhase < 0 || play == NULL || this == NULL) { + return; + } + + savedActionVar = this->av1.actionVar1; + this->av1.actionVar1 = sVrChestAwardPhase; + finished = func_8084DFF4(play, this); + sVrChestAwardPhase = this->av1.actionVar1; + this->av1.actionVar1 = savedActionVar; + + if (finished) { + VrChest_AwardFinished(sVrChestAwardChest); + sVrChestAwardChest = NULL; + sVrChestAwardPhase = -1; + this->unk_862 = 0; + } +} + void Player_Action_8084E1EC(Player* this, PlayState* play) { this->stateFlags2 |= PLAYER_STATE2_DISABLE_ROTATION_Z_TARGET;