mirror of
https://github.com/storytold/texturecraft.git
synced 2026-11-30 10:03:56 +01:00
feat(bake): paint the skew map in the 2D view
A Skew correction section in the Bake panel turns on a brush (radius, value, hardness) that paints the map in the 2D view; the map shows as an orange overlay while baking. The 2D view is shown in bake mode while the brush is on. Strings in all ten languages. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
650af529e2
commit
9bb2f91809
14 files changed
+231
-3
No files matched your search
@@ -115,7 +115,12 @@ impl SkewMap {
|
||||
if t >= 1.0 {
|
||||
continue;
|
||||
}
|
||||
let fall = if t <= hardness { 1.0 } else { let k = (1.0 - t) / (1.0 - hardness); k * k * (3.0 - 2.0 * k) };
|
||||
let fall = if t <= hardness {
|
||||
1.0
|
||||
} else {
|
||||
let k = (1.0 - t) / (1.0 - hardness);
|
||||
k * k * (3.0 - 2.0 * k)
|
||||
};
|
||||
if let Some(v) = self.values.get_mut(y * w + x) {
|
||||
*v += (value - *v) * fall * strength;
|
||||
}
|
||||
@@ -311,7 +316,9 @@ mod tests {
|
||||
let mut map = SkewMap::constant(0.3).resized(16, 16).unwrap();
|
||||
let before = map.clone();
|
||||
let c = [Vec2::new(0.5, 0.5)];
|
||||
for (pts, r, v) in [(&c[..], 0.0, 1.0), (&c[..], -1.0, 1.0), (&c[..], f32::NAN, 1.0), (&c[..], 0.1, f32::INFINITY), (&[Vec2::new(f32::NAN, 0.0)][..], 0.1, 1.0)] {
|
||||
for (pts, r, v) in
|
||||
[(&c[..], 0.0, 1.0), (&c[..], -1.0, 1.0), (&c[..], f32::NAN, 1.0), (&c[..], 0.1, f32::INFINITY), (&[Vec2::new(f32::NAN, 0.0)][..], 0.1, 1.0)]
|
||||
{
|
||||
assert!(map.paint(pts, r, v, 0.5, 1.0).is_err(), "{pts:?} {r} {v}");
|
||||
}
|
||||
// Points far outside the atlas are harmless; a huge stroke is refused before any dab lands.
|
||||
|
||||
@@ -947,4 +947,12 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Unsaved changes", "تغييرات غير محفوظة"),
|
||||
("Don't save", "عدم الحفظ"),
|
||||
("Save the changes to {name} before closing?", "هل تريد حفظ التغييرات في {name} قبل الإغلاق؟"),
|
||||
("Skew correction", "تصحيح الانحراف"),
|
||||
("Paint skew in the 2D view", "ارسم الانحراف في العرض ثنائي الأبعاد"),
|
||||
(
|
||||
"Drag in the 2D view to paint where the bake rays turn onto the base normal; paint with a value of 0 to erase",
|
||||
"اسحب في العرض ثنائي الأبعاد لرسم المواضع التي تنعطف فيها أشعة الخَبْز نحو الناظم الأساسي؛ ارسم بالقيمة 0 للمسح",
|
||||
),
|
||||
("Radius", "نصف القطر"),
|
||||
("Remove skew correction", "إزالة تصحيح الانحراف"),
|
||||
];
|
||||
@@ -1002,4 +1002,12 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Unsaved changes", "Ungespeicherte Änderungen"),
|
||||
("Don't save", "Nicht speichern"),
|
||||
("Save the changes to {name} before closing?", "Änderungen an {name} vor dem Schließen speichern?"),
|
||||
("Skew correction", "Skew-Korrektur"),
|
||||
("Paint skew in the 2D view", "Skew in der 2D-Ansicht malen"),
|
||||
(
|
||||
"Drag in the 2D view to paint where the bake rays turn onto the base normal; paint with a value of 0 to erase",
|
||||
"In der 2D-Ansicht ziehen, um zu malen, wo sich die Bake-Strahlen zur Basisnormalen drehen; mit dem Wert 0 wird gelöscht",
|
||||
),
|
||||
("Radius", "Radius"),
|
||||
("Remove skew correction", "Skew-Korrektur entfernen"),
|
||||
];
|
||||
@@ -987,4 +987,12 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Unsaved changes", "Cambios sin guardar"),
|
||||
("Don't save", "No guardar"),
|
||||
("Save the changes to {name} before closing?", "¿Guardar los cambios de {name} antes de cerrar?"),
|
||||
("Skew correction", "Corrección de sesgo"),
|
||||
("Paint skew in the 2D view", "Pintar el sesgo en la vista 2D"),
|
||||
(
|
||||
"Drag in the 2D view to paint where the bake rays turn onto the base normal; paint with a value of 0 to erase",
|
||||
"Arrastra en la vista 2D para pintar dónde los rayos del bake se giran hacia la normal base; pinta con valor 0 para borrar",
|
||||
),
|
||||
("Radius", "Radio"),
|
||||
("Remove skew correction", "Quitar la corrección de sesgo"),
|
||||
];
|
||||
@@ -1002,4 +1002,12 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Unsaved changes", "Modifications non enregistrées"),
|
||||
("Don't save", "Ne pas enregistrer"),
|
||||
("Save the changes to {name} before closing?", "Enregistrer les modifications de {name} avant de fermer ?"),
|
||||
("Skew correction", "Correction d'inclinaison"),
|
||||
("Paint skew in the 2D view", "Peindre l'inclinaison dans la vue 2D"),
|
||||
(
|
||||
"Drag in the 2D view to paint where the bake rays turn onto the base normal; paint with a value of 0 to erase",
|
||||
"Faites glisser dans la vue 2D pour peindre où les rayons du bake se tournent vers la normale de base ; peignez avec la valeur 0 pour effacer",
|
||||
),
|
||||
("Radius", "Rayon"),
|
||||
("Remove skew correction", "Supprimer la correction d'inclinaison"),
|
||||
];
|
||||
@@ -996,4 +996,12 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Unsaved changes", "Modifiche non salvate"),
|
||||
("Don't save", "Non salvare"),
|
||||
("Save the changes to {name} before closing?", "Salvare le modifiche a {name} prima di chiudere?"),
|
||||
("Skew correction", "Correzione dell'inclinazione"),
|
||||
("Paint skew in the 2D view", "Dipingi l'inclinazione nella vista 2D"),
|
||||
(
|
||||
"Drag in the 2D view to paint where the bake rays turn onto the base normal; paint with a value of 0 to erase",
|
||||
"Trascina nella vista 2D per dipingere dove i raggi del bake si orientano verso la normale di base; dipingi con valore 0 per cancellare",
|
||||
),
|
||||
("Radius", "Raggio"),
|
||||
("Remove skew correction", "Rimuovi la correzione dell'inclinazione"),
|
||||
];
|
||||
@@ -969,4 +969,12 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Unsaved changes", "未保存の変更"),
|
||||
("Don't save", "保存しない"),
|
||||
("Save the changes to {name} before closing?", "閉じる前に {name} の変更を保存しますか?"),
|
||||
("Skew correction", "スキュー補正"),
|
||||
("Paint skew in the 2D view", "2Dビューでスキューをペイント"),
|
||||
(
|
||||
"Drag in the 2D view to paint where the bake rays turn onto the base normal; paint with a value of 0 to erase",
|
||||
"2Dビューでドラッグして、ベイクのレイがベース法線へ向かう箇所をペイントします。値0でペイントすると消去されます",
|
||||
),
|
||||
("Radius", "半径"),
|
||||
("Remove skew correction", "スキュー補正を削除"),
|
||||
];
|
||||
@@ -954,4 +954,12 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Unsaved changes", "저장되지 않은 변경 사항"),
|
||||
("Don't save", "저장 안 함"),
|
||||
("Save the changes to {name} before closing?", "닫기 전에 {name}의 변경 사항을 저장할까요?"),
|
||||
("Skew correction", "스큐 보정"),
|
||||
("Paint skew in the 2D view", "2D 뷰에서 스큐 칠하기"),
|
||||
(
|
||||
"Drag in the 2D view to paint where the bake rays turn onto the base normal; paint with a value of 0 to erase",
|
||||
"2D 뷰에서 드래그하여 베이크 레이가 기본 노멀 쪽으로 향하는 위치를 칠합니다. 값 0으로 칠하면 지워집니다",
|
||||
),
|
||||
("Radius", "반경"),
|
||||
("Remove skew correction", "스큐 보정 제거"),
|
||||
];
|
||||
@@ -984,4 +984,12 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Unsaved changes", "Alterações não salvas"),
|
||||
("Don't save", "Não salvar"),
|
||||
("Save the changes to {name} before closing?", "Salvar as alterações em {name} antes de fechar?"),
|
||||
("Skew correction", "Correção de inclinação"),
|
||||
("Paint skew in the 2D view", "Pintar a inclinação na vista 2D"),
|
||||
(
|
||||
"Drag in the 2D view to paint where the bake rays turn onto the base normal; paint with a value of 0 to erase",
|
||||
"Arraste na vista 2D para pintar onde os raios do bake se voltam para a normal base; pinte com valor 0 para apagar",
|
||||
),
|
||||
("Radius", "Raio"),
|
||||
("Remove skew correction", "Remover a correção de inclinação"),
|
||||
];
|
||||
@@ -900,4 +900,12 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Unsaved changes", "未保存的更改"),
|
||||
("Don't save", "不保存"),
|
||||
("Save the changes to {name} before closing?", "关闭前是否保存对 {name} 的更改?"),
|
||||
("Skew correction", "倾斜校正"),
|
||||
("Paint skew in the 2D view", "在 2D 视图中绘制倾斜"),
|
||||
(
|
||||
"Drag in the 2D view to paint where the bake rays turn onto the base normal; paint with a value of 0 to erase",
|
||||
"在 2D 视图中拖动,绘制烘焙射线转向基础法线的位置;以值 0 绘制可擦除",
|
||||
),
|
||||
("Radius", "半径"),
|
||||
("Remove skew correction", "移除倾斜校正"),
|
||||
];
|
||||
@@ -255,6 +255,25 @@ pub struct UiState {
|
||||
/// The baker whose parameters bake mode shows (None: the common parameters).
|
||||
#[serde(default)]
|
||||
pub bake_baker: Option<BakedMap>,
|
||||
/// The brush that paints the skew correction map in the 2D view of bake mode.
|
||||
#[serde(default)]
|
||||
pub skew_brush: SkewBrush,
|
||||
}
|
||||
|
||||
/// Settings of the skew correction brush (radius in UV units).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct SkewBrush {
|
||||
pub on: bool,
|
||||
pub radius: f32,
|
||||
/// 1 turns the rays onto the base normal, 0 erases.
|
||||
pub value: f32,
|
||||
pub hardness: f32,
|
||||
}
|
||||
|
||||
impl Default for SkewBrush {
|
||||
fn default() -> Self {
|
||||
SkewBrush { on: false, radius: 0.03, value: 1.0, hardness: 0.5 }
|
||||
}
|
||||
}
|
||||
|
||||
impl UiState {
|
||||
@@ -297,6 +316,7 @@ impl Default for UiState {
|
||||
recent: Vec::new(),
|
||||
keymap: Keymap::new(),
|
||||
bake_baker: None,
|
||||
skew_brush: SkewBrush::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,7 +46,8 @@ pub fn central(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
let full = ui.max_rect();
|
||||
let mode = app.ui.mode;
|
||||
path_keys(app, ui);
|
||||
let layout = if mode == crate::state::Mode::Painting { app.ui.layout } else { ViewLayout::Only3D };
|
||||
// Bake mode shows the 3D view alone, except while the skew brush needs the 2D view to paint in.
|
||||
let layout = if mode == crate::state::Mode::Painting || app.ui.skew_brush.on { app.ui.layout } else { ViewLayout::Only3D };
|
||||
match layout {
|
||||
ViewLayout::Only3D => view_3d(app, ui, full, &mut sync),
|
||||
ViewLayout::Only2D => view_2d(app, ui, full, &mut sync),
|
||||
@@ -836,6 +837,10 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
|
||||
let uv = to_uv(p);
|
||||
app.run("tool.cloneSource", json!({"uv": [uv.x, uv.y]}));
|
||||
}
|
||||
let skew_on = app.ui.mode == crate::state::Mode::Baking && app.ui.skew_brush.on && !alt;
|
||||
if skew_on {
|
||||
skew_input(app, ui, &resp, &to_uv);
|
||||
}
|
||||
let painting = app.ui.mode == crate::state::Mode::Painting && !alt && !v_held;
|
||||
if painting && path_tool {
|
||||
path_input(app, ui, &resp, true, |_, p| Some(to_uv(p).extend(0.0)), show);
|
||||
@@ -898,9 +903,60 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
|
||||
if app.ui.mode == crate::state::Mode::Painting && path_tool {
|
||||
path_overlay(app, ui, rect, &resp, true, show);
|
||||
}
|
||||
if app.ui.mode == crate::state::Mode::Baking {
|
||||
skew_overlay(app, ui, &painter, to(0.0, 1.0), to(1.0, 0.0));
|
||||
if skew_on && let Some(hover) = resp.hover_pos() {
|
||||
let r = (to(app.ui.skew_brush.radius, 0.0).x - to(0.0, 0.0).x).abs().max(2.0);
|
||||
painter.circle_stroke(hover, r, Stroke::new(1.0, Color32::from_white_alpha(200)));
|
||||
}
|
||||
}
|
||||
view_header(app, ui, rect, "v2d");
|
||||
axis_gizmo(ui, rect, app, true);
|
||||
let name = app.session.doc.project.texture_sets.get(ts).map(|t| t.name.clone()).unwrap_or_default();
|
||||
ui.painter().text(rect.right_bottom() + vec2(-10.0, -10.0), egui::Align2::RIGHT_BOTTOM, name, egui::FontId::proportional(11.0), tk.viewport_text);
|
||||
let _ = (RichText::new(""), Channel::BaseColor);
|
||||
}
|
||||
|
||||
/// Paint the skew map under the pointer in the 2D view (a click is one dab, a drag a stroke).
|
||||
fn skew_input(app: &mut TextureCraftApp, ui: &Ui, resp: &egui::Response, to_uv: &dyn Fn(egui::Pos2) -> Vec2) {
|
||||
let last = ui.scope_id().with("skew_last");
|
||||
let brush = app.ui.skew_brush;
|
||||
let started = resp.drag_started_by(PointerButton::Primary) || resp.clicked_by(PointerButton::Primary);
|
||||
if !(started || resp.dragged_by(PointerButton::Primary)) {
|
||||
return;
|
||||
}
|
||||
let Some(p) = resp.interact_pointer_pos() else { return };
|
||||
let uv = to_uv(p);
|
||||
let previous: Option<[f32; 2]> = if started { None } else { ui.data(|d| d.get_temp(last)) };
|
||||
let points: Vec<[f32; 2]> = previous.into_iter().chain([[uv.x, uv.y]]).collect();
|
||||
if app.run("bake.skew.paint", json!({"points": points, "radius": brush.radius, "value": brush.value, "hardness": brush.hardness})).is_some() {
|
||||
ui.data_mut(|d| d.insert_temp(last, [uv.x, uv.y]));
|
||||
}
|
||||
}
|
||||
|
||||
/// The skew map as a translucent orange layer over the UV square from `top_left` to `bottom_right`.
|
||||
fn skew_overlay(app: &TextureCraftApp, ui: &Ui, painter: &egui::Painter, top_left: egui::Pos2, bottom_right: egui::Pos2) {
|
||||
let Some(k) = app.session.bake_meshes.skew.as_ref().filter(|k| k.values.len() > 1) else { return };
|
||||
let key = (app.session.bake_meshes.skew_rev, std::sync::Arc::as_ptr(k) as usize);
|
||||
let id = ui.scope_id().with("skew_overlay_texture");
|
||||
let cached: Option<((u64, usize), egui::TextureHandle)> = ui.data(|d| d.get_temp(id));
|
||||
let tex = match cached {
|
||||
Some((c, t)) if c == key => t,
|
||||
_ => {
|
||||
// At most 256 texels a side: the overlay is a guide, not the map.
|
||||
let (w, h) = (k.width as usize, k.height as usize);
|
||||
let (ow, oh) = (w.min(256), h.min(256));
|
||||
let mut rgba = Vec::with_capacity(ow * oh * 4);
|
||||
for y in 0..oh {
|
||||
for x in 0..ow {
|
||||
let v = k.values.get((y * h / oh) * w + x * w / ow).copied().unwrap_or(0.0).clamp(0.0, 1.0);
|
||||
rgba.extend_from_slice(&[255, 140, 40, (v * 170.0) as u8]);
|
||||
}
|
||||
}
|
||||
let tex = ui.ctx().load_texture("skew_overlay", egui::ColorImage::from_rgba_unmultiplied([ow, oh], &rgba), egui::TextureOptions::NEAREST);
|
||||
ui.data_mut(|d| d.insert_temp(id, (key, tex.clone())));
|
||||
tex
|
||||
}
|
||||
};
|
||||
painter.image(tex.id(), Rect::from_two_pos(top_left, bottom_right), Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE);
|
||||
}
|
||||
@@ -792,6 +792,9 @@ fn common_params(app: &mut TextureCraftApp, ui: &mut Ui, b: &mut BakeSettings) {
|
||||
});
|
||||
});
|
||||
|
||||
ui.add_space(6.0);
|
||||
skew_section(app, ui);
|
||||
|
||||
ui.add_space(6.0);
|
||||
if ui.button(tr("Apply to all texture sets")).on_hover_text(tr("Copy these bake settings to every texture set")).clicked() {
|
||||
let mut p = bake_cmds::settings_params(b);
|
||||
@@ -803,6 +806,27 @@ fn common_params(app: &mut TextureCraftApp, ui: &mut Ui, b: &mut BakeSettings) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Skew correction: paint a map over the UV atlas that turns the bake rays onto the base normal.
|
||||
fn skew_section(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
ui.label(caption(tr("Skew correction")));
|
||||
let has = app.session.bake_meshes.skew.is_some();
|
||||
let mut brush = app.ui.skew_brush;
|
||||
ui.checkbox(&mut brush.on, tr("Paint skew in the 2D view"))
|
||||
.on_hover_text(tr("Drag in the 2D view to paint where the bake rays turn onto the base normal; paint with a value of 0 to erase"));
|
||||
if brush.on {
|
||||
slider(ui, tr("Radius"), &mut brush.radius, 0.002..=0.2, 3);
|
||||
slider(ui, tr("Value"), &mut brush.value, 0.0..=1.0, 2);
|
||||
slider(ui, tr("Hardness"), &mut brush.hardness, 0.0..=1.0, 2);
|
||||
}
|
||||
if brush.on && !app.ui.skew_brush.on && app.ui.layout == crate::state::ViewLayout::Only3D {
|
||||
app.ui.layout = crate::state::ViewLayout::Split;
|
||||
}
|
||||
app.ui.skew_brush = brush;
|
||||
if has && ui.button(tr("Remove skew correction")).clicked() {
|
||||
app.run("bake.skew.clear", json!({}));
|
||||
}
|
||||
}
|
||||
|
||||
/// A combo box picking one of `options` (value, label).
|
||||
fn choice<T: Copy + PartialEq>(ui: &mut Ui, label: &str, value: &mut T, options: &[(T, &str)]) {
|
||||
let shown = options.iter().find(|(v, _)| v == value).map_or("", |(_, l)| *l);
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
//! Bake mode: with the skew brush on, dragging in the 2D view paints the skew map, and the
|
||||
//! brush controls are in the Bake panel.
|
||||
|
||||
use egui_kittest::Harness;
|
||||
use egui_kittest::kittest::Queryable;
|
||||
use texturecraft_ui_egui::TextureCraftApp;
|
||||
use texturecraft_ui_egui::state::{Mode, ViewLayout};
|
||||
|
||||
fn harness() -> Harness<'static, TextureCraftApp> {
|
||||
let session = texturecraft_engine::sample_session(256, 64).unwrap();
|
||||
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
|
||||
h.state_mut().ui.mode = Mode::Baking;
|
||||
h.state_mut().ui.layout = ViewLayout::Only2D;
|
||||
h.run_steps(4);
|
||||
h
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_bake_panel_has_the_skew_brush_and_dragging_paints_the_map() {
|
||||
let mut h = harness();
|
||||
h.get_by_label("Skew correction");
|
||||
assert!(h.state().session.bake_meshes.skew.is_none() && !h.state().ui.skew_brush.on);
|
||||
// Off: a drag in the view paints nothing.
|
||||
h.drag_at(egui::pos2(600.0, 500.0));
|
||||
h.hover_at(egui::pos2(800.0, 500.0));
|
||||
h.drop_at(egui::pos2(800.0, 500.0));
|
||||
h.run_steps(3);
|
||||
assert!(h.state().session.bake_meshes.skew.is_none(), "the brush is off");
|
||||
|
||||
// On: the checkbox turns it on, and the same drag makes a map with paint along the stroke.
|
||||
h.get_by_label("Paint skew in the 2D view").click();
|
||||
h.run_steps(3);
|
||||
assert!(h.state().ui.skew_brush.on);
|
||||
h.get_by_label("Radius");
|
||||
h.drag_at(egui::pos2(600.0, 500.0));
|
||||
h.run_steps(2);
|
||||
h.hover_at(egui::pos2(800.0, 500.0));
|
||||
h.run_steps(2);
|
||||
h.drop_at(egui::pos2(800.0, 500.0));
|
||||
h.run_steps(3);
|
||||
let map = h.state().session.bake_meshes.skew.clone().expect("the stroke made a skew map");
|
||||
let painted = map.values.iter().filter(|v| **v > 0.5).count();
|
||||
assert!(painted > 50 && painted < map.values.len() / 2, "a stroke, not the whole map: {painted} of {}", map.values.len());
|
||||
|
||||
// Removing it from the panel clears the map.
|
||||
h.get_by_label("Remove skew correction").click();
|
||||
h.run_steps(3);
|
||||
assert!(h.state().session.bake_meshes.skew.is_none());
|
||||
}
|
||||
Reference in new issue
Block a user