import { BufferAttribute, BufferGeometry } from 'three';
import { STRIDE } from './buffer';
const colorStride = (colors, positions) => {
    const numVertices = positions.length / STRIDE.POSITIONS;
    const stride = colors.length / numVertices;
    return stride === STRIDE.COLORS_RGBA ? STRIDE.COLORS_RGBA : STRIDE.COLORS_RGB;
};
export const createBufferGeometry = (positions, colors) => {
    const geometry = new BufferGeometry();
    geometry.setAttribute('position', new BufferAttribute(positions, 3));
    if (colors) {
        const stride = colorStride(colors, positions);
        geometry.setAttribute('color', new BufferAttribute(colors, stride, true));
    }
    return geometry;
};
export const updateBufferGeometry = (geometry, positions, colors) => {
    const positionAttr = geometry.getAttribute('position');
    if (positionAttr && positionAttr.array.length >= positions.length) {
        positionAttr.array.set(positions, 0);
        geometry.setDrawRange(0, positions.length);
        positionAttr.needsUpdate = true;
    }
    else {
        geometry.setAttribute('position', new BufferAttribute(positions, 3));
    }
    if (colors) {
        const colorAttr = geometry.getAttribute('color');
        if (colorAttr && colorAttr.array.length >= colors.length) {
            colorAttr.array.set(colors, 0);
            colorAttr.needsUpdate = true;
        }
        else {
            const stride = colorStride(colors, positions);
            geometry.setAttribute('color', new BufferAttribute(colors, stride, true));
        }
    }
};
