Skip to content

feat: add a texture fill mode that doesn't stretch the texture#56

Merged
antouhou merged 2 commits into
mainfrom
feat-textures
Apr 27, 2026
Merged

feat: add a texture fill mode that doesn't stretch the texture#56
antouhou merged 2 commits into
mainfrom
feat-textures

Conversation

@antouhou
Copy link
Copy Markdown
Owner

@antouhou antouhou commented Apr 27, 2026

Summary by CodeRabbit

Release Notes

  • New Features
    • Added OriginalSize texture fitting mode that preserves original texture dimensions instead of stretching to fill shapes.
    • Introduced enhanced texture configuration options for both background and foreground layers with per-layer fit mode control.
    • Texture rendering now correctly scales with shape transforms while maintaining proper clipping behavior outside scaled bounds.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 27, 2026

Warning

Rate limit exceeded

@antouhou has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 48 minutes and 4 seconds before requesting another review.

To keep reviews running without waiting, you can enable usage-based add-on for your organization. This allows additional reviews beyond the hourly cap. Account admins can enable it under billing.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 1aeb620d-c3da-4d7f-95e0-c65233eacc59

📥 Commits

Reviewing files that changed from the base of the PR and between a292a64 and 6c9e5c0.

📒 Files selected for processing (2)
  • src/shaders/shader.wgsl
  • src/shape.rs
📝 Walkthrough

Walkthrough

The PR adds texture fitting modes (OriginalSize and Stretch) to shape rendering. It calculates per-layer UV scaling factors based on texture dimensions and mapping size, threads them through the rendering pipeline via new instance data structures, updates shaders to apply per-layer UV coordinates, and adds regression tests to verify the behavior.

Changes

Cohort / File(s) Summary
Core Texture Fitting Types
src/shape.rs
Introduces ShapeTextureFitMode enum (Stretch, OriginalSize) and ShapeTextureOptions struct. Replaces background_texture_id/foreground_texture_id fields with richer ShapeTextureOptions in ShapeDrawCommandOptions. Adds texture_mapping_size to CachedShapeHandle, computed from rectangle bounds or tessellated vertex AABB. Includes builder methods for per-layer fit mode configuration.
Renderer UV Scale Computation
src/renderer/draw_queue.rs
Calculates per-layer texture UV scaling factors derived from texture_mapping_size, renderer scale factor, and actual texture dimensions when fit mode is OriginalSize. Passes computed scales to append_instance_data via new InstanceTextureData struct instead of raw texture IDs.
Instance Data Threading
src/renderer/preparation.rs, src/vertex.rs
Introduces InstanceTextureData bundle containing texture IDs and per-layer UV scales. Updates append_instance_data to accept InstanceTextureData and populate new texture_uv_scale_layer0/texture_uv_scale_layer1 fields in InstanceMetadata. Adds vertex buffer attributes for UV scales at shader locations 11 and 12 with Float32x2 format.
Shader Per-Layer UV Application
src/shaders/shader.wgsl
Adds per-instance UV scale inputs and produces separate layer0_tex_coords and layer1_tex_coords varyings in vertex shaders. Updates fragment shaders to sample textures for each active layer using its corresponding scaled UVs. Renumbers varying locations to accommodate per-layer UV data.
Support Infrastructure
src/texture_manager.rs
Adds texture_dimensions() method to query stored texture width/height for a given texture ID.
Testing and Scene Setup
src/renderer/traversal.rs, tests/visual_regression.rs, grafo-test-scenes/src/scene.rs
Updates test helper to initialize CachedShapeHandle with texture_mapping_size. Refactors visual regression test setup by extracting create_headless_renderer_with_size_and_scale(). Adds new regression test validating OriginalSize texture fitting in physical pixel space. Introduces two new texture-focused regression tiles verifying foreground texture non-stretch and scaling/clipping behavior.

Sequence Diagram

sequenceDiagram
    actor Shape as Shape Definition
    participant RenderPass as Render Pipeline
    participant UVCalc as UV Scale Calculator
    participant InstanceData as Instance Data
    participant Shader as GPU Shader
    
    Shape->>RenderPass: Configure texture with fit mode (OriginalSize)
    RenderPass->>UVCalc: Request UV scales for layer
    UVCalc->>UVCalc: Calculate scale = texture_size / mapping_size
    UVCalc-->>RenderPass: Return per-layer UV scales [x, y]
    RenderPass->>InstanceData: Create InstanceTextureData<br/>(texture_ids, uv_scales)
    RenderPass->>Shader: Pass InstanceMetadata with<br/>texture_uv_scale_layer0/1
    Shader->>Shader: Compute layer0_tex_coords = uv \\* scale_layer0<br/>Compute layer1_tex_coords = uv \\* scale_layer1
    Shader->>Shader: Sample textures at scaled UVs
    Shader-->>RenderPass: Output pixels with<br/>correctly fitted textures
