Skip to content

Instantly share code, notes, and snippets.

@Mars073
Created April 15, 2022 19:04
Show Gist options
  • Save Mars073/4e6839d422426a1adb81915b46f95c3a to your computer and use it in GitHub Desktop.
Save Mars073/4e6839d422426a1adb81915b46f95c3a to your computer and use it in GitHub Desktop.
import { BufferAttribute, BufferGeometry } from 'three'
export const outerWidth = 200
export const outerLength = 200
export default class LandscapeGeometry extends BufferGeometry {
private innerWidth: number
private innerLength: number
constructor (inWidth = 200, inLength = 100) {
super()
this.innerWidth = Math.min(inWidth, outerWidth - 2)
this.innerLength = Math.min(inLength, outerLength - 2)
this.setAttribute('position', new BufferAttribute(this.vertices, 3))
this.setAttribute('uv', new BufferAttribute(this.uvs, 2))
this.setIndex(new BufferAttribute(this.indices, 1))
this.computeVertexNormals()
}
get vertices (): Float32Array {
const ox = Math.abs(outerWidth) / 2
const oz = Math.abs(outerLength) / 2
const dx = Math.abs(this.innerWidth) / 2
const dz = Math.abs(this.innerLength) / 2
return new Float32Array([
// North
-ox, 0, -oz, -dx, 0, -dz, +ox, 0, -oz,
+dx, 0, -dz, ox, 0, -oz, -dx, 0, -dz,
// East
+ox, 0, oz, +ox, 0, -oz, +dx, 0, -dz,
+ox, 0, oz, +dx, 0, -dz, +dx, 0, +dz,
// South
+ox, 0, +oz, +dx, 0, +dz, -ox, 0, +oz,
-ox, 0, +oz, +dx, 0, +dz, -dx, 0, +dz,
// West
-ox, 0, +oz, -dx, 0, +dz, -ox, 0, -oz,
-ox, 0, -oz, -dx, 0, +dz, -dx, 0, -dz
])
}
get uvs (): Float32Array {
const du = (outerWidth - this.innerWidth) / 2 / outerWidth
const dv = (outerLength - this.innerLength) / 2 / outerLength
return new Float32Array([
// North
0, 1, du, 1 - dv, 1, 1,
1 - du, 1 - dv, 1, 1, du, 1 - dv,
// East
1, 0, 1, 1, 1 - du, 1 - dv,
1, 0, 1 - du, 1 - dv, 1 - du, dv,
// South
1, 0, 1 - du, dv, 0, 0,
0, 0, 1 - du, dv, du, dv,
// West
0, 0, du, dv, 0, 1,
0, 1, du, dv, du, 1 - dv
])
}
get indices (): Uint32Array {
return new Uint32Array([
0, 1, 2,
3, 4, 5,
6, 7, 8,
9, 10, 11,
12, 13, 14,
15, 16, 17,
18, 19, 20,
21, 22, 23
])
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment