Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
100 changes: 100 additions & 0 deletions src/components/editors/MeshPaintPanel.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
<script module>
/** the painter (meshPaint.js), imported from THIS lazy chunk so its long preload list stays out of the boot one */
export function loadPainter() {
return import('$lib/meshPaint');
}
</script>

<script>
// 102 M6: the UV editor's brush panel for painting on meshes (channel, value, hardness / opacity / flow, eraser,
// Mirror X, stamp, new-map size, channel view, what a stroke paints). A lazy chunk: UvEditor imports it with the
// painter (meshPaint.js) when Paint is armed, so none of it is in the boot bundle.
import Icon from '../ui/Icon.svelte';
import HudImagePicker from '../hud/HudImagePicker.svelte';
import {
paintChannel, paintValue, paintHardness, paintOpacity, paintFlow, paintErase, paintMirror, paintStamp,
paintMapSize, paintShowChannel, paintTargetInfo
} from '$lib/meshPaintPrefs';

const CHANNEL_CHOICES = /** @type {const} */ ([
['color', 'Colour', 'Paint the base colour'],
['roughness', 'Rough', 'Paint roughness: white is rough, black is shiny'],
['metalness', 'Metal', 'Paint metalness: white is metal, black is not'],
['emissive', 'Glow', 'Paint emission: where the surface glows, in the brush colour']
]);
</script>

