orienteeringCourse.ts 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. import { type LonLatPoint } from './projection'
  2. export type OrienteeringCourseNodeKind = 'start' | 'control' | 'finish'
  3. export interface OrienteeringCourseStart {
  4. label: string
  5. point: LonLatPoint
  6. headingDeg: number | null
  7. }
  8. export interface OrienteeringCourseControl {
  9. label: string
  10. point: LonLatPoint
  11. sequence: number
  12. }
  13. export interface OrienteeringCourseFinish {
  14. label: string
  15. point: LonLatPoint
  16. }
  17. export interface OrienteeringCourseLeg {
  18. fromKind: OrienteeringCourseNodeKind
  19. toKind: OrienteeringCourseNodeKind
  20. fromPoint: LonLatPoint
  21. toPoint: LonLatPoint
  22. }
  23. export interface OrienteeringCourseLayers {
  24. starts: OrienteeringCourseStart[]
  25. controls: OrienteeringCourseControl[]
  26. finishes: OrienteeringCourseFinish[]
  27. legs: OrienteeringCourseLeg[]
  28. }
  29. export interface OrienteeringCourseData {
  30. title: string
  31. layers: OrienteeringCourseLayers
  32. }
  33. interface ParsedPlacemarkPoint {
  34. label: string
  35. point: LonLatPoint
  36. explicitKind: OrienteeringCourseNodeKind | null
  37. }
  38. interface OrderedCourseNode {
  39. label: string
  40. point: LonLatPoint
  41. kind: OrienteeringCourseNodeKind
  42. }
  43. function decodeXmlEntities(text: string): string {
  44. return text
  45. .replace(/&lt;/g, '<')
  46. .replace(/&gt;/g, '>')
  47. .replace(/&quot;/g, '"')
  48. .replace(/&#39;/g, "'")
  49. .replace(/&apos;/g, "'")
  50. .replace(/&amp;/g, '&')
  51. }
  52. function stripXml(text: string): string {
  53. return decodeXmlEntities(text.replace(/<[^>]+>/g, ' ')).replace(/\s+/g, ' ').trim()
  54. }
  55. function extractTagText(block: string, tagName: string): string {
  56. const match = block.match(new RegExp(`<${tagName}\\b[^>]*>([\\s\\S]*?)<\\/${tagName}>`, 'i'))
  57. return match ? stripXml(match[1]) : ''
  58. }
  59. function parseCoordinateTuple(rawValue: string): LonLatPoint | null {
  60. const parts = rawValue.trim().split(',')
  61. if (parts.length < 2) {
  62. return null
  63. }
  64. const lon = Number(parts[0])
  65. const lat = Number(parts[1])
  66. if (!Number.isFinite(lon) || !Number.isFinite(lat)) {
  67. return null
  68. }
  69. return { lon, lat }
  70. }
  71. function extractPointCoordinates(block: string): LonLatPoint | null {
  72. const pointMatch = block.match(/<Point\b[\s\S]*?<coordinates>([\s\S]*?)<\/coordinates>[\s\S]*?<\/Point>/i)
  73. if (!pointMatch) {
  74. return null
  75. }
  76. const coordinateMatch = pointMatch[1].trim().match(/-?\d+(?:\.\d+)?,-?\d+(?:\.\d+)?(?:,-?\d+(?:\.\d+)?)?/)
  77. return coordinateMatch ? parseCoordinateTuple(coordinateMatch[0]) : null
  78. }
  79. function normalizeCourseLabel(label: string): string {
  80. return label.trim().replace(/\s+/g, ' ')
  81. }
  82. function inferExplicitKind(label: string, placemarkBlock: string): OrienteeringCourseNodeKind | null {
  83. const normalized = label.toUpperCase().replace(/[^A-Z0-9]/g, '')
  84. const styleHint = placemarkBlock.toUpperCase()
  85. if (
  86. normalized === 'S'
  87. || normalized.startsWith('START')
  88. || /^S\d+$/.test(normalized)
  89. || styleHint.includes('START')
  90. || styleHint.includes('TRIANGLE')
  91. ) {
  92. return 'start'
  93. }
  94. if (
  95. normalized === 'F'
  96. || normalized === 'M'
  97. || normalized.startsWith('FINISH')
  98. || normalized.startsWith('GOAL')
  99. || /^F\d+$/.test(normalized)
  100. || styleHint.includes('FINISH')
  101. || styleHint.includes('GOAL')
  102. ) {
  103. return 'finish'
  104. }
  105. return null
  106. }
  107. function extractPlacemarkPoints(kmlText: string): ParsedPlacemarkPoint[] {
  108. const placemarkBlocks = kmlText.match(/<Placemark\b[\s\S]*?<\/Placemark>/gi) || []
  109. const points: ParsedPlacemarkPoint[] = []
  110. for (const placemarkBlock of placemarkBlocks) {
  111. const point = extractPointCoordinates(placemarkBlock)
  112. if (!point) {
  113. continue
  114. }
  115. const label = normalizeCourseLabel(extractTagText(placemarkBlock, 'name'))
  116. points.push({
  117. label,
  118. point,
  119. explicitKind: inferExplicitKind(label, placemarkBlock),
  120. })
  121. }
  122. return points
  123. }
  124. function classifyOrderedNodes(points: ParsedPlacemarkPoint[]): OrderedCourseNode[] {
  125. if (!points.length) {
  126. return []
  127. }
  128. const startIndex = points.findIndex((point) => point.explicitKind === 'start')
  129. let finishIndex = -1
  130. for (let index = points.length - 1; index >= 0; index -= 1) {
  131. if (points[index].explicitKind === 'finish') {
  132. finishIndex = index
  133. break
  134. }
  135. }
  136. return points.map((point, index) => {
  137. let kind = point.explicitKind
  138. if (!kind) {
  139. if (startIndex === -1 && index === 0) {
  140. kind = 'start'
  141. } else if (finishIndex === -1 && points.length > 1 && index === points.length - 1) {
  142. kind = 'finish'
  143. } else {
  144. kind = 'control'
  145. }
  146. }
  147. return {
  148. label: point.label,
  149. point: point.point,
  150. kind,
  151. }
  152. })
  153. }
  154. function getInitialBearingDeg(from: LonLatPoint, to: LonLatPoint): number {
  155. const fromLatRad = from.lat * Math.PI / 180
  156. const toLatRad = to.lat * Math.PI / 180
  157. const deltaLonRad = (to.lon - from.lon) * Math.PI / 180
  158. const y = Math.sin(deltaLonRad) * Math.cos(toLatRad)
  159. const x = Math.cos(fromLatRad) * Math.sin(toLatRad)
  160. - Math.sin(fromLatRad) * Math.cos(toLatRad) * Math.cos(deltaLonRad)
  161. const bearingDeg = Math.atan2(y, x) * 180 / Math.PI
  162. return (bearingDeg + 360) % 360
  163. }
  164. function buildCourseLayers(nodes: OrderedCourseNode[]): OrienteeringCourseLayers {
  165. const starts: OrienteeringCourseStart[] = []
  166. const controls: OrienteeringCourseControl[] = []
  167. const finishes: OrienteeringCourseFinish[] = []
  168. const legs: OrienteeringCourseLeg[] = []
  169. let controlSequence = 1
  170. nodes.forEach((node, index) => {
  171. const nextNode = index < nodes.length - 1 ? nodes[index + 1] : null
  172. const label = node.label || (
  173. node.kind === 'start'
  174. ? 'Start'
  175. : node.kind === 'finish'
  176. ? 'Finish'
  177. : String(controlSequence)
  178. )
  179. if (node.kind === 'start') {
  180. starts.push({
  181. label,
  182. point: node.point,
  183. headingDeg: nextNode ? getInitialBearingDeg(node.point, nextNode.point) : null,
  184. })
  185. return
  186. }
  187. if (node.kind === 'finish') {
  188. finishes.push({
  189. label,
  190. point: node.point,
  191. })
  192. return
  193. }
  194. controls.push({
  195. label,
  196. point: node.point,
  197. sequence: controlSequence,
  198. })
  199. controlSequence += 1
  200. })
  201. for (let index = 1; index < nodes.length; index += 1) {
  202. legs.push({
  203. fromKind: nodes[index - 1].kind,
  204. toKind: nodes[index].kind,
  205. fromPoint: nodes[index - 1].point,
  206. toPoint: nodes[index].point,
  207. })
  208. }
  209. return {
  210. starts,
  211. controls,
  212. finishes,
  213. legs,
  214. }
  215. }
  216. export function parseOrienteeringCourseKml(kmlText: string): OrienteeringCourseData {
  217. const points = extractPlacemarkPoints(kmlText)
  218. if (!points.length) {
  219. throw new Error('KML 中没有可用的 Point 控制点')
  220. }
  221. const documentTitle = extractTagText(kmlText, 'name')
  222. const nodes = classifyOrderedNodes(points)
  223. return {
  224. title: documentTitle || 'Orienteering Course',
  225. layers: buildCourseLayers(nodes),
  226. }
  227. }