VEHwang's picture
Upload CoCogni4D-Bench (questions, media, scripts, render records, code) (part 6)
5afd2f7 verified
Raw History Blame Contribute Delete
2.04 kB
// Presentation geometry only: no trajectory or visibility facts are derived.
export type Rect = {left: number; top: number; right: number; bottom: number};
export const intersects = (a: Rect, b: Rect) => a.left < b.right && b.left < a.right && a.top < b.bottom && b.top < a.bottom;
export function pointInside(point: [number, number], polygon: [number, number][]): boolean {
let inside = false;
for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
const a = polygon[i], b = polygon[j];
if ((a[1] > point[1]) !== (b[1] > point[1]) && point[0] < (b[0] - a[0]) * (point[1] - a[1]) / (b[1] - a[1]) + a[0]) inside = !inside;
}
return inside;
}
export function layoutRoomLabels(svg: SVGSVGElement, polygons: Record<string, [number, number][]>) {
const bounds = svg.getBoundingClientRect(), matrix = svg.getScreenCTM();
if (!matrix || bounds.width <= 0 || bounds.height <= 0) return;
const inverse = matrix.inverse();
if (![inverse.a, inverse.b, inverse.c, inverse.d, inverse.e, inverse.f].every(Number.isFinite)) return;
const accepted: Rect[] = [];
for (const text of svg.querySelectorAll<SVGTextElement>('[data-room-label]')) {
const r = text.getBoundingClientRect();
// Include the 2px stroke and a further 2px space between labels.
const box = {left: r.left - 2, top: r.top - 2, right: r.right + 2, bottom: r.bottom + 2};
const polygon = polygons[text.dataset.roomLabel!];
const corners = [[box.left, box.top], [box.right, box.top], [box.right, box.bottom], [box.left, box.bottom]];
const fits = r.width > 0 && r.height > 0 && box.left >= bounds.left && box.right <= bounds.right && box.top >= bounds.top && box.bottom <= bounds.bottom
&& corners.every(([x, y]) => {const p = new DOMPoint(x, y).matrixTransform(inverse); return pointInside([p.x, -p.y], polygon);})
&& !accepted.some(other => intersects(box, other));
text.style.visibility = fits ? 'visible' : 'hidden';
text.dataset.labelVisible = String(fits);
if (fits) accepted.push(box);
}
}