19659 Commits
Author SHA1 Message Date
Goober5000andClaude Opus 4.8 41ce07b33a Extract common name conflict checker for FRED2 and qtFRED
The ship editor, wing editor, waypoint path dialog, and jump node
dialog all had near-identical code to check whether a new name
conflicts with an existing ship, wing, waypoint path, jump node, or
target priority group (or is empty, or begins with '<').  Both FRED2
and qtFRED carried their own copies of this logic.

Extract it into a single check_name_conflict() function in
code/missioneditor/common.cpp, shared by both editors, and replace the
duplicated validation at each call site with a one-line call:

  - FRED2:  shipeditordlg, wing_editor, waypointpathdlg, jumpnodedlg
  - qtFRED: ShipEditorDialogModel, WaypointEditorDialogModel,
            JumpNodeEditorDialogModel, and Editor::validate_wing_name

This also aligns a few small behavioral differences that had crept in
between the two editors: the waypoint and jump node dialogs now skip
empty wing slots (wave_count == 0) when checking for wing-name
collisions, and the qtFRED wing editor now rejects names beginning
with '<'.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
2026-07-31 00:26:07 -04:00
John Fernandez 92384b3c60 More Search UI/UX Enhancements (#7612)
* Prioritize items that begin with search string

Items that begin with the search string should be prioritized before those that simply contain the search string.

* Add Search Operators option

* Add Safety to Action Handler

I didn't see any crashes, but this matches the pattern of other keyboard shortcuts.

* Allow search for numeric nodes

The working code existed already

* Limit matches on operator search

This limits matches on operator searches by setting a minimum size that a string match has to meet.  Function returns -1 on failure, and the warning has been removed to allow this behavior.

* Try this option name better

* Add keyboard shortcut for search

This allows ctrl+s (which can be listed instead of spacebar) to initiate search.  There is a new menu item added as well.

* Put this in the correct place

* Address Feedback

* Wrong state

We want the item to be inserted here, not ignored.
2026-07-30 12:59:33 -04:00
Goober5000 6180173fe8 Merge pull request #7487 from Goober5000/feature/format_classes
Convert CSG/PLR fixed ship/weapon arrays to SCP_vector
2026-07-30 03:23:56 -04:00
Goober5000andClaude Fable 5 5fa6674688 send-message-list arg-count forgiveness, plus better error checking
Due to a long-standing bug, the groups-of-4 argument count check for
send-message-list and send-message-chain never actually worked, so
missions through 25.0 could includes sexps with truncated argument lists
that recovered gracefully at runtime.  Now that the check works, don't
punish those missions: introduce SEXP_CHECK_BAD_ARG_COUNT_BENIGN, which
warns but does not prevent the mission from loading.

To make sexp tree validation more robust, check_sexp_syntax now defers
recoverable errors rather than returning them immediately; otherwise
a recoverable error could mask a fatal error deeper in the tree.

Also fix a stale-variable bug in FRED's fred_check_sexp that could
produce a bogus empty dialog.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-30 01:03:06 -04:00
Goober5000 bb1948abeb Merge pull request #7660 from Goober5000/fix/gtbc_disable
fix crash when a ship with no primary banks is ordered to disable/disarm
2026-07-29 22:50:17 -04:00
Goober5000 1971931649 Merge pull request #7666 from Goober5000/fix/subsystem_targets
fix player subsystem targeting from sexps and scripting
2026-07-29 22:36:25 -04:00
Goober5000 53e31c9f70 Merge pull request #7667 from Goober5000/fix/keycontrol
fix keycontrol unsetting dual-fire
2026-07-29 22:32:32 -04:00
Mike Nelson ec798feb5d Fix space mouse detection under SDL_hidapi (#7665)
Since #7646 switched from the bundled hidapi to SDL_hidapi, no space mouse is
found. SDL_hid_enumerate() nominally auto-inits HIDAPI, but in practice it only
reliably reports an already-connected device when SDL_hid_init() has been called
up front. Call SDL_hid_init() once in os_init() (before SDL_Init), balanced by
SDL_hid_exit() in os_deinit(). io::spacemouse (qtFRED's only consumer) then
enumerates the device correctly.
2026-07-29 21:03:35 -04:00
Mike Nelson 2f8b4f2962 Clear stale Prop_info model handles when a model is unloaded (#7669)
Repro: create a prop, File -> New Mission & Discard, then create the same prop
again. Asserts in model_get with "Index collision between model <other>.pof and
requested model N".

model_unload() walks Ship_info and Weapon_info clearing any cached model_num
that pointed at the model being freed, but never did the same for Prop_info.
props_level_close() only clears the prop instances, so prop_info::model_num
survived the discard pointing at a freed slot. Placing that prop class again hit
EditorViewport::create_object_on_grid, which reads pip->model_num directly to
size the placement distance, and by then the slot had been reused by an
unrelated model.

Adds the matching Prop_info pass. Doing it in model_unload rather than
props_level_close mirrors how the two closest analogues are handled -- Ship_info
and Weapon_info are likewise class tables holding a cached handle for placeable
objects -- and covers any unload path, not just level close. (asteroid_level_close
solves the same problem for Asteroid_info from the other direction.)

This is not OFP-specific; SCP master has props and the same missing pass.
2026-07-29 21:02:37 -04:00
Goober5000andClaude Fable 5 d40fcd16c0 fix player subsystem targeting from sexps and scripting
Fix a regression from #7393: `last_targeted_subobject` must be updated when the player's target and target subsystem are changed, or the subsystem will be retargeted due to `hud_target_change_check`.

Also fix related issues:
- the `ship.Target` and `ship.TargetSubsystem` scripting setters now use the standard `set_target_objnum` function and also correctly handle the new target subsystem
- fix an indexing error in `order.TargetSubsystem`

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-28 23:09:24 -04:00
Goober5000 fb13f1aec5 fix keycontrol unsetting dual-fire
Quick follow-up to #7635.  Even though you can't set dual-fire when a non-dual-fire bank is active, you should be able to *un*set it.  Reorder the conditions so this is possible.
2026-07-28 22:57:54 -04:00
Goober5000 4e26511055 Merge pull request #7635 from Goober5000/fix/firingpoints
fix dual fire handling for banks that cannot use it
2026-07-28 19:42:24 -04:00
Goober5000andClaude Fable 5 60c554354c fix dual fire handling for banks that cannot use it
The Secondary_dual_fire flag is per-ship, but not every secondary bank
can dual fire.  Previously the HUD drew the dual fire link icon even
when the armed bank had only one firepoint, and firing such a bank
cleared the flag entirely, silently discarding the player's dual fire
preference for the other banks.

Extend the ignored-rather-than-cleared approach already established
for no-doublefire weapons to the single-firepoint case:

- add ship_secondary_bank_can_dual_fire() as the single source of truth
  for bank validity, No_doublefire, ai_profiles restrictions, and
  firepoint count
- ship_fire_secondary() now fires single and leaves the flag alone when
  the bank cannot dual fire, instead of removing the flag
- the weapons gauges and the hardpoints gauge consult the helper, so the
  link icon and second-firepoint highlight are no longer drawn for
  incapable banks
- the dual fire toggle on a single-firepoint bank now explains why it
  cannot dual fire and leaves the preference untouched
- restoring the saved dual fire preference no longer depends on bank 0's
  firepoint count, since incapable banks now simply ignore the flag
- key control and force feedback also consult the helper

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-28 01:08:07 -04:00
Goober5000andClaude Opus 4.8 b7cd9765a1 fix crash when a ship with no primary banks is ordered to disable/disarm
Gunships and other custom ship classes may run through the primary weapon code despite having no primary banks.  Add a few guards to prevent this from causing crashes.

Fixes a crash reported in Causality: The Great War.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
2026-07-27 12:12:10 -04:00
Taylor Richards 29116e7ba4 remove hidapi lib in favor of SDL_hidapi (#7646)
* remove hidapi lib in favor of SDL_hidapi

Funtionally identical under the hood, but offering maximum capability and
compatability without adding any system dependencies. The main difference on
our side is that hidapi functions and types will be prefixed with "SDL_". And
SDL will dynamically load in the hidapi features best supported by the running
operating system.

* remove residual SDL_hid_exit call
2026-07-26 13:57:57 -04:00
The Force da05081405 Fix C4709 Warnings In modern VS (#7576)
* Fix C4709 Warnings on latest VS

* more

* suppress false positive

* Switch to using any/none_of

* Address Feedback

* Fix Line endings?

* Fix commits and strip out flag_combinator

* more fixes

* nolint
2026-07-26 14:33:00 +01:00
Fabian Woltermann 09ab04193b Merge pull request #7651 from The-E/fix/resolution-initialization-on-empty-config
Fix resolution_default to handle uninitialized SDL video subsystem
2026-07-24 21:16:10 +02:00
Fabian Woltermann d0cefc87bd Fix inverted scpui icons and 3d ship/weapon select models rendering in the wrong place (#7647)
* Fix Vulkan render target readback orientation to match OpenGL behavior

* Add render target pass resumption after Vulkan shadow rendering

Ensure that Vulkan render targets resume rendering properly after shadow passes, particularly for off-screen targets like SCPUI's 3D previews, to prevent unintended content leakage onto the screen.

* Skip alpha writes for additive batched bitmaps in render targets to preserve coverage and prevent opaque artifacts.

* Add external subpass dependencies to Vulkan render passes to fix read/write hazards

Introduce explicit memory dependencies for color attachments sampled between passes to prevent flickering and graphical artifacts caused by read-after-write and write-after-read hazards.

* Support fractional alpha values in createColor function and preserve 0-255 compatibility
2026-07-24 21:10:13 +02:00
the-e 9eb11aec7f Fix resolution_default to handle uninitialized SDL video subsystem
Ensure SDL video is temporarily initialized if needed during startup to safely query desktop display mode, preventing reliance on a potentially dead subsystem and avoiding silent fallback to invalid resolutions.
2026-07-24 20:38:14 +02:00
Fabian Woltermann 6ae666d10a Merge pull request #7643 from Shivansps/vulkan-etc2
ETC2 textures support in Vulkan
2026-07-24 17:43:16 +02:00
Taylor Richards aaa48d4374 fix uniform type mismatch error in shadow_map shader (#7649) 2026-07-24 04:18:48 +00:00
Taylor Richards 039880491a port to SDL3 (#7220)
Basic port from SDL2 to SDL3. Also updates imgui to 1.92.5.
2026-07-23 15:52:27 +02:00
Fabian Woltermann 1abbea499b Merge pull request #7640 from The-E/fix/various-scpui-issues-in-vulkan
Fix various issues in SCPUI when using Vulkan
2026-07-23 09:12:20 +02:00
Mike Nelson e75f72456e QtFRED add object reorder dialog (#7636)
* Add Reorder Objects dialog to QtFRED

* clang

* clang again

* address feedback
2026-07-22 20:31:38 -04:00
Salvador Cipolla a40868497e ETC2 textures support in vulkan 2026-07-22 19:45:29 -03:00
Fabian Woltermann 2c3e052ec6 Fix Vulkan FXAA/SMAA handling and ensure proper Scene_ldr transitions (#7639)
Address FXAA/SMAA shader selection logic by aligning it with the current anti-aliasing mode. Fix undefined behavior for discarded non-edge pixels during the FXAA main pass by transitioning Scene_ldr to a load-preserving layout. Optimize compatibility across IMR and tiled GPUs, preventing visual artifacts.
2026-07-23 00:38:44 +02:00
the-e 1e5bf66c84 Remove unsupported graphics options for non-raytracing renderers
Disable raytraced-shadow and HDR settings in the options menu when unsupported by the current renderer, reducing UI clutter and ensuring only relevant options are displayed.
2026-07-22 20:41:24 +02:00
the-e 0d64f7f237 Add load-variant render pass support for Vulkan render targets
Introduce load-variant render passes to Vulkan textures, enabling content preservation during mid-frame readbacks. Changes include creating `renderPassLoad`, flushing command buffers for readbacks, and resuming rendering into targets with `loadOp=eLoad` to avoid clearing previously rendered content.
2026-07-22 19:57:10 +02:00
the-e 334682c44d Add depth/stencil support to Vulkan render targets
This commit introduces optional depth/stencil attachments for Vulkan render targets, enabling z-testing and addressing earlier limitations where depth-tested geometry rendered in submission order without depth attachments. Changes include resource allocation, attachment handling, and layout transitions.
2026-07-22 19:18:01 +02:00
the-e 52fd215b3f Include cmdline.h in voicerec.cpp for command-line argument handling 2026-07-21 19:57:54 +02:00
b26b9cf743 Add Vulkan rendering backend, with HDR10 output and raytraced shadows (#7554)
* Shadow overhaul round 2: PCSS, dynamic cascades, cockpit/instanced shadows

Squashed snapshot of lafiel/shadow_overhaul_2's continuation work
(d3922aa87..010f9d2d9), which has no separate upstream PR of its own.

* Add Vulkan rendering backend

Squashed snapshot of the Vulkan backend as vendored into this branch
(ce2d1e85f..6ce539463, authored by Mara van der Laan with build/CI
fixes by Taylor Richards). This work has its own upstream PR #7553
(notimaginative:vulkan-pr-new) and is not otherwise original to true-hdr.

* Add true HDR output, RT shadows, and PCSS shadows for Vulkan

Squashed snapshot of true-hdr's own integration work: true HDR
framebuffer output, wiring the shadow overhaul into the Vulkan
backend (raytraced + cascaded shadow maps), logging refactors, log
filter UI, and CI/build fixes.

* refactor: update Vulkan logging calls to use `nprintf` for scoped logging

* fix: correct shadow cascade count in Vulkan logging calls

* fix: fall back to PATH-resolved ccache when CCACHE_PATH is stale

CI hardcodes /usr/local/bin/ccache, but macOS runners on Apple Silicon
hosts install Homebrew (and ccache) under /opt/homebrew instead,
causing all four Mac configs to fail with "No such file or directory".

* Fix vulkan texture readback to correctly handle transparent pipelines

* Put the pixel swizzles into a util file

* OOB safety check

* Fix fog handling

* Fix MSAA in Vulkan

* fix: enable SMAA for vulkan

* adapt the post-processing AA shaders to hdr

* fix clang-tidy warnings: concatenate nested namespaces, static methods

pixel_swizzle.{h,cpp}: collapse `namespace graphics { namespace util {`
into `namespace graphics::util {` (modernize-concat-nested-namespaces).

VulkanState.h/VulkanDraw.h: getClearColor()/setClearColor() only touch
gr_screen and other globals, no instance state, so make them static
(readability-convert-member-functions-to-static) and drop the
top-level const on getClearColor()'s return type
(readability-const-return-type).

* fix clang-tidy warning

* Extend raytraced shadows to all directional lights

RT shadows previously only shadowed the first directional light in the
scene, even though multi-sun missions push more than one directional
light into the engine. The TLAS raytraced shadows query against is
already light-agnostic, so this extends both the deferred lighting
pass and the forward MODEL shader to shadow every directional light
(capped by a new Max Raytraced Shadow Lights option, configurable via
the in-game Options menu or the Lab's Scene rendering options).

Cascaded shadow maps are untouched: they're built for a single light
only, so the deferred pass still limits itself to one shadowed
directional light whenever CSM (not raytracing) is the active method.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_016DA6JHJ3twz2oHGQcZ1Udc

* refactor: improve shader flag handling and render target finalization in Vulkan backend

- Consolidate shader flag setup logic in VulkanPostProcessingLighting to simplify configuration.
- Fix dead field usage in VulkanDraw by ensuring correct image view selection for environment maps.
- Add mip chain regeneration in VulkanRenderer::endRenderTarget to ensure correct mip levels for cubemaps.

* fix: ensure correct mip chain initialization in cubemap rendering

- Add mip chain generation to VulkanDraw for cubemaps with multiple mip levels.
- Fix potential issue with uninitialized mip levels above level 0 in deferred-f.sdr sampling paths.

* fix: don't crash on startup when environment locale is unavailable

std::locale("") pulls in the process's environment locale categories
(LC_CTYPE, LC_MONETARY, LC_PAPER, etc.), and throws std::runtime_error
if any of them names a locale not installed on the host (e.g.
mismatched regional-format overrides). Since SCP_default_locale is
constructed during static initialization, before main() and before any
of our own exception handling exists, an uncaught throw here aborted
the whole process before the game even started. Fall back to the
classic "C" locale instead, which is sufficient since this locale is
only ever used for ASCII case-folding (SCP_toupper/tolower/isdigit).

Co-Authored-By: Claude Sonnet 5 <[email protected]>

* `feat: add raytraced shadows for local lights and optimize TLAS management`

* Make the Commandline authoritative for -res and -vulkan / -opengl

* address BMagnu's comments on the original PR

* update prebuilt version hash to 62c89ef6

* refactor: standardize graphics API handling and document Vulkan limitations in qtFRED

- Updated `AboutDialogModel.cpp` to use `GraphicsAPI` enum for better clarity.
- Ensured qtFRED falls back to OpenGL when Vulkan is requested.
- Added detailed documentation in `qtfred/README.md` regarding Vulkan backend limitations and requirements.

* chore: include cmdline library in main and mission management modules

* docs: add known issue for blank render viewport under Wayland in README.md

* fix CI issues

* chore: add `GR_DEBUG_SCOPE` markers across Vulkan post-processing and rendering paths for improved debugging

* feat: improve Vulkan HDR pipeline with separate encode paths for SDR and HDR10

- Added an HDR10-specific output encode pass in `VulkanRenderer` and `VulkanPostProcessor` that applies PQ/BT.2020 transfer.
- Introduced an optimized SDR fallback path with direct blit support for devices that can skip shader draws.
- Updated `m_sceneLdrCompressed` to provide [0,1]-clamped proxies for HDR edge detection.
- Refactored `copyImageToImage` and added `blitImageToImage` to allow format conversions and optimized transfers.
- Replaced `hdr_mode` with explicit HDR10 flags and data structures for clearer state handling.

* refactor: encapsulate SMAA processing and refactor VulkanPostProcessor

- Moved SMAA-specific logic into `VulkanSMAA` class for better separation of concerns.
- Simplified `initSMAA`, `shutdownSMAA`, and `executeSMAA` logic by leveraging `VulkanLDR` and `PostProcessContext` abstractions.
- Improved initialization and cleanup code with clearer resource lifecycle management.
- Updated debug markers and messages to reference `VulkanSMAA`.
- Enhanced flexibility of fullscreen triangle rendering API with additional parameters (`sampleCount`, `bindGlobalSet`).

* Update Vulkan porting credits in AboutDialogModel

* fix CI issues again

* fix: correct Y-flip in viewport setup for Vulkan light volumes

- Adjusted viewport height to negative value to account for G-buffer render pass's negative Y-axis convention.
- Ensured proper alignment of point and tube light volumes with actual light positions.

* feat: add user-adjustable gamma correction to SDR and HDR10 output paths

- Added gamma correction to HDR10 path, applying user settings before PQ/BT.2020 encode.
- Replaced the SDR blit-only path with an encode pass that applies gamma correction, ensuring consistent behavior across devices.
- Refactored VulkanPostProcessor and associated shaders to support gamma slider adjustments for both SDR and HDR output.

* fix: ensure proper uniform and cull mode setup for Vulkan sphere rendering

- Added uniform buffer setup and default material uniforms in `vulkan_draw_sphere`.
- Disabled face culling in material definition for sphere rendering to align behavior with OpenGL.

* Ensure memory flushes after UBO updates and add explicit pipeline barrier for MoltenVK compatibility.

* fix: add clear pass for SMAA edge detection to prevent persistent artifacts

* feat: add Vulkan debug-utils messenger, opt-in sync validation, frame diagnostics

Groundwork for the renderer-review fix series (.agents/plans/
vulkan-renderer-review-fixes.md, Phase 0):

- Register a VK_EXT_debug_utils messenger (preferred) instead of only the
  deprecated VK_EXT_debug_report callback, which is kept as a fallback for
  loaders without debug-utils. The messenger config is also chained into
  instance creation so vkCreateInstance-time messages are captured.
  Validation errors/warnings now go to the main log via mprintf.
- New -gr_sync_validation cmdline flag (implies -gr_debug): chains
  VkValidationFeaturesEXT with synchronization validation into instance
  creation when VK_LAYER_KHRONOS_validation is available. This is the
  regression net for the synchronization fixes in the following commits.
- Frame stats now report descriptor sets/writes allocated per frame and the
  total pipeline count (descriptor-manager counters; DescriptorWriter::flush
  moved out-of-line to report into the manager).

Co-Authored-By: Claude Fable 5 <[email protected]>

* refactor: unify Vulkan render-pass begins, clamp in-pass clears, add per-frame UBO ring

Phase 1 of the renderer-review fix series: shared helpers that the
correctness fixes build on.

- New VulkanRenderer::beginTrackedRenderPass(PassBeginDesc): every render-pass
  begin on the frame command buffer now records vkCmdBeginRenderPass and
  updates the state tracker (pass, color attachment count, sample count,
  render area, viewport) in one place. Converted: setupFrame,
  beginSceneRendering (both branches), resumeSceneRendering,
  endSceneRendering, beginRenderTarget (viewport kept for gr_set_viewport),
  resumeSwapChainPass, plus new resumeScenePassAfterCopy() shared by
  copyEffectTexture/copySceneDepthForParticles and
  rebeginSwapChainPassAfterReadback() shared by both readbackFramebuffer
  exits (~200 lines of duplicated begin/clear/viewport blocks removed).
- The state tracker records the active render area; all four
  vkCmdClearAttachments sites clamp their rects against it and skip empty
  results. Previously gr_screen-sized clear rects could exceed a smaller
  off-screen render target's render area, which is invalid API usage.
- New PerFrameUboRing utility (VulkanPerFrameUbo.h/.cpp): a persistently
  mapped uniform buffer with one slot region per frame in flight and a
  self-flushing alloc(). Used by the next commit to fix the cross-frame
  UBO races.

Deliberate behavior deltas (all safe-direction): the helper always sets
colorAttachmentCount/sampleCount (some sites previously inherited stale
values), and resumeSwapChainPass/resumeSceneRendering now also reset the
standard flipped viewport instead of leaving the previous one.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix: eliminate Vulkan cross-frame UBO/buffer races, make gr_sync honest

Phase 2 of the renderer-review fix series: with two frames in flight, several
host-visible resources were rewritten by the CPU while the previous frame's
GPU work could still be reading them.

- The post-processing scratch UBO is now a PerFrameUboRing (per-frame-in-
  flight slot regions, persistently mapped, self-flushing alloc). All the
  per-pass map/unmap/cursor bookkeeping in bloom/LDR/fog/SMAA is deleted;
  the cursor resets exactly once per frame via the new
  VulkanPostProcessor::beginFrame() hook in setupFrame.
  This also fixes two latent bugs: (a) fog consumed scratch slots mid-scene
  and bloom's later same-frame cursor reset overwrote them before submission
  whenever fog+bloom were both active; (b) volumetric_fog_data (288 bytes)
  overflowed the 256-byte slots - the memcpy spilled into the neighboring
  slot and the shader's bound range ended before the aspect/fov/noise
  fields. Slots are now 512 bytes (static_assert at the fog call site) and
  the per-frame budget is 32 slots.
- The dedicated tonemap, output-encode, and MSAA-resolve UBOs (each a single
  instance rewritten per frame, i.e. racy; the MSAA one also never flushed)
  are deleted entirely - those passes build their structs on the stack and
  allocate from the scratch ring.
- Static-buffer rewrites orphan instead of racing: getVkBuffer() stamps a
  last-used frame number, and a full-content updateBufferData() on a Static
  buffer used within the last MAX_FRAMES_IN_FLIGHT frames defers the old
  VkBuffer to the deletion queue and writes a fresh one. Offset writes
  (GPU-heap appends to fresh regions) and PersistentMapping buffers (the
  engine holds their mapped pointer and syncs via gr_sync) are exempt.
- gr_sync_wait now honors its contract: VulkanRenderFrame::waitForFinish
  takes a timeout and reports expiry without consuming the fence;
  VulkanRenderer::waitForFrame returns false for fences taken during the
  still-recording frame (previously it waited on a stale or idle slot and
  reported success) and resolves the frame->slot mapping correctly. This
  makes UniformBufferManager's segment-fence throttling actually protective
  on Vulkan for the first time.

Co-Authored-By: Claude Fable 5 <[email protected]>

* Refactor framebuffer and target lifecycle: centralized creation/resizing logic, improved resource management across Vulkan post-processing subsystems.

* Improve Vulkan cross-frame sync with explicit access masks and validation updates

- Unified Vulkan validation flag handling in setup, separating engine debug output from synchronization validation.
- Specified access masks and stage flags to address cross-frame WRITE_AFTER_WRITE vulnerabilities, notably in G-buffer, post-processing, and MSAA resolve paths.
- Adjusted subpass dependencies and image layout transitions to prevent read-after-write and write-after-write hazards, detected using `-gr_sync_validation`.
- Fixed uniform buffer and barrier transitions to ensure proper ordering in render passes across frames.

* Refactor Vulkan render-pass dependencies and sync stages for clarity and future testing

- Clarified dependency logic for cross-pass and cross-frame synchronization, ensuring explicit stage and access flag comments match observed behavior.
- Adjusted subpass dependencies to decouple render-pass compatibility definitions from dependency assumptions.
- Highlighted MoltenVK-specific issues and retained workarounds with notes for re-testing on macOS hardware.
- Updated synchronization barriers and validation notes to address historical inconsistencies across platforms.

* Remove transfer queue support; consolidate all operations into the graphics queue

- Removed transfer queue handling, simplifying buffer and queue logic to use the graphics queue for all transfer operations.
- Updated buffer sharing modes and removed related code paths and parameters for transfer queue families.
- Introduced exclusive buffer access, noting async transfer and queue ownership transfers are future work.
- Limited enabled device features to only those actively used by the renderer, reducing unnecessary feature requests (e.g., robustBufferAccess).

* Refactor frame advancement and descriptor management in VulkanRenderer

- Removed `endFrame()` from `VulkanDescriptorManager`, replacing it with `setCurrentFrame(frameIndex)` for explicit frame synchronization.
- Centralized frame index advancement within `VulkanRenderer` to ensure consistency across components.
- Invalidated cached descriptor set bindings at render-pass boundaries to handle raw recorder staleness correctly.
- Optimized pipeline descriptor rebind logic by removing redundant clears during pipeline changes.

* Refactor `PipelineConfig::hash` and Global descriptor set management for improved hashing and memoization efficiency

- Replaced inefficient shift-based hashing in `PipelineConfig::hash` with a robust `hashCombine` strategy to minimize bucket collisions.
- Introduced `maskBits` helper to streamline bitmask creation for boolean fields.
- Implemented memoization for Global (Set 0) descriptor sets, reducing redundant rebuilds across frames and improving performance.
- Added dirty state tracking (`m_globalSetDirty`) and invalidation logic for Global set updates following relevant input changes (e.g., TLAS or UBO modifications).

* Refactor Vulkan post-processing output logic: extracted shared `encodeToSwapChainPass` method to streamline HDR and SDR output paths.

* Optimize Vulkan descriptor set management with per-frame memoization

- Added memoization for Material (Set 1) and PerDraw (Set 2) descriptor sets to reuse cached sets across frames if inputs remain unchanged.
- Implemented precise input tracking for Material and PerDraw descriptor sets to detect and rebuild only when necessary.
- Reduced redundant Vulkan descriptor allocations and writes, improving performance on repeated or batched draw calls.

* Fix Vulkan access masks for G-buffer and scene pass transitions

- Added `eColorAttachmentRead` to access masks in multiple barriers to ensure proper synchronization for load operations (e.g., `loadOp=eLoad`) across render passes.
- Prevented `READ_AFTER_WRITE` synchronization validation issues in deferred and multi-pass rendering scenarios.
- Updated comments to clarify the reasoning behind the access mask changes and load dependencies.

* Refactor Vulkan resource management and indexed draw logic

- Consolidated destruction queue methods in `VulkanDeletionQueue` using a shared `queueHandle` template to reduce redundancy.
- Introduced `ModelDrawParams` structure and `computeModelDrawParams` function to unify indexed draw parameters for models and shadows.
- Simplified draw logic by eliminating repeated calculation of indexed draw parameters and improving code reuse.

* Add `releaseAnimationSlotRef` for ref-count handling of shared animation texture arrays

- Introduced `releaseAnimationSlotRef` to manage reference counting for shared animation texture-array slots, preventing premature destruction of shared resources.
- Updated `flushTextures` and related methods to integrate `releaseAnimationSlotRef` for shared slot cleanup.
- Refactored staging buffer creation into `createStagingBuffer` for 3D texture uploads and shared path consistency.
- Enhanced texture upload logic with improved tracking and logging for re-upload cases, aiding preloading gap analysis.
- Added instrumentation for on-demand mid-frame texture uploads in `FrameStats`.

* Refactor Vulkan resource and texture management, extend debug logging

- Updated smart pointer usage for consistency across Vulkan resource managers (`std::make_unique`).
- Removed redundant `cubeImageView` member and related cleanup logic; unified sampling view management.
- Added per-instance debug log counters (avoiding static state) for Vulkan texture uploads and bindings, improving visibility during initialization and run-time.
- Optimized `VulkanRenderer` property/feature getters by caching physical device properties and features during device creation.
- Improved memory region flushing logic for out-of-date offsets, aligning with Vulkan Memory Allocator behavior.
- Refactored render pass state tracking to reapply dynamic state reliably after mid-frame render passes.
- Enhanced validation and error handling for mismatched update texture formats.

* fix CI build warning

* Fix on-demand YUV texture locking and set alpha uniform for movie rendering in Vulkan

- Corrected bitmap lock type from `BMP_TEX_OTHER` to `BMP_AABITMAP` for YUV textures during on-demand loading.
- Updated movie rendering to bind alpha from the `MovieData` UBO (set 2, binding 4) for Vulkan, aligning behavior with OpenGL implementation.

* revert inadvertent changes introduced by a squash commit

* address ci issues

* remove wip stuff from code comments that make no sense to people who aren't me

* Remove unused LD_LIBRARY_PATH export and fix shader shadow map sampling.

* Refactor batched rendering uniform setup in Vulkan

- Removed unused fields from `genericData` uniform block, simplifying shader definitions.
- Updated Vulkan material uniform handling to align with OpenGL's batched rendering logic.
- Introduced `batched_data` struct for streamlined UBO updates, improving maintainability and clarity.

* Add `-hdr` command-line option for HDR nits configuration

- Introduced `-hdr` parameter to set paper white and peak luminance in nits, overriding in-game HDR settings.
- Added input validation with error feedback for incorrect format.

* Remove unused `MODEL_SDR_FLAG_SHADOW_MAP` macro from shader flags

* clean up unrelated changes

* Invalidate Vulkan state tracker bindings after external command buffer modifications

- Added `invalidateExternalBindings()` to `VulkanStateTracker` to handle stale pipelines, descriptors, and dynamic states caused by external Vulkan commands (e.g., ImGui renders mid-pass).
- Updated ImGui rendering flow to call `invalidateExternalBindings()` post-draw, ensuring consistent pipeline state for subsequent engine renders.
- Adjusted image usage flags to account for `eTransferSrc` in texture readbacks.
- Fixed barrier `dstAccessMask` and pipeline stage flags to ensure proper synchronization for image transitions.

* Add a few more generically useful lines to the log

* Simplify Qt deployment logic and improve handling for system-installed Qt on Linux

* add cmdline headers to make qtFred compile

* use VK_KHR_synchronization2 for sync and barrier purposes

* Simplify and clean up Qt deployment logic in CMake for qtfred

* update get_bitmap_from_texture to match the new API

* Enhance `-hdr` command-line option to force HDR output and support optional nits configuration with improved input validation and overrides.

* Improve Vulkan robustness, add device feature checks, and refine memory/logging.

- Added depth clamping support gated by device feature checks, with fallback where unsupported.
- Improved deferred lighting UBO overflow handling with user-accessible warnings and buffer size adjustments.
- Enhanced Vulkan logging for validation, allocation, and debugging:
  - Automatic logging for descriptor pool exhaustion/fragmentation.
  - Vertex format and resource destruction checks.
  - Notifications for generic layout transitions and volumetric texture uploads.
- Consolidated shader logic to ensure Vulkan and OpenGL parity.

* Remove HDR10 encode shader and consolidate gamma correction logic for SDR and HDR10. Replace `Verify` assertions with `Assert`

* Add braces to conditional in object lighting logic for clarity

* Refine Vulkan memory allocation checks with `Verification` for improved error handling and messaging.

* Refine VulkanBuffer resize logic to preserve contents with CPU-side copy and add safeguards for non-coherent memory scenarios.

* Add detailed comments explaining descriptor array capacity constants in VulkanDescriptorManager

* Gate shadow support on depth clamp feature availability and clarify its necessity with improved comments.

---------

Co-authored-by: BMagnu <[email protected]>
Co-authored-by: Mara van der Laan <[email protected]>
Co-authored-by: Claude <[email protected]>
2026-07-21 16:58:21 +00:00
Goober5000 3e317d9734 Merge pull request #7515 from Goober5000/feature/reorder_ships_wings
add a Reorder Ships and Wings editor to FRED
2026-07-20 23:56:30 -04:00
Goober5000 47d5ccca35 Merge pull request #7588 from Goober5000/cleanup/external_weapons
External weapon model cleanup: consolidate duplicated logic, fix several longstanding bugs
2026-07-20 23:40:35 -04:00
Goober5000andClaude Opus 4.7 175f414c03 add Wings[] slot reassignment utilities for FRED/qtFRED
reassign_wing_slot moves a wing between Wings[] slots, fixing up every
back-reference: Ships[i].wingnum, the Starting/Squadron/TVT_wings caches
(via update_custom_wing_indexes), the FRED-side parallel array
wing_objects, and cur_wing (passed via FredWingSlotConfig so non-FRED
callers can opt out).  swap_wing_slots wraps it as a three-leg swap
through a temporary empty slot.

Also consolidates update_custom_wing_indexes (previously duplicated
verbatim in fred2/management.cpp and qtfred Editor) into common.cpp so
the new utility — and any future caller — has one shared implementation.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
2026-07-20 23:04:56 -04:00
Goober5000andClaude Opus 4.7 74b2776c00 add Ships[] slot reassignment utilities for FRED/qtFRED
reassign_ship_slot moves a ship between Ships[] slots, fixing up every
back-reference: Objects[].instance, Ai_info[].shipnum, Wings[].ship_index[],
Player_start_shipnum, Ship_registry's cached shipnum, and the FRED-side
parallel arrays Fred_alt_names/Fred_callsigns plus cur_ship (passed via
FredShipSlotConfig so non-FRED callers can opt out).  swap_ship_slots
wraps it as a three-leg swap through a temporary empty slot.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
2026-07-20 23:04:56 -04:00
Goober5000andClaude Fable 5 7b241812ed make ship move-correct
Ship's implicit move operations compiled but were semantically broken in
two ways: moving copied the subsys_list sentinel's links verbatim,
leaving the bookend nodes of the intrusive subsystem list pointing at
the old sentinel address; and the raw owning warpin_effect /
warpout_effect pointers were copied without nulling the source, so a
vacated Ships[] slot aliased live WarpEffects that ship::clear() (on
slot reuse) or ship_close() (which walks every slot) would delete out
from under the destination ship.

Fix both at the member level so the compiler-generated moves are
correct by composition:

- Add ship_subsys_sentinel, derived from ship_subsys, whose move
  operations re-link the bookend nodes (handling the null-linked,
  self-referential-empty, and populated source states) and leave the
  moved-from sentinel as an initialized empty list.  Copying is
  deleted.  Public inheritance keeps &ship::subsys_list convertible to
  ship_subsys*, so list_init, GET_FIRST, and every other call site is
  unchanged.

- Convert warpin_effect and warpout_effect to std::unique_ptr.  The
  delete-and-null blocks in ship::clear(), ship_close(), and
  ship_set_warp_effects() collapse into reset(); call sites that borrow
  the pointer into a raw local now use get().

With the members handling themselves, declare ship's special member
functions: defaulted default constructor and moves, deleted copies
(previously implicit via the unique_ptr members, now stated intent).
The moves are deliberately not declared noexcept because members like
SCP_map and std::deque do not have standard-guaranteed nothrow moves;
the computed exception specification is used instead.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-20 23:04:56 -04:00
Goober5000 820048bda8 Merge pull request #7608 from Goober5000/fix/vector_movable_collections
fix move semantics for data loaded from .tbl and .tbm files
2026-07-20 19:15:31 -04:00
Goober5000 cdb11f7357 patch mission format compatibility for new support features (#7624)
Although #7249 added the new support features to `check_for_25_1_data()`, the new fields were still written to the mission file in all formats except retail.  Use a version check when writing the fields too.
2026-07-20 16:51:46 -04:00
Goober5000 b82fa2a996 refactor CJumpNode to use SCP_vector
Jump nodes previously used SCP_list; refactor to use SCP_vector.  Also improve resource handling and life cycle management.

Follow-up to #7431.
2026-07-19 22:25:33 -04:00
Goober5000 69c6ce3b5f Merge pull request #7617 from Goober5000/fix/texture_upload
Exempt user bitmaps from texture detail culling
2026-07-19 01:47:28 -04:00
Goober5000andClaude Fable 5 35312d379c Check texture bind results in the volumetric nebula pass
gr_opengl_tcache_set() leaves the previous binding active when it
fails, so the glTexParameteri calls that follow would modify the filter
state of an unrelated texture.  Only set the parameter when the volume
texture actually bound.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-19 00:12:21 -04:00
Goober5000andClaude Fable 5 61a217c462 Exempt user bitmaps from texture detail culling
At texture detail below maximum, opengl_create_texture() culls texture
dimensions on upload, but user bitmaps are streaming surfaces
(streamed animations, video) whose frames are updated through
gr_update_texture() with the bitmap's own dimensions.  Once culled, the
glTexSubImage3D update exceeds the texture's actual size, so OpenGL
rejects it with GL_INVALID_VALUE and the animation silently freezes on
its first, downsampled frame.  Culling them also saves nothing, since
full-size frame data is streamed every frame regardless.

Also assert in gr_opengl_update_texture() that the update dimensions
match the texture, so any future mismatch of this kind is caught in
debug builds instead of failing silently.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-19 00:12:21 -04:00
wookieejedi 47726f21d0 Fix AI Bug with Strafing (#7619)
* Fix AI Bug with Strafing

Bug:
When a fighter or bomber enters strafe mode attacking a large ship, that large ship may die or depart, which results in the fighter/bomber AI slowing down to 0 and then not moving until another order is issued. This is most apparent in mods that force strafe to be used more via the ai profile flags (such as FotG).

Cause:
This bug is caused by the following. A fighter/bomber whose strafe target is destroyed drops to AIM_NONE (see ai_execute_behavior) with its active_goal still set, so a standing order like attack-any is never re-processed and the ship slows to zero and remains still until another order is issued.

Fix:
If we're chasing or strafing against large ship but have lost our target, we need to clear the active goal to ensure ai_process_mission_orders() re-evaluates our orders next frame. Of course gate this behind a flag.

Tested and update fixes the issue. We are very much hoping this can be a part of a point-release since it is substantially needed for FotG missions and we want to release in the next month or so. Happy to answer any questions or discuss, too!

* target 26.2
2026-07-18 22:44:34 -04:00
Goober5000andClaude Fable 5 6f4825c45e Fix heap overrun in texture readback for the model transparency scan (#7616)
* Fix heap overrun in texture readback for the model transparency scan

gr_opengl_get_bitmap_from_texture() sized its readback buffer from the
texture cache slot dimensions and the bmpman frame count, but
glGetTexImage() returns whatever the bound GL texture actually contains.
When texture detail below maximum culls textures on upload, the two can
disagree, and the readback overruns the buffer (observed as heap
corruption when loading Zeus.pof with Texture Detail: Minimum).  Size
the readback from the dimensions and layer count OpenGL itself reports
for the texture, and pad the staging buffer to 4x4 block granularity in
case a driver writes tiny compressed mips back in whole blocks.

The readback now also allocates the returned buffer and reports the
dimensions of the data it returns, because the second half of the bug
was on the consumer side: bitmap_lookup indexed the readback data by
the bitmap's own dimensions, so with any culling in effect the
transparency scan read mostly uninitialized memory.  bitmap_lookup (and
its cache) now carries the actual readback dimensions, and it skips the
texture cleanly if the readback fails.

Also pairs the cache's vm_malloc allocations with vm_free instead of
free, and no longer ignores a failed tcache_set before reading back.

Co-Authored-By: Claude Fable 5 <[email protected]>

* Harden the transparency-scan texture readback

Return fully opaque from bitmap_lookup::get_channel_alpha() when the
bitmap has no alpha channel, since indexing channel 3 of a 3-channel
buffer reads out of bounds (currently unreachable because the only
caller checks bm_has_alpha_channel() first, but no longer a trap).

Per review, also assert at maximum texture detail, where no culling
occurs on upload, that the readback dimensions OpenGL reports match the
texture cache slot, so any future slot mismatch is caught immediately
in debug builds instead of surfacing as corruption.

Co-Authored-By: Claude Fable 5 <[email protected]>

* Fix inverted dimension check in opengl_export_render_target

The validation rejected the export only if both the width and the
height mismatched the texture cache slot, so a texture wrong in one
dimension passed through into opengl_get_texture, which trusts the
caller-supplied dimensions for its mipmap loop.

Co-Authored-By: Claude Fable 5 <[email protected]>

---------

Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-18 09:50:46 +02:00
wookieejedi 86a4af4fc3 Fix fighter/bomber AI remaining stationary if engines repaired (#7609)
* draft both options

* cleanup

* authors

* whitespace
2026-07-17 20:42:14 -04:00
BMagnu 856e676e79 Add render path to dispatch Particles as Decals (#7507)
* Add path to dispatch particles as decals

* Testing and bugfixing

* Address feedback

* Fix Typo

* Fix obj attachment
2026-07-17 13:38:45 +09:00
BMagnu fcaa9dd998 Allow trail particles to be parented to their spawner (#7528)
* Adapt particle at runtime

* Refactor EffectHosts

* fix issues

* cleanup

* Remove live transitive particles

* paticle hosts now do local correctly

* Fix effecthostparticle local mode

* again

* Set particle host orientation

* I don't like mixed local and global vectors

* agaiiin

* Fix validity check

* parent foo

* Fix bugs, hopefully finally

* refactor

* Flip new table option for intuitiveness

* Fix support for GCC9 due to issues with LWG3052

* Address feedback
2026-07-15 15:10:15 +09:00
Goober5000andClaude Fable 5 9bebf2592f give the "Set as Player Ship" button exclusive semantics in both editors (#7605)
In single-player missions, the "Set as Player Ship" button is supposed to make
the selected ship the one and only player start.  FRED did this correctly, but
qtFRED routed the button through the same setPlayer() toggle used by the
multiplayer "Player Ship" checkbox, which only promoted the selected ship and
never demoted the previous player start.  Since the checkbox is disabled in
single player, there was no way to demote the old start, so single-player
missions could accumulate multiple player starts.

Consolidate the exclusive logic into a shared helper,
set_single_player_start() in missioneditor/common.cpp, and call it from both
FRED's OnSetAsPlayerShip() and a new qtFRED model method,
makeSolePlayerStart(), which the button now uses.  This also avoids
setPlayer()'s early return on stale dialog state, which could cause the button
to silently do nothing.

Follow-up to #7600.

Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-14 20:05:13 -04:00
Goober5000andClaude Fable 5 da24cdae38 store glowpoint override indices instead of pointers
glowpoint_bank_override_map stored raw pointers into the growable global glowpoint_bank_overrides vector.  Store indices instead, which survive vector reallocation.  The readers also lose a redundant second map lookup (they previously called find() and then operator[] on the same key), and prop_info's parallel map gets the same conversion.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-14 13:23:37 -04:00
Goober5000andClaude Fable 5 473630ed85 make ship_info's subsystems a unique_ptr and default the moves
The hand-written ~350-line memberwise move existed only to manage the
one raw owning pointer, and silently left any member it didn't mention
uninitialized in the destination.  With subsystems as a unique_ptr, the
defaulted moves and destructor are correct by composition.  Copies
become explicitly deleted (use clone()).  n_subsystems stays a plain
int because it is passed to varargs functions.  The moves are not
declared noexcept because libstdc++ computes a potentially-throwing
implicit specification; NOLINT suppresses clang-tidy accordingly.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-14 13:23:37 -04:00