Skip to content

depth_write_offset is ignored in apply_pipeline function #597

Open

Description

@yashchvn

The depth_write_offset field in PipelineParams is ignored:

fn apply_pipeline(&mut self, pipeline: &Pipeline) {
        self.cache.cur_pipeline = Some(*pipeline);

        {
            let pipeline = &self.pipelines[pipeline.0];
            let shader = &self.shaders[pipeline.shader.0];
            unsafe {
                glUseProgram(shader.program);
            }

            unsafe {
                glEnable(GL_SCISSOR_TEST);
            }

            if pipeline.params.depth_write {
                unsafe {
                    glEnable(GL_DEPTH_TEST);
                    glDepthFunc(pipeline.params.depth_test.into())
                }
            } else {
                unsafe {
                    glDisable(GL_DEPTH_TEST);
                }
            }

            match pipeline.params.front_face_order {
                FrontFaceOrder::Clockwise => unsafe {
                    glFrontFace(GL_CW);
                },
                FrontFaceOrder::CounterClockwise => unsafe {
                    glFrontFace(GL_CCW);
                },
            }
        }

        self.set_cull_face(self.pipelines[pipeline.0].params.cull_face);
        self.set_blend(
            self.pipelines[pipeline.0].params.color_blend,
            self.pipelines[pipeline.0].params.alpha_blend,
        );

        self.set_stencil(self.pipelines[pipeline.0].params.stencil_test);
        self.set_color_write(self.pipelines[pipeline.0].params.color_write);
    }

Furthermore, there is no documentation for this field.

