Skip to content

Practice & Add Interactivity

Video Lecture

Section Video Links
Practice Practice Practice
Add Interactivity Add Interactivity Add Interactivity

Description

We will practice many of the concepts we've learned so far and create this small interactive demo.

<>

Start Script

./src/main.ts

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
import './style.css'
import * as THREE from 'three/webgpu'
import {
  positionLocal,
  Fn,
  uniform,
  abs,
  length,
  smoothstep,
  vec4,
  vec3,
  vec2,
  sin,
  time,
  mx_noise_float,
  mix,
  min,
  max,
  If,
  atan,
  Loop,
  float,
} from 'three/tsl'
import { OrbitControls } from 'three/addons/controls/OrbitControls.js'
//import JEASINGS from 'jeasings'

const scene = new THREE.Scene()

const camera = new THREE.PerspectiveCamera(
  75,
  window.innerWidth / window.innerHeight,
  0.1,
  2
)
camera.position.z = 1

const renderer = new THREE.WebGPURenderer({ antialias: true })
renderer.setSize(window.innerWidth, window.innerHeight)
document.body.appendChild(renderer.domElement)
renderer.setAnimationLoop(animate)

window.addEventListener('resize', function () {
  camera.aspect = window.innerWidth / window.innerHeight
  camera.updateProjectionMatrix()
  renderer.setSize(window.innerWidth, window.innerHeight)
})

const controls = new OrbitControls(camera, renderer.domElement)
controls.enableDamping = true
// controls.minAzimuthAngle = -Math.PI / 8
// controls.maxAzimuthAngle = Math.PI / 4

// const wheelOffset = uniform(new THREE.Vector2(-10, 0))
// const bulletOffset = uniform(20)
// const shellOffset = uniform(25)

// @ts-ignore
const groundLayer = Fn(([position]) => {
  return position.y
  //return position.y.sub(sin(position.x))
  //return position.y.sub(mx_noise_float(position.x))
})

// @ts-ignore
const sunRays = Fn(([position]) => {
  const angle = atan(position.y, position.x)
  const frequency = 20.0
  const amplitude = 0.5

  const rays = sin(angle.mul(frequency).add(time))
    .mul(amplitude)
    .add(sin(time.mul(2)))

  return length(position).sub(0.5).add(rays)
})

// @ts-ignore
const Sphere = Fn(([position, offset, radius]) => {
  const distance = length(position.sub(offset)).sub(radius)
  return distance
})

// @ts-ignore
const Ellipse = Fn(([position, radius, scale]) => {
  const scaledPosition = position.mul(scale)
  return length(scaledPosition).sub(radius)
})

// @ts-ignore
const Box = Fn(([position, dimensions]) => {
  const distance = abs(position).sub(dimensions)
  return length(max(distance, 0.0)).add(min(max(distance.x, distance.y), 0.0))
})

// @ts-ignore
const Sky = Fn(([position]) => {
  const topColor = vec3(0.1, 0.2, 0.5)
  const midColor = vec3(1.0, 0.4, 0.2)
  const bottomColor = vec3(0.9, 0.6, 0.3)

  return mix(bottomColor, midColor, position.y.div(5))
  //return mix(mix(bottomColor, midColor, position.y.div(10)), topColor, position.y.div(5))
})

// // @ts-ignore
// const Tank = Fn(([position, offset]) => {
//   const a = Ellipse(position.sub(offset), 5, vec2(1, 2))
//   const b = Box(position.sub(offset).sub(vec2(0, -1.5)), vec2(4.5, 1))
//   const c = Box(position.sub(offset).sub(vec2(0, 2.5)), vec2(2, 1)) // canopy
//   const d = Box(position.sub(offset).sub(vec2(2, 2.7)), vec2(4, 0.2)) // turret
//   const e = Box(position.sub(offset).sub(vec2(-3.5, 2.8)), vec2(0.1, 2)) // gun
//   const f = Box(position.sub(offset).sub(vec2(0.5, 2.8)), vec2(1, 0.5)) // window

//   const sdf = max(a, b.negate())
//   sdf.assign(min(sdf, c))
//   sdf.assign(min(sdf, d))
//   sdf.assign(min(sdf, e))
//   sdf.assign(max(sdf, f.negate()))

//   return smoothstep(0.01, 0, a) //sdf)
// })

// // @ts-ignore
// const Camouflage = Fn(([position]) => {
//   const n = mx_noise_float(position)
//   const colour = vec3(0.4, 0.7, 0.3).toVar() // Light Green
//   If(n.lessThan(0.2), () => {
//     colour.assign(vec3(0.1, 0.3, 0.1)) // Dark green
//   })
//   If(n.lessThan(-0.3), () => {
//     colour.assign(vec3(0.2, 0.5, 0.2)) // Medium green
//   })
//   return colour
// })

const main = Fn(() => {
  const p = positionLocal.xy.mul(20)

  //const t = float(0) //time.div(5)
  //const t = time.div(2)

  const finalColour = Sky(p).toVar()

  // finalColour.assign(
  //   mix(finalColour, vec3(1, 0.75, 0), smoothstep(10, 0, sunRays(p.sub(vec2(7, 7)))))
  // )

  //const mountains = groundLayer(p)
  //finalColour.assign(mix(finalColour, vec3(0.1, 0.1, 0.1), smoothstep(0.01, 0.0, mountains)))

  //const hills = groundLayer(p)
  //finalColour.assign(mix(finalColour, vec3(0.2, 0.2, 0.1), smoothstep(0.01, 0.0, hills)))

  // const mounds = groundLayer(p.add(vec2(t.mul(4), 3)).div(vec2(2.5, 2.5)))
  // finalColour.assign(mix(finalColour, vec3(0.3, 0.3, 0.1), smoothstep(0.01, 0.0, mounds)))

  // const bumps = groundLayer(p.add(vec2(t.mul(8), 6)).div(vec2(4, 1)))
  // finalColour.assign(mix(finalColour, vec3(0.4, 0.4, 0.1), smoothstep(0.01, 0.0, bumps)))

  // const foreground = groundLayer(p.add(vec2(t.mul(16), 8.5)).div(vec2(5, 1)))
  // finalColour.assign(mix(finalColour, vec3(0.5, 0.4, 0.1), smoothstep(0.01, 0.0, foreground)))

  //let offset = float(0).toVar()
  //let offset = wheelOffset.x.toVar()

  //Loop({ start: 0, end: 4, condition: '<' }, () => {
  //const wheel = Sphere(p, vec2(0, 0), 1)
  //finalColour.assign(mix(finalColour, vec3(0.025, 0.025, 0.025), smoothstep(0.01, 0, wheel)))
  //offset.addAssign(2.25)
  //})

  //offset.subAssign(5.6)

  // const tank = Tank(p, vec2(0, 0))
  // finalColour.assign(mix(finalColour, vec3(0, 1, 0), tank))

  // const bullet = Sphere(
  //   p,
  //   vec2(offset.sub(3.5), mx_noise_float(t.mul(2).add(offset.div(4))).add(bulletOffset)),
  //   0.1
  // )
  // finalColour.assign(mix(finalColour, vec3(0.5, 0, 0), smoothstep(0.01, 0, bullet)))

  // const shell = Sphere(
  //   p,
  //   vec2(offset.add(5).add(shellOffset), mx_noise_float(t.mul(2).add(offset.div(4))).sub(1.6)),
  //   0.2
  // )
  // finalColour.assign(mix(finalColour, vec3(0.5, 0, 0), smoothstep(0.01, 0, shell)))

  return vec4(finalColour, 1)
})

const material = new THREE.NodeMaterial()
material.fragmentNode = main()

const mesh = new THREE.Mesh(new THREE.PlaneGeometry(2, 2), material)
scene.add(mesh)

//scene.backgroundNode = main()

// let canJump = true
// const jump = () => {
//   canJump = false
//   // Going up
//   new JEASINGS.JEasing(wheelOffset.value)
//     .to(
//       {
//         y: 5
//       },
//       250
//     )
//     .easing(JEASINGS.Cubic.Out)
//     .start()
//     .onComplete(() => {
//       // Going down
//       new JEASINGS.JEasing(wheelOffset.value)
//         .to(
//           {
//             y: 0
//           },
//           250
//         )
//         .easing(JEASINGS.Bounce.Out)
//         .start()
//         .onComplete(() => {
//           canJump = true
//         })
//     })
// }

// let canShoot = true
// const shoot = () => {
//   canShoot = false

//   bulletOffset.value = 0
//   new JEASINGS.JEasing(bulletOffset)
//     .to(
//       {
//         value: 20
//       },
//       500
//     )
//     .start()
//     .onComplete(() => {
//       canShoot = true
//     })

//   shellOffset.value = 0
//   new JEASINGS.JEasing(shellOffset)
//     .to(
//       {
//         value: 25
//       },
//       500
//     )
//     .start()
// }

const keyMap: { [key: string]: boolean } = {}
const onDocumentKey = (e: KeyboardEvent) => {
  keyMap[e.code] = e.type === 'keydown'
  return false
}
document.addEventListener('keydown', onDocumentKey)
document.addEventListener('keyup', onDocumentKey)

//const clock = new THREE.Clock()
//let delta

function animate() {
  //delta = clock.getDelta()

  controls.update()

  //JEASINGS.update()

  // if (keyMap['KeyW'] || keyMap['ArrowUp']) {
  //   // jump
  //   canJump && jump()
  // }
  // if (keyMap['KeyA'] || keyMap['ArrowLeft']) {
  //   // move backwards
  //   wheelOffset.value.x -= 4 * delta
  // }
  // if (keyMap['KeyD'] || keyMap['ArrowRight']) {
  //   // move forwards
  //   //console.log(wheelOffset.value)
  //   wheelOffset.value.x += 4 * delta
  // }
  // if (keyMap['Space']) {
  //   canShoot && shoot()
  // }

  renderer.render(scene, camera)
}

Part 2 Script

We add the keyboard interactivity to this 2D practice example.

We will also use the JEasings library to smoothly animate some uniforms.

npm install jeasings --save-dev

./src/main.ts

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
import './style.css'
import * as THREE from 'three/webgpu'
import {
  positionLocal,
  Fn,
  uniform,
  abs,
  length,
  smoothstep,
  vec4,
  vec3,
  vec2,
  sin,
  time,
  mx_noise_float,
  mix,
  min,
  max,
  If,
  atan,
  Loop,
  float,
} from 'three/tsl'
import { OrbitControls } from 'three/addons/controls/OrbitControls.js'
//import JEASINGS from 'jeasings'

const scene = new THREE.Scene()

const camera = new THREE.PerspectiveCamera(
  75,
  window.innerWidth / window.innerHeight,
  0.1,
  2
)
camera.position.z = 1

const renderer = new THREE.WebGPURenderer({ antialias: true })
renderer.setSize(window.innerWidth, window.innerHeight)
document.body.appendChild(renderer.domElement)
renderer.setAnimationLoop(animate)

window.addEventListener('resize', function () {
  camera.aspect = window.innerWidth / window.innerHeight
  camera.updateProjectionMatrix()
  renderer.setSize(window.innerWidth, window.innerHeight)
})

const controls = new OrbitControls(camera, renderer.domElement)
controls.enableDamping = true
// controls.minAzimuthAngle = -Math.PI / 8
// controls.maxAzimuthAngle = Math.PI / 4

// const wheelOffset = uniform(new THREE.Vector2(-10, 0))
// const bulletOffset = uniform(20)
// const shellOffset = uniform(25)

// @ts-ignore
const groundLayer = Fn(([position]) => {
  //return position.y
  //return position.y.sub(sin(position.x))
  return position.y.sub(mx_noise_float(position.x))
})

// @ts-ignore
const sunRays = Fn(([position]) => {
  const angle = atan(position.y, position.x)
  const frequency = 20.0
  const amplitude = 0.5

  const rays = sin(angle.mul(frequency).add(time))
    .mul(amplitude)
    .add(sin(time.mul(2)))

  return length(position).sub(0.5).add(rays)
})

// @ts-ignore
const Sphere = Fn(([position, offset, radius]) => {
  const distance = length(position.sub(offset)).sub(radius)
  return distance
})

// @ts-ignore
const Ellipse = Fn(([position, radius, scale]) => {
  const scaledPosition = position.mul(scale)
  return length(scaledPosition).sub(radius)
})

// @ts-ignore
const Box = Fn(([position, dimensions]) => {
  const distance = abs(position).sub(dimensions)
  return length(max(distance, 0.0)).add(min(max(distance.x, distance.y), 0.0))
})

// @ts-ignore
const Sky = Fn(([position]) => {
  const topColor = vec3(0.1, 0.2, 0.5)
  const midColor = vec3(1.0, 0.4, 0.2)
  const bottomColor = vec3(0.9, 0.6, 0.3)

  //return mix(bottomColor, midColor, position.y.div(5))
  return mix(
    mix(bottomColor, midColor, position.y.div(10)),
    topColor,
    position.y.div(5)
  )
})

