Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix rendering for polygons #9

Merged
merged 3 commits into from
Jul 9, 2024
Merged
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
2 changes: 1 addition & 1 deletion examples/polygon.fixture.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { JsCadFixture } from "../lib/components/jscad-fixture"
import { Polygon } from "../lib/jscad-fns/polygon"

export default () => (
<JsCadFixture wireframe>
<JsCadFixture>
<Polygon
points={[
[-2, -1],
Expand Down
31 changes: 24 additions & 7 deletions lib/components/jscad-fixture.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -54,13 +54,30 @@ export function JsCadFixture({

for (const csg of jscadGeoms) {
const geometry = convertCSGToThreeGeom(csg)
console.log(geometry)
const material = new THREE.MeshStandardMaterial({
color: 0xffffff,
wireframe,
})
const cube = new THREE.Mesh(geometry, material)
scene.add(cube)

let material
if (csg.sides) {
// 2D shape
// material = new THREE.MeshBasicMaterial({
// color: 0xffffff,
// side: THREE.DoubleSide,
// wireframe: wireframe,
// })
const material = new THREE.LineBasicMaterial({
color: 0xffffff,
linewidth: 2, // Note: linewidth > 1 only works in WebGL 2
})
const lineLoop = new THREE.LineLoop(geometry, material)
scene.add(lineLoop)
} else {
// 3D shape
material = new THREE.MeshStandardMaterial({
color: 0xffffff,
wireframe: wireframe,
})
const mesh = new THREE.Mesh(geometry, material)
scene.add(mesh)
}
}

camera.position.x = 20
Expand Down
146 changes: 72 additions & 74 deletions lib/convert-csg-to-three-geom.ts
Original file line number Diff line number Diff line change
@@ -1,83 +1,81 @@
import { BufferGeometry, BufferAttribute, Vector3, Matrix4 } from "three"
import {
BufferGeometry,
BufferAttribute,
Vector3,
Vector2,
Matrix4,
Shape,
ShapeGeometry,
} from "three"

export default function convertCSGToThreeGeom(csg) {
const vertices = []
const indices = []
let idx = 0
csg.polygons.forEach((polygon) => {
polygon.vertices.forEach((vertex) => {
vertex.index = idx
vertices.push(vertex[0], vertex[1], vertex[2])
idx++
export default function convertCSGToThreeGeom(csg): BufferGeometry {
console.log("csg", csg)

if (csg.polygons) {
// 3D shape
const vertices = []
const indices = []
let idx = 0

csg.polygons.forEach((polygon) => {
polygon.vertices.forEach((vertex) => {
vertex.index = idx
vertices.push(vertex[0], vertex[1], vertex[2])

Check failure on line 23 in lib/convert-csg-to-three-geom.ts

View workflow job for this annotation

GitHub Actions / type-check

Argument of type 'any' is not assignable to parameter of type 'never'.
idx++
})
const first = polygon.vertices[0].index
for (let i = 2; i < polygon.vertices.length; i++) {
const second = polygon.vertices[i - 1].index
const third = polygon.vertices[i].index
indices.push(first, second, third)

Check failure on line 30 in lib/convert-csg-to-three-geom.ts

View workflow job for this annotation

GitHub Actions / type-check

Argument of type 'any' is not assignable to parameter of type 'never'.
}
})
const first = polygon.vertices[0].index
for (let i = 2; i < polygon.vertices.length; i++) {
const second = polygon.vertices[i - 1].index
const third = polygon.vertices[i].index
indices.push(first, second, third)

const geo = new BufferGeometry()
geo.setAttribute(
"position",
new BufferAttribute(new Float32Array(vertices), 3),
)
geo.setIndex(indices)
if (csg.transforms) {
const transforms = new Matrix4()
transforms.set(...csg.transforms).transpose()

Check failure on line 42 in lib/convert-csg-to-three-geom.ts

View workflow job for this annotation

GitHub Actions / type-check

A spread argument must either have a tuple type or be passed to a rest parameter.
geo.applyMatrix4(transforms)
}
})
geo.computeVertexNormals()

const geo = new BufferGeometry()
geo.setAttribute(
"position",
new BufferAttribute(new Float32Array(vertices), 3),
)
geo.setIndex(indices)
if (csg.transforms) {
const transforms = new Matrix4()
transforms.set(...csg.transforms).transpose()
geo.applyMatrix4(transforms)
}
geo.computeVertexNormals()
// Vertex normal averaging code (if needed)
// ...

const positions = {}
for (let i = 0; i < geo.attributes.position.count; i++) {
const pArray = geo.attributes.position.array
const x = Math.round(pArray[i * 3] * 100)
const y = Math.round(pArray[i * 3 + 1] * 100)
const z = Math.round(pArray[i * 3 + 2] * 100)
const position = `${x},${y},${z}`
if (!positions[position]) {
positions[position] = { normals: [] }
}
const nArray = geo.attributes.normal.array
const nx = nArray[i * 3]
const ny = nArray[i * 3 + 1]
const nz = nArray[i * 3 + 2]
const normal = new Vector3(nx, ny, nz)
positions[position].normals.push({ index: i, normal: normal })
}
geo.attributes.normal.needsUpdate = true
return geo
} else if (csg.sides) {
const points = csg.sides.map((side) => new Vector2(side[0][0], side[0][1]))

for (let p in positions) {
const currentPosition = positions[p]
const nl = currentPosition.normals.length
const toAverage = {}
for (let i = 0; i < nl - 1; i += 1) {
for (let j = i + 1; j < nl; j += 1) {
const n1 = currentPosition.normals[i].normal
const n2 = currentPosition.normals[j].normal
if (n1.angleTo(n2) < Math.PI * 0.5 && n1.angleTo(n2) !== 0) {
toAverage[currentPosition.normals[i].index] =
currentPosition.normals[i].normal
toAverage[currentPosition.normals[j].index] =
currentPosition.normals[j].normal
}
}
const geometry = new BufferGeometry().setFromPoints(points)

// // 2D shape
// const shape = new Shape()

// // Move to the first point
// const firstPoint = csg.sides[0][0]
// shape.moveTo(firstPoint[0], firstPoint[1])

// // Draw lines to subsequent points
// for (let i = 1; i < csg.sides.length; i++) {
// const point = csg.sides[i][0]
// shape.lineTo(point[0], point[1])
// }

if (csg.transforms) {
const transforms = new Matrix4()
transforms.set(...csg.transforms).transpose()

Check failure on line 72 in lib/convert-csg-to-three-geom.ts

View workflow job for this annotation

GitHub Actions / type-check

A spread argument must either have a tuple type or be passed to a rest parameter.
geometry.applyMatrix4(transforms)
}
const averageNormal = new Vector3()
const indexes = Object.keys(toAverage)
indexes.forEach((index) => {
averageNormal.add(toAverage[index])
averageNormal.normalize()
})
indexes.forEach((index) => {
geo.attributes.normal.array[index * 3] = averageNormal.x
geo.attributes.normal.array[index * 3 + 1] = averageNormal.y
geo.attributes.normal.array[index * 3 + 2] = averageNormal.z
})
}

geo.attributes.normal.array.needsUpdate = true
return geo
return geometry
} else {
console.error("Invalid CSG object: neither polygons nor sides found")
return new BufferGeometry()
}
}
Loading