<div class="mt-3 text-[11px] text-text-muted">Channel</div>
<div id="paint-channel" class="mt-1 grid grid-cols-4 gap-1" role="radiogroup" aria-label="Paint channel">
{#each CHANNEL_CHOICES as [value, label, hint] (value)}
<button
type="button"
role="radio"
aria-checked={$paintChannel === value}
data-value={value}
title={hint}
class={'rounded-sm px-1 py-0.5 text-[11px] ' + ($paintChannel === value ? 'bg-accent-fill text-on-accent' : 'bg-surface-2 text-text-2 hover:bg-surface-active')}
onclick={() => paintChannel.set(/** @type {any} */ (value))}>{label}</button>
{/each}
</div>
{#if $paintChannel === 'roughness' || $paintChannel === 'metalness'}
<label class="mt-2 block text-[11px] text-text-muted" title="The value the brush paints. A map multiplies the material's own slider.">
Value <span class="tabular-nums text-text-2">{$paintValue.toFixed(2)}</span>
<input id="paint-value" type="range" min="0" max="1" step="0.01" class="mt-1 w-full accent-accent"
value={$paintValue} oninput={(e) => paintValue.set(parseFloat(e.currentTarget.value) || 0)} />
</label>
{/if}
<label class="mt-2 block text-[11px] text-text-muted" title="1 is a hard edge; lower fades the edge softly">
Hardness <span class="tabular-nums text-text-2">{Math.round($paintHardness * 100)}%</span>
<input id="paint-hardness" type="range" min="0" max="1" step="0.01" class="mt-1 w-full accent-accent"
value={$paintHardness} oninput={(e) => paintHardness.set(parseFloat(e.currentTarget.value))} />
</label>
<label class="mt-2 block text-[11px] text-text-muted" title="The most one stroke can reach, however often you go over a spot">
Opacity <span class="tabular-nums text-text-2">{Math.round($paintOpacity * 100)}%</span>
<input id="paint-opacity" type="range" min="0.01" max="1" step="0.01" class="mt-1 w-full accent-accent"
value={$paintOpacity} oninput={(e) => paintOpacity.set(parseFloat(e.currentTarget.value))} />
</label>
<label class="mt-2 block text-[11px] text-text-muted" title="How much each dab adds: low flow builds up as you go over a spot">
Flow <span class="tabular-nums text-text-2">{Math.round($paintFlow * 100)}%</span>
<input id="paint-flow" type="range" min="0.01" max="1" step="0.01" class="mt-1 w-full accent-accent"
value={$paintFlow} oninput={(e) => paintFlow.set(parseFloat(e.currentTarget.value))} />
</label>
<div class="mt-2 flex gap-1">
<button id="paint-erase" type="button" aria-pressed={$paintErase}
title="Eraser: paints back to the material's own colour or value (white for colour, roughness and metalness, black for glow)"
class={'flex flex-1 items-center justify-center gap-1 rounded-sm px-2 py-0.5 text-[11px] ' + ($paintErase ? 'bg-accent-fill text-on-accent' : 'bg-surface-2 text-text-2 hover:bg-surface-active')}
onclick={() => paintErase.update((v) => !v)}><Icon name="eraser" size={12} aria-hidden="true" />Eraser</button>
<button id="paint-mirror" type="button" aria-pressed={$paintMirror}
title="Mirror X: a stroke on the model also paints its mirror across the object's own X axis (not in this 2D view)"
class={'flex flex-1 items-center justify-center gap-1 rounded-sm px-2 py-0.5 text-[11px] ' + ($paintMirror ? 'bg-accent-fill text-on-accent' : 'bg-surface-2 text-text-2 hover:bg-surface-active')}
onclick={() => paintMirror.update((v) => !v)}><Icon name="flip-horizontal" size={12} aria-hidden="true" />Mirror X</button>
</div>
<div class="mt-2 text-[11px] text-text-muted" title="Use an image as the brush tip: its transparency (or its dark parts) is where it paints">Stamp</div>
<div id="paint-stamp" class="mt-1 flex">
<HudImagePicker hash={$paintStamp} onpick={(next) => paintStamp.set(next)} />
</div>
<div class="mt-2 text-[11px] text-text-muted" title="How big a new map is when a stroke paints a slot that has no image yet">New map</div>
<div id="paint-map-size" class="mt-1 flex gap-1" role="radiogroup" aria-label="New map size">
{#each [[1024, '1k'], [2048, '2k']] as [value, label] (value)}
<button type="button" role="radio" aria-checked={$paintMapSize === value} data-value={value}
title={'A new map is ' + value + ' x ' + value + ' pixels'}
class={'flex-1 rounded-sm px-2 py-0.5 text-[11px] ' + ($paintMapSize === value ? 'bg-accent-fill text-on-accent' : 'bg-surface-2 text-text-2 hover:bg-surface-active')}
onclick={() => paintMapSize.set(/** @type {any} */ (value))}>{label}</button>
{/each}
</div>
<label class="mt-2 flex items-center gap-2 text-[11px] text-text-muted" title="Show the channel you are painting by itself on the model (only on your screen)">
<input id="paint-show-channel" type="checkbox" class="tp-check" checked={$paintShowChannel}
onchange={(e) => paintShowChannel.set(e.currentTarget.checked)} />
Show this channel alone
</label>
{#if $paintTargetInfo?.mode === 'vertex'}
<p id="paint-target-info" class="mt-2 rounded-sm bg-surface-2 p-1.5 text-[10px] leading-relaxed text-ink-warn" role="status">
{$paintTargetInfo.reason}
</p>
{/if}
<p class="mt-2 text-[10px] leading-relaxed text-text-faint">
Paint on the model in the viewport too: drag over the selected object. <span class="text-text-2">Alt+click</span>
picks the colour (or value) under the cursor, <span class="text-text-2">[</span> and <span class="text-text-2">]</span>
size the brush, <span class="text-text-2">Esc</span> cancels a stroke. A shared material asks whether to paint
every object that wears it.
</p>
89 changes: 86 additions & 3 deletions src/components/editors/UvEditor.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,74 @@
$objectsGroup;
return textureImageOf(target, slot);
});
const backdrop = $derived(paintCanvas ?? mapImage ?? liveImage);
// 102 M6: the painter, loaded on first use (Paint armed). `paintMod` is the loaded module or null.
// Its brush panel and settings ride the same lazy load, so none of it is in the boot bundle (boot rule).
let paintMod = $state(/** @type {any} */ (null));
let PaintPanel = $state(/** @type {any} */ (null));
/** @type {Promise<any> | null} */ let paintLoading = null;
function loadPaint() {
// the panel chunk imports the painter: a dynamic import's preload list (the painter's whole static graph,
// ~400 chunk names) is written into the IMPORTING chunk, so it must not be this boot one (5 KB gz measured)
paintLoading ??= import('./MeshPaintPanel.svelte').then(async (panel) => {
// the panel shows as soon as its own small chunk lands; the painter follows (the old brush paints meanwhile)
PaintPanel = panel.default;
paintMod = await panel.loadPainter();
});
return paintLoading;
}
$effect(() => {
if ($uvTool === 'paint') untrack(() => void loadPaint());
});
/** the brush state the editor needs (channel, channel view, and whether meshPaint owns the stroke) */
let paintUi = $state({ channel: 'color', showChannel: false, newBrush: false });
$effect(() => {
const mod = paintMod;
if (!mod) return;
return mod.paintUi.subscribe((/** @type {any} */ v) => (paintUi = v));
});
const usesNewBrush = $derived(paintUi.newBrush);
/** which painter owns the stroke in flight: the shipped one (`uv`) or meshPaint (`mesh`) */
let paintEngine = /** @type {'uv'|'mesh'} */ ('uv');
// a roughness / metalness / emission channel shows ITS map behind the wire (none yet: the first stroke makes one)
const channelImage = $derived.by(() => {
$uvPaintTick;
$objectsGroup;
if ($uvTool !== 'paint' || paintUi.channel === 'color' || !paintMod) return undefined;
return paintMod.channelBackdrop(target, slot, paintUi.channel) ?? null;
});
const backdrop = $derived(channelImage !== undefined ? channelImage : paintCanvas ?? mapImage ?? liveImage);
// the brush on the MODEL: with Paint armed and the editor open, a drag on the selected object paints it
$effect(() => {
const on = $uvTool === 'paint' && !$uvEditorClose && !!target && !!paintMod;
if (!on) return;
const mod = paintMod;
const detach = untrack(() =>
mod.attachViewportPainting({ target: () => untrack(() => target), slot: () => untrack(() => slot) })
);
return detach;
});
// what a stroke on this object paints (map, or vertex colours and why), for the panel
$effect(() => {
$objectsGroup;
const mesh = target;
const s = slot;
if ($uvTool !== 'paint' || !paintMod) return;
untrack(() => (mesh ? paintMod.targetFor(mesh, s) : paintMod.clearTargetInfo()));
});
// LOCAL view: the painted channel alone on the model
$effect(() => {
const on = paintUi.showChannel && $uvTool === 'paint' && !$uvEditorClose && !!target && !!paintMod;
const mod = paintMod;
if (!on) {
untrack(() => mod?.hideChannelView());
return;
}
const mesh = target;
const s = slot;
const ch = paintUi.channel;
untrack(() => mod.showChannelView(mesh, s, ch));
return () => mod.hideChannelView();
});
// An imported (glTF) texture samples v=0 from the image TOP, while the editor
// draws v UP — so its backdrop has to be blitted vertically flipped or the view
// disagrees with the model about which end is which.
Expand Down Expand Up @@ -331,6 +398,7 @@
grab.cancel();
cancelUvDrag();
cancelPaintStroke();
paintMod?.cancelStroke();
selCluster = [];
hoverIndex = -1;
pivotPlaced = null; // an origin belongs to the map you placed it on
Expand Down Expand Up @@ -851,8 +919,19 @@
// The stroke opens ASYNChronously (the canvas has to carry the existing
// texture before the first dab), so claim the gesture NOW and let the
// pending moves queue behind the seed.
if ($uvTool === 'paint' && usesNewBrush && paintMod) {
// 102 M6: a new channel or brush paints through meshPaint (the same canvas for colour)
gesture = 'paint';
paintEngine = 'mesh';
attachDragListeners();
void paintMod.beginStroke({ uuid: target.uuid, slot, sp: 'uv', at: [toU(x), toV(y)], w: pressureOf(e) }).then((/** @type {boolean} */ ok) => {
if (!ok && gesture === 'paint') gesture = 'idle';
});
return;
}
if ($uvTool === 'paint') {
gesture = 'paint';
paintEngine = 'uv';
// 24-F1 (found on the way): this branch returned WITHOUT the window move/up
// pair, so a pointer stroke got its first dab and nothing else — no moves
// painted and no pointerup ever committed it (the uv-paint suite asserted only
Expand Down Expand Up @@ -956,7 +1035,8 @@
}
for (const sample of samples.length ? samples : [e]) {
const { x, y } = localPoint(sample);
paintMove(toU(x), toV(y), $uvBrushColor, brushUv(), pressureOf(sample));
if (paintEngine === 'mesh') paintMod?.strokeTo([toU(x), toV(y)], pressureOf(sample));
else paintMove(toU(x), toV(y), $uvBrushColor, brushUv(), pressureOf(sample));
}
}
}
Expand All @@ -977,7 +1057,8 @@