// @ts-ignore
const Tank = Fn(([position, offset]) => {
  const a = Ellipse(position.sub(offset), 5, vec2(1, 2))
  const b = Box(position.sub(offset).sub(vec2(0, -1.5)), vec2(4.5, 1))
  const c = Box(position.sub(offset).sub(vec2(0, 2.5)), vec2(2, 1)) // canopy
  const d = Box(position.sub(offset).sub(vec2(2, 2.7)), vec2(4, 0.2)) // turret
  const e = Box(position.sub(offset).sub(vec2(-3.5, 2.8)), vec2(0.1, 2)) // gun
  const f = Box(position.sub(offset).sub(vec2(0.5, 2.8)), vec2(1, 0.5)) // window

  const sdf = max(a, b.negate())
  sdf.assign(min(sdf, c))
  sdf.assign(min(sdf, d))
  sdf.assign(min(sdf, e))
  sdf.assign(max(sdf, f.negate()))

  return smoothstep(0.01, 0, sdf)
})

// @ts-ignore
const Camouflage = Fn(([position]) => {
  const n = mx_noise_float(position)
  const colour = vec3(0.4, 0.7, 0.3).toVar() // Light Green
  If(n.lessThan(0.2), () => {
    colour.assign(vec3(0.1, 0.3, 0.1)) // Dark green
  })
  If(n.lessThan(-0.3), () => {
    colour.assign(vec3(0.2, 0.5, 0.2)) // Medium green
  })
  return colour
})

const main = Fn(() => {
  const p = positionLocal.xy.mul(20)

  //const t = float(0) //time.div(5)
  const t = time.div(2)

  const finalColour = Sky(p).toVar()

  finalColour.assign(
    mix(
      finalColour,
      vec3(1, 0.75, 0),
      smoothstep(10, 0, sunRays(p.sub(vec2(7, 7))))
    )
  )

  const mountains = groundLayer(p.add(vec2(t, -1)).div(vec2(10, 10)))
  finalColour.assign(
    mix(finalColour, vec3(0.1, 0.1, 0.1), smoothstep(0.01, 0.0, mountains))
  )

  const hills = groundLayer(p.add(vec2(t.mul(2), 0)).div(vec2(5, 5)))
  finalColour.assign(
    mix(finalColour, vec3(0.2, 0.2, 0.1), smoothstep(0.01, 0.0, hills))
  )

  const mounds = groundLayer(p.add(vec2(t.mul(4), 3)).div(vec2(2.5, 2.5)))
  finalColour.assign(
    mix(finalColour, vec3(0.3, 0.3, 0.1), smoothstep(0.01, 0.0, mounds))
  )

  const bumps = groundLayer(p.add(vec2(t.mul(8), 6)).div(vec2(4, 1)))
  finalColour.assign(
    mix(finalColour, vec3(0.4, 0.4, 0.1), smoothstep(0.01, 0.0, bumps))
  )

  const foreground = groundLayer(p.add(vec2(t.mul(16), 8.5)).div(vec2(5, 1)))
  finalColour.assign(
    mix(finalColour, vec3(0.5, 0.4, 0.1), smoothstep(0.01, 0.0, foreground))
  )

  let offset = float(-10).toVar()
  //let offset = wheelOffset.x.toVar()

  Loop({ start: 0, end: 4, condition: '<' }, () => {
    const wheel = Sphere(
      p,
      vec2(offset, mx_noise_float(t.mul(2).add(offset.div(4))).sub(5)),
      1
    )
    finalColour.assign(
      mix(finalColour, vec3(0.025, 0.025, 0.025), smoothstep(0.01, 0, wheel))
    )

    offset.addAssign(2.25)
  })

  offset.subAssign(5.6)

  const tank = Tank(
    p,
    vec2(offset, mx_noise_float(t.mul(2).add(offset.div(4))).sub(4))
  )
  finalColour.assign(mix(finalColour, Camouflage(p), tank))

  // const bullet = Sphere(
  //   p,
  //   vec2(offset.sub(3.5), mx_noise_float(t.mul(2).add(offset.div(4))).add(bulletOffset)),
  //   0.1
  // )
  // finalColour.assign(mix(finalColour, vec3(0.5, 0, 0), smoothstep(0.01, 0, bullet)))

  // const shell = Sphere(
  //   p,
  //   vec2(offset.add(5).add(shellOffset), mx_noise_float(t.mul(2).add(offset.div(4))).sub(1.6)),
  //   0.2
  // )
  // finalColour.assign(mix(finalColour, vec3(0.5, 0, 0), smoothstep(0.01, 0, shell)))

  return vec4(finalColour, 1)
})