Activity

  1. McGittyHub commented on Feb 26, 2026

    @McGittyHub

    Depth testing is also ignored if depth writing is off, this is not ideal for particles.

  2. ricande commented on Oct 15, 2026

    @ricande

    Confirmed with unmodified miniquad 0.4.11 on Apple M2: reproduced in 3/3 separate process runs, with all four control cases passing each time. Since the original report contains an implementation excerpt but no runnable reproduction, the complete test program is included below.

    Environment: MacBook Air / Apple M2, macOS 26.5.2 (25F84), native arm64 release build, rustc 1.99.1. Explicitly selected miniquad's OpenGL backend. Driver: Apple M2, 4.1 Metal - 90.5. Miniquad's Metal backend was not tested.

    Relation to #670: both concern GlContext::apply_pipeline, but this test always uses depth_write=true and asserts that GL_DEPTH_TEST stays enabled. It isolates the ignored offset from the separate depth-test disabling bug.

    Test and results

    The test uses a 64×64 RGBA8 render target with a depth attachment. It draws an opaque green quad, then an opaque red quad with identical geometry at the same depth. It checks both signs of offset using pixel readback and queries the actual GL offset state. Each case starts with cleared buffers and reset offset state.

    Red quad configuration Expected center color Actual center color GL offset enabled / factor / units
    Less, no offset Green Green 0 / 0 / 0
    Less, API offset (-4,-4) Red Green — failure 0 / 0 / 0
    Less, direct GL offset (-4,-4) Red Red 1 / -4 / -4
    LessOrEqual, no offset Red Red 0 / 0 / 0
    LessOrEqual, API offset (4,4) Green Red — failure 0 / 0 / 0
    LessOrEqual, direct GL offset (4,4) Green Green 1 / 4 / 4

    All three runs produced this output and exited with code 1:

    GL renderer: Apple M2
    GL version: 4.1 Metal - 90.5
    less_no_offset: offset_enabled=0, factor=0, units=0, depth_test=1, rgba=[0, 255, 0, 255]
    less_api_negative: offset_enabled=0, factor=0, units=0, depth_test=1, rgba=[0, 255, 0, 255]
    less_manual_negative: offset_enabled=1, factor=-4, units=-4, depth_test=1, rgba=[255, 0, 0, 255]
    lequal_no_offset: offset_enabled=0, factor=0, units=0, depth_test=1, rgba=[255, 0, 0, 255]
    lequal_api_positive: offset_enabled=0, factor=0, units=0, depth_test=1, rgba=[255, 0, 0, 255]
    lequal_manual_positive: offset_enabled=1, factor=4, units=4, depth_test=1, rgba=[0, 255, 0, 255]
    RESULT: issue 597 reproduced; both API offsets ignored; all four controls pass
    

    No GL errors or GPU-memory errors were reported. The direct GL controls demonstrate that the driver supports the requested offset. The flat geometry exercises the constant offset term; slope-dependent factor behavior is not independently tested.

    Reproduce

    Create a standalone Cargo project with the following two files, then run:

    cargo build --release
    ./target/release/miniquad-offset-597

    Run the executable three times to repeat this batch. It opens a small window and exits after the six cases. Exit code 1 intentionally means the bug was reproduced with passing controls; 0 means both API offsets work. Unexpected pixels, failed controls, or GL errors cause a separate assertion/panic. A local graphical session is required.

    Cargo.toml:

    [package]
    name = "miniquad-offset-597"
    version = "0.1.0"
    edition = "2021"
    publish = false
    
    [dependencies]
    miniquad = "=0.4.11"
    Complete src/main.rs (the exact test source used)
    use miniquad::{native::gl::*, *};
    
    struct Stage {
        context: Box<dyn RenderingBackend>,
        bindings: Bindings,
        shader: ShaderId,
        pass: RenderPass,
    }
    
    impl Stage {
        fn new() -> Self {
            let mut context = window::new_rendering_backend();
            unsafe {
                for (label, parameter) in [("renderer", 0x1F01), ("version", GL_VERSION)] {
                    let value = std::ffi::CStr::from_ptr(glGetString(parameter).cast());
                    println!("GL {label}: {}", value.to_string_lossy());
                }
            }
            let shader = context.new_shader(
                ShaderSource::Glsl {
                    vertex: "#version 100\nattribute vec2 position; void main() { gl_Position = vec4(position, 0.0, 1.0); }",
                    fragment: "#version 100\nprecision mediump float; uniform vec4 tint; void main() { gl_FragColor = tint; }",
                },
                ShaderMeta {
                    images: vec![],
                    uniforms: UniformBlockLayout {
                        uniforms: vec![UniformDesc::new("tint", UniformType::Float4)],
                    },
                },
            ).unwrap();
            let vertices: [[f32; 2]; 4] = [
                [-0.8, -0.8], [0.8, -0.8], [0.8, 0.8], [-0.8, 0.8],
            ];
            let indices: [u16; 6] = [0, 1, 2, 0, 2, 3];
            let vertex_buffer = context.new_buffer(
                BufferType::VertexBuffer,
                BufferUsage::Immutable,
                BufferSource::slice(&vertices),
            );
            let index_buffer = context.new_buffer(
                BufferType::IndexBuffer,
                BufferUsage::Immutable,
                BufferSource::slice(&indices),
            );
            let bindings = Bindings {
                vertex_buffers: vec![vertex_buffer],
                index_buffer,
                images: vec![],
            };
            let color = context.new_render_texture(TextureParams {
                width: 64,
                height: 64,
                format: TextureFormat::RGBA8,
                ..Default::default()
            });
            let depth = context.new_render_texture(TextureParams {
                width: 64,
                height: 64,
                format: TextureFormat::Depth,
                ..Default::default()
            });
            let pass = context.new_render_pass(color, Some(depth));
            Self { context, bindings, shader, pass }
        }
    
        fn pipeline(&mut self, comparison: Comparison, offset: Option<(f32, f32)>) -> Pipeline {
            self.context.new_pipeline(
                &[BufferLayout::default()],
                &[VertexAttribute::new("position", VertexFormat::Float2)],
                self.shader,
                PipelineParams {
                    depth_test: comparison,
                    depth_write: true,
                    depth_write_offset: offset,
                    ..Default::default()
                },
            )
        }
    
        fn sample(
            &mut self,
            label: &str,
            comparison: Comparison,
            api_offset: Option<(f32, f32)>,
            manual_offset: Option<(f32, f32)>,
        ) -> [u8; 4] {
            let base = self.pipeline(Comparison::Less, None);
            let overlay = self.pipeline(comparison, api_offset);
            unsafe {
                glDisable(GL_POLYGON_OFFSET_FILL);
                glPolygonOffset(0.0, 0.0);
                glDepthMask(GL_TRUE as u8);
            }
            self.context.begin_pass(Some(self.pass), PassAction::clear_color(0.0, 0.0, 0.0, 1.0));
            self.context.apply_pipeline(&base);
            self.context.apply_bindings(&self.bindings);
            self.context.apply_uniforms(UniformsSource::table(&[0.0f32, 1.0, 0.0, 1.0]));
            self.context.draw(0, 6, 1);
            self.context.apply_pipeline(&overlay);
            if let Some((factor, units)) = manual_offset {
                unsafe {
                    glEnable(GL_POLYGON_OFFSET_FILL);
                    glPolygonOffset(factor, units);
                }
            }
            let mut enabled = 0;
            let mut factor = 0;
            let mut units = 0;
            let mut depth_test = 0;
            unsafe {
                glGetIntegerv(GL_POLYGON_OFFSET_FILL, &mut enabled);
                glGetIntegerv(0x8038, &mut factor);
                glGetIntegerv(0x2A00, &mut units);
                glGetIntegerv(GL_DEPTH_TEST, &mut depth_test);
            }
            assert_eq!(depth_test, 1, "depth test must remain enabled in {label}");
            self.context.apply_uniforms(UniformsSource::table(&[1.0f32, 0.0, 0.0, 1.0]));
            self.context.draw(0, 6, 1);
            let mut pixel = [0u8; 4];
            unsafe {
                glReadPixels(31, 32, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, pixel.as_mut_ptr().cast());
                assert_eq!(glGetError(), GL_NO_ERROR, "GL error in {label}");
                glDisable(GL_POLYGON_OFFSET_FILL);
                glPolygonOffset(0.0, 0.0);
            }
            self.context.end_render_pass();
            self.context.delete_pipeline(base);
            self.context.delete_pipeline(overlay);
            println!("{label}: offset_enabled={enabled}, factor={factor}, units={units}, depth_test={depth_test}, rgba={pixel:?}");
            pixel
        }
    }
    
    impl EventHandler for Stage {
        fn update(&mut self) {}
    
        fn draw(&mut self) {
            let less_none = self.sample("less_no_offset", Comparison::Less, None, None);
            let less_api = self.sample("less_api_negative", Comparison::Less, Some((-4.0, -4.0)), None);
            let less_manual = self.sample("less_manual_negative", Comparison::Less, None, Some((-4.0, -4.0)));
            let equal_none = self.sample("lequal_no_offset", Comparison::LessOrEqual, None, None);
            let equal_api = self.sample("lequal_api_positive", Comparison::LessOrEqual, Some((4.0, 4.0)), None);
            let equal_manual = self.sample("lequal_manual_positive", Comparison::LessOrEqual, None, Some((4.0, 4.0)));
            let green = [0, 255, 0, 255];
            let red = [255, 0, 0, 255];
            assert_eq!(less_none, green, "equal depth must fail Less");
            assert_eq!(equal_none, red, "equal depth must pass LessOrEqual");
            assert_eq!(less_manual, red, "manual negative offset must bring overlay forward");
            assert_eq!(equal_manual, green, "manual positive offset must push overlay back");
            if less_api == green && equal_api == red {
                println!("RESULT: issue 597 reproduced; both API offsets ignored; all four controls pass");
                std::process::exit(1);
            }
            assert_eq!(less_api, red, "unexpected negative API offset result");
            assert_eq!(equal_api, green, "unexpected positive API offset result");
            println!("RESULT: issue 597 not reproduced; both API offsets work");
            std::process::exit(0);
        }
    }
    
    fn main() {
        let mut configuration = conf::Conf {
            window_title: "Miniquad issue 597 verification".to_owned(),
            window_width: 160,
            window_height: 160,
            ..Default::default()
        };
        configuration.platform.apple_gfx_api = conf::AppleGfxApi::OpenGl;
        miniquad::start(configuration, || Box::new(Stage::new()));
    }

    Source inspection also found no handling of depth_write_offset / glPolygonOffset in the OpenGL backend on master at 39c928f. Runtime tests were against the published 0.4.11 crate, not master. No library fix was applied, and no other platform or miniquad backend was tested.

  3. ricande commented on Oct 15, 2026

    @ricande

    Follow-up: I have now runtime-tested master at 39c928f, not just the published crate, and prepared a shared proposed fix for #670 and #597.

    Reproduction package, instructions and full logs · proposed patch · design and compatibility rationale

    On Apple M2 / macOS 26.5.2 / native arm64 OpenGL:

    • Both original reproductions fail as expected without the patch and pass with it, in 3/3 runs.
    • The combined suite has 37 failures / 115 checks on unmodified master and 0 / 115 with the patch, in each run. It includes depth comparisons, Always-with-writes, clear/restore, offset signs/slope/transitions and reapplying the same pipeline after external GL changes.
    • A bounded Macroquad 0.4.16 integration test passes 70/70 checks on both versions, in 3/3 runs.

    Real browser tests against the pinned upstream builds also completed: 32 failures / 107 checks without the Rust fix versus 0 / 107 with it, for both WebGL1 and WebGL2. Both variants use the updated JavaScript bridge to isolate Rust behavior. Caveat: WebGL2 uses a test-created depth renderbuffer to avoid a separate incomplete-framebuffer issue; this does not validate the ordinary WebGL2 depth-texture path. The harness also supplies a real glGetError import.

    The proposal separates depth testing/writing, applies or disables polygon offset, and preserves the actual write mask across depth-clear. It deliberately does not cache these states: direct GL changes could otherwise leave a stale cache. JavaScript bundles need the included glDepthMask/glPolygonOffset imports. Other OS/drivers, Miniquad Metal and large games remain unverified; no FPS improvement is claimed.

    This is supporting evidence and a proposed patch, not an upstream-merged fix. Feedback on the approach and the documented compatibility changes would be welcome.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions