-
Notifications
You must be signed in to change notification settings - Fork 83
/
factory.js
573 lines (549 loc) · 19.6 KB
/
factory.js
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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
/*Copyright 2019-2021 Kirk McDonald
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.*/
import { Formatter } from "./align.js"
import { renderDebug } from "./debug.js"
import { displayItems } from "./display.js"
import { formatSettings } from "./fragment.js"
import { PriorityList } from "./priority.js"
import { Rational, zero, half, one } from "./rational.js"
import { DISABLED_RECIPE_PREFIX } from "./recipe.js"
import { solve } from "./solve.js"
import { BuildTarget } from "./target.js"
import { reapTooltips } from "./tooltip.js"
import { renderTotals } from "./visualize.js"
const DEFAULT_ITEM_KEY = "supercomputer"
let minerCategories = new Set(["mineral", "oil"])
export let resourcePurities = [
{key: "0", name: "Impure", factor: half},
{key: "1", name: "Normal", factor: one},
{key: "2", name: "Pure", factor: Rational.from_float(2)},
]
export let DEFAULT_PURITY = resourcePurities[1]
export let DEFAULT_BELT = "belt1"
export let DEFAULT_PIPE = "pipe1"
const OVERCLOCK_POWER_EXPONENT = Math.log2(2.5)
class FactorySpecification {
constructor() {
// Game data definitions
this.items = null
this.recipes = null
this.buildings = null
this.belts = null
this.pipes = null
this.itemTiers = []
this.buildTargets = []
// Map resource recipe to {miner, purity}
this.miners = new Map()
this.minerSettings = new Map()
// Map recipe to overclock factor
this.overclock = new Map()
// Map recipe to somersloop count
this.somersloop = new Map()
this.belt = null
this.ignore = new Set()
this.disable = new Set()
this.defaultDisable = new Set()
this.priority = null
this.defaultPriority = null
this.format = new Formatter()
this.lastTotals = null
this.lastPartial = null
this.lastTableau = null
this.lastMetadata = null
this.lastSolution = null
this.debug = false
}
setData(items, recipes, buildings, belts, pipes) {
this.items = items
let tierMap = new Map()
this.defaultDisable = new Set()
for (let [itemKey, item] of items) {
let tier = tierMap.get(item.tier)
if (tier === undefined) {
tier = []
tierMap.set(item.tier, tier)
}
tier.push(item)
// By default, disable all recipes but one for (most) items that
// have multiple recipes.
if (item.recipes.length > 1) {
let chosen = null
let skip = false
for (let recipe of item.recipes) {
if (recipe.isResource()) {
chosen = recipe
}
// If any of this item's recipes produce multiple items,
// then don't disable any of these recipes, and let the
// linear program sort it out.
if (recipe.products.length > 1) {
skip = true
}
}
if (skip) {
continue
}
if (chosen === null) {
chosen = item.recipes[0]
}
for (let recipe of item.recipes) {
if (recipe !== chosen) {
this.defaultDisable.add(recipe)
}
}
}
}
this.itemTiers = []
for (let [tier, tierItems] of tierMap) {
this.itemTiers.push(tierItems)
}
this.itemTiers.sort((a, b) => a[0].tier - b[0].tier)
this.recipes = recipes
this.resourceNameMap = new Map()
for (let [key, recipe] of recipes) {
if (recipe.isResource()) {
this.resourceNameMap.set(recipe.name, recipe)
}
}
this.buildings = new Map()
for (let building of buildings) {
let category = this.buildings.get(building.category)
if (category === undefined) {
category = []
this.buildings.set(building.category, category)
}
category.push(building)
if (minerCategories.has(building.category)) {
this.miners.set(building.key, building)
}
}
this.belts = belts
this.belt = belts.get(DEFAULT_BELT)
this.pipes = pipes
this.pipe = belts.get(DEFAULT_PIPE)
this.initMinerSettings()
this.defaultPriority = this.getDefaultPriorityArray()
this.priority = null
}
setDefaultDisable() {
this.disable.clear()
for (let recipe of this.defaultDisable) {
this.setDisable(recipe)
}
}
isDefaultDisable() {
if (this.disable.size !== this.defaultDisable.size) {
return false
}
for (let recipe of this.disable) {
if (!this.defaultDisable.has(recipe)) {
return false
}
}
return true
}
setDisable(recipe) {
let candidates = new Set()
let items = new Set()
for (let ing of recipe.products) {
let item = ing.item
items.add(item)
if (!this.isItemDisabled(item) && !this.ignore.has(item)) {
candidates.add(item)
}
}
this.disable.add(recipe)
for (let item of candidates) {
if (this.isItemDisabled(item)) {
let resource = this.priority.getResource(item.disableRecipe)
// The item might already be in the priority list due to being
// ignored. In this case, do nothing.
if (resource === null) {
let level = this.priority.getLastLevel()
let makeNew = true
for (let r of level) {
if (r.recipe.isDisable()) {
makeNew = false
break
}
}
if (makeNew) {
level = this.priority.addPriorityBefore(null)
}
let hundred = Rational.from_float(100)
this.priority.addRecipe(item.disableRecipe, hundred, level)
}
}
}
// Update build targets.
for (let target of this.buildTargets) {
if (items.has(target.item)) {
target.displayRecipes()
}
}
}
setEnable(recipe) {
// Enabling this recipe could potentially remove these items'
// disableRecipe from the priority list. The item is only removed if it
// goes from being disabled to not disabled, and is not ignored.
//
// Note that enabling a recipe for an item does not inherently mean the
// item is not considered "disabled" in this sense. For example, if the
// enabled recipe is net-negative in its use of the item.
let candidates = new Set()
let items = new Set()
for (let ing of recipe.products) {
let item = ing.item
items.add(item)
if (this.isItemDisabled(item) && !this.ignore.has(item)) {
candidates.add(item)
}
}
this.disable.delete(recipe)
for (let item of candidates) {
if (!this.isItemDisabled(item)) {
this.priority.removeRecipe(item.disableRecipe)
}
}
// Update build targets.
for (let target of this.buildTargets) {
if (items.has(target.item)) {
target.displayRecipes()
}
}
}
getDefaultPriorityArray() {
let a = []
for (let [recipeKey, recipe] of this.recipes) {
if (recipe.isResource()) {
let pri = recipe.defaultPriority
while (a.length < pri + 1) {
a.push(new Map())
}
a[pri].set(recipe, recipe.defaultWeight)
}
}
return a
}
setDefaultPriority() {
this.priority = PriorityList.fromArray(this.defaultPriority)
}
setPriorities(tiers) {
let a = []
for (let tier of tiers) {
let m = new Map()
for (let [recipeKey, weight] of tier) {
let recipe = this.recipes.get(recipeKey)
if (recipe === undefined && recipeKey.startsWith(DISABLED_RECIPE_PREFIX)) {
let itemKey = recipeKey.slice(DISABLED_RECIPE_PREFIX.length)
recipe = this.items.get(itemKey).disableRecipe
}
m.set(recipe, weight)
}
a.push(m)
}
this.priority.applyArray(a)
}
isDefaultPriority() {
return this.priority.equalArray(this.defaultPriority)
}
initMinerSettings() {
this.minerSettings = new Map()
for (let [recipeKey, recipe] of this.recipes) {
if (minerCategories.has(recipe.category)) {
let miners = this.buildings.get(recipe.category)
// Default to miner mk1.
let miner = miners[0]
// Default to normal purity.
let purity = DEFAULT_PURITY
this.minerSettings.set(recipe, {miner, purity})
}
}
}
getUses(item) {
let recipes = []
for (let recipe of item.uses) {
if (!this.disable.has(recipe)) {
recipes.push(recipe)
}
}
return recipes
}
// Returns whether the current item requires the use of its DisabledRecipe
// as a consequence of its recipes being disabled. (It may still require it
// as a consequence of the item being ignored, independent of this.)
//
// It's worth mentioning that this is insufficent to guarantee that no
// infeasible solutions exist. Catching net-negative single recipes ought
// to account for the most common cases, but net-negative recipe loops are
// still possible.
isItemDisabled(item) {
for (let recipe of item.recipes) {
if (!this.disable.has(recipe)) {
if (recipe.isNetProducer(item)) {
return false
}
}
}
return true
}
getRecipes(item) {
let recipes = []
for (let recipe of item.recipes) {
if (!this.disable.has(recipe)) {
recipes.push(recipe)
}
}
// The disableRecipe's purpose is to provide an item ex nihilo, in
// cases where solutions are infeasible otherwise. This happens in two
// cases: When enough recipes have been disabled to prevent its
// production in any other way, and when the item is being ignored.
if (this.isItemDisabled(item) || this.ignore.has(item)) {
let result = [item.disableRecipe]
// Still consider any recipes which produce both this item and any
// other un-ignored items.
for (let r of recipes) {
for (let ing of r.products) {
if (!this.ignore.has(ing.item)) {
result.push(r)
break
}
}
}
return result
}
return recipes
}
_getItemGraph(item, recipes) {
for (let recipe of this.getRecipes(item)) {
if (recipes.has(recipe)) {
continue
}
recipes.add(recipe)
for (let ing of recipe.ingredients) {
this._getItemGraph(ing.item, recipes)
}
}
}
// Returns the set of recipes which may contribute to the production of
// the given collection of items.
getRecipeGraph(items) {
let graph = new Set()
for (let [item, rate] of items) {
this._getItemGraph(item, graph)
}
return graph
}
getBuilding(recipe) {
if (recipe.category === null) {
return null
} else if (this.minerSettings.has(recipe)) {
return this.minerSettings.get(recipe).miner
} else {
// NOTE: Only miners offer alternative buildings. May need to
// revisit this if higher tiers of constructors are added.
return this.buildings.get(recipe.category)[0]
}
}
getOverclock(recipe) {
return this.overclock.get(recipe) || one
}
setOverclock(recipe, overclock) {
if (overclock.equal(one)) {
this.overclock.delete(recipe)
} else {
this.overclock.set(recipe, overclock)
}
}
// Returns somersloop factor as a fraction from 0 (no somersloops) to 1
// (all possible somersloops).
getSomersloop(recipe) {
let building = this.getBuilding(recipe)
if (building === null || building.maxSomersloop === null) {
return zero
}
let sloops = this.somersloop.get(recipe)
if (sloops === undefined) {
return zero
}
return sloops.div(building.maxSomersloop)
}
setSomersloop(recipe, count) {
if (count.equal(zero)) {
this.somersloop.delete(recipe)
} else {
this.somersloop.set(recipe, count)
}
}
// Returns the recipe-rate at which a single building can produce a recipe.
// Returns null for recipes that do not have a building.
getRecipeRate(recipe) {
let building = this.getBuilding(recipe)
if (building === null) {
return null
}
return building.getRecipeRate(this, recipe)
}
getResourcePurity(recipe) {
// XXX: water extractors, blah
if (this.minerSettings.has(recipe)) {
return this.minerSettings.get(recipe).purity
} else {
return resourcePurities[1]
}
}
setMiner(recipe, miner, purity) {
this.minerSettings.set(recipe, {miner, purity})
}
getCount(recipe, rate) {
let building = this.getBuilding(recipe)
if (building === null) {
return zero
}
return building.getCount(this, recipe, rate)
}
getBeltCount(rate) {
return rate.div(this.belt.rate)
}
getPipeCount(rate) {
return rate.div(this.pipe.rate)
}
getPowerUsage(recipe, rate) {
let building = this.getBuilding(recipe)
if (building === null) {
return {average: zero, peak: zero}
}
let count = this.getCount(recipe, rate)
let sloop = one.add(this.getSomersloop(recipe))
sloop = sloop.mul(sloop)
let average = building.power.mul(count).mul(sloop)
let peak = building.power.mul(count.ceil()).mul(sloop)
let overclock = this.overclock.get(recipe)
if (overclock !== undefined) {
// The result of this exponent will typically be irrational, so
// this approximation is a necessity. Because overclock is limited
// to the range [1.0, 2.5], any imprecision introduced by this
// approximation is minimal (and is probably less than is present
// in the game itself).
let overclockFactor = Rational.from_float(Math.pow(overclock.toFloat(), OVERCLOCK_POWER_EXPONENT))
average = average.mul(overclockFactor)
peak = peak.mul(overclockFactor)
}
return {average, peak}
}
addTarget(itemKey) {
if (itemKey === undefined) {
itemKey = DEFAULT_ITEM_KEY
}
let item = this.items.get(itemKey)
let target = new BuildTarget(this.buildTargets.length, itemKey, item, this.itemTiers)
this.buildTargets.push(target)
d3.select("#targets").insert(() => target.element, "#plusButton")
return target
}
removeTarget(target) {
this.buildTargets.splice(target.index, 1)
for (let i=target.index; i < this.buildTargets.length; i++) {
this.buildTargets[i].index--
}
d3.select(target.element).remove()
}
toggleIgnore(item) {
if (this.ignore.has(item)) {
this.ignore.delete(item)
if (!this.isItemDisabled(item)) {
this.priority.removeRecipe(item.disableRecipe)
}
} else {
this.ignore.add(item)
if (!this.isItemDisabled(item)) {
let level = this.priority.getFirstLevel()
let makeNew = true
for (let r of level) {
if (r.recipe.isDisable()) {
makeNew = false
break
}
}
if (makeNew) {
level = this.priority.addPriorityBefore(level)
}
let hundred = Rational.from_float(100)
this.priority.addRecipe(item.disableRecipe, hundred, level)
}
}
}
solve() {
let outputs = []
for (let target of this.buildTargets) {
let item = target.item
let rate = target.getRate()
let recipe
if (target.changedBuilding) {
recipe = target.recipe
} else {
recipe = null
}
outputs.push([item, rate, recipe])
}
// JS isn't good at using tuples as Map keys/Set items, so just do this
// quadratically. It's fine.
let dedupedOutputs = []
outer: for (let [origItem, origRate, origRecipe] of outputs) {
for (let i = 0; i < dedupedOutputs.length; i++) {
let {item, rate, recipe} = dedupedOutputs[i]
if (recipe === origRecipe && item === origItem) {
rate = rate.add(origRate)
dedupedOutputs[i] = {item, rate, recipe}
continue outer
}
}
dedupedOutputs.push({
item: origItem,
rate: origRate,
recipe: origRecipe,
})
}
let totals = solve(this, dedupedOutputs)
return totals
}
setHash() {
window.location.hash = "#" + formatSettings()
}
// The top-level calculation function. Called whenever the solution
// requires recalculation.
updateSolution() {
this.lastTotals = this.solve()
this.display()
}
// Re-renders the current solution, without re-computing it.
//
// This is useful for when settings can be applied without altering the
// solution. In general, if something would alter recipe-rate ratios, then
// it requires a new solution. If it only alters building counts (e.g.
// from changing the speed of a building), then we need merely re-display
// the existing solution.
display() {
// Update build target text boxes, if needed.
for (let target of this.buildTargets) {
target.getRate()
}
displayItems(this, this.lastTotals)
renderTotals(this.lastTotals, this.ignore)
reapTooltips()
this.setHash()
if (this.debug) {
renderDebug()
}
}
}
export let spec = new FactorySpecification()
window.spec = spec