const material = new THREE.NodeMaterial()
material.fragmentNode = main()

const mesh = new THREE.Mesh(new THREE.PlaneGeometry(2, 2), material)
scene.add(mesh)

//scene.backgroundNode = main()

// let canJump = true
// const jump = () => {
//   canJump = false
//   // Going up
//   new JEASINGS.JEasing(wheelOffset.value)
//     .to(
//       {
//         y: 5
//       },
//       250
//     )
//     .easing(JEASINGS.Cubic.Out)
//     .start()
//     .onComplete(() => {
//       // Going down
//       new JEASINGS.JEasing(wheelOffset.value)
//         .to(
//           {
//             y: 0
//           },
//           250
//         )
//         .easing(JEASINGS.Bounce.Out)
//         .start()
//         .onComplete(() => {
//           canJump = true
//         })
//     })
// }

// let canShoot = true
// const shoot = () => {
//   canShoot = false

//   bulletOffset.value = 0
//   new JEASINGS.JEasing(bulletOffset)
//     .to(
//       {
//         value: 20
//       },
//       500
//     )
//     .start()
//     .onComplete(() => {
//       canShoot = true
//     })

//   shellOffset.value = 0
//   new JEASINGS.JEasing(shellOffset)
//     .to(
//       {
//         value: 25
//       },
//       500
//     )
//     .start()
// }

const keyMap: { [key: string]: boolean } = {}
const onDocumentKey = (e: KeyboardEvent) => {
  keyMap[e.code] = e.type === 'keydown'
  return false
}
document.addEventListener('keydown', onDocumentKey)
document.addEventListener('keyup', onDocumentKey)

//const clock = new THREE.Clock()
//let delta

function animate() {
  //delta = clock.getDelta()

  controls.update()

  //JEASINGS.update()

  // if (keyMap['KeyW'] || keyMap['ArrowUp']) {
  //   // jump
  //   canJump && jump()
  // }
  // if (keyMap['KeyA'] || keyMap['ArrowLeft']) {
  //   // move backwards
  //   wheelOffset.value.x -= 4 * delta
  // }
  // if (keyMap['KeyD'] || keyMap['ArrowRight']) {
  //   // move forwards
  //   //console.log(wheelOffset.value)
  //   wheelOffset.value.x += 4 * delta
  // }
  // if (keyMap['Space']) {
  //   canShoot && shoot()
  // }

  renderer.render(scene, camera)
}

Final Script

./src/main.ts

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
import './style.css'
import * as THREE from 'three/webgpu'
import {
  positionLocal,
  Fn,
  uniform,
  abs,
  length,
  smoothstep,
  vec4,
  vec3,
  vec2,
  sin,
  time,
  mx_noise_float,
  mix,
  min,
  max,
  If,
  atan,
  Loop,
  float,
} from 'three/tsl'
import { OrbitControls } from 'three/addons/controls/OrbitControls.js'
import JEASINGS from 'jeasings'

const scene = new THREE.Scene()

const camera = new THREE.PerspectiveCamera(
  75,
  window.innerWidth / window.innerHeight,
  0.1,
  2
)
camera.position.z = 1

const renderer = new THREE.WebGPURenderer({ antialias: true })
renderer.setSize(window.innerWidth, window.innerHeight)
document.body.appendChild(renderer.domElement)
renderer.setAnimationLoop(animate)

window.addEventListener('resize', function () {
  camera.aspect = window.innerWidth / window.innerHeight
  camera.updateProjectionMatrix()
  renderer.setSize(window.innerWidth, window.innerHeight)
})

const controls = new OrbitControls(camera, renderer.domElement)
controls.enableDamping = true
controls.minAzimuthAngle = -Math.PI / 8
controls.maxAzimuthAngle = Math.PI / 4

const wheelOffset = uniform(new THREE.Vector2(-10, 0))
const bulletOffset = uniform(20)
const shellOffset = uniform(25)

// @ts-ignore
const groundLayer = Fn(([position]) => {
  //return position.y
  //return position.y.sub(sin(position.x))
  return position.y.sub(mx_noise_float(position.x))
})

// @ts-ignore
const sunRays = Fn(([position]) => {
  const angle = atan(position.y, position.x)
  const frequency = 20.0
  const amplitude = 0.5

  const rays = sin(angle.mul(frequency).add(time))
    .mul(amplitude)
    .add(sin(time.mul(2)))

  return length(position).sub(0.5).add(rays)
})

// @ts-ignore
const Sphere = Fn(([position, offset, radius]) => {
  const distance = length(position.sub(offset)).sub(radius)
  return distance
})

// @ts-ignore
const Ellipse = Fn(([position, radius, scale]) => {
  const scaledPosition = position.mul(scale)
  return length(scaledPosition).sub(radius)
})

// @ts-ignore
const Box = Fn(([position, dimensions]) => {
  const distance = abs(position).sub(dimensions)
  return length(max(distance, 0.0)).add(min(max(distance.x, distance.y), 0.0))
})

// @ts-ignore
const Sky = Fn(([position]) => {
  const topColor = vec3(0.1, 0.2, 0.5)
  const midColor = vec3(1.0, 0.4, 0.2)
  const bottomColor = vec3(0.9, 0.6, 0.3)

  //return mix(bottomColor, midColor, position.y.div(5))
  return mix(
    mix(bottomColor, midColor, position.y.div(10)),
    topColor,
    position.y.div(5)
  )
})

// @ts-ignore
const Tank = Fn(([position, offset]) => {
  const a = Ellipse(position.sub(offset), 5, vec2(1, 2))
  const b = Box(position.sub(offset).sub(vec2(0, -1.5)), vec2(4.5, 1))
  const c = Box(position.sub(offset).sub(vec2(0, 2.5)), vec2(2, 1)) // canopy
  const d = Box(position.sub(offset).sub(vec2(2, 2.7)), vec2(4, 0.2)) // turret
  const e = Box(position.sub(offset).sub(vec2(-3.5, 2.8)), vec2(0.1, 2)) // gun
  const f = Box(position.sub(offset).sub(vec2(0.5, 2.8)), vec2(1, 0.5)) // window

  const sdf = max(a, b.negate())
  sdf.assign(min(sdf, c))
  sdf.assign(min(sdf, d))
  sdf.assign(min(sdf, e))
  sdf.assign(max(sdf, f.negate()))

  return smoothstep(0.01, 0, sdf)
})

// @ts-ignore
const Camouflage = Fn(([position]) => {
  const n = mx_noise_float(position)
  const colour = vec3(0.4, 0.7, 0.3).toVar() // Light Green
  If(n.lessThan(0.2), () => {
    colour.assign(vec3(0.1, 0.3, 0.1)) // Dark green
  })
  If(n.lessThan(-0.3), () => {
    colour.assign(vec3(0.2, 0.5, 0.2)) // Medium green
  })
  return colour
})

const main = Fn(() => {
  const p = positionLocal.xy.mul(20)

  //const t = float(0) //time.div(5)
  const t = time.div(2)

  const finalColour = Sky(p).toVar()

  finalColour.assign(
    mix(
      finalColour,
      vec3(1, 0.75, 0),
      smoothstep(10, 0, sunRays(p.sub(vec2(7, 7))))
    )
  )

  const mountains = groundLayer(p.add(vec2(t, -1)).div(vec2(10, 10)))
  finalColour.assign(
    mix(finalColour, vec3(0.1, 0.1, 0.1), smoothstep(0.01, 0.0, mountains))
  )

  const hills = groundLayer(p.add(vec2(t.mul(2), 0)).div(vec2(5, 5)))
  finalColour.assign(
    mix(finalColour, vec3(0.2, 0.2, 0.1), smoothstep(0.01, 0.0, hills))
  )

  const mounds = groundLayer(p.add(vec2(t.mul(4), 3)).div(vec2(2.5, 2.5)))
  finalColour.assign(
    mix(finalColour, vec3(0.3, 0.3, 0.1), smoothstep(0.01, 0.0, mounds))
  )

  const bumps = groundLayer(p.add(vec2(t.mul(8), 6)).div(vec2(4, 1)))
  finalColour.assign(
    mix(finalColour, vec3(0.4, 0.4, 0.1), smoothstep(0.01, 0.0, bumps))
  )

  const foreground = groundLayer(p.add(vec2(t.mul(16), 8.5)).div(vec2(5, 1)))
  finalColour.assign(
    mix(finalColour, vec3(0.5, 0.4, 0.1), smoothstep(0.01, 0.0, foreground))
  )

  //let offset = float(-10).toVar()
  let offset = wheelOffset.x.toVar()

  Loop({ start: 0, end: 4, condition: '<' }, () => {
    const wheel = Sphere(
      p,
      vec2(
        offset,
        mx_noise_float(t.mul(2).add(offset.div(4)))
          .sub(5)
          .add(wheelOffset.y)
      ),
      1
    )
    finalColour.assign(
      mix(finalColour, vec3(0.025, 0.025, 0.025), smoothstep(0.01, 0, wheel))
    )

    offset.addAssign(2.25)
  })

  offset.subAssign(5.6)

  const bullet = Sphere(
    p,
    vec2(
      offset.sub(3.5),
      mx_noise_float(t.mul(2).add(offset.div(4))).add(bulletOffset)
    ),
    0.1
  )
  finalColour.assign(
    mix(finalColour, vec3(0.5, 0, 0), smoothstep(0.01, 0, bullet))
  )

  const shell = Sphere(
    p,
    vec2(
      offset.add(5).add(shellOffset),
      mx_noise_float(t.mul(2).add(offset.div(4))).sub(1.6)
    ),
    0.2
  )
  finalColour.assign(
    mix(finalColour, vec3(0.5, 0, 0), smoothstep(0.01, 0, shell))
  )

  const tank = Tank(
    p,
    vec2(
      offset,
      mx_noise_float(t.mul(2).add(offset.div(4)))
        .sub(4.3)
        .add(wheelOffset.y)
    )
  )
  finalColour.assign(
    mix(
      finalColour,
      Camouflage(
        p.sub(
          vec2(
            offset,
            mx_noise_float(t.mul(2).add(offset.div(4))).add(wheelOffset.y)
          )
        )
      ),
      tank
    )
  )

  return vec4(finalColour, 1)
})

// const material = new THREE.NodeMaterial()
// material.fragmentNode = main()

// const mesh = new THREE.Mesh(new THREE.PlaneGeometry(2, 2), material)
// scene.add(mesh)

scene.backgroundNode = main()

let canJump = true
const jump = () => {
  canJump = false
  // Going up
  new JEASINGS.JEasing(wheelOffset.value)
    .to(
      {
        y: 5,
      },
      250
    )
    .easing(JEASINGS.Cubic.Out)
    .start()
    .onComplete(() => {
      // Going down
      new JEASINGS.JEasing(wheelOffset.value)
        .to(
          {
            y: 0,
          },
          250
        )
        .easing(JEASINGS.Bounce.Out)
        .start()
        .onComplete(() => {
          canJump = true
        })
    })
}

let canShoot = true
const shoot = () => {
  canShoot = false

  bulletOffset.value = 0
  new JEASINGS.JEasing(bulletOffset)
    .to(
      {
        value: 20,
      },
      500
    )
    .start()
    .onComplete(() => {
      canShoot = true
    })

  shellOffset.value = 0
  new JEASINGS.JEasing(shellOffset)
    .to(
      {
        value: 25,
      },
      500
    )
    .start()
}

const keyMap: { [key: string]: boolean } = {}
const onDocumentKey = (e: KeyboardEvent) => {
  keyMap[e.code] = e.type === 'keydown'
  return false
}
document.addEventListener('keydown', onDocumentKey)
document.addEventListener('keyup', onDocumentKey)

const clock = new THREE.Clock()
let delta

function animate() {
  delta = clock.getDelta()

  controls.update()

  JEASINGS.update()

  if (keyMap['KeyW'] || keyMap['ArrowUp']) {
    // jump
    canJump && jump()
  }
  if (keyMap['KeyA'] || keyMap['ArrowLeft']) {
    // move backwards
    wheelOffset.value.x -= 4 * delta
  }
  if (keyMap['KeyD'] || keyMap['ArrowRight']) {
    // move forwards
    //console.log(wheelOffset.value)
    wheelOffset.value.x += 4 * delta
  }
  if (keyMap['Space']) {
    canShoot && shoot()
  }

  renderer.render(scene, camera)
}

Animated mx_noise_float Wave

JEasings