summaryrefslogtreecommitdiffhomepage
path: root/derelict.js
blob: 53358d615d353ed34c083db87e180a29a677a9ee (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
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
import * as THREE from 'https://unpkg.com/three@0.126.1/build/three.module.js'
import { OrbitControls } from 'https://unpkg.com/three@0.126.1/examples/jsm/controls/OrbitControls.js'
import { CSS2DRenderer, CSS2DObject } from 'https://unpkg.com/three@0.126.1/examples/jsm/renderers/CSS2DRenderer.js'

const ESI = "https://esi.evetech.net/latest"
const SCALE = 10000
const METERS_IN_AU = 149597871000
const EXPIRY = 1000 * 60 * 5

class SkirmishGrid {
	scene = new THREE.Scene()
	helper = new THREE.GridHelper(50, 50)
	camera
	controls
	renderer
	renderer2d
	active = false

	constructor({container, renderer, renderer2d}) {
		this.container = container
		this.renderer = renderer
		this.renderer2d = renderer2d

		const aspect = this.container.clientWidth / this.container.clientHeight
		this.camera = new THREE.PerspectiveCamera(80, aspect, 0.1, 1000)
		this.camera.position.set(8, 8, 8)
		this.camera.lookAt(0, 0, 0)
		this.controls = new OrbitControls(this.camera, this.renderer2d.domElement)
		this.controls.minDistance = 2
		this.controls.maxDistance = 30
		this.controls.enableDamping = true
		this.controls.dampingFactor = 0.4

		this.add(this.helper)
	}

	add(obj) {
		this.scene.add(obj)
	}

	draw() {
		this.renderer.render(this.scene, this.camera)
		this.renderer2d.render(this.scene, this.camera)
		this.controls.update()
		if (this.active)
			requestAnimationFrame(() => this.draw())
		else
			this.renderer2d.domElement.innerHTML = ''
	}

	onresize() {
		this.renderer.setSize(this.container.clientWidth, this.container.clientHeight)
		this.renderer2d.setSize(this.container.clientWidth, this.container.clientHeight)
		this.camera.aspect = this.container.clientWidth / this.container.clientHeight
		this.camera.updateProjectionMatrix()
	}

	enable() {
		this.active = true
	}

	disable() {
		this.active = false
	}
}

class Wreck {
	domElement = document.createElement('div')
	point = new THREE.Object3D()
	killmail

	constructor({killmail, icon, grid}) {
		const iconElement = document.importNode(icon, true)
		const labelElement = document.createElement('div')
		const object2d = new CSS2DObject(this.domElement)
		const ownerId = "alliance_id" in killmail.victim ? killmail.victim.alliance_id : killmail.victim.corporation_id
		const team = killmail.teams.findIndex(team => undefined !== team.find(id => id == ownerId)) == 0 ? "teamA" : "teamB"
		const shipTypeId = killmail.victim.ship_type_id

		fetch(`${ESI}/universe/types/${shipTypeId}/`, {cache: "force-cache"})
			.then(response => response.json())
			.then(typeId => {
				labelElement.textContent = typeId.name
				this.domElement.dataset.type = typeId.name
				return fetch(`${ESI}/universe/groups/${typeId.group_id}/`, {cache: "force-cache"})
			})
			.then(response => response.json())
			.then(group => this.domElement.dataset.group = group.name)

		labelElement.classList.add('label')

		this.killmail = killmail

		this.point.position.copy(killmail.victim.position)
		this.point.add(object2d)

		this.domElement.classList.add('wreck', team)
		this.domElement.appendChild(labelElement)
		this.domElement.appendChild(iconElement)
		this.domElement.onclick = () => window.open(`https://zkillboard.com/kill/${this.killmail.killmail_id}/`)
		this.domElement.oncontextmenu = () => {
			grid.controls.target.copy(this.point.position)
			grid.controls.update()
		}
	}

	toggleKilled(timestamp) {
		const timeDifference = timestamp - Date.parse(this.killmail.killmail_time)
		if (timeDifference > EXPIRY) {
			this.domElement.classList.add('expired')
			this.domElement.classList.remove('future', 'killed')
		}
		else if (timeDifference >= 0) {
			this.domElement.classList.add('killed')
			this.domElement.classList.remove('expired', 'future')
		}
		else {
			this.domElement.classList.add('future')
			this.domElement.classList.remove('killed', 'expired')
		}
	}
}

function loadWreckIcon() {
	return fetch("/wreck.svg")
		.then(response => response.text())
		.then(text => {
			const parser = new window.DOMParser()
			const svg = parser.parseFromString(text, "image/svg+xml")
			return svg.documentElement
		})
}

function vec3FromXYZ({x, y, z}) {
	return new THREE.Vector3(x, y, z)
}

function splitKillmails(clusters, killmail) {
	const vec3 = vec3FromXYZ(killmail.victim.position)
	const found = clusters.find(cluster => cluster[0].victim.position.distanceTo(vec3) < 100 * SCALE)
	killmail.victim.position = vec3
	if (found === undefined) {
		clusters.push([killmail])
	}
	else {
		found.push(killmail)
	}
	return clusters
}

function averagePosition(positions) {
	const sum = positions.reduce((sum, pos) => sum.add(pos), new THREE.Vector3())
	return sum.divideScalar(positions.length)
}

function processKillmails(obj, killmails, icon) {
	const dates = killmails.map(km => Date.parse(km.killmail_time))
	const start = Math.min(...dates)
	const end = Math.max(...dates)
	const clusters = killmails.reduce(splitKillmails, new Array())

	let elements = []
	let grids = []
	const gridSelection = document.getElementById("grid")
	clusters.forEach(cluster => {
		const option = document.createElement("option")
		const origin = new THREE.Vector3()
		origin.copy(cluster[0].victim.position)
		origin.divideScalar(METERS_IN_AU)
		option.text = `${origin.x.toFixed(1)} AU, ${origin.y.toFixed(1)} AU, ${origin.z.toFixed(1)} AU`
		gridSelection.options.add(option)

		const center = averagePosition(cluster.map(km => km.victim.position))
		const grid = new SkirmishGrid(obj)
		cluster.forEach(killmail => {
			killmail.victim.position.sub(center).divideScalar(SCALE)
			const wreck = new Wreck({killmail, icon, grid})
			grid.add(wreck.point)
			elements.push(wreck)
		})
		grids.push(grid)
		window.addEventListener('resize', () => grid.onresize())
	})
	gridSelection.oninput = () => {
		grids.forEach(g => g.disable())
		grids[gridSelection.selectedIndex].enable()
		grids[gridSelection.selectedIndex].draw()
	}
	gridSelection.oninput()

	obj.skybox.then(skybox => {
		const rt = new THREE.WebGLCubeRenderTarget(skybox.image.height)
		rt.fromEquirectangularTexture(obj.renderer, skybox)
		grids.forEach(g => g.scene.background = rt)
	})

	const timeline = document.getElementById("timeline")
	const step = 1000
	const toggleAll = () => elements.forEach(item => item.toggleKilled(timeline.value))
	timeline.min = start - step
	timeline.max = end + step + EXPIRY
	timeline.value = timeline.min
	timeline.step = step
	timeline.oninput = toggleAll
	toggleAll()
}

function init() {
	const container = document.getElementById("container")
	const renderer = new THREE.WebGLRenderer({antialias: true})
	const renderer2d = new CSS2DRenderer()

	renderer.setSize(container.clientWidth, container.clientHeight)
	renderer2d.setSize(container.clientWidth, container.clientHeight)
	renderer2d.domElement.style.position = 'absolute'
	renderer2d.domElement.style.top = '0px'

	container.appendChild(renderer.domElement)
	container.appendChild(renderer2d.domElement)

	const url = new URL(window.location.href)
	const loader = new THREE.TextureLoader()
	const skybox = loader.loadAsync("https://i.imgur.com/rDGOLFC.jpg") // TODO: Don't use imgur as CDN.

	let icon = loadWreckIcon()

	fetch(url.pathname.replace("view", "battles"))
		.then(response => response.json())
		.then(killmails => {
			const url = km => `${ESI}/killmails/${km.id}/${km.hash}/?datasource=tranquility`
			const retrieve = km => fetch(url(km))
				.then(response => response.json())
				.then(data => { data.teams = killmails.teams; return data })
			return Promise.all(killmails.killmails.map(retrieve))
		})
		.then(killmails => {
			icon.then(icon => processKillmails({skybox, renderer, renderer2d, container}, killmails, icon))
		})
}

init()