summaryrefslogtreecommitdiff
path: root/src/main/java/at/hannibal2/skyhanni/data/model/Graph.kt
blob: 8c63be891fb37038522c8137073429cd7a31f30e (plain)
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
package at.hannibal2.skyhanni.data.model

import at.hannibal2.skyhanni.utils.LorenzUtils.round
import at.hannibal2.skyhanni.utils.LorenzVec
import at.hannibal2.skyhanni.utils.json.SkyHanniTypeAdapters.registerTypeAdapter
import at.hannibal2.skyhanni.utils.json.fromJson
import com.google.gson.GsonBuilder
import com.google.gson.JsonElement
import com.google.gson.annotations.Expose
import com.google.gson.stream.JsonToken
import java.util.PriorityQueue

@JvmInline
value class Graph(
    @Expose val nodes: List<GraphNode>,
) : List<GraphNode> {
    override val size
        get() = nodes.size

    override fun contains(element: GraphNode) = nodes.contains(element)

    override fun containsAll(elements: Collection<GraphNode>) = nodes.containsAll(elements)

    override fun get(index: Int) = nodes.get(index)

    override fun isEmpty() = nodes.isEmpty()

    override fun indexOf(element: GraphNode) = nodes.indexOf(element)

    override fun iterator(): Iterator<GraphNode> = nodes.iterator()
    override fun listIterator() = nodes.listIterator()

    override fun listIterator(index: Int) = nodes.listIterator(index)

    override fun subList(fromIndex: Int, toIndex: Int) = nodes.subList(fromIndex, toIndex)

    override fun lastIndexOf(element: GraphNode) = nodes.lastIndexOf(element)

    companion object {
        val gson = GsonBuilder().setPrettyPrinting().registerTypeAdapter<Graph>(
            { out, value ->
                out.beginObject()
                value.forEach {
                    out.name(it.id.toString()).beginObject()

                    out.name("Position").value(with(it.position) { "$x:$y:$z" })

                    it.name?.let {
                        out.name("Name").value(it)
                    }

                    it.tagNames?.takeIf { it.isNotEmpty() }?.let {
                        out.name("Tags")
                        out.beginArray()
                        for (tagName in it) {
                            out.value(tagName)
                        }
                        out.endArray()
                    }

                    out.name("Neighbours")
                    out.beginObject()
                    for ((node, weight) in it.neighbours) {
                        val id = node.id.toString()
                        out.name(id).value(weight.round(2))
                    }
                    out.endObject()

                    out.endObject()
                }
                out.endObject()
            },
            { reader ->
                reader.beginObject()
                val list = mutableListOf<GraphNode>()
                val neighbourMap = mutableMapOf<GraphNode, List<Pair<Int, Double>>>()
                while (reader.hasNext()) {
                    val id = reader.nextName().toInt()
                    reader.beginObject()
                    var position: LorenzVec? = null
                    var name: String? = null
                    var tags: List<String>? = null
                    var neighbors = mutableListOf<Pair<Int, Double>>()
                    while (reader.hasNext()) {
                        if (reader.peek() != JsonToken.NAME) {
                            reader.skipValue()
                            continue
                        }
                        when (reader.nextName()) {
                            "Position" -> {
                                position = reader.nextString().split(":").let { parts ->
                                    LorenzVec(parts[0].toDouble(), parts[1].toDouble(), parts[2].toDouble())
                                }
                            }

                            "Neighbours" -> {
                                reader.beginObject()
                                while (reader.hasNext()) {
                                    val nId = reader.nextName().toInt()
                                    val distance = reader.nextDouble()
                                    neighbors.add(nId to distance)
                                }
                                reader.endObject()
                            }

                            "Name" -> {
                                name = reader.nextString()
                            }

                            "Tags" -> {
                                tags = mutableListOf()
                                reader.beginArray()
                                while (reader.hasNext()) {
                                    val tagName = reader.nextString()
                                    tags.add(tagName)
                                }
                                reader.endArray()
                            }

                        }
                    }
                    val node = GraphNode(id, position!!, name, tags)
                    list.add(node)
                    neighbourMap[node] = neighbors
                    reader.endObject()
                }
                neighbourMap.forEach { (node, edge) ->
                    node.neighbours = edge.associate { (id, distance) ->
                        list.first { it.id == id } to distance
                    }
                }
                reader.endObject()
                Graph(list)
            },
        ).create()

        fun fromJson(json: String): Graph = gson.fromJson<Graph>(json)
        fun fromJson(json: JsonElement): Graph = gson.fromJson<Graph>(json)
    }
}

// The node object that gets parsed from/to json
class GraphNode(val id: Int, val position: LorenzVec, val name: String? = null, val tagNames: List<String>? = null) {

    val tags: List<GraphNodeTag> by lazy {
        tagNames?.mapNotNull { GraphNodeTag.byId(it) } ?: emptyList()
    }

    /** Keys are the neighbours and value the edge weight (e.g. Distance) */
    lateinit var neighbours: Map<GraphNode, Double>

    override fun hashCode(): Int {
        return id
    }

    override fun equals(other: Any?): Boolean {
        if (this === other) return true
        if (javaClass != other?.javaClass) return false

        other as GraphNode

        if (id != other.id) return false

        return true
    }
}

fun Graph.findShortestPathAsGraph(start: GraphNode, end: GraphNode): Graph = this.findShortestPathAsGraphWithDistance(start, end).first

fun Graph.findShortestPathAsGraphWithDistance(start: GraphNode, end: GraphNode): Pair<Graph, Double> {
    val distances = mutableMapOf<GraphNode, Double>()
    val previous = mutableMapOf<GraphNode, GraphNode>()
    val visited = mutableSetOf<GraphNode>()
    val queue = PriorityQueue<GraphNode>(compareBy { distances.getOrDefault(it, Double.MAX_VALUE) })

    distances[start] = 0.0
    queue.add(start)

    while (queue.isNotEmpty()) {
        val current = queue.poll()
        if (current == end) break

        visited.add(current)

        current.neighbours.forEach { (neighbour, weight) ->
            if (neighbour !in visited) {
                val newDistance = distances.getValue(current) + weight
                if (newDistance < distances.getOrDefault(neighbour, Double.MAX_VALUE)) {
                    distances[neighbour] = newDistance
                    previous[neighbour] = current
                    queue.add(neighbour)
                }
            }
        }
    }

    return Graph(
        buildList {
            var current = end
            while (current != start) {
                add(current)
                current = previous[current] ?: return Graph(emptyList()) to 0.0
            }
            add(start)
        }.reversed(),
    ) to distances[end]!!
}

fun Graph.findShortestPath(start: GraphNode, end: GraphNode): List<LorenzVec> = this.findShortestPathAsGraph(start, end).toPositionsList()

fun Graph.findShortestDistance(start: GraphNode, end: GraphNode): Double = this.findShortestPathAsGraphWithDistance(start, end).second

fun Graph.toPositionsList() = this.map { it.position }

fun Graph.toJson(): String = Graph.gson.toJson(this)