diff --git a/furniture-3d-system/src/app/diy/components/DiyBaseAccessoryMesh.tsx b/furniture-3d-system/src/app/diy/components/DiyBaseAccessoryMesh.tsx index fc62e2db..7dbce3c8 100644 --- a/furniture-3d-system/src/app/diy/components/DiyBaseAccessoryMesh.tsx +++ b/furniture-3d-system/src/app/diy/components/DiyBaseAccessoryMesh.tsx @@ -2,6 +2,7 @@ import { useEffect, useMemo } from 'react' import { xg0268BaseAccessory } from '@/lib/diy/xg0268' +import { diyBaseSupports } from '@/lib/diy/floor-contact' import type { CabinetStyle, DiyItem } from '@/lib/diy/types' import { createXg0268MetalLegGeometry } from '../lib/xg0268-metal-leg' import { createXg0268BallCasterGeometry } from '../lib/xg0268-ball-caster' @@ -10,22 +11,18 @@ import { createXg0268HardwareMaterials } from '../lib/xg0268-hardware-materials' export default function DiyBaseAccessoryMesh({ item, style }: { item: DiyItem; style: CabinetStyle }) { const accessory = xg0268BaseAccessory(item) const leg = useMemo(() => accessory?.kind === 'legs' - ? createXg0268MetalLegGeometry(accessory.height) : null, [accessory?.kind, accessory?.height]) + ? createXg0268MetalLegGeometry(accessory.height) : null, [accessory]) const caster = useMemo(() => accessory?.kind === 'wheels' - ? createXg0268BallCasterGeometry(accessory.height) : null, [accessory?.kind, accessory?.height]) + ? createXg0268BallCasterGeometry(accessory.height) : null, [accessory]) const finishes = useMemo(() => accessory ? createXg0268HardwareMaterials() : null, [accessory]) useEffect(() => () => { if (leg) Object.values(leg).forEach(geometry => geometry.dispose()) }, [leg]) useEffect(() => () => { caster?.forEach(part => part.geometry.dispose()) }, [caster]) useEffect(() => () => { finishes?.dispose() }, [finishes]) if (!accessory || !finishes) return null - const width = style.realSize.width * .01, depth = style.realSize.depth * .01 - const positions: [number, number][] = [ - [-width / 2 + .45, -depth / 2 + .45], [width / 2 - .45, -depth / 2 + .45], - [-width / 2 + .45, depth / 2 - .45], [width / 2 - .45, depth / 2 - .45], [0, 0], - ] return - {positions.map(([x, z], index) => - {leg ? + {diyBaseSupports(style.realSize, accessory.height, accessory.kind).map(({ x, z, rotation }, index) => + + {leg ? {(['plate', 'collar', 'tube'] as const).map(part => )} : caster?.map(part => )} diff --git a/furniture-3d-system/src/app/diy/components/DiyReferenceContactShadow.tsx b/furniture-3d-system/src/app/diy/components/DiyReferenceContactShadow.tsx new file mode 100644 index 00000000..f4d54cab --- /dev/null +++ b/furniture-3d-system/src/app/diy/components/DiyReferenceContactShadow.tsx @@ -0,0 +1,49 @@ +'use client' + +import { useEffect, useMemo } from 'react' +import { DataTexture, LinearFilter, RGBAFormat } from 'three' +import { createDiyCatalogAccess } from '@/lib/diy/catalog' +import { diyBaseSupports } from '@/lib/diy/floor-contact' +import type { DiyCatalogDTO, DiyItem } from '@/lib/diy/types' +import { xg0268BaseAccessory } from '@/lib/diy/xg0268' + +function softShadow(round: boolean, width: number, depth: number, spread: number) { + const size = 64 + const pixels = new Uint8Array(size * size * 4) + for (let y = 0; y < size; y++) for (let x = 0; x < size; x++) { + const u = Math.abs((x + .5) / size * 2 - 1), v = Math.abs((y + .5) / size * 2 - 1) + const dx = Math.max(0, (width / 2 + spread) * u - width / 2) + const dz = Math.max(0, (depth / 2 + spread) * v - depth / 2) + const distance = (round ? Math.hypot(u, v) : Math.max(dx, dz) / spread) + pixels[(y * size + x) * 4 + 3] = Math.round((round ? 108 : 68) * Math.max(0, 1 - distance) ** 2) + } + const texture = new DataTexture(pixels, size, size, RGBAFormat) + texture.magFilter = texture.minFilter = LinearFilter + texture.needsUpdate = true + return texture +} + +function Contact({ x, z, width, depth, round = false }: { + x: number; z: number; width: number; depth: number; round?: boolean +}) { + const spread = round ? 0 : .19 + const texture = useMemo(() => softShadow(round, width, depth, spread), [round, width, depth, spread]) + useEffect(() => () => texture.dispose(), [texture]) + return + + + +} + +export default function DiyReferenceContactShadow({ items, catalog }: { items: DiyItem[]; catalog: DiyCatalogDTO }) { + const { getStyle } = useMemo(() => createDiyCatalogAccess(catalog), [catalog]) + return <>{items.filter(item => item.supportId === 'floor').map(item => { + const size = getStyle(item.code).realSize + const accessory = xg0268BaseAccessory(item) + return accessory ? + {diyBaseSupports(size, accessory.height, accessory.kind).map(({ contactX, contactZ }, index) => + )} + : + })} +} diff --git a/furniture-3d-system/src/app/diy/components/DiyViewport.tsx b/furniture-3d-system/src/app/diy/components/DiyViewport.tsx index 93beb364..1d66410c 100644 --- a/furniture-3d-system/src/app/diy/components/DiyViewport.tsx +++ b/furniture-3d-system/src/app/diy/components/DiyViewport.tsx @@ -13,6 +13,7 @@ import DiyCabinetMesh from './DiyCabinetMesh' import DiyCameraRig from './DiyCameraRig' import DiyDimensions from './DiyDimensions' import DiyCaptureBridge, { type DiyCaptureRequest } from './DiyCaptureBridge' +import DiyReferenceContactShadow from './DiyReferenceContactShadow' import type { DiyCaptureRef } from '../lib/ai-capture' function Scene({ controller:c, disabled, grid, dimensions, capture, captureRef, onCapture, onCapturing }: { controller:DiyWorkbenchController;disabled:boolean;grid:boolean;dimensions:boolean;capture:DiyCaptureRequest|null @@ -54,6 +55,7 @@ function Scene({ controller:c, disabled, grid, dimensions, capture, captureRef, {grid&&!capture&&} + {capture && } {previewItems.map(item=> + {request && } {snapshot.items.map(item => { + const rotation = index === 4 ? -Math.PI / 2 : -Math.atan2(z, x) + const splay = kind === 'legs' ? (heightMm * .01 - .025) * legSlope : 0 + return { x, z, rotation, contactX: x + splay * Math.cos(rotation), contactZ: z - splay * Math.sin(rotation) } + }) +} + +export function diyFloorContactPrompt(items: DiyItem[], scene: boolean, cleanCutout: boolean) { + const floor = items.filter(item => item.supportId === 'floor') + if (!floor.length) return '' + const supports = floor.map(xg0268BaseAccessory) + const surface = scene ? 'room floor' : 'white studio surface' + const contacts = [ + supports.some(support => !support) ? 'Flat bases touch directly, with no bright gap.' : '', + supports.some(support => support?.kind === 'legs') ? 'Fitted foot pads touch; keep under-cabinet clearance.' : '', + supports.some(support => support?.kind === 'wheels') ? 'Fitted wheels touch; keep under-cabinet clearance.' : '', + ].filter(Boolean).join(' ') + const shadow = cleanCutout ? '' : scene ? 'Contact shadows start at the supports and match the room light.' : 'Contact shadows fade into pure white.' + return `Match the reference supports on the ${surface}. ${contacts} No added plinth, feet or wheels. ${shadow} ` +} diff --git a/furniture-3d-system/src/server/services/__tests__/diy-ai-render.service.test.ts b/furniture-3d-system/src/server/services/__tests__/diy-ai-render.service.test.ts index 2e48573e..e212c7af 100644 --- a/furniture-3d-system/src/server/services/__tests__/diy-ai-render.service.test.ts +++ b/furniture-3d-system/src/server/services/__tests__/diy-ai-render.service.test.ts @@ -19,6 +19,8 @@ import type { DiyAiRenderInput } from '@/lib/diy/ai-render' import { doorCatalog, doorSnapshot } from '@/lib/diy/__tests__/door-fittings.fixture' import { readXg0268Import, xg0268ImportDto } from '../../../../scripts/diy-xg0268/source' import { createDiyLayout } from '@/lib/diy/layout' +import sharp from 'sharp' +import { readDiyToolImage } from '../diy-image-template.service' jest.mock('@/server/repositories/diy-ai-render.repository', () => ({ diyAiRenderRepository: { findOwned: jest.fn(), listOwned: jest.fn(), create: jest.fn(), update: jest.fn() } })) jest.mock('@/server/repositories/diy-scheme.repository', () => ({ diySchemeRepository: { findOwned: jest.fn() } })) @@ -30,6 +32,10 @@ jest.mock('@/server/repositories/native-render.repository', () => ({ nativeRende jest.mock('../diy-ai-render.storage', () => ({ uploadDiyAiReference: jest.fn(), storeDiyAiResults: jest.fn(), discardDiyAiUploads: jest.fn() })) jest.mock('../prompt-optimizer.service', () => ({ promptOptimizerService: { optimize: jest.fn() } })) jest.mock('../diy-solid-door-colors.service', () => ({ prepareDiySolidDoorLock: jest.fn().mockResolvedValue(null) })) +jest.mock('../diy-image-template.service', () => ({ readDiyToolImage: jest.fn().mockRejectedValue(new Error('Fixture has no image')) })) +jest.mock('@/lib/object-storage-url', () => ({ + readObjectStorageKeyFromUrl: (url: string) => new URL(url, 'http://localhost').searchParams.get('key'), +})) jest.mock('../diy-ai-render.delete', () => ({ deleteDiyAiRender: jest.fn() })) const repo = jest.mocked(diyAiRenderRepository) const user: AuthUser = { id: 'designer', name: 'Designer', role: 'SUPER_ADMIN', email: 'diy@example.local', status: 'ACTIVE' } @@ -148,6 +154,48 @@ test('fixed Gujia SKU requests no exterior shadow while normal white images keep await diyAiRenderService.create({ ...input, requestId: 'ea7ade88-9db3-412c-86ec-94e4ba222511' }, user) expect(jest.mocked(enqueueNativeImageGeneration).mock.calls[0][0].input.prompt).toContain('a tight natural contact shadow') }) + +test('the three white outputs send the same distinct cabinet and wood door samples; scene keeps its own rules', async () => { + const woodDoor = { name: '经典北美黑胡桃色', itemCode: 'SJ038082', barcode: 'SJ038082N1410V01', + image: '/api/storage/object?key=product-development%2Fdiy%2FSJ0380%2Fwalnut.jpg' } + const catalog = { ...catalogFixture, sourceHash: 'b'.repeat(64), patterns: [woodDoor] } + jest.mocked(diyCatalogService.getWorkbenchCatalog).mockResolvedValue(catalog) + const snapshot = { ...input.snapshot, doors: { 'cabinet-one#c1r1': woodDoor.itemCode } } + const solid = async (background: string) => ({ buffer: await sharp({ create: { width: 400, height: 300, channels: 3, background } }).png().toBuffer(), + contentType: 'image/png', width: 400, height: 300 }) + const elm = await solid('#a3a3a3'), walnut = await solid('#a65f36') + jest.mocked(readDiyToolImage).mockImplementation(async key => key.endsWith('walnut.jpg') ? walnut : elm) + try { + const common = { ...input, catalogHash: catalog.sourceHash, snapshot, prompt: 'Keep photographic composition.' } + const variants: DiyAiRenderInput[] = [common, { ...common, eightView: { groupId: 'ea7ade88-9db3-412c-86ec-94e4ba222519', index: 4 }, + cameraView: { position: [0, 3, -12], target: [0, 2, 0] } }, + { ...common, mode: 'sku', sku: { template: 'gujia', background: 'white', title: '', color: '', features: '', showDimensions: true } }, + { ...common, mode: 'scene', userPrompt: 'Bright living room' }] + for (const variant of variants) { + repo.findOwned.mockResolvedValue(null) + await diyAiRenderService.create(variant, user) + } + const requests = jest.mocked(enqueueNativeImageGeneration).mock.calls.map(([options]) => options.input) + const sheets = requests.slice(0, 3).map(request => { + expect(request.prompt).toContain('A = Black elm (cabinet body); B = Classic North American black walnut (wood-grain door)') + expect(request.prompt).toContain('neutral white balance') + expect(request.prompt).not.toContain('never lighten dark wood') + expect(request.referenceImage?.buffer).toEqual(Buffer.from([1, 2, 3])) + return request.additionalReferenceImages?.find(image => image.fileName === 'diy-wood-finish-samples.jpg')?.buffer + }) + expect(sheets[0]).toBeDefined() + expect(sheets[1]).toEqual(sheets[0]); expect(sheets[2]).toEqual(sheets[0]) + const { data, info } = await sharp(sheets[0]!).raw().toBuffer({ resolveWithObject: true }) + const pixel = (x: number) => [...data.subarray((80 * info.width + x) * 3, (80 * info.width + x) * 3 + 3)] + expect(Math.max(...pixel(100))).toBeLessThan(100) + expect(pixel(370)[0] - pixel(370)[2]).toBeGreaterThan(60) + expect(requests[2].prompt).toContain('NO cast shadow, contact shadow, floor shadow') + expect(requests[3].prompt).toContain('never lighten dark wood') + expect(requests[3].additionalReferenceImages).toEqual([]) + } finally { + jest.mocked(readDiyToolImage).mockRejectedValue(new Error('Fixture has no image')) + } +}) test('retrying the same owned request returns its record without generating again', async () => { const first = await diyAiRenderService.create(input,user) repo.findOwned.mockResolvedValue(row as never) @@ -196,6 +244,7 @@ test.each(['gujia', 'suofeiya'])('%s scene freezes the variant, uses scene light expect(request.prompt).toContain(`fixed ${template === 'suofeiya' ? 'Sofia' : 'Gujia'} template and true dimensions will be added separately`) expect(request.prompt).toContain('MAY change the photographic camera angle') expect(request.prompt).toContain('Scene requests describe the environment, lighting and removable styling objects') + expect(request.prompt).toContain('Flat bases touch directly, with no bright gap.') expect(request.prompt).toContain('自然搭配柜上、柜内和周围的陈设') expect(request.prompt).not.toMatch(/Do not place scene objects over the product|Do not add objects in front of or touching the cabinet/) expect(request.prompt).toContain('surrounding furniture, objects and room at believable real-world scale') @@ -319,6 +368,7 @@ test.each(['white', 'scene', 'gujia-scene', 'suofeiya-scene', 'batch', 'eight-vi expect(request.prompt).toContain('柜体榆木黑色;层板禅香色') expect(request.prompt).toContain('右门位(door-2):右侧铰接右开,向外平开约100°') expect(request.prompt).toContain('NO wood grain or printed artwork') + expect(request.prompt).toContain('Fitted wheels touch; keep under-cabinet clearance.') expect(request.negativePrompt).toContain('user restriction') expect(request.negativePrompt).toContain('keys, keyholes, dangling keys') if (skuScene) { diff --git a/furniture-3d-system/src/server/services/__tests__/diy-sku-image.test.ts b/furniture-3d-system/src/server/services/__tests__/diy-sku-image.test.ts index 299f3380..78777ed9 100644 --- a/furniture-3d-system/src/server/services/__tests__/diy-sku-image.test.ts +++ b/furniture-3d-system/src/server/services/__tests__/diy-sku-image.test.ts @@ -41,6 +41,16 @@ test('finished SKU bytes, dimensions and stable names are persisted, while ordin .composite([{ input: logo }]).raw().toBuffer() const actual = await sharp(square).extract({ left: 77, top: 110, width: 365, height: 47 }).ensureAlpha().raw().toBuffer() expect(actual.equals(expected)).toBe(true) + // The shadow touches the product, keeps the rest of the white canvas clean, + // and preserves the product pixels. + const center = await sharp(square).extract({ left: 720, top: 0, width: 1, height: 1257 }) + .removeAlpha().raw().toBuffer() + let productBottom = -1 + for (let y = 0; y < 1257; y++) if (center[y * 3] < 80) productBottom = y + expect(productBottom).toBeGreaterThan(0) + expect(center[(productBottom - 4) * 3]).toBe(49) + expect(center[(productBottom + 2) * 3]).toBeLessThan(254) + expect(center[(productBottom + 20) * 3]).toBe(255) }) test('scene SKU fills the header with room pixels, overlays the fixed brand and keeps the black footer', async () => { diff --git a/furniture-3d-system/src/server/services/diy-ai-render.create.ts b/furniture-3d-system/src/server/services/diy-ai-render.create.ts index 73079800..6c99ff7c 100644 --- a/furniture-3d-system/src/server/services/diy-ai-render.create.ts +++ b/furniture-3d-system/src/server/services/diy-ai-render.create.ts @@ -22,6 +22,8 @@ import { isFixedDiySkuTemplate, normalizeDiySkuTemplate } from '@/lib/diy/sku/br import { diyScenePlacementPrompt } from './diy-scene-placement-prompt' import { prepareDiyBatchSceneAnchor } from './diy-batch-scene-lock' import { isXg0268 } from '@/lib/diy/xg0268' +import { DIY_WHITE_MATERIAL_LIGHTING, prepareDiyWhiteMaterialReference } from './diy-white-material-reference' +import { diyFloorContactPrompt } from '@/lib/diy/floor-contact' const json = (value: unknown) => JSON.parse(JSON.stringify(value)) as Prisma.InputJsonValue export async function createDiyAiRender(input: DiyAiRenderInput, user: AuthUser, catalog: DiyCatalogDTO, requestFingerprint = nativeRenderRequestFingerprint(input), batch?: DiyAiBatchMetadata) { @@ -36,6 +38,7 @@ export async function createDiyAiRender(input: DiyAiRenderInput, user: AuthUser, const scene = input.mode === 'scene' || input.mode === 'sku' && isDiySkuScene(input.sku) const structures = !scene && !sku?.template ? decodeReferenceImageDataUrls(input.structureReferenceImageDataUrls) : [] const colors = await prepareDiySolidDoorLock(input.solidDoorColorLock, catalog, input.snapshot) + const whiteMaterials = scene ? null : await prepareDiyWhiteMaterialReference(input.snapshot, catalog) const compositionKey = createHash('sha256').update(diyCompositionText(input.snapshot)).digest('hex') const codes = new Set(input.snapshot.items.map(item => item.code)) const materials = input.snapshot.items.flatMap(item => Object.values(resolveDiyMaterials(catalog, item)).filter(Boolean)) @@ -48,8 +51,11 @@ export async function createDiyAiRender(input: DiyAiRenderInput, user: AuthUser, const framing = room ? 'Use the approved ROOM reference for the room camera and placement; use the PRIMARY image for the current product. ' : skuScene ? 'The primary image is a product reference, not a room layout. Choose a coherent room camera and sensible wall placement while reserving the scene template space. ' : 'Keep the exact primary camera, framing and visible faces. ' const placementRule = skuScene ? 'relative placement, gaps, proportions and rotations within the assembled product' : 'placement, gaps, scale, rotations' - const lock = `The ENTIRE DIY arrangement is one product subject: exactly ${count} cabinets and ${doors} installed door panels. Keep ALL cabinets, exact ${placementRule}, openings and door artwork from the PRIMARY image. Do not combine, remove or add cabinets or doors. Match the reference finish darkness and wood-grain direction; never lighten dark wood. ${framing}Auxiliary structure images are geometry guides only, never color guides. ` - const modeLock = isFixedDiySkuTemplate(sku?.saved.template) && !scene + const sceneFinishLock = scene ? 'Match the reference finish darkness and wood-grain direction; never lighten dark wood. ' : '' + const whiteFinishLock = scene ? '' : DIY_WHITE_MATERIAL_LIGHTING + (whiteMaterials?.prompt || '') + const lock = `The ENTIRE DIY arrangement is one product subject: exactly ${count} cabinets and ${doors} installed door panels. Keep ALL cabinets, exact ${placementRule}, openings and door artwork from the PRIMARY image. Do not combine, remove or add cabinets or doors. ${sceneFinishLock}${framing}Auxiliary structure images are geometry guides only, never color guides. ` + whiteFinishLock + const cleanCutout = isFixedDiySkuTemplate(sku?.saved.template) && !scene + const modeLock = cleanCutout ? 'Prepare an isolated product cutout on a uniform pure white background. Use even studio lighting, with NO cast shadow, contact shadow, floor shadow, reflection, gray halo or vignette outside the product silhouette. Preserve shading INSIDE compartments and the product materials. No UI, grid, selection outlines or text outside the product. ' : input.mode !== 'scene' ? 'Use a pure white seamless background, soft studio lighting and a tight natural contact shadow. No room, floor texture, UI, grid, selection outlines, green targets or material swatches. ' @@ -58,7 +64,8 @@ export async function createDiyAiRender(input: DiyAiRenderInput, user: AuthUser, const placement = skuScene && sku ? diyScenePlacementPrompt(sku.saved.content.dimensions, Boolean(room)) : null // XG0268 assembly/finish rules must survive long room instructions and scene text. const productFirst = input.snapshot.items.some(isXg0268) - const prefix = lock + (productFirst ? appearance?.prompt || '' : '') + (room?.prompt || '') + (placement?.prompt || '') + const ground = sku?.saved.template === 'custom' ? '' : diyFloorContactPrompt(input.snapshot.items, scene, cleanCutout) + const prefix = lock + ground + (productFirst ? appearance?.prompt || '' : '') + (room?.prompt || '') + (placement?.prompt || '') + (productFirst ? '' : appearance?.prompt || '') + (colors?.prompt || '') const presentation = sku?.prompt || modeLock + input.prompt // Scene text is user content; shorten generated framing instructions before truncating it. @@ -88,6 +95,7 @@ export async function createDiyAiRender(input: DiyAiRenderInput, user: AuthUser, imageCount: input.imageCount, aspectRatio: input.aspectRatio, imageSize: input.imageSize, referenceImage: { ...reference, fileName: `diy-current-view.${reference.extension}` }, additionalReferenceImages: [...(room ? [room.reference] : []), ...(sku?.template ? [sku.template] : []), ...structures.map((image,index) => ({ ...image, fileName: `same-view-structure-${index + 1}.${image.extension}` })), + ...(whiteMaterials ? [whiteMaterials.reference] : []), ...(colors ? [colors.reference] : [])] }, completion: { kind: 'render', renderId: input.requestId, source: 'diy', ...(batch?.previousRequestId ? { afterJobId: `render:${batch.previousRequestId}` } : {}) }, diff --git a/furniture-3d-system/src/server/services/diy-scene-placement-prompt.ts b/furniture-3d-system/src/server/services/diy-scene-placement-prompt.ts index 1a0cd496..4bb0e3a5 100644 --- a/furniture-3d-system/src/server/services/diy-scene-placement-prompt.ts +++ b/furniture-3d-system/src/server/services/diy-scene-placement-prompt.ts @@ -5,10 +5,10 @@ import { DIY_SCENE_PLACEMENT_NEGATIVE_PROMPT } from '@/lib/diy/negative-prompt' export function diyScenePlacementPrompt(dimensions: DiyDimensions, lockedRoom = false) { const cm = (mm: number) => Number((mm / 10).toFixed(2)) return { - prompt: 'PRODUCT AND SCENE PRIORITY: Scene requests describe the environment, lighting and removable styling objects; they must never override the product structure, arrangement, materials, colors, door artwork or physical size. Adapt conflicting scene details around the unchanged product. ' + prompt: `The real overall product size is ${cm(dimensions.width)} cm wide, ${cm(dimensions.depth)} cm deep and ${cm(dimensions.height)} cm high. ` + + 'PRODUCT AND SCENE PRIORITY: Scene requests describe the environment, lighting and removable styling objects; they must never override the product structure, arrangement, materials, colors, door artwork or physical size. Adapt conflicting scene details around the unchanged product. ' + (lockedRoom ? 'Keep the approved room camera, perspective and cabinet location. ' : 'You MAY change the photographic camera angle to obtain a physically believable room layout. ') + 'Keep product geometry and the relative arrangement of its units intact. ' - + `The real overall product size is ${cm(dimensions.width)} cm wide, ${cm(dimensions.depth)} cm deep and ${cm(dimensions.height)} cm high. ` + 'Keep surrounding furniture, objects and room at believable real-world scale, accounting for distance from the camera. Physical scale takes priority over framing. ' + (lockedRoom ? 'Preserve the approved room camera and its furniture scale. ' : 'Choose a wider view and retain more room background when template space is needed. ') + 'Never make the cabinet physically larger or shrink surrounding furniture to emphasize it. ' diff --git a/furniture-3d-system/src/server/services/diy-sku-contact-shadow.ts b/furniture-3d-system/src/server/services/diy-sku-contact-shadow.ts new file mode 100644 index 00000000..ebec3878 --- /dev/null +++ b/furniture-3d-system/src/server/services/diy-sku-contact-shadow.ts @@ -0,0 +1,53 @@ +import sharp from 'sharp' +import type { DiyAiCameraView } from '@/lib/diy/ai-render' +import type { SkuEdge } from '@/lib/diy/sku/outline' + +interface ContactOptions { + camera?: DiyAiCameraView + hasRaisedBase: boolean + /** Ground edges already fitted to the photograph, in final template pixels. */ + floorEdges: SkuEdge[] + left: number + top: number + canvasWidth: number + footerTop: number +} + +function floorAt(x: number, edge: SkuEdge) { + const [[ax, ay], [bx, by]] = edge + if (x < Math.min(ax, bx) - 4 || x > Math.max(ax, bx) + 4 || Math.abs(bx - ax) < 8) return Infinity + const t = Math.max(0, Math.min(1, (x - ax) / (bx - ax))) + return ay + t * (by - ay) +} + +export async function diySkuContactShadow(product: Buffer, options: ContactOptions): Promise { + const { camera, hasRaisedBase, floorEdges, left, top, canvasWidth, footerTop } = options + if ((camera && camera.position[1] < -.01) || (hasRaisedBase && !floorEdges.length)) return + const { data, info: { width, height } } = await sharp(product).toColourspace('srgb').ensureAlpha().raw().toBuffer({ resolveWithObject: true }) + const spread = Math.max(4, Math.min(12, Math.round(Math.min(width, height) * .015))) + const shadowLeft = Math.max(0, left - spread), shadowTop = Math.max(0, top) + const shadowWidth = Math.min(canvasWidth, left + width + spread) - shadowLeft + const shadowHeight = Math.min(footerTop, top + height + spread) - shadowTop + if (shadowWidth <= 0 || shadowHeight <= 0) return + const pixels = Buffer.alloc(shadowWidth * shadowHeight * 4) + let found = false + for (let x = 0; x < width; x++) { + let y = height - 1 + while (y >= 0 && data[(y * width + x) * 4 + 3] <= 127) y-- + if (y < 2) continue + const canvasX = left + x, canvasY = top + y + const dx = canvasX - shadowLeft + if (dx < 0 || dx >= shadowWidth) continue + if (hasRaisedBase && !floorEdges.some(edge => Math.abs(floorAt(canvasX, edge) - canvasY) <= spread + 2)) continue + for (let d = -1; d < spread; d++) { + const dy = canvasY + d - shadowTop + if (dy < 0 || dy >= shadowHeight) continue + pixels[(dy * shadowWidth + dx) * 4 + 3] = Math.round(42 * (1 - Math.max(d, 0) / spread) ** 2) + found = true + } + } + if (!found) return + const input = await sharp(pixels, { raw: { width: shadowWidth, height: shadowHeight, channels: 4 } }) + .blur(Math.max(1, spread / 3)).png().toBuffer() + return { input, left: shadowLeft, top: shadowTop } +} diff --git a/furniture-3d-system/src/server/services/diy-sku-image.ts b/furniture-3d-system/src/server/services/diy-sku-image.ts index 65e32d6a..7d13449b 100644 --- a/furniture-3d-system/src/server/services/diy-sku-image.ts +++ b/furniture-3d-system/src/server/services/diy-sku-image.ts @@ -6,13 +6,14 @@ import type { DiySkuContent } from '@/lib/diy/sku/content' import { skuCentimeters, skuDimensionText } from '@/lib/diy/sku/content' import { skuDimensionLines, type SkuProductRect } from '@/lib/diy/sku/geometry' import { fitDiySkuProduct } from '@/lib/diy/sku/layout' -import type { SkuProductEdges } from '@/lib/diy/sku/outline' +import type { SkuEdge, SkuProductEdges } from '@/lib/diy/sku/outline' import { skuAnnotationInk, skuLabelSamples, skuLineSamples } from '@/lib/diy/sku/annotation-contrast' import { placeSkuDimensions, planSkuDimensionAnnotations } from '@/lib/diy/sku/annotation-placement' import { skuAnnotationPreference } from '@/lib/diy/sku/annotation-view' import { skuSceneAnnotationPreference } from '@/lib/diy/sku/annotation-scene-view' import type { ImageSubjectBounds } from '@/lib/diy/dimension-annotation-geometry' import { isolateDiySkuProduct } from './diy-sku-subject' +import { diySkuContactShadow } from './diy-sku-contact-shadow' import { locateDiySkuSceneProduct, prepareDiySkuSceneImage, type DiySkuSceneLocation } from './diy-sku-scene-image' import { AppError, ErrorCode } from '@/server/core/errors' import { refineDiySkuProductEdges } from './diy-sku-edge-refinement' @@ -67,6 +68,7 @@ async function renderAttempt(buffer: Buffer, settings: SavedDiySku, location?: D const metadata = await sharp(input).metadata(), iw = metadata.width!, ih = metadata.height! let rect: SkuProductRect, subject: ImageSubjectBounds, edges: SkuProductEdges | undefined const layers: sharp.OverlayOptions[] = [] + let contactShadow: sharp.OverlayOptions | undefined if (sceneVariant) { const scene = await prepareDiySkuSceneImage(input, height, location!, adjustment, { headerBottom: header.bottom + headerDelta, showDimensions: settings.showDimensions, @@ -100,7 +102,17 @@ async function renderAttempt(buffer: Buffer, settings: SavedDiySku, location?: D const right = Math.min(iw, Math.ceil(subject.right * iw + iw * .012)), bottom = Math.min(ih, Math.ceil(subject.bottom * ih + ih * .035)) const product = await sharp(isolated.image).extract({ left, top, width: right - left, height: bottom - top }) .resize(Math.round((right - left) * scale), Math.round((bottom - top) * scale)).png().toBuffer() - layers.push({ input: product, left: Math.round(rect.left - (subject.left * iw - left) * scale), top: Math.round(rect.top - (subject.top * ih - top) * scale) }) + const productLeft = Math.round(rect.left - (subject.left * iw - left) * scale) + const productTop = Math.round(rect.top - (subject.top * ih - top) * scale) + const floorEdges: SkuEdge[] = [] + if (isolated.supportFrameApplied && edges) { + for (const edge of [edges.width, edges.depth]) if (edge) { + floorEdges.push(edge.map(([x, y]) => [productLeft + (x * iw - left) * scale, productTop + (y * ih - top) * scale]) as SkuEdge) + } + } + contactShadow = await diySkuContactShadow(product, { camera: settings.camera, hasRaisedBase: Boolean(settings.supportFrame), + floorEdges, left: productLeft, top: productTop, canvasWidth: width, footerTop }) + layers.push({ input: product, left: productLeft, top: productTop }) } const { pill } = header const shapes = `` @@ -164,5 +176,7 @@ async function renderAttempt(buffer: Buffer, settings: SavedDiySku, location?: D for (const line of lines) await label(skuCentimeters(content.dimensions[line.axis]), DIY_SKU_TYPOGRAPHY.dimensionSize, color, ...line.label, 240, true, line.angle) await label(summary, DIY_SKU_TYPOGRAPHY.summarySize, color, 720, summaryY, 1100, true) } - return sharp({ create: { width, height, channels: 3, background: '#fff' } }).composite(layers).png().toBuffer() + // Compute annotation positions and contrast on the unshadowed template. + return sharp({ create: { width, height, channels: 3, background: '#fff' } }) + .composite(contactShadow ? [contactShadow, ...layers] : layers).png().toBuffer() } diff --git a/furniture-3d-system/src/server/services/diy-white-material-reference.ts b/furniture-3d-system/src/server/services/diy-white-material-reference.ts new file mode 100644 index 00000000..80655de9 --- /dev/null +++ b/furniture-3d-system/src/server/services/diy-white-material-reference.ts @@ -0,0 +1,98 @@ +import { readFile } from 'node:fs/promises' +import { join } from 'node:path' +import sharp from 'sharp' +import { resolveDiyMaterials } from '@/lib/diy/catalog' +import { diyTextureTint } from '@/lib/diy/material-appearance' +import { readObjectStorageKeyFromUrl } from '@/lib/object-storage-url' +import type { DiyCatalogDTO, DiySnapshot } from '@/lib/diy/types' +import { readDiyToolImage } from './diy-image-template.service' + +const woodFinishes = new Map([ + ['榆木黑色', 'Black elm'], + ['经典北美黑胡桃色', 'Classic North American black walnut'], + ['柚木色', 'Teak'], +]) +type Part = 'cabinet body' | 'cabinet top' | 'shelf' | 'wood-grain door' +type Sample = { name: string; source: string; tint?: string; parts: Set } + +export const DIY_WHITE_MATERIAL_LIGHTING = + 'White-background material standard: neutral white balance, broad soft studio key and gentle fill. Preserve the selected base colors and the visible grain direction and scale on each panel. Keep dark grain readable without bleaching its color or crushing shadows. Show fine matte furniture laminate grain, edge bands, and existing panel joins with soft shading and subdued highlights; no plastic shine, deep relief, or fabricated seams. ' + +function selectSamples(snapshot: DiySnapshot, catalog: DiyCatalogDTO) { + const samples = new Map() + function add(name: string, source: string | null, part: Part, tint?: string) { + if (!source) return + const finish = woodFinishes.get(name.replace(/顶板$/, '')) + if (!finish) return + const key = JSON.stringify([finish, source, tint ?? '']) + const sample = samples.get(key) ?? { name: finish, source, tint, parts: new Set() } + sample.parts.add(part) + samples.set(key, sample) + } + for (const item of snapshot.items) { + const { main, shelf } = resolveDiyMaterials(catalog, item) + if (main && !main.deletedAt) add(main.name, main.texture, main.name.endsWith('顶板') ? 'cabinet top' : 'cabinet body', diyTextureTint(main)) + if (shelf && !shelf.deletedAt) add(shelf.name, shelf.texture, 'shelf', diyTextureTint(shelf)) + } + const doorCodes = new Set(Object.values(snapshot.doors)) + for (const door of catalog.patterns) { + if (door.deletedAt || !doorCodes.has(door.itemCode)) continue + const finishName = door.name.replace(/^(?:左开门|右开门|右开门带锁)\s*·\s*/, '') + add(finishName, door.image, 'wood-grain door') + } + return [...samples.entries()].sort(([a], [b]) => a.localeCompare(b, 'en')).slice(0, 6).map(([, sample]) => sample) +} + +const tileWidth = 256, tileHeight = 182, gutter = 12, captionHeight = 30 +const sampleCache = new Map>() +async function prepareSample({ name, source, tint }: Sample, catalogHash: string) { + const cacheKey = JSON.stringify([catalogHash, name, source, tint]) + let job = sampleCache.get(cacheKey) + if (!job) { + if (sampleCache.size >= 48) sampleCache.delete(sampleCache.keys().next().value!) + job = (async () => { + const key = readObjectStorageKeyFromUrl(source) + const local = /^\/diy\/finishes\/([a-z0-9-]+\.(?:jpg|jpeg|png|webp))$/i.exec(source) + const data = local ? await readFile(join(process.cwd(), 'public', 'diy', 'finishes', local[1])) + : key ? (await readDiyToolImage(key)).buffer : null + if (!data) return null + // Use an interior crop with its original aspect and hue. No auto contrast or color remapping. + const thumbnail = sharp(data, { limitInputPixels: 32_000_000 }).rotate().toColorspace('srgb') + .resize(tileWidth + 32, tileHeight + 32, { fit: 'cover' }).flatten({ background: 'white' }) + if (tint) thumbnail.linear([1, 3, 5].map(i => parseInt(tint.slice(i, i + 2), 16) / 255), [0, 0, 0]) + return thumbnail.extract({ left: 16, top: 16, width: tileWidth, height: tileHeight }).png().toBuffer() + })() + sampleCache.set(cacheKey, job) + } + try { + return await job + } catch { + if (sampleCache.get(cacheKey) === job) sampleCache.delete(cacheKey) + return null + } +} + +export async function prepareDiyWhiteMaterialReference(snapshot: DiySnapshot, catalog: DiyCatalogDTO) { + const samples = selectSamples(snapshot, catalog) + const tiles = await Promise.all(samples.map(async sample => ({ sample, image: await prepareSample(sample, catalog.sourceHash) }))) + const available = tiles.filter((tile): tile is { sample: Sample; image: Buffer } => Boolean(tile.image)) + if (!available.length) return null + const columns = Math.min(3, available.length) + const rows = Math.ceil(available.length / columns), spacing = tileHeight + captionHeight + gutter + const width = columns * (tileWidth + gutter) + gutter, height = rows * spacing + gutter + const positions = available.map(({ sample, image }, index) => ({ + sample, image, label: String.fromCharCode(65 + index), + left: gutter + (index % columns) * (tileWidth + gutter), top: gutter + Math.floor(index / columns) * spacing, + })) + const captions = positions.map(({ label, left, top }) => + `Sample ${label}`).join('') + const labels = Buffer.from(`${captions}`) + const buffer = await sharp({ create: { width, height, channels: 3, background: '#ffffff' } }) + .composite([...positions.map(({ image, left, top }) => ({ input: image, left, top })), { input: labels }]) + .jpeg({ quality: 90 }).toBuffer() + const mapping = positions.map(({ label, sample }) => `${label} = ${sample.name} (${[...sample.parts].sort().join(' / ')})`).join('; ') + return { + prompt: `The reference labeled Sample A, B, etc. is for surface finish only: ${mapping}. Match each sample only to its existing matching part in the PRIMARY image. That image alone sets part positions, grain direction, geometry and camera. Do not copy swatch labels, artwork, or swatch layout into the output; keep printed doors and solid colors from the product reference. `, + reference: { buffer, contentType: 'image/jpeg', fileName: 'diy-wood-finish-samples.jpg' }, + } +}