1 /*
2 * Copyright (C) 2023 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package com.android.egg.landroid
18
19 import androidx.compose.ui.geometry.Offset
20 import kotlin.math.PI
21 import kotlin.math.atan2
22 import kotlin.math.cos
23 import kotlin.math.sin
24
25 const val PIf = PI.toFloat()
26 const val PI2f = (2 * PI).toFloat()
27
28 typealias Vec2 = Offset
29
strnull30 fun Vec2.str(fmt: String = "%+.2f"): String = "<$fmt,$fmt>".format(x, y)
31
32 fun Vec2(x: Float, y: Float): Vec2 = Offset(x, y)
33
34 fun Vec2.mag(): Float {
35 return getDistance()
36 }
37
distancenull38 fun Vec2.distance(other: Vec2): Float {
39 return (this - other).mag()
40 }
41
Vec2null42 fun Vec2.angle(): Float {
43 return atan2(y, x)
44 }
45
Vec2null46 fun Vec2.dot(o: Vec2): Float {
47 return x * o.x + y * o.y
48 }
49
productnull50 fun Vec2.product(f: Float): Vec2 {
51 return Vec2(x * f, y * f)
52 }
53
makeWithAngleMagnull54 fun Offset.Companion.makeWithAngleMag(a: Float, m: Float): Vec2 {
55 return Vec2(m * cos(a), m * sin(a))
56 }
57
rotatenull58 fun Vec2.rotate(angle: Float, origin: Vec2 = Vec2.Zero): Offset {
59 val translated = this - origin
60 return origin +
61 Offset(
62 (translated.x * cos(angle) - translated.y * sin(angle)),
63 (translated.x * sin(angle) + translated.y * cos(angle))
64 )
65 }
66