function onPointerUp(/** @type {PointerEvent} */ e) {
if (gesture === 'paint') {
endPaintStroke($uvBrushColor, brushUv());
if (paintEngine === 'mesh') paintMod?.endStroke();
else endPaintStroke($uvBrushColor, brushUv());
} else if (gesture === 'box' && marquee && target) {
const hits = uvIndicesInRect(target, slot, {
u0: toU(marquee.x0), v0: toV(marquee.y0), u1: toU(marquee.x1), v1: toV(marquee.y1)
Expand Down Expand Up @@ -1947,6 +2028,8 @@
Each stroke is one undo step; peers watch it live. A pen's pressure varies the
width (or the opacity); a mouse stroke is unchanged.
</p>
<!-- 102 M6: what the brush paints, and how (a lazy chunk, with the painter) -->
{#if PaintPanel}<PaintPanel />{/if}
</div>
{/if}
<div class="p-2 text-[11px] leading-relaxed text-text-muted">
Expand Down
6 changes: 6 additions & 0 deletions src/components/menu/Inspector.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,7 @@
saveSnapAnchorAsOrigin
} from '$lib/snapEngine';
import { peers, inspectorClose, inspectorKind, showToast, inspectorFilter, userdata, closeSelectionInspector } from '../../stores/appStore.js';
import { get as getStore } from 'svelte/store'; // 102 M6: the unlink send reads the peer once
// 78-int PL13: "changed by <peer / agent> · time" under the shared Configure Scene sections
import { sceneSectionEdits } from '$lib/sceneEditBy.js';
import { editLine } from '$lib/sceneEditByCore.js';
Expand Down Expand Up @@ -615,6 +616,11 @@
if (!uuid) return;
const count = sharedWith.length;
if (!unlinkMaterial(uuid)) return;
// 102 M6 (found on the way): the unlink used to stay on this machine, so a peer kept the objects linked
// and the next edit of this one changed both over there. An older peer ignores the parameter.
/** @type {any} */
const peer = getStore(peers);
peer?.send({ type: 'objectParameters', parameter: 'materialUnlink', uuid });
showToast(
'This object has its own material now — the other ' +
count +
Expand Down
2 changes: 2 additions & 0 deletions src/components/ui/Icon.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,7 @@
Eye,
EyeOff,
FileCode,
Eraser,
FileInput,
FilePlus,
FileText,
Expand Down Expand Up @@ -376,6 +377,7 @@
'file-input': FileInput,
'file-plus': FilePlus,
'file-text': FileText,
eraser: Eraser, // 102 M6 paint eraser
filter: Filter,
flag: Flag,
'flip-horizontal': FlipHorizontal,
Expand Down
1 change: 1 addition & 0 deletions src/lib/agentPresenceCore.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ const UUID_EDITS = new Set([
'group',
'lock',
'uvpaint',
'meshpaint',
'splineedit',
'graphcreate', // an object graph's id is its owner's uuid
'graphdelete'
Expand Down
4 changes: 4 additions & 0 deletions src/lib/commandsHandler.svelte.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import * as THREE from 'three';
import { notifyOn } from './notifyPrefs';
import { globalScene, objectsGroup, showGrid, TControls, lockedObjects, selectedObject, globalCamera, peerHands, pokeScene, beginSceneBatch, endSceneBatch } from '../stores/sceneStore.js';
import { receiveMapSlot, receiveTexTransform, receiveNormalStrength } from '$lib/materialMaps';
import { unlinkMaterial } from '$lib/materialSharing';
import { GLTFExporter } from 'three/addons/exporters/GLTFExporter.js';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { createGeometry, createLight, createGroup } from '$lib/geometries.svelte'
Expand Down Expand Up @@ -612,6 +613,9 @@ export async function objectParameters(data, from = 'peer') {
if (mesh) applyMap(mesh, data.map, data.slot ?? 0, typeof data.source === 'string' ? data.source : null);
} else if (data.parameter == 'materialParam') {
setMaterialParam(data.uuid, data.key, data.value, false);
} else if (data.parameter == 'materialUnlink') {
// 102 M6: "this object only" on a shared material — this object gets its own copy here too
unlinkMaterial(data.uuid);
} else if (data.parameter == 'mapSlot') {
receiveMapSlot(data); // 72 LK1: normal, roughness, metalness, emissive, AO
} else if (data.parameter == 'texTransform') {
Expand Down
3 changes: 3 additions & 0 deletions src/lib/debugHooks.js
Original file line number Diff line number Diff line change
Expand Up @@ -382,6 +382,9 @@ export const DEBUG_HOOKS = [
['moduleGallery', () => import('./moduleGallery')],
['moduleInstallJobs', () => import('./moduleInstallJobs')],
['uvEditor', () => import('./uvEditor')],
// 102 M6: paint on meshes (the lazy painter + its prefs leaf)
['meshPaint', () => import('./meshPaint')],
['meshPaintPrefs', () => import('./meshPaintPrefs')],
['uvUnwrap', () => import('./uvUnwrap')],
['meshTopology', () => import('./meshTopology')],
['meshBoolean', () => import('./meshBoolean')],
Expand Down
18 changes: 18 additions & 0 deletions src/lib/materialMaps.js
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,24 @@ export async function setObjectsMapSlot(uuids, key, file, slot = 0) {
return applied;
}

/**
* 102 M6: commit a PAINTED map slot. The brush has been drawing on a canvas installed as the slot's texture, so
* the slot's current image is no longer what undo should go back to: the caller passes the image it held when
* the stroke began (`before`, null when the stroke made the map). Records, applies and sends (the send fans to a
* shared material's other users, `broadcastMaterial`). Inside a caller's history batch when one is open.
* @param {string} uuid @param {string} key @param {string | null} before @param {string} url @param {number} [slot]
*/
export function commitPaintedMapSlot(uuid, key, before, url, slot = 0) {
const object = objectOf(uuid);
const material = object && materialAt(object, slot);
if (!material || !isMapSlotKey(key) || !(key in material) || !isMapSlotImage(url)) return false;
recordEntry({ kind: 'materialmaps', uuid, param: 'slot', key, ...(slot ? { slot } : {}), before: { value: before }, after: { value: url } });
applyMapSlotTo(material, key, url, object);
material.userData.tpEdited = true;
sendSlot(uuid, key, url, slot);
return true;
}

/**
* Clear a map slot on many objects, one undo step. A compressed (KTX2) map has no image to keep, so undo
* cannot bring that one back.
Expand Down
Loading
Loading