diff --git a/Cargo.lock b/Cargo.lock index 3793afab4..f8d2d87f7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5725,6 +5725,7 @@ name = "xtask" version = "0.24.0" dependencies = [ "proc-macro2", + "quick-xml", "serde", "serde_json", "sha2 0.10.9", diff --git a/assets/locales/pending/fillet-options-plain.json b/assets/locales/pending/fillet-options-plain.json index 6a635f9c4..369f48932 100644 --- a/assets/locales/pending/fillet-options-plain.json +++ b/assets/locales/pending/fillet-options-plain.json @@ -4,12 +4,12 @@ "ui.copy_details_tip": "Copy the full message, to look it up or to report it.", "ui.fillet_error_corner": "The smooth corner could not be built here. Try another Setback, or Tangent corners.", "ui.fillet_error_failed": "This fillet could not be built on these edges. Try another radius, or round fewer edges at once.", - "ui.fillet_error_too_large": "The radius is too large for the faces beside these edges. Try a smaller radius, or set If too large to Largest that fits.", - "ui.fillet_fit": "If too large", - "ui.fillet_fit_exact": "Stop and say so", - "ui.fillet_fit_reduce": "Largest that fits", - "ui.fillet_fit_taper": "Narrow where needed", - "ui.fillet_fit_tip": "When the radius is larger than the faces beside an edge allow: stop with a message, round every edge with the largest radius that fits, or keep the radius and narrow the round only where the faces run out.", + "ui.fillet_error_too_large": "The radius is too large for the faces beside these edges. Try a smaller radius, or set Face limits to Largest radius.", + "ui.fillet_fit": "Face limits", + "ui.fillet_fit_exact": "Exact radius", + "ui.fillet_fit_reduce": "Largest radius", + "ui.fillet_fit_taper": "Narrowed radius", + "ui.fillet_fit_tip": "When the radius is larger than the faces beside an edge allow.\nExact radius: the radius as given, or nothing rounded and a message saying why.\nLargest radius: every edge rounded with the largest radius that fits.\nNarrowed radius: the radius kept, the round narrowed only where the faces run out.", "ui.fillet_options_tip": "Tangent chain: also round the edges that continue smoothly from the picked ones.\nPreview: show the result in the view while you edit.", "ui.fillet_type_choices_tip": "Constant radius: one radius all along the edge.\nChord length: the width across the round stays the same, whatever angle the faces meet at.\nVariable radius: a radius at each end, and more along the edge if you add them.\nCurvature continuous: a section without a kink in reflections where it meets flat faces (G2).\nSpline: the radius along the edge follows control radii you set." }, @@ -18,12 +18,12 @@ "ui.copy_details_tip": "انسخ الرسالة كاملة للبحث عنها أو للإبلاغ عنها.", "ui.fillet_error_corner": "تعذّر بناء الزاوية الناعمة هنا. جرّب مسافة إرجاع أخرى، أو زوايا مماسّة.", "ui.fillet_error_failed": "تعذّر بناء هذا التقويس على هذه الحواف. جرّب نصف قطر آخر، أو قوّس حوافّ أقل في المرة الواحدة.", - "ui.fillet_error_too_large": "نصف القطر كبير جدًا على الوجوه المجاورة لهذه الحواف. جرّب نصف قطر أصغر، أو اختر في «إذا كان كبيرًا جدًا» الخيار «استخدم أكبر ما يتّسع».", - "ui.fillet_fit": "إذا كان كبيرًا جدًا", - "ui.fillet_fit_exact": "توقّف وأخبرني", - "ui.fillet_fit_reduce": "استخدم أكبر ما يتّسع", - "ui.fillet_fit_taper": "ضيّقه حيث يلزم", - "ui.fillet_fit_tip": "عندما يكون نصف القطر أكبر مما تسمح به الوجوه المجاورة للحافة: توقّف برسالة، أو قوّس كل حافة بأكبر نصف قطر يتّسع، أو أبقِ نصف القطر وضيّق التقويس فقط حيث تنتهي الوجوه.", + "ui.fillet_error_too_large": "نصف القطر كبير جدًا على الوجوه المجاورة لهذه الحواف. جرّب نصف قطر أصغر، أو اختر في «حدود الوجوه» الخيار «أكبر نصف قطر».", + "ui.fillet_fit": "حدود الوجوه", + "ui.fillet_fit_exact": "نصف قطر دقيق", + "ui.fillet_fit_reduce": "أكبر نصف قطر", + "ui.fillet_fit_taper": "نصف قطر مُضيَّق", + "ui.fillet_fit_tip": "عندما يكون نصف القطر أكبر مما تسمح به الوجوه المجاورة للحافة.\nنصف قطر دقيق: نصف القطر كما هو، أو لا تقويس ورسالة توضّح السبب.\nأكبر نصف قطر: تُقوَّس كل حافة بأكبر نصف قطر يتّسع.\nنصف قطر مُضيَّق: يبقى نصف القطر، ويُضيَّق التقويس فقط حيث تنتهي الوجوه.", "ui.fillet_options_tip": "سلسلة مماسّة: قوّس أيضًا الحواف التي تتصل بسلاسة بالحواف المختارة.\nمعاينة: اعرض النتيجة في العرض أثناء التحرير.", "ui.fillet_type_choices_tip": "نصف قطر ثابت: نصف قطر واحد على طول الحافة.\nطول الوتر: يبقى عرض التقويس نفسه مهما كانت الزاوية بين الوجوه.\nنصف قطر متغيّر: نصف قطر عند كل طرف، ومزيد على طول الحافة إن أضفته.\nمتصل الانحناء: مقطع بلا انكسار في الانعكاسات حيث يلتقي بالوجوه المستوية (G2).\nمنحنى: يتبع نصف القطر على طول الحافة أنصاف أقطار تحكّم تحدّدها." }, @@ -32,12 +32,12 @@ "ui.copy_details_tip": "Die vollständige Meldung kopieren, um sie nachzuschlagen oder zu melden.", "ui.fillet_error_corner": "Die glatte Ecke ließ sich hier nicht bauen. Versuchen Sie einen anderen Rücksprung oder tangentiale Ecken.", "ui.fillet_error_failed": "Diese Rundung ließ sich an diesen Kanten nicht bauen. Versuchen Sie einen anderen Radius oder runden Sie weniger Kanten auf einmal.", - "ui.fillet_error_too_large": "Der Radius ist zu groß für die Flächen neben diesen Kanten. Versuchen Sie einen kleineren Radius oder stellen Sie „Wenn zu groß“ auf „Größter passender“.", - "ui.fillet_fit": "Wenn zu groß", - "ui.fillet_fit_exact": "Anhalten und melden", - "ui.fillet_fit_reduce": "Größter passender", - "ui.fillet_fit_taper": "Wo nötig verjüngen", - "ui.fillet_fit_tip": "Wenn der Radius größer ist, als die Flächen neben einer Kante zulassen: mit einer Meldung anhalten, jede Kante mit dem größten passenden Radius runden oder den Radius behalten und die Rundung nur dort verjüngen, wo die Flächen enden.", + "ui.fillet_error_too_large": "Der Radius ist zu groß für die Flächen neben diesen Kanten. Versuchen Sie einen kleineren Radius oder stellen Sie „Flächengrenzen“ auf „Größter Radius“.", + "ui.fillet_fit": "Flächengrenzen", + "ui.fillet_fit_exact": "Exakter Radius", + "ui.fillet_fit_reduce": "Größter Radius", + "ui.fillet_fit_taper": "Verjüngter Radius", + "ui.fillet_fit_tip": "Wenn der Radius größer ist, als die Flächen neben einer Kante zulassen.\nExakter Radius: der angegebene Radius, oder keine Rundung und eine Meldung mit dem Grund.\nGrößter Radius: jede Kante mit dem größten passenden Radius gerundet.\nVerjüngter Radius: der Radius bleibt, die Rundung wird nur dort verjüngt, wo die Flächen enden.", "ui.fillet_options_tip": "Tangentenkette: auch die Kanten runden, die glatt an die gewählten anschließen.\nVorschau: das Ergebnis beim Bearbeiten in der Ansicht zeigen.", "ui.fillet_type_choices_tip": "Konstanter Radius: ein Radius entlang der ganzen Kante.\nSehnenlänge: die Breite der Rundung bleibt gleich, in welchem Winkel die Flächen auch aufeinandertreffen.\nVariabler Radius: ein Radius an jedem Ende und weitere entlang der Kante, wenn Sie sie hinzufügen.\nKrümmungsstetig: ein Querschnitt ohne Knick in den Spiegelungen, wo er auf ebene Flächen trifft (G2).\nSpline: der Radius entlang der Kante folgt Steuerradien, die Sie festlegen." }, @@ -46,12 +46,12 @@ "ui.copy_details_tip": "העתקת ההודעה המלאה, כדי לחפש אותה או לדווח עליה.", "ui.fillet_error_corner": "לא ניתן היה לבנות כאן את הפינה החלקה. נסו נסיגה אחרת, או פינות משיקות.", "ui.fillet_error_failed": "לא ניתן היה לבנות את העיגול הזה על הקצוות האלה. נסו רדיוס אחר, או עגלו פחות קצוות בבת אחת.", - "ui.fillet_error_too_large": "הרדיוס גדול מדי עבור הפאות שליד הקצוות האלה. נסו רדיוס קטן יותר, או בחרו ב„אם גדול מדי” את „להשתמש בגדול ביותר שנכנס”.", - "ui.fillet_fit": "אם גדול מדי", - "ui.fillet_fit_exact": "לעצור ולהודיע", - "ui.fillet_fit_reduce": "להשתמש בגדול ביותר שנכנס", - "ui.fillet_fit_taper": "להצר היכן שצריך", - "ui.fillet_fit_tip": "כשהרדיוס גדול ממה שהפאות שליד הקצה מאפשרות: לעצור עם הודעה, לעגל כל קצה ברדיוס הגדול ביותר שנכנס, או לשמור על הרדיוס ולהצר את העיגול רק היכן שהפאות נגמרות.", + "ui.fillet_error_too_large": "הרדיוס גדול מדי עבור הפאות שליד הקצוות האלה. נסו רדיוס קטן יותר, או בחרו ב„גבולות הפאות” את „הרדיוס הגדול ביותר”.", + "ui.fillet_fit": "גבולות הפאות", + "ui.fillet_fit_exact": "רדיוס מדויק", + "ui.fillet_fit_reduce": "הרדיוס הגדול ביותר", + "ui.fillet_fit_taper": "רדיוס מוצר", + "ui.fillet_fit_tip": "כשהרדיוס גדול ממה שהפאות שליד הקצה מאפשרות.\nרדיוס מדויק: הרדיוס כפי שניתן, או ללא עיגול והודעה שמסבירה למה.\nהרדיוס הגדול ביותר: כל קצה מעוגל ברדיוס הגדול ביותר שנכנס.\nרדיוס מוצר: הרדיוס נשמר, והעיגול מוצר רק היכן שהפאות נגמרות.", "ui.fillet_options_tip": "שרשרת משיקה: לעגל גם את הקצוות שממשיכים בחלקות מהקצוות שנבחרו.\nתצוגה מקדימה: להציג את התוצאה בתצוגה בזמן העריכה.", "ui.fillet_type_choices_tip": "רדיוס קבוע: רדיוס אחד לכל אורך הקצה.\nאורך מיתר: רוחב העיגול נשאר זהה, בכל זווית שבה הפאות נפגשות.\nרדיוס משתנה: רדיוס בכל קצה, ועוד לאורך הקצה אם מוסיפים.\nרציף בעקמומיות: חתך בלי שבר בהשתקפויות היכן שהוא פוגש פאות מישוריות (G2).\nספליין: הרדיוס לאורך הקצה עוקב אחרי רדיוסי בקרה שאתם קובעים." }, @@ -60,12 +60,12 @@ "ui.copy_details_tip": "調べたり報告したりできるよう、メッセージ全文をコピーします。", "ui.fillet_error_corner": "ここではなめらかなコーナーを作れませんでした。別のセットバックか、接線のコーナーを試してください。", "ui.fillet_error_failed": "このフィレットをこれらのエッジに作れませんでした。別の半径を試すか、一度に丸めるエッジを減らしてください。", - "ui.fillet_error_too_large": "これらのエッジの隣の面に対して半径が大きすぎます。小さい半径を試すか、「大きすぎるとき」を「収まる最大の半径を使う」にしてください。", - "ui.fillet_fit": "大きすぎるとき", - "ui.fillet_fit_exact": "止めて知らせる", - "ui.fillet_fit_reduce": "収まる最大の半径を使う", - "ui.fillet_fit_taper": "必要な所だけ細くする", - "ui.fillet_fit_tip": "半径がエッジの隣の面で収まる大きさを超えるとき: メッセージを出して止める、各エッジを収まる最大の半径で丸める、または半径を保って面が足りない所だけフィレットを細くする。", + "ui.fillet_error_too_large": "これらのエッジの隣の面に対して半径が大きすぎます。小さい半径を試すか、「面の境界」を「最大半径」にしてください。", + "ui.fillet_fit": "面の境界", + "ui.fillet_fit_exact": "正確な半径", + "ui.fillet_fit_reduce": "最大半径", + "ui.fillet_fit_taper": "狭めた半径", + "ui.fillet_fit_tip": "半径がエッジの隣の面で収まる大きさを超えるとき。\n正確な半径: 指定どおりの半径。収まらなければ丸めずに理由を知らせます。\n最大半径: 各エッジを収まる最大の半径で丸めます。\n狭めた半径: 半径を保ち、面が足りない所だけフィレットを細くします。", "ui.fillet_options_tip": "正接チェーン: 選んだエッジからなめらかに続くエッジも丸めます。\nプレビュー: 編集中に結果をビューに表示します。", "ui.fillet_type_choices_tip": "一定の半径: エッジ全体で一つの半径。\n弦長: 面がどんな角度で交わっても、フィレットの幅が同じ。\n可変半径: 両端の半径と、追加すればエッジ沿いの半径。\n曲率連続: 平面と接する所で映り込みが折れない断面 (G2)。\nスプライン: エッジ沿いの半径が、設定した制御半径に従います。" }, @@ -74,12 +74,12 @@ "ui.copy_details_tip": "찾아보거나 보고할 수 있도록 전체 메시지를 복사합니다.", "ui.fillet_error_corner": "여기에서는 부드러운 코너를 만들 수 없었습니다. 다른 셋백이나 접선 코너를 시도해 보세요.", "ui.fillet_error_failed": "이 모서리들에 이 필렛을 만들 수 없었습니다. 다른 반지름을 시도하거나 한 번에 둥글게 하는 모서리 수를 줄여 보세요.", - "ui.fillet_error_too_large": "이 모서리 옆의 면에 비해 반지름이 너무 큽니다. 더 작은 반지름을 시도하거나 '너무 클 때'를 '들어가는 가장 큰 반지름 사용'으로 설정하세요.", - "ui.fillet_fit": "너무 클 때", - "ui.fillet_fit_exact": "멈추고 알리기", - "ui.fillet_fit_reduce": "들어가는 가장 큰 반지름 사용", - "ui.fillet_fit_taper": "필요한 곳만 좁히기", - "ui.fillet_fit_tip": "반지름이 모서리 옆 면이 허용하는 것보다 클 때: 메시지와 함께 멈추거나, 모든 모서리를 들어가는 가장 큰 반지름으로 둥글게 하거나, 반지름을 유지하고 면이 모자란 곳에서만 라운드를 좁힙니다.", + "ui.fillet_error_too_large": "이 모서리 옆의 면에 비해 반지름이 너무 큽니다. 더 작은 반지름을 시도하거나 '면 경계'를 '최대 반지름'으로 설정하세요.", + "ui.fillet_fit": "면 경계", + "ui.fillet_fit_exact": "정확한 반지름", + "ui.fillet_fit_reduce": "최대 반지름", + "ui.fillet_fit_taper": "좁힌 반지름", + "ui.fillet_fit_tip": "반지름이 모서리 옆 면이 허용하는 것보다 클 때.\n정확한 반지름: 지정한 반지름 그대로, 또는 둥글게 하지 않고 이유를 알리는 메시지.\n최대 반지름: 모든 모서리를 들어가는 가장 큰 반지름으로 둥글게 합니다.\n좁힌 반지름: 반지름을 유지하고 면이 모자란 곳에서만 라운드를 좁힙니다.", "ui.fillet_options_tip": "접선 체인: 선택한 모서리에서 부드럽게 이어지는 모서리도 둥글게 합니다.\n미리 보기: 편집하는 동안 결과를 뷰에 표시합니다.", "ui.fillet_type_choices_tip": "일정한 반지름: 모서리 전체에 하나의 반지름.\n현 길이: 면이 어떤 각도로 만나든 라운드의 폭이 같습니다.\n가변 반지름: 양 끝의 반지름과, 추가하면 모서리를 따라 더.\n곡률 연속: 평면과 만나는 곳에서 반사가 꺾이지 않는 단면(G2).\n스플라인: 모서리를 따라 반지름이 설정한 제어 반지름을 따릅니다." }, @@ -88,12 +88,12 @@ "ui.copy_details_tip": "复制完整消息,以便查找或报告。", "ui.fillet_error_corner": "无法在此处构建平滑角点。请尝试其他后退距离,或相切角点。", "ui.fillet_error_failed": "无法在这些边上构建此圆角。请尝试其他半径,或一次少倒几条边。", - "ui.fillet_error_too_large": "半径对这些边旁边的面来说太大。请尝试更小的半径,或将“过大时”设为“使用能容纳的最大半径”。", - "ui.fillet_fit": "过大时", - "ui.fillet_fit_exact": "停止并提示", - "ui.fillet_fit_reduce": "使用能容纳的最大半径", - "ui.fillet_fit_taper": "在需要处收窄", - "ui.fillet_fit_tip": "当半径大于边旁边的面所允许的大小时:给出提示并停止,用能容纳的最大半径倒每条边,或保持半径、只在面不够的地方收窄圆角。", + "ui.fillet_error_too_large": "半径对这些边旁边的面来说太大。请尝试更小的半径,或将“面边界”设为“最大半径”。", + "ui.fillet_fit": "面边界", + "ui.fillet_fit_exact": "精确半径", + "ui.fillet_fit_reduce": "最大半径", + "ui.fillet_fit_taper": "收窄半径", + "ui.fillet_fit_tip": "当半径大于边旁边的面所允许的大小时。\n精确半径:按给定的半径倒圆,否则不倒圆并说明原因。\n最大半径:用能容纳的最大半径倒每条边。\n收窄半径:保持半径,只在面不够的地方收窄圆角。", "ui.fillet_options_tip": "相切链:同时倒圆与所选边平滑相连的边。\n预览:编辑时在视图中显示结果。", "ui.fillet_type_choices_tip": "恒定半径:整条边一个半径。\n弦长:无论面以什么角度相交,圆角宽度都相同。\n可变半径:两端各一个半径,添加后沿边还有更多。\n曲率连续:与平面相接处反射没有折痕的截面 (G2)。\n样条:沿边的半径跟随您设置的控制半径。" } diff --git a/crates/kernel/src/blend.rs b/crates/kernel/src/blend.rs index 8933b91a2..4b752e14e 100644 --- a/crates/kernel/src/blend.rs +++ b/crates/kernel/src/blend.rs @@ -837,6 +837,253 @@ pub(crate) fn rounds_too_small(body: &Body, picks: &[Vec3], edges: &[usize], rad Ok(()) } +/// Refuses a round whose section would cut through the material into a hollow behind its edge, +/// opening the part (a slit into the hollow, or a cut through the part): the owner's rule of +/// 2026-10-30, as [`KernelError::TooLarge`], so a fillet feature names the largest radius that +/// fits. A round running past a rim of its faces into open air is left to the blend (tangent +/// where it has room, cut where it runs out). +/// +/// Decided exactly in the section square to a picked straight edge between two planar faces +/// (A and B, convex): the round's circle of radius r has its centre at E + r k, the point at +/// depth r below both planes (k = −(n_A + n_B)/(1 + n_A·n_B)), and removes the region between the +/// edge E and its arc. That region grows with r. Material behind the faces first opens into a +/// hollow where the arc, moving away from E, uncovers a point q of the body's boundary strictly +/// inside the wedge with no material just beyond it (toward the centre): q lies on the circle, +/// |q − E − r k| = r, whose larger root in r is where it opens ([`opening_radius`]). Where the +/// strips of faces A and B themselves leave their faces, the round runs out past a rim into the +/// air, which is not a point of this kind (it lies on a face's plane, not inside the wedge). +/// +/// The boundary points looked at run along the edge, so their section is the same all along the +/// stretch they share with it: straight edges parallel to it (a hollow's corner), cylindrical +/// faces about axes parallel to it (a hollow's rounded corner), and a picked concave edge parallel +/// to it, rounded in the same fillet (the arc of its round, which fills the hollow's corner). +/// Whether the point uncovered is material is the body's exact point classification. +pub(crate) fn rounds_into_hollow(body: &Body, picks: &[Vec3], edges: &[usize], radii: &[f64]) -> Result<()> { + let rec = Faces::of(body)?; + for (i, (&e, &r)) in edges.iter().zip(radii).enumerate() { + let Some(section) = Section::of(&rec, e) else { continue }; + let Some((opens, at)) = section.opening(body, &rec, edges, radii)? else { continue }; + if r <= opens + section.tolerance { + continue; + } + let pick = picks.get(i).map(|p| format!(" at ({:.3}, {:.3}, {:.3})", p.x, p.y, p.z)).unwrap_or_default(); + return Err(KernelError::TooLarge(format!( + "the round of radius {r} mm on the edge{pick} would cut through the material behind it into the hollow at ({:.3}, {:.3}, \ + {:.3}) and open the part", + at.x, at.y, at.z + ))); + } + Ok(()) +} + +/// The section of a round of a straight, convex edge between two planar faces, as +/// [`rounds_into_hollow`] reads it. +struct Section { + /// The edge's start, its unit direction and its length. + start: Vec3, + dir: Vec3, + length: f64, + /// The faces' outward unit normals. + na: Vec3, + nb: Vec3, + /// The centre of the round of radius r is at `start + r k` in the section through `start`. + k: Vec3, + tolerance: f64, +} + +impl Section { + fn of(rec: &Faces, e: usize) -> Option
{ + if !rec.straight(e) { + return None; + } + let [fa, fb] = <[u32; 2]>::try_from(rec.faces_of(e).into_iter().collect::>()).ok()?; + let (na, nb) = (rec.plane_normal(fa as usize)?, rec.plane_normal(fb as usize)?); + let (start, end) = rec.ends(e)?; + let length = start.dist(end); + let dir = (end - start).normalized()?; + let g = na.dot(nb); + if !(g.is_finite() && g.abs() < 1.0 - 1e-9) { + return None; + } + // Convex: going into face A from the edge goes below face B's plane. + let use_a = rec.uses(fa as usize).find(|u| u.edge as usize == e)?; + let into_a = rec.direction_into_face(fa as usize, use_a)?; + if into_a.dot(nb) >= 0.0 { + return None; + } + let tolerance = rec.rec.edges.get(e)?.tolerance.max(rec.rec.tolerance).max(1e-9); + let k = (na + nb) * (-1.0 / (1.0 + g)); + Some(Section { start, dir, length, na, nb, k, tolerance }) + } + + /// `p − start` without its part along the edge: its place in the section. + fn flat(&self, p: Vec3) -> Vec3 { + let w = p - self.start; + w - self.dir * w.dot(self.dir) + } + + /// Whether `p` (in the section) runs along the edge: a direction parallel to it. + fn parallel(&self, d: Vec3) -> bool { + d.normalized().is_some_and(|d| d.cross(self.dir).len() <= 1e-9) + } + + /// The stretch `[lo, hi]` along the edge (from its start) that `[a, b]` (points' places along + /// it) shares with it, its middle; `None` where they share none. + fn shared(&self, a: f64, b: f64) -> Option { + let (lo, hi) = (a.min(b).max(0.0), a.max(b).min(self.length)); + (hi - lo > self.tolerance).then_some(0.5 * (lo + hi)) + } + + /// The smallest radius at which the round opens into a hollow behind it and the point where it + /// does (at the middle of the stretch the opening runs along); `None` where it never does + /// through the boundary looked at ([`rounds_into_hollow`]). `edges` and `radii`: the fillet's. + fn opening(&self, body: &Body, rec: &Faces, edges: &[usize], radii: &[f64]) -> Result> { + let mut best: Option<(f64, Vec3)> = None; + let mut keep = |found: Option<(f64, Vec3)>| { + if let Some((r, p)) = found + && best.is_none_or(|(b, _)| r < b) + { + best = Some((r, p)); + } + }; + // Straight edges parallel to the round's: a hollow's corner, or a picked concave edge whose + // round of its own fills it. + for (j, edge) in rec.rec.edges.iter().enumerate() { + if !matches!(edge.curve, Curve::Line { .. }) { + continue; + } + let Some((a, b)) = rec.ends(j) else { continue }; + if !self.parallel(b - a) { + continue; + } + let Some(middle) = self.shared((a - self.start).dot(self.dir), (b - self.start).dot(self.dir)) else { continue }; + // The round's own edge, and edges on its line, lie at the section's origin. + let q = self.flat(a); + if q.len() <= self.tolerance { + continue; + } + let found = match edges.iter().position(|&p| p == j) { + Some(at) => match (concave_round_centre(rec, j, radii.get(at).copied()), radii.get(at)) { + (Some((o, arc)), Some(&rho)) => self.through_circle(body, self.flat(o), rho, middle, Some(arc))?, + _ => None, + }, + None => self.through_point(body, q, middle)?, + }; + keep(found); + } + // Cylindrical faces about axes parallel to the edge: a hollow's rounded corner. + for (f, face) in rec.rec.faces.iter().enumerate() { + let Surface::Cylinder { frame, radius } = &face.surface else { continue }; + if !self.parallel(v3(frame.x_axis).cross(v3(frame.y_axis))) { + continue; + } + let along: Vec = + rec.uses(f).filter_map(|u| rec.ends(u.edge as usize)).flat_map(|(a, b)| [a, b]).map(|p| (p - self.start).dot(self.dir)).collect(); + let (lo, hi) = along.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), t| (lo.min(*t), hi.max(*t))); + let Some(middle) = self.shared(lo, hi) else { continue }; + keep(self.through_circle(body, self.flat(v3(frame.origin)), *radius, middle, None)?); + } + Ok(best) + } + + /// Where the round opens through the section point `q` (a boundary point running along the + /// edge): its larger radius on the circle through `q`, when `q` then lies on the round's arc + /// strictly inside the wedge and no material lies just beyond it, toward the centre. + fn through_point(&self, body: &Body, q: Vec3, middle: f64) -> Result> { + // |q − r k|² = r²: (|k|² − 1) r² − 2 (q·k) r + |q|² = 0. + let Some(r) = larger_root(self.k.len2() - 1.0, q.dot(self.k), q.len2()) else { return Ok(None) }; + self.opens_at(body, r, q, middle) + } + + /// Where the round opens through a circle of the section, centre `o`, radius `rho`, with the + /// hollow inside it: where the circle's far point from the round's centre reaches the round's + /// arc (|o − r k| + rho = r). `arc`: the directions from `o` the circle is the boundary + /// along, when it is a picked concave edge's round, not yet built. + fn through_circle(&self, body: &Body, o: Vec3, rho: f64, middle: f64, arc: Option<(Vec3, Vec3)>) -> Result> { + // |o − r k|² = (r − rho)²: (|k|² − 1) r² − 2 (o·k − rho) r + |o|² − rho² = 0. + let Some(r) = larger_root(self.k.len2() - 1.0, o.dot(self.k) - rho, o.len2() - rho * rho) else { return Ok(None) }; + let Some(out) = (o - self.k * r).normalized() else { return Ok(None) }; + let q = o + out * rho; + match arc { + Some((m1, m2)) => { + // On the concave round's own arc: between its two contacts, seen from its centre. + if !within(out, m1, m2, self.tolerance / rho.max(1.0)) { + return Ok(None); + } + self.opens_at(body, r, q, middle) + } + None => { + // On the face itself. + if body.classify_point(self.place(q, middle))? != crate::body::PointClass::OnBoundary { + return Ok(None); + } + self.opens_at(body, r, q, middle) + } + } + } + + /// The section point `q` at `middle` along the edge. + fn place(&self, q: Vec3, middle: f64) -> Vec3 { + self.start + self.dir * middle + q + } + + /// `Some((r, q placed))` when, at radius `r`, `q` lies on the round's arc strictly inside the + /// wedge and the body has no material just beyond it toward the centre. + fn opens_at(&self, body: &Body, r: f64, q: Vec3, middle: f64) -> Result> { + if !(r.is_finite() && r > self.tolerance) { + return Ok(None); + } + let centre = self.k * r; + // q − centre = α n_A + β n_B with α, β > 0: on the arc between the contacts. + if !within(q - centre, self.na, self.nb, self.tolerance) { + return Ok(None); + } + let Some(inward) = (centre - q).normalized() else { return Ok(None) }; + let step = (r * 1e-3).max(self.tolerance * 10.0); + let at = self.place(q, middle); + Ok((body.classify_point(at + inward * step)? == crate::body::PointClass::Outside).then_some((r, at))) + } +} + +/// Whether `w` = α a + β b with α, β > `margin` (a, b unit, not parallel). +fn within(w: Vec3, a: Vec3, b: Vec3, margin: f64) -> bool { + let g = a.dot(b); + let det = 1.0 - g * g; + if !(det > 1e-12) { + return false; + } + let (wa, wb) = (w.dot(a), w.dot(b)); + let alpha = (wa - g * wb) / det; + let beta = (wb - g * wa) / det; + alpha > margin && beta > margin +} + +/// The larger root of a x² − 2 b x + c = 0 (a > 0). +fn larger_root(a: f64, b: f64, c: f64) -> Option { + let disc = b * b - a * c; + (a > 1e-12 && disc >= 0.0).then(|| (b + disc.sqrt()) / a).filter(|r| r.is_finite()) +} + +/// The centre of the round of radius `r` of concave straight edge `e` between planar faces, and +/// the directions from it to the round's two contacts: the circle tangent to both faces' planes +/// on the side away from the material. +fn concave_round_centre(rec: &Faces, e: usize, r: Option) -> Option<(Vec3, (Vec3, Vec3))> { + let r = r?; + let [f1, f2] = <[u32; 2]>::try_from(rec.faces_of(e).into_iter().collect::>()).ok()?; + let (n1, n2) = (rec.plane_normal(f1 as usize)?, rec.plane_normal(f2 as usize)?); + let use1 = rec.uses(f1 as usize).find(|u| u.edge as usize == e)?; + // Concave: going into face 1 from the edge goes above face 2's plane. + if rec.direction_into_face(f1 as usize, use1)?.dot(n2) <= 0.0 { + return None; + } + let g = n1.dot(n2); + if !(g.is_finite() && g.abs() < 1.0 - 1e-9) { + return None; + } + let (a, _) = rec.ends(e)?; + Some((a + (n1 + n2) * (r / (1.0 + g)), (-n1, -n2))) +} + /// A blend's failure where a picked edge continues tangentially into `next`, an edge left out /// ([`unfinished_chain`]): SMLib rounds a tangent chain as one sequence and could not end the /// blend there, so the reason and the way out are named. @@ -1301,6 +1548,42 @@ mod tests { /// At 1° the crease rounds from 0.526 mm: R2 lies 0.076 µm in and R20 0.76 µm, and each /// builds, removing 20 · r²(tan(δ/2) − δ/2). + /// A box 104 x 64 x 42 hollowed 2 mm from the inside, open at the bottom: 1668's thin wall. + fn thin_walled_case() -> Body { + let outer = crate::build::box_solid(Vec3::new(-52.0, -32.0, 0.0), Vec3::new(52.0, 32.0, 42.0)).unwrap(); + let hollow = crate::build::box_solid(Vec3::new(-50.0, -30.0, -1.0), Vec3::new(50.0, 30.0, 40.0)).unwrap(); + crate::ops::boolean(&outer, &hollow, crate::BoolOp::Cut).unwrap().unwrap() + } + + #[test] + fn a_round_cutting_through_a_thin_wall_into_the_hollow_is_refused_naming_the_largest_that_fits() { + let case = thin_walled_case(); + let top = Vec3::new(0.0, 32.0, 42.0); + // The round's centre is at (32 - r, 42 - r); the hollow's corner (30, 40) leaves its circle + // where sqrt2 (r - 2) = r: r = 4 + 2 sqrt2 = 6.8284. + let e = fillet(&case, &[top], 7.0).unwrap_err(); + assert!(matches!(e, KernelError::TooLarge(_)), "{e}"); + let e = e.to_string(); + assert!(e.contains("into the hollow at (0.000, 30.000, 40.000) and open the part"), "{e}"); + let (largest, _) = fillet_max(&case, &[top], 7.0).unwrap().unwrap(); + assert!((largest - 6.828).abs() < 1e-9, "{largest}"); + + // Just short of the corner it rounds, its whole section along the 104. + let r = 6.8; + let rounded = fillet(&case, &[top], r).unwrap(); + let want = 104.0 * 64.0 * 42.0 - 100.0 * 60.0 * 40.0 - (1.0 - std::f64::consts::FRAC_PI_4) * r * r * 104.0; + let got = crate::measure(&rounded).unwrap().volume; + assert!((got - want).abs() < 1e-6 * want, "{got} vs {want}"); + + // The inside edge rounded with it fills the hollow's corner: the outer round reaches the + // inner R7's arc (centre (23, 33)) only at sqrt2 (r - 9) + 7 = r, r = 13.83. + let inside = Vec3::new(0.0, 30.0, 40.0); + assert!(fillet(&case, &[top, inside], 7.0).is_ok()); + assert!(fillet_each(&case, &[top, inside], &[13.8, 7.0]).is_ok()); + let e = fillet_each(&case, &[top, inside], &[13.9, 7.0]).unwrap_err().to_string(); + assert!(e.contains("into the hollow at"), "{e}"); + } + #[test] fn a_one_degree_crease_rounds_from_the_smallest_radius_named() { let (gentle, crease) = roof(0.5); diff --git a/crates/kernel/src/blend_smlib.rs b/crates/kernel/src/blend_smlib.rs index 1fd61898c..49030caa0 100644 --- a/crates/kernel/src/blend_smlib.rs +++ b/crates/kernel/src/blend_smlib.rs @@ -218,6 +218,7 @@ mod imp { let next = crate::blend::unfinished_chain(body, edges, &picked.edges, &picked.hidden)?; if matches!(kind, Kind::Round) { crate::blend::rounds_too_small(body, edges, &picked.edges, sizes)?; + crate::blend::rounds_into_hollow(body, edges, &picked.edges, sizes)?; } let tol = pick_tolerance(body); let Kind::Round = kind else { @@ -285,6 +286,7 @@ mod imp { let picked = resolve(body, edges)?; let next = crate::blend::unfinished_chain(body, edges, &picked.edges, &picked.hidden)?; crate::blend::rounds_too_small(body, edges, &picked.edges, sizes)?; + crate::blend::rounds_into_hollow(body, edges, &picked.edges, sizes)?; let corners = corner_vertices(body, setbacks.iter().map(|(p, _)| *p))?; let distances: Vec = setbacks.iter().map(|(_, d)| *d).collect(); let tol = pick_tolerance(body); diff --git a/crates/ui-egui/src/dialogs_dense.rs b/crates/ui-egui/src/dialogs_dense.rs index 77767212c..3814f8c02 100644 --- a/crates/ui-egui/src/dialogs_dense.rs +++ b/crates/ui-egui/src/dialogs_dense.rs @@ -134,7 +134,7 @@ const FILLET_FITS: [(&str, &str); 3] = [("ui.fillet_fit_exact", "exact"), ("ui.f /// Which fillet options apply together, exactly as `solid.fillet` takes them (`fillet` in /// crates/engine/src/cmd/features.rs): /// -/// | Type | If too large (`fit`) | Corners (`corner`) | Setback (`setbacks`) | +/// | Type | Face limits (`fit`) | Corners (`corner`) | Setback (`setbacks`) | /// |---------------|-------------------------|-------------------------------------|----------------------| /// | Constant | exact, reduce or taper | tangent; curvature with exact only | with curvature only | /// | any other | exact (not sent) | tangent (not sent) | none | @@ -229,7 +229,7 @@ fn fillet_corner_rows( enter } -/// A Constant radius fillet's "If too large" row (`fit`), with the radius a reduced fillet used. +/// A Constant radius fillet's "Face limits" row (`fit`), with the radius a reduced fillet used. fn fillet_fit_rows(app: &SolveApp, ui: &mut egui::Ui, extra: &mut serde_json::Map, setback: &mut Option) { let t = Tokens::get(); let before = extra.get("fit").cloned(); @@ -1227,7 +1227,7 @@ mod tests { let exact = p.get("fit").is_none_or(|f| f == "exact"); assert!(constant || p.get("fit").is_none(), "{what}: fit without Constant radius: {p}"); assert!(constant && exact || (p.get("corner").is_none() && p.get("setbacks").is_none()), "{what}: a curvature corner with {p}"); - assert_eq!(scenario::handle_at("dialog:ui.fillet_fit").is_some(), constant, "{what}: If too large shows exactly with Constant radius"); + assert_eq!(scenario::handle_at("dialog:ui.fillet_fit").is_some(), constant, "{what}: Face limits shows exactly with Constant radius"); assert_eq!(scenario::handle_at("dialog:ui.corners").is_some(), constant, "{what}: Corners shows exactly with Constant radius"); if !ran.borrow_mut().insert(p.to_string()) { return; @@ -1254,7 +1254,7 @@ mod tests { choose(&mut h, "ui.fillet_fit", fit); check(&h, &what); choose(&mut h, "ui.corners", Continuity::G2.label_id()); - assert!(parameters(&h).get("fit").is_none(), "{what}: a curvature corner puts If too large back to Stop"); + assert!(parameters(&h).get("fit").is_none(), "{what}: a curvature corner puts Face limits back to Exact radius"); } check(&h, &what); choose(&mut h, "Type", label); diff --git a/tests/KNOWN_FAILING_TESTS b/tests/KNOWN_FAILING_TESTS new file mode 100644 index 000000000..2aaf3e407 --- /dev/null +++ b/tests/KNOWN_FAILING_TESTS @@ -0,0 +1,10 @@ +# The cargo tests that fail today, one a line: ` `, with the issue that +# tracks it when there is one. Sorted. `` is nextest's `::`, as the +# junit report names it. CI's test jobs (`cargo xtask known-failing`) fail on a test that fails +# and is not listed here, and on a listed test that passes: a fix removes its line in the same +# pull request. The tests stay un-ignored, so every run shows whether they still fail. +# Refresh (after an SMLib pin bump): download the junit artifacts of develop's latest CI run, one +# directory each (`gh run download -R tangency-labs/solidcraft -n -D /` +# for junit and junit-gpu-1..4), run `cargo xtask known-failing --junit `, then drop each +# FIXED line and add each REGRESSION line with its cause, from the test's failure message. +# Baseline: none yet. diff --git a/tests/kernel-cases/fillets/1668-fillet-outer-top-edge-of-thin-wall-r7-past-inside-corner/expected.json b/tests/kernel-cases/fillets/1668-fillet-outer-top-edge-of-thin-wall-r7-past-inside-corner/expected.json index 0a596941c..75a8e9430 100644 --- a/tests/kernel-cases/fillets/1668-fillet-outer-top-edge-of-thin-wall-r7-past-inside-corner/expected.json +++ b/tests/kernel-cases/fillets/1668-fillet-outer-top-edge-of-thin-wall-r7-past-inside-corner/expected.json @@ -3,15 +3,9 @@ "tangency-labs/solidcraft#1668", "tangency-labs/solidcraft#1080" ], - "what": "an R7 round of the outer top edge of a 2 mm wall alone: past the sharp inside corner it is cut from the wall as if the hollow were not there, opening a slit along the hollow", + "what": "an R7 round of the outer top edge of a 2 mm wall alone: past the sharp inside corner it would cut through the wall into the hollow, opening a slit along it, so it is refused, naming the largest radius that fits", "source": "analytic", - "method": "box 100x60x40 shelled outward 2 mm open at the bottom: 104x64x42 less 100x60x40 = 39552. The round's circle about (y, z) = (25, 35), r 7, takes (1-pi/4) 49 along the edge's 104, less its part over the hollow (y < 30, z < 40), the square [25,30]x[35,40] outside the circle: Int_sqrt24^5 (5 - sqrt(49-u^2)) du = 5(5-sqrt24) - (F(5) - F(sqrt24)), F(t) = (t sqrt(49-t^2) + 49 asin(t/7))/2, = 0.005068, along the hollow's 100 (the end walls x = +-50..52 are solid). V = 38458.895826, exact: the tolerance holds it to 0.04 mm^3", - "body_count": 1, - "volume_mm3": 38458.89582646349, - "tolerance": { - "rel": 1e-06 - }, - "continuity": { - "order": "g1" - } + "method": "box 100x60x40 shelled outward 2 mm open at the bottom: the wall runs y 30..32, z 40..42 at the top edge (y, z) = (32, 42). The round's centre is at (32 - r, 42 - r); it removes what lies between the edge and its arc. The hollow's corner (30, 40) lies at sqrt2 (r - 2) from the centre: the arc uncovers it, and the section breaks into the hollow along its 100, where sqrt2 (r - 2) = r, r = 4 + 2 sqrt2 = 6.8284. Past that the wall would open (the owner's ruling of 2026-10-30: refused as too large, naming the largest that fits, 6.828).", + "outcome": "refused", + "refusal": "the largest radius that fits is 6.828 mm" } diff --git a/tests/kernel-cases/fillets/KNOWN_FAILING b/tests/kernel-cases/fillets/KNOWN_FAILING index ebfc234e9..19b8560ab 100644 --- a/tests/kernel-cases/fillets/KNOWN_FAILING +++ b/tests/kernel-cases/fillets/KNOWN_FAILING @@ -7,9 +7,7 @@ 1080-fillet-sloped-basin-1-mm-rim-r4-2-edges not supported yet: a convex round past its face is not yet built by subtraction 1080-fillet-sloped-basin-1-mm-rim-r4-4-edges not supported yet: a convex round past its face is not yet built by subtraction 1207-fillet-bar-top-edge-after-boss-arc-round-r0-5 SMLib's check refuses the round: internal coincident control points in a B-spline curve (an internal pole) -1668-fillet-outer-top-edge-of-thin-wall-r7-past-inside-corner a slit along the hollow, 0.507 mm^3 off: 38458.389 is V0 less the round's whole section along 104, so the section's part over the hollow (0.005068 mm^2 along 100), which is not material, is taken anyway 190-fillet-disc-rim-past-its-2mm-wall SMLib status 1001: a convex round past its face is not yet built by subtraction -2852-fillet-outer-round-r30-past-inner-round-refused refused for another reason: SMLib's result is not a closed solid, not too large naming 25.24 2893-chamfer-distance-and-angle-past-the-wall-refused refused for another reason: SMLib SM_ERR_INVALID_INPUT, not a check saying the angle runs past the wall 2893-chamfer-two-distances-elliptical-rim SMLib status 1001 on the elliptical rim's chamfer 2893-chamfer-two-distances-past-the-bottom SMLib status 1001: SmFilletNx1ClosedCorner cannot compute the closed rim's corner geometry, where the chamfer past the bottom rim should build the frustum diff --git a/xtask/Cargo.toml b/xtask/Cargo.toml index 3715ecaf2..2f95f5505 100644 --- a/xtask/Cargo.toml +++ b/xtask/Cargo.toml @@ -7,6 +7,7 @@ publish = false [dependencies] proc-macro2 = { workspace = true } +quick-xml = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } sha2 = { workspace = true } diff --git a/xtask/src/kernel_cases.rs b/xtask/src/kernel_cases.rs index 9e94eedec..e931beb31 100644 --- a/xtask/src/kernel_cases.rs +++ b/xtask/src/kernel_cases.rs @@ -372,7 +372,7 @@ pub fn run(rest: &[&str]) -> Result<(), String> { /// The cases a known-failing baseline lists, with their causes: one per line, ` `, /// the case's directory relative to the baseline's own; `#` starts a comment line. The list is /// sorted with no case twice, and every case has a cause. -fn known_failing(text: &str) -> Result, String> { +pub(crate) fn known_failing(text: &str) -> Result, String> { let mut out: Vec<(&str, &str)> = Vec::new(); for (n, line) in text.lines().enumerate() { let line = line.trim(); diff --git a/xtask/src/known_failing.rs b/xtask/src/known_failing.rs new file mode 100644 index 000000000..b85b3a0c9 --- /dev/null +++ b/xtask/src/known_failing.rs @@ -0,0 +1,267 @@ +//! `cargo xtask known-failing --junit PATH... [--list FILE]`: grades a nextest run (its junit +//! report) against the tests known to fail today, `tests/KNOWN_FAILING_TESTS`. CI's test jobs +//! run it after nextest, in place of failing on any failed test. It fails on a test that failed +//! and is not listed, and on a listed test that passed (fixed: its line comes off in the same +//! pull request); a listed test that did not run (a pull request tests only the packages it +//! touches) is neither. The list has the kernel rig's format (`kernel_cases::known_failing`): +//! one test a line, ` `, sorted, with `` nextest's +//! `::` (`solidcraft-kernel::tests::...`, or +//! `solidcraft-cli::action_matrix::action_matrix_sample` for an integration test binary). + +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +use quick_xml::Reader; +use quick_xml::events::{BytesStart, Event}; + +pub const LIST: &str = "tests/KNOWN_FAILING_TESTS"; + +pub fn run(root: &Path, rest: &[&str]) -> Result<(), String> { + let mut reports = Vec::new(); + let mut list = root.join(LIST); + let mut args = rest.iter(); + while let Some(arg) = args.next() { + match *arg { + "--junit" => reports.push(PathBuf::from(args.next().ok_or("--junit needs a junit file or a directory of them")?)), + "--list" => list = PathBuf::from(args.next().ok_or("--list needs a file")?), + other => return Err(format!("known-failing: unknown argument `{other}`")), + } + } + if reports.is_empty() { + return Err("known-failing: give the nextest junit report with --junit FILE or DIR".into()); + } + let mut files = Vec::new(); + for path in &reports { + xml_files(path, &mut files)?; + } + if files.is_empty() { + return Err(format!( + "known-failing: no junit (.xml) file in {}", + reports.iter().map(|p| p.display().to_string()).collect::>().join(", ") + )); + } + let mut outcomes = BTreeMap::new(); + for file in &files { + let text = std::fs::read_to_string(file).map_err(|e| format!("{}: {e}", file.display()))?; + add(&mut outcomes, &text).map_err(|e| format!("{}: {e}", file.display()))?; + } + let text = std::fs::read_to_string(&list).map_err(|e| format!("{}: {e}", list.display()))?; + println!("{}", grade(&text, &outcomes).map_err(|e| format!("{}: {e}", list.display()))?); + Ok(()) +} + +/// The tests of one junit report into `all`. A test in two reports failed if it failed in either. +fn add(all: &mut BTreeMap, xml: &str) -> Result<(), String> { + for (test, failed) in junit_outcomes(xml)? { + *all.entry(test).or_insert(false) |= failed; + } + Ok(()) +} + +/// `cargo xtask lists`: the list is sorted, each test once, with a cause each. +pub fn check_list(root: &Path) -> Result<(), String> { + let file = root.join(LIST); + let text = std::fs::read_to_string(&file).map_err(|e| format!("{}: {e}", file.display()))?; + crate::kernel_cases::known_failing(&text).map(|_| ()).map_err(|e| format!("{LIST}: {e}")) +} + +/// `path` itself, or every `.xml` file under it (sorted), into `out`. +fn xml_files(path: &Path, out: &mut Vec) -> Result<(), String> { + if path.is_file() { + out.push(path.to_path_buf()); + return Ok(()); + } + let entries = std::fs::read_dir(path).map_err(|e| format!("{}: {e}", path.display()))?; + let mut paths: Vec = entries.filter_map(Result::ok).map(|e| e.path()).collect(); + paths.sort(); + for p in paths { + if p.is_dir() { + xml_files(&p, out)?; + } else if p.extension().is_some_and(|x| x == "xml") { + out.push(p); + } + } + Ok(()) +} + +/// Every test a junit report ran, as `::` with whether it failed (a `failure` +/// or `error` in its case). A skipped case did not run and is left out; a case that passed on a +/// retry (nextest's `flakyFailure`) passed. +fn junit_outcomes(xml: &str) -> Result, String> { + let mut reader = Reader::from_str(xml); + let mut suite: Option = None; + // The open test case: its id, whether it failed, whether it was skipped. + let mut case: Option<(String, bool, bool)> = None; + let mut out = Vec::new(); + loop { + let event = reader.read_event().map_err(|e| format!("not a junit report: {e}"))?; + let empty = matches!(event, Event::Empty(_)); + match event { + Event::Start(e) | Event::Empty(e) => match e.name().as_ref() { + b"testsuite" if !empty => suite = Some(attribute(&e, "name")?), + b"testcase" => { + let name = attribute(&e, "name")?; + let suite = suite.as_deref().ok_or_else(|| format!("test case {name} outside a testsuite"))?; + let id = format!("{suite}::{name}"); + if empty { + out.push((id, false)); + } else { + case = Some((id, false, false)); + } + } + b"failure" | b"error" => { + if let Some(c) = case.as_mut() { + c.1 = true; + } + } + b"skipped" => { + if let Some(c) = case.as_mut() { + c.2 = true; + } + } + _ => {} + }, + Event::End(e) => match e.name().as_ref() { + b"testcase" => { + if let Some((id, failed, skipped)) = case.take() + && !skipped + { + out.push((id, failed)); + } + } + b"testsuite" => suite = None, + _ => {} + }, + Event::Eof => break, + _ => {} + } + } + Ok(out) +} + +fn attribute(e: &BytesStart, name: &str) -> Result { + let tag = String::from_utf8_lossy(e.name().as_ref()).into_owned(); + let a = e.try_get_attribute(name).map_err(|err| format!("<{tag}>: {err}"))?.ok_or_else(|| format!("<{tag}> has no {name}"))?; + a.normalized_value(quick_xml::XmlVersion::Implicit1_0).map(|v| v.into_owned()).map_err(|err| format!("<{tag} {name}>: {err}")) +} + +/// The gate: every test that ran passes except those `list` names. A failed test the list does +/// not name is a regression; a listed test that passed is fixed and must leave the list, so the +/// list only shrinks. A listed test that did not run is neither. +fn grade(list: &str, outcomes: &BTreeMap) -> Result { + let listed = crate::kernel_cases::known_failing(list)?; + let is_listed = |test: &str| listed.iter().any(|(t, _)| *t == test); + let mut problems = Vec::new(); + let mut known = 0; + for (test, failed) in outcomes { + match (is_listed(test), *failed) { + (false, true) => problems.push(format!("REGRESSION, failed and not on the known-failing list: {test}")), + (true, false) => problems.push(format!("FIXED, remove it from the known-failing list: {test}")), + (true, true) => known += 1, + (false, false) => {} + } + } + let not_run = listed.iter().filter(|(t, _)| !outcomes.contains_key(*t)).count(); + let summary = format!( + "known-failing: {} ran, {} pass, {known} known failing, {not_run} listed did not run here", + outcomes.len(), + outcomes.values().filter(|f| !**f).count() + ); + if problems.is_empty() { Ok(format!("{summary}; no regression")) } else { Err(format!("{summary}\n {}", problems.join("\n "))) } +} + +#[cfg(test)] +mod tests { + use std::collections::BTreeMap; + + use super::{add, grade, junit_outcomes}; + + /// A nextest report in miniature: a library and an integration test binary, a pass, a + /// failure, an error, a skipped case and a pass on a retry. + const REPORT: &str = r#" + + + + + panicked: 1 vs 2 + running 1 test + + + + + + + + + + + + + +"#; + + fn outcomes(xml: &str) -> BTreeMap { + junit_outcomes(xml).unwrap().into_iter().collect() + } + + #[test] + fn a_junit_report_gives_each_test_that_ran_with_whether_it_failed() { + let got: Vec<(String, bool)> = junit_outcomes(REPORT).unwrap(); + let want = [ + ("solidcraft-kernel::tests::passes", false), + ("solidcraft-kernel::tests::fails", true), + ("solidcraft-kernel::tests::times_out", true), + ("solidcraft-cli::action_matrix::action_matrix_sample", false), + ("solidcraft-cli::action_matrix::a__case", false), + ]; + assert_eq!(got, want.map(|(t, f)| (t.to_string(), f))); + assert!(junit_outcomes("").unwrap_err().contains("outside a testsuite")); + assert!(junit_outcomes("").unwrap_err().contains("has no name")); + assert!(junit_outcomes("").unwrap_err().contains("not a junit report")); + } + + #[test] + fn the_gate_passes_listed_failures_and_fails_on_a_new_failure_or_a_fixed_test() { + let list = "# today\n\ + solidcraft-kernel::tests::fails SMLib status 1001\n\ + solidcraft-kernel::tests::not_run_here volume 1e-4 off (#2422)\n\ + solidcraft-kernel::tests::times_out SMLib hangs on the corner\n"; + let ok = grade(list, &outcomes(REPORT)).unwrap(); + assert_eq!(ok, "known-failing: 5 ran, 3 pass, 2 known failing, 1 listed did not run here; no regression"); + + let fixed = REPORT.replace("", ""); + let err = grade(list, &outcomes(&fixed)).unwrap_err(); + assert!(err.contains("FIXED, remove it from the known-failing list: solidcraft-kernel::tests::times_out"), "{err}"); + assert!(err.starts_with("known-failing: 5 ran, 4 pass, 1 known failing"), "{err}"); + + let shorter = list.replace("solidcraft-kernel::tests::fails SMLib status 1001\n", ""); + let err = grade(&shorter, &outcomes(REPORT)).unwrap_err(); + assert!(err.contains("REGRESSION, failed and not on the known-failing list: solidcraft-kernel::tests::fails"), "{err}"); + assert!(!err.contains("FIXED"), "{err}"); + } + + #[test] + fn a_test_failing_in_any_report_failed() { + let passed = REPORT.replace( + "panicked: 1 vs 2", + "", + ); + for reports in [[REPORT, passed.as_str()], [passed.as_str(), REPORT]] { + let mut all = BTreeMap::new(); + for r in reports { + add(&mut all, r).unwrap(); + } + assert_eq!(all.get("solidcraft-kernel::tests::fails"), Some(&true)); + assert_eq!(all.get("solidcraft-kernel::tests::passes"), Some(&false)); + } + assert_eq!(outcomes(&passed).get("solidcraft-kernel::tests::fails"), Some(&false)); + } + + #[test] + fn the_list_is_sorted_with_a_cause_each() { + let none = BTreeMap::new(); + assert!(grade("b x\na y\n", &none).unwrap_err().contains("out of order")); + assert!(grade("a x\na y\n", &none).unwrap_err().contains("a repeat of")); + assert!(grade("a\n", &none).unwrap_err().contains("gives no cause")); + } +} diff --git a/xtask/src/lists.rs b/xtask/src/lists.rs index 7f4054013..30311966c 100644 --- a/xtask/src/lists.rs +++ b/xtask/src/lists.rs @@ -5,6 +5,8 @@ //! //! - The message catalogs (`assets/locales/*.json`): one message per line, sorted by id, no //! duplicate ids, as `serde_json` pretty-prints them. +//! - `tests/KNOWN_FAILING_TESTS`: one test a line with its cause, sorted, each test once +//! (checked only; `cargo xtask known-failing` reads it). use std::path::Path; @@ -39,7 +41,8 @@ pub fn run(root: &Path, fix: bool) -> Result<(), String> { } crate::pending::check_locales(root)?; crate::pending::check_attribution(root)?; - println!("lists: message catalogs are sorted; pending locale and attribution files fold cleanly"); + crate::known_failing::check_list(root)?; + println!("lists: message catalogs and the known-failing tests are sorted; pending locale and attribution files fold cleanly"); Ok(()) } diff --git a/xtask/src/main.rs b/xtask/src/main.rs index d4ae31264..2807783ab 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -12,6 +12,7 @@ mod i18n; mod icons; mod kernel_cases; mod kernel_ladder; +mod known_failing; mod layers; mod licences; mod lists; @@ -68,6 +69,12 @@ commands: --coverage: instead of running cases, fail on a registry command (the CLI's `commands`, planned ones aside) that no recipe.json under tests/kernel-cases/ uses and tests/kernel-cases/EXEMPT does not list, and on a stale EXEMPT line + known-failing --junit PATH... [--list FILE] + grade a nextest run's junit report (a file, or every .xml under a directory) + against the tests known to fail today, tests/KNOWN_FAILING_TESTS (FILE): fails + on a test that failed and is not listed, and on a listed test that passed + (fixed: take its line off); a listed test that did not run is neither. CI's + test jobs run it after nextest action-matrix [--bless] [--results FILE] [--from DIR] try every ordinary action on every face, edge, vertex and body of the design corpus and compare with tests/action_matrix/baseline.json (--bless rewrites it; @@ -91,7 +98,8 @@ commands: into ATTRIBUTION.md, and delete them (the Generated files workflow runs this on main; pull requests add the pending files instead of editing the shared ones) lists [--fix] check that files many changes add to are sorted one item per line (the - message catalogs in assets/locales); --fix sorts them + message catalogs in assets/locales, tests/KNOWN_FAILING_TESTS); --fix sorts + the catalogs skills check that AGENTS.md and skills/*/SKILL.md cite files, `cargo xtask` commands and skills that exist, that the router table lists exactly the skills there are, and that AGENTS.md and new skills stay short @@ -126,6 +134,7 @@ fn main() -> ExitCode { Some("features") => features::run(&root()), Some("i18n") => i18n::run(&root(), &rest), Some("kernel-cases") => kernel_cases::run(&rest), + Some("known-failing") => known_failing::run(&root(), &rest), Some("oracle") => cmd_oracle(rest.iter().position(|a| *a == "--cli").and_then(|i| rest.get(i + 1)).copied()), Some("action-matrix") => { let arg = |name: &str| rest.iter().position(|a| *a == name).and_then(|i| rest.get(i + 1)).copied();