Loading

Estimated Code Review Effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly Related PRs

Poem

🐰 Textures now stretch or stay true to size,
Per-layer UV scales beneath renderer skies,
The shader reads pixels with perfect precision,
Each fit mode dancing with pixel-wise vision! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 74.36% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main feature addition: introducing a non-stretching texture fill mode (OriginalSize) alongside the existing stretch mode.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat-textures

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (3)
tests/visual_regression.rs (1)

16-31: Make pixel assertions size-aware instead of open-coding the non-default path.

Now that the renderer helper accepts arbitrary physical_size, assert_pixels_match() being hard-wired to CANVAS_WIDTH/CANVAS_HEIGHT forced this test to duplicate the failure formatting. Passing (width, height) into the helper keeps custom-size regressions on the same assertion path and avoids future drift.

♻️ Suggested refactor
-fn assert_pixels_match(pixel_buffer: &[u8], expectations: &[grafo_test_scenes::PixelExpectation]) {
-    let failures = check_pixels(pixel_buffer, CANVAS_WIDTH, CANVAS_HEIGHT, expectations);
+fn assert_pixels_match(
+    pixel_buffer: &[u8],
+    size: (u32, u32),
+    expectations: &[grafo_test_scenes::PixelExpectation],
+) {
+    let failures = check_pixels(pixel_buffer, size.0, size.1, expectations);
     if !failures.is_empty() {
         let message = format!(
             "{} pixel expectation(s) failed:\n{}",
@@
-    assert_pixels_match(&pixel_buffer, &expectations);
+    assert_pixels_match(&pixel_buffer, (CANVAS_WIDTH, CANVAS_HEIGHT), &expectations);
@@
-    let failures = check_pixels(
-        &pixel_buffer,
-        physical_size.0,
-        physical_size.1,
-        &expectations,
-    );
-    if !failures.is_empty() {
-        let message = format!(
-            "{} pixel expectation(s) failed:\n{}",
-            failures.len(),
-            failures.join("\n"),
-        );
-        panic!("{message}");
-    }
+    assert_pixels_match(&pixel_buffer, physical_size, &expectations);

Also applies to: 122-196

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/visual_regression.rs` around lines 16 - 31, The test duplicates failure
formatting because assert_pixels_match is hard-coded to
CANVAS_WIDTH/CANVAS_HEIGHT instead of using the physical_size passed to
create_headless_renderer_with_size_and_scale; update the test(s) (including the
failure path currently duplicating formatting) to call assert_pixels_match with
the actual (width, height) used for the renderer rather than relying on
CANVAS_WIDTH/CANVAS_HEIGHT, and adjust any helper callsites so
create_headless_renderer_with_size_and_scale and the assertion path share the
same (physical_size) tuple to keep custom-size regressions on the common
assertion logic (references: create_headless_renderer_with_size_and_scale,
assert_pixels_match, CANVAS_WIDTH/CANVAS_HEIGHT).
src/shape.rs (1)

111-139: Extract one shared bounds helper for path UVs and texture_mapping_size.

compute_texture_mapping_size() re-runs the same AABB pass that PathShape::tessellate_into_buffers() already uses to generate tex_coords. These two calculations now define the same mapping contract, so letting them drift will desynchronize OriginalSize scaling from the actual vertex UVs. Please derive both from one helper.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/shape.rs` around lines 111 - 139, compute_texture_mapping_size()
duplicates the AABB pass used in PathShape::tessellate_into_buffers() (which
produces tex_coords) causing potential drift; extract a single helper (e.g.
compute_vertex_bounds or compute_aabb_from_vertices) that takes
&VertexBuffers<CustomVertex, u16> or &[CustomVertex] and returns the computed
bounds or size (min_x,min_y,max_x,max_y or width,height). Replace the AABB loop
in compute_texture_mapping_size() with a call to that helper to derive the size
(clamped with .max(1e-6) as before) and update
PathShape::tessellate_into_buffers() to call the same helper when generating
tex_coords and when computing OriginalSize so both UVs and mapping_size come
from the same bounds.
src/shaders/shader.wgsl (1)

22-24: Optional: pack per-layer UVs into a single vec4 varying.

layer0_tex_coords and layer1_tex_coords each occupy a varying interpolator slot. Packing them as vec4<f32> (xy = layer0, zw = layer1) saves one interpolator per pipeline and keeps the vertex/fragment interfaces a bit tighter, which is helpful given GradientVertexOutput already uses 7 locations. Same applies to texture_uv_scale_layer0/1 on the vertex input — they can be a single vec4 attribute. Purely an optimization; functionally equivalent.

Also applies to: 30-33, 39-46

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/shaders/shader.wgsl` around lines 22 - 24, Pack per-layer UV varyings and
per-layer UV scale vertex inputs into vec4s to save an interpolator: replace
separate varyings layer0_tex_coords and layer1_tex_coords with a single varying
(e.g., layer_tex_coords: vec4<f32> where xy = layer0, zw = layer1) and update
all uses to swizzle (.xy / .zw); likewise replace texture_uv_scale_layer0 and
texture_uv_scale_layer1 with a single attribute (e.g., texture_uv_scale_layers:
vec4<f32>) and update references to use .xy and .zw. Update the
GradientVertexOutput / corresponding vertex input/output structs and any places
that read those symbols so types and swizzles match and remove the now-unused
individual fields.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/shaders/shader.wgsl`:
- Around line 329-331: Remove the dead helper function
texture_coords_are_in_bounds from src/shaders/shader.wgsl: locate the fn
texture_coords_are_in_bounds(tex_coords: vec2<f32>) -> bool { ... } and delete
it entirely (it is unused and bounds checking is handled by ClampToEdge +
transparent padding), and verify no other shader code references this symbol
before committing.

In `@src/shape.rs`:
- Around line 1087-1098: The docstring for the ShapeTextureFitMode::OriginalSize
variant is out of date: it claims sampling outside the original texture uses
clamp-to-edge and recommends a transparent 1px padding, but the implemented
behavior (and tests in grafo-test-scenes and visual_regression) reveals the
underlying fill/background outside the texture footprint. Update the
ShapeTextureFitMode::OriginalSize documentation to state that one texture texel
maps to one physical pixel before transform, translation is ignored while
scale/rotation/perspective apply, and importantly that samples outside the
original texture footprint do not clamp but instead allow the underlying
fill/background to show (remove the padding recommendation and clarify expected
compositing behavior).

---

Nitpick comments:
In `@src/shaders/shader.wgsl`:
- Around line 22-24: Pack per-layer UV varyings and per-layer UV scale vertex
inputs into vec4s to save an interpolator: replace separate varyings
layer0_tex_coords and layer1_tex_coords with a single varying (e.g.,
layer_tex_coords: vec4<f32> where xy = layer0, zw = layer1) and update all uses
to swizzle (.xy / .zw); likewise replace texture_uv_scale_layer0 and
texture_uv_scale_layer1 with a single attribute (e.g., texture_uv_scale_layers:
vec4<f32>) and update references to use .xy and .zw. Update the
GradientVertexOutput / corresponding vertex input/output structs and any places
that read those symbols so types and swizzles match and remove the now-unused
individual fields.

In `@src/shape.rs`:
- Around line 111-139: compute_texture_mapping_size() duplicates the AABB pass
used in PathShape::tessellate_into_buffers() (which produces tex_coords) causing
potential drift; extract a single helper (e.g. compute_vertex_bounds or
compute_aabb_from_vertices) that takes &VertexBuffers<CustomVertex, u16> or
&[CustomVertex] and returns the computed bounds or size (min_x,min_y,max_x,max_y
or width,height). Replace the AABB loop in compute_texture_mapping_size() with a
call to that helper to derive the size (clamped with .max(1e-6) as before) and
update PathShape::tessellate_into_buffers() to call the same helper when
generating tex_coords and when computing OriginalSize so both UVs and
mapping_size come from the same bounds.

In `@tests/visual_regression.rs`:
- Around line 16-31: The test duplicates failure formatting because
assert_pixels_match is hard-coded to CANVAS_WIDTH/CANVAS_HEIGHT instead of using
the physical_size passed to create_headless_renderer_with_size_and_scale; update
the test(s) (including the failure path currently duplicating formatting) to
call assert_pixels_match with the actual (width, height) used for the renderer
rather than relying on CANVAS_WIDTH/CANVAS_HEIGHT, and adjust any helper
callsites so create_headless_renderer_with_size_and_scale and the assertion path
share the same (physical_size) tuple to keep custom-size regressions on the
common assertion logic (references:
create_headless_renderer_with_size_and_scale, assert_pixels_match,
CANVAS_WIDTH/CANVAS_HEIGHT).
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: b521a577-f1b3-4a88-bc3c-4149ed2386da

📥 Commits

Reviewing files that changed from the base of the PR and between c3e16c5 and a292a64.

📒 Files selected for processing (9)
  • grafo-test-scenes/src/scene.rs
  • src/renderer/draw_queue.rs
  • src/renderer/preparation.rs
  • src/renderer/traversal.rs
  • src/shaders/shader.wgsl
  • src/shape.rs
  • src/texture_manager.rs
  • src/vertex.rs
  • tests/visual_regression.rs

Comment thread src/shaders/shader.wgsl Outdated
Comment thread src/shape.rs
@antouhou antouhou merged commit 0d7c38d into main Apr 27, 2026
5 checks passed
@antouhou antouhou deleted the feat-textures branch April 27, 2026 22:50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant