-
Notifications
You must be signed in to change notification settings - Fork 2
/
camera.go
494 lines (427 loc) · 15.4 KB
/
camera.go
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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
// Package kamera provides a camera object for Ebitengine v2.
package kamera
import (
"fmt"
"math"
"github.com/hajimehoshi/ebiten/v2"
"github.com/hajimehoshi/ebiten/v2/colorm"
"github.com/setanarut/fastnoise"
)
// SmoothType is the camera movement smoothing type.
type SmoothType int
const (
// None is instant movement to the target. No smoothing.
None SmoothType = iota
// Lerp is Lerp() function.
Lerp
// SmoothDamp is SmoothDamp() function.
SmoothDamp
)
// Camera object.
//
// Use the `Camera.LookAt()` to align the center of the camera to the target.
type Camera struct {
// Top-left X position of camera
TopLeftX float64
// Top-left Y position of camera
TopLeftY float64
// ZoomFactor is the camera zoom (scaling) factor. Default is 1.
ZoomFactor float64
// SmoothType is the camera movement smoothing type.
SmoothType SmoothType
// SmoothOptions holds the camera movement smoothing settings
SmoothOptions *SmoothOptions
// If ShakeEnabled is false, AddTrauma() has no effect and shake is always 0.
//
// The default value is false
ShakeEnabled bool
XAxisSmoothingDisabled bool
YAxisSmoothingDisabled bool
// ShakeOptions holds the camera shake options.
ShakeOptions *ShakeOptions
// private
drawOptions *ebiten.DrawImageOptions
drawOptionsCM *colorm.DrawImageOptions
angle, actualAngle, tickSpeed, tick, trauma, w, h, zoomFactorShake float64
tempTargetX, centerOffsetX, traumaOffsetX, currentVelocityX float64
tempTargetY, centerOffsetY, traumaOffsetY, currentVelocityY float64
}
// NewCamera returns new Camera
func NewCamera(lookAtX, lookAtY, w, h float64) *Camera {
c := &Camera{
ZoomFactor: 1.0,
SmoothType: None,
SmoothOptions: DefaultSmoothOptions(),
ShakeOptions: DefaultCameraShakeOptions(),
// private
w: w,
h: h,
angle: 0,
zoomFactorShake: 1.0,
trauma: 0,
drawOptions: &ebiten.DrawImageOptions{},
centerOffsetX: -(w * 0.5),
centerOffsetY: -(h * 0.5),
tickSpeed: 1.0 / 60.0,
tick: 0,
}
c.LookAt(lookAtX, lookAtY)
c.tempTargetX = lookAtX
c.tempTargetY = lookAtY
return c
}
func DefaultCameraShakeOptions() *ShakeOptions {
opt := &ShakeOptions{
Noise: fastnoise.New[float64](),
MaxX: 10.0,
MaxY: 10.0,
MaxAngle: 0.05,
MaxZoomFactor: 0.1,
Decay: 0.666,
TimeScale: 10,
}
opt.Noise.Frequency = 0.5
return opt
}
// smoothDampX gradually changes a value towards a desired goal over time for X axis.
func (cam *Camera) smoothDampX(targetX float64) float64 {
// Ensure smooth time is not too small to avoid division by zero
smoothTimeX := math.Max(0.0001, cam.SmoothOptions.SmoothDampTimeX)
// Calculate exponential decay factor for X
omegaX := 2.0 / smoothTimeX
xX := omegaX * 0.016666666666666666
expX := 1.0 / (1.0 + xX + 0.48*xX*xX + 0.235*xX*xX*xX)
// Calculate change with max speed
changeX := cam.tempTargetX - targetX
originalToX := targetX
maxChangeX := cam.SmoothOptions.SmoothDampMaxSpeedX * smoothTimeX
maxChangeXSq := maxChangeX * maxChangeX
// Limit change
if changeX*changeX > maxChangeXSq {
changeX = math.Copysign(maxChangeX, changeX)
}
targetX = cam.tempTargetX - changeX
// Calculate velocity and output with exponential decay
tempVelocityX := (cam.currentVelocityX + changeX*omegaX) * 0.016666666666666666
cam.currentVelocityX = (cam.currentVelocityX - tempVelocityX*omegaX) * expX
outputX := targetX + (changeX+tempVelocityX)*expX
// Check if we've overshot the target
origMinusCurrentX := originalToX - cam.tempTargetX
outMinusOrigX := outputX - originalToX
if origMinusCurrentX*outMinusOrigX > 0 {
outputX = originalToX
cam.currentVelocityX = (outputX - originalToX) / 0.016666666666666666
}
return outputX
}
// smoothDampY gradually changes a value towards a desired goal over time for Y axis.
func (cam *Camera) smoothDampY(targetY float64) float64 {
// Ensure smooth time is not too small to avoid division by zero
smoothTimeY := math.Max(0.0001, cam.SmoothOptions.SmoothDampTimeY)
// Calculate exponential decay factor for Y
omegaY := 2.0 / smoothTimeY
xY := omegaY * 0.016666666666666666
expY := 1.0 / (1.0 + xY + 0.48*xY*xY + 0.235*xY*xY*xY)
// Calculate change with max speed
changeY := cam.tempTargetY - targetY
originalToY := targetY
maxChangeY := cam.SmoothOptions.SmoothDampMaxSpeedY * smoothTimeY
maxChangeYSq := maxChangeY * maxChangeY
// Limit change
if changeY*changeY > maxChangeYSq {
changeY = math.Copysign(maxChangeY, changeY)
}
targetY = cam.tempTargetY - changeY
// Calculate velocity and output with exponential decay
tempVelocityY := (cam.currentVelocityY + changeY*omegaY) * 0.016666666666666666
cam.currentVelocityY = (cam.currentVelocityY - tempVelocityY*omegaY) * expY
outputY := targetY + (changeY+tempVelocityY)*expY
// Check if we've overshot the target
origMinusCurrentY := originalToY - cam.tempTargetY
outMinusOrigY := outputY - originalToY
if origMinusCurrentY*outMinusOrigY > 0 {
outputY = originalToY
cam.currentVelocityY = (outputY - originalToY) / 0.016666666666666666
}
return outputY
}
// LookAt aligns the midpoint of the camera viewport to the target.
//
// Camera motion smoothing is only applied with this method.
// Use this function only once in Update() and change only the (targetX, targetY)
func (cam *Camera) LookAt(targetX, targetY float64) {
switch cam.SmoothType {
case SmoothDamp:
if !cam.XAxisSmoothingDisabled && !cam.YAxisSmoothingDisabled {
cam.tempTargetX = cam.smoothDampX(targetX)
cam.tempTargetY = cam.smoothDampY(targetY)
cam.TopLeftX = cam.tempTargetX
cam.TopLeftY = cam.tempTargetY
} else if !cam.XAxisSmoothingDisabled && cam.YAxisSmoothingDisabled {
cam.tempTargetX = cam.smoothDampX(targetX)
cam.TopLeftX = cam.tempTargetX
cam.TopLeftY = targetY
} else if cam.XAxisSmoothingDisabled && !cam.YAxisSmoothingDisabled {
cam.tempTargetY = cam.smoothDampY(targetY)
cam.TopLeftY = cam.tempTargetY
cam.TopLeftX = targetX
} else {
cam.TopLeftX = targetX
cam.TopLeftY = targetY
}
case Lerp:
if !cam.XAxisSmoothingDisabled && !cam.YAxisSmoothingDisabled {
cam.tempTargetX = lerp(cam.tempTargetX, targetX, cam.SmoothOptions.LerpSpeedX)
cam.tempTargetY = lerp(cam.tempTargetY, targetY, cam.SmoothOptions.LerpSpeedY)
cam.TopLeftX = cam.tempTargetX
cam.TopLeftY = cam.tempTargetY
} else if !cam.XAxisSmoothingDisabled && cam.YAxisSmoothingDisabled {
cam.tempTargetX = lerp(cam.tempTargetX, targetX, cam.SmoothOptions.LerpSpeedX)
cam.TopLeftX = cam.tempTargetX
cam.TopLeftY = targetY
} else if cam.XAxisSmoothingDisabled && !cam.YAxisSmoothingDisabled {
cam.tempTargetY = lerp(cam.tempTargetY, targetY, cam.SmoothOptions.LerpSpeedY)
cam.TopLeftY = cam.tempTargetY
cam.TopLeftX = targetX
} else {
cam.TopLeftX = targetX
cam.TopLeftY = targetY
}
default:
cam.TopLeftX = targetX
cam.TopLeftY = targetY
}
if cam.ShakeEnabled {
if cam.trauma > 0 {
var shake = math.Pow(cam.trauma, 2)
noiseValueX := cam.ShakeOptions.Noise.GetNoise3D(cam.tick*cam.ShakeOptions.TimeScale, 0, 0)
noiseValueY := cam.ShakeOptions.Noise.GetNoise3D(0, cam.tick*cam.ShakeOptions.TimeScale, 0)
noiseValueAngle := cam.ShakeOptions.Noise.GetNoise3D(0, 0, cam.tick*cam.ShakeOptions.TimeScale)
cam.traumaOffsetX = noiseValueX * cam.ShakeOptions.MaxX * shake
cam.traumaOffsetY = noiseValueY * cam.ShakeOptions.MaxY * shake
cam.actualAngle = noiseValueAngle * cam.ShakeOptions.MaxAngle * shake
noiseValueZoom := cam.ShakeOptions.Noise.GetNoise3D(cam.tick*cam.ShakeOptions.TimeScale+300, 0, 0)
cam.zoomFactorShake = noiseValueZoom * cam.ShakeOptions.MaxZoomFactor * shake
cam.zoomFactorShake *= cam.ZoomFactor
cam.zoomFactorShake += cam.ZoomFactor
// clamp
cam.trauma = min(max(cam.trauma-(cam.tickSpeed*cam.ShakeOptions.Decay), 0), 1)
} else {
cam.actualAngle = 0.0
cam.zoomFactorShake = cam.ZoomFactor
}
// offset
cam.actualAngle += cam.angle
cam.TopLeftX += cam.traumaOffsetX
cam.TopLeftY += cam.traumaOffsetY
// tick
cam.tick += cam.tickSpeed
if cam.tick > 1000000 {
cam.tick = 0
}
} else {
cam.zoomFactorShake = cam.ZoomFactor
cam.actualAngle = cam.angle
cam.TopLeftX += cam.centerOffsetX
cam.TopLeftY += cam.centerOffsetY
cam.trauma = 0
cam.traumaOffsetX, cam.traumaOffsetY = 0, 0
}
}
// AddTrauma adds trauma. Factor is in the range [0-1]
func (cam *Camera) AddTrauma(factor float64) {
if cam.ShakeEnabled {
cam.trauma = min(max(cam.trauma+factor, 0), 1) // clamp
}
}
// TopLeft returns top-left position of the camera in world-space
func (cam *Camera) TopLeft() (X float64, Y float64) {
return cam.TopLeftX, cam.TopLeftY
}
// Right returns the right edge position of the camera in world-space.
func (cam *Camera) Right() float64 {
return cam.TopLeftX + cam.w
}
// Bottom returns the bottom edge position of the camera in world-space.
func (cam *Camera) Bottom() float64 {
return cam.TopLeftY + cam.h
}
// SetTopLeft sets top-left position of the camera in world-space.
//
// Unlike the LookAt() method, the position is set directly without any smoothing.
//
// Useful for static cameras.
func (cam *Camera) SetTopLeft(x, y float64) {
cam.TopLeftX, cam.TopLeftY = x, y
}
// Center returns center point of the camera in world-space
func (cam *Camera) Center() (X float64, Y float64) {
return cam.TopLeftX - cam.centerOffsetX, cam.TopLeftY - cam.centerOffsetY
}
// ActualAngle returns camera rotation angle (including the angle of trauma shaking.).
//
// The unit is radian.
func (cam *Camera) ActualAngle() (angle float64) {
return cam.actualAngle
}
// Angle returns camera rotation angle (The angle of trauma shake is not included.).
//
// The unit is radian.
func (cam *Camera) Angle() (angle float64) {
return cam.angle
}
// SetAngle sets rotation. The unit is radian.
func (cam *Camera) SetAngle(angle float64) {
cam.angle = angle
}
// Width returns width of the camera
func (cam *Camera) Width() float64 {
return cam.w
}
// Height returns height of the camera
func (cam *Camera) Height() float64 {
return cam.h
}
// SetSize sets camera rectangle size from center.
func (cam *Camera) SetSize(w, h float64) {
cx, cy := cam.Center()
cam.w, cam.h = w, h
cam.centerOffsetX = -(w * 0.5)
cam.centerOffsetY = -(h * 0.5)
cam.LookAt(cx, cy)
}
// Reset resets rotation and zoom factor to zero
func (cam *Camera) Reset() {
cam.angle, cam.ZoomFactor, cam.zoomFactorShake = 0.0, 1.0, 1.0
}
const cameraStats = `TargetX: %.2f
TargetY: %.2f
Cam Rotation: %.2f
Zoom factor: %.2f
ShakeEnabled: %v
Smoothing Function: %s
LerpSpeedX: %.4f
LerpSpeedY: %.4f
SmoothDampTimeX: %.4f
SmoothDampTimeY: %.4f
SmoothDampMaxSpeedX: %.2f
SmoothDampMaxSpeedY: %.2f`
// String returns camera values as string
func (cam *Camera) String() string {
smoothTypeStr := ""
switch cam.SmoothType {
case None:
smoothTypeStr = "None"
case Lerp:
smoothTypeStr = "Lerp"
case SmoothDamp:
smoothTypeStr = "SmoothDamp"
}
return fmt.Sprintf(
cameraStats,
cam.TopLeftX-cam.centerOffsetX,
cam.TopLeftY-cam.centerOffsetY,
cam.actualAngle,
cam.zoomFactorShake,
cam.ShakeEnabled,
smoothTypeStr,
cam.SmoothOptions.LerpSpeedX,
cam.SmoothOptions.LerpSpeedY,
cam.SmoothOptions.SmoothDampTimeX,
cam.SmoothOptions.SmoothDampTimeY,
cam.SmoothOptions.SmoothDampMaxSpeedX,
cam.SmoothOptions.SmoothDampMaxSpeedY,
)
}
// ScreenToWorld converts screen-space coordinates to world-space
func (cam *Camera) ScreenToWorld(screenX, screenY int) (worldX float64, worldY float64) {
g := ebiten.GeoM{}
cam.ApplyCameraTransform(&g)
if g.IsInvertible() {
g.Invert()
worldX, worldY := g.Apply(float64(screenX), float64(screenY))
return worldX, worldY
} else {
// When scaling it can happened that matrix is not invertable
return math.NaN(), math.NaN()
}
}
// ApplyCameraTransformToPoint applies camera transformation to given point
func (cam *Camera) ApplyCameraTransformToPoint(x, y float64) (float64, float64) {
geoM := ebiten.GeoM{}
cam.ApplyCameraTransform(&geoM)
return geoM.Apply(x, y)
}
// ApplyCameraTransform applies geometric transformation to given geoM
func (cam *Camera) ApplyCameraTransform(geoM *ebiten.GeoM) {
geoM.Translate(-cam.TopLeftX, -cam.TopLeftY) // camera movement
geoM.Translate(cam.centerOffsetX, cam.centerOffsetY) // rotate and scale from center.
geoM.Rotate(cam.actualAngle) // rotate
geoM.Scale(cam.zoomFactorShake, cam.zoomFactorShake) // apply zoom factor
geoM.Translate(math.Abs(cam.centerOffsetX), math.Abs(cam.centerOffsetY)) // restore center translation
}
// Draw applies the Camera's geometric transformation then draws the object on the screen with drawing options.
func (cam *Camera) Draw(worldObject *ebiten.Image, worldObjectOps *ebiten.DrawImageOptions, screen *ebiten.Image) {
cam.drawOptions = worldObjectOps
cam.ApplyCameraTransform(&cam.drawOptions.GeoM)
screen.DrawImage(worldObject, cam.drawOptions)
cam.drawOptions.GeoM.Reset()
}
// DrawWithColorM applies the Camera's geometric transformation then draws the object on the screen with colorm package drawing options.
func (cam *Camera) DrawWithColorM(worldObject *ebiten.Image, cm colorm.ColorM, worldObjectOps *colorm.DrawImageOptions, screen *ebiten.Image) {
cam.drawOptionsCM = worldObjectOps
cam.ApplyCameraTransform(&cam.drawOptionsCM.GeoM)
colorm.DrawImage(screen, worldObject, cm, worldObjectOps)
cam.drawOptionsCM.GeoM.Reset()
}
type ShakeOptions struct {
// Noise generator for noise types and settings.
Noise *fastnoise.State[float64]
MaxX float64 // Maximum X-axis shake. 0 means disabled
MaxY float64 // Maximum Y-axis shake. 0 means disabled
MaxAngle float64 // Max shake angle (radians). 0 means disabled
MaxZoomFactor float64 // Zoom factor strength [1-0]. 0 means disabled
TimeScale float64 // Noise time domain speed
Decay float64 // Decay for trauma
}
// SmoothOptions is the camera movement smoothing options.
type SmoothOptions struct {
// LerpSpeedX is the X-axis linear interpolation speed every frame.
// Value is in the range [0-1]. Default value is 0.09
//
// A smaller value will reach the target slower.
LerpSpeedX float64
// LerpSpeedY is the Y-axis linear interpolation speed every frame. Value is in the range [0-1].
//
// A smaller value will reach the target slower.
LerpSpeedY float64
// SmoothDampTimeX is the X-Axis approximate time it will take to reach the target.
//
// A smaller value will reach the target faster. Default value is 0.2
SmoothDampTimeX float64
// SmoothDampTimeY is the Y-Axis approximate time it will take to reach the target.
//
// A smaller value will reach the target faster. Default value is 0.2
SmoothDampTimeY float64
// SmoothDampMaxSpeedX is the maximum speed the camera can move while smooth damping in X-Axis
//
// Default value is 1000
SmoothDampMaxSpeedX float64
// SmoothDampMaxSpeedY is the maximum speed the camera can move while smooth damping in Y-Axis
//
// Default value is 1000
SmoothDampMaxSpeedY float64
}
func DefaultSmoothOptions() *SmoothOptions {
return &SmoothOptions{
LerpSpeedX: 0.09,
LerpSpeedY: 0.09,
SmoothDampTimeX: 0.2,
SmoothDampTimeY: 0.2,
SmoothDampMaxSpeedX: 1000.0,
SmoothDampMaxSpeedY: 1000.0,
}
}
func lerp(start, end, t float64) float64 {
return start + t*(end-start)
}