onmessage = function (e) {
    const { materials, positions, sizes } = e.data;
    const collisions = [];
    const allPairs = [];

    for (let i = 0; i < materials.length; i++) {
        for (let j = i + 1; j < materials.length; j++) {
            const mat1 = materials[i];
            const mat2 = materials[j];
            const pos1 = positions[mat1.materialId];
            const pos2 = positions[mat2.materialId];

            if (!pos1 || !pos2) continue;

            const size1 = sizes[mat1.materialId] || 0.2;
            const size2 = sizes[mat2.materialId] || 0.2;

            const distance = Math.sqrt(
                Math.pow(pos1.x - pos2.x, 2) +
                Math.pow(pos1.y - pos2.y, 2) +
                Math.pow(pos1.z - pos2.z, 2)
            );

            allPairs.push({
                materialId1: mat1.materialId,
                materialId2: mat2.materialId
            });

            if (distance < (size1 + size2)) {
                collisions.push({
                    materialId1: mat1.materialId,
                    materialId2: mat2.materialId,
                    distance: distance
                });
            }
        }
    }

    postMessage({ collisions, allPairs });
};