-
Notifications
You must be signed in to change notification settings - Fork 11
/
calculator.c
1945 lines (1691 loc) · 75.2 KB
/
calculator.c
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
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "calculator.h"
#include <omp.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "absl/base/port.h"
#include "pcg_basic.h"
#include "base.h"
#include "config.h"
#include "FTPManagement.h"
#include "logger.h"
#include "node_print.h"
#include "recipes.h"
#include "shutdown.h"
#include "start.h"
// Constants
#define INVENTORY_SIZE 20
// Frame penalty for a particular action
#define CHOOSE_2ND_INGREDIENT_FRAMES 56
#define TOSS_FRAMES 32
#define ALPHA_ASC_SORT_FRAMES 38
#define ALPHA_DESC_SORT_FRAMES 40
#define TYPE_ASC_SORT_FRAMES 39
#define TYPE_DESC_SORT_FRAMES 41
#define JUMP_STORAGE_NO_TOSS_FRAMES 5 // Penalty for not tossing the last item (because we need to get Jump Storage)
// algorithm parameters
#define BUFFER_SEARCH_FRAMES 150 // Threshold to try optimizing a roadmap to attempt to beat the current record
#define DEFAULT_ITERATION_LIMIT 100000 // Cutoff for iterations explored before resetting
#define ITERATION_LIMIT_INCREASE 100000000 // Amount to increase the iteration limit by when finding a new record
#define CHECK_SHUTDOWN_INTERVAL 30000
static const int INT_OUTPUT_ARRAY_SIZE_BYTES = sizeof(outputCreatedArray_t);
static const outputCreatedArray_t EMPTY_RECIPES = {0};
static const Cook EMPTY_COOK = {0};
// globals
int **invFrames;
Recipe *recipeList;
pcg32_random_t *rng;
/*-------------------------------------------------------------------
* Function : checkShutdownOnIndex
*
* Called periodically to check for shutdown. Performs modulo operation
* before the function call to reduce overhead cost from repeated checks.
-------------------------------------------------------------------*/
ABSL_ATTRIBUTE_ALWAYS_INLINE static inline bool checkShutdownOnIndex(int i) {
return i % CHECK_SHUTDOWN_INTERVAL == 0 && askedToShutdown();
}
/*-------------------------------------------------------------------
* Function : copyOutputsFulfilled
*
* A simple memcpy to duplicate srcOutputsFulfilled into destOutputsFulfilled
-------------------------------------------------------------------*/
ABSL_ATTRIBUTE_ALWAYS_INLINE static inline void copyOutputsFulfilled(outputCreatedArray_t dest, const outputCreatedArray_t src) {
memcpy((void*)dest, (const void*)src, INT_OUTPUT_ARRAY_SIZE_BYTES);
}
/*-------------------------------------------------------------------
* Function : initializeInvFrames
*
* Initializes global invFrames, which is used to calculate
* the number of frames it takes to navigate to an item in the menu.
-------------------------------------------------------------------*/
void initializeInvFrames() {
invFrames = getInventoryFrames();
}
/*-------------------------------------------------------------------
* Function : initializeRecipeList
*
* Initializes global variable recipeList, which stores data pertaining
* to each of the 57 recipes, plus a representation of Chapter 5. This
* data consists of recipe outputs, number of different ways to cook the
* recipe, and the items required for each recipe combination.
-------------------------------------------------------------------*/
void initializeRecipeList() {
recipeList = getRecipeList();
}
/*-------------------------------------------------------------------
* Function : initializeRoot
*
* Generate the root of the tree graph
-------------------------------------------------------------------*/
ABSL_MUST_USE_RESULT BranchPath* initializeRoot() {
BranchPath* root = malloc(sizeof(BranchPath));
checkMallocFailed(root);
root->moves = 0;
root->inventory = getStartingInventory();
root->description.action = EBegin;
root->description.data = NULL;
root->description.framesTaken = 0;
root->description.totalFramesTaken = 0;
root->prev = NULL;
root->next = NULL;
// This will also 0 out all the other elements
copyOutputsFulfilled(root->outputCreated, EMPTY_RECIPES);
root->numOutputsCreated = 0;
root->legalMoves = NULL;
root->numLegalMoves = 0;
root->totalSorts = 0;
return root;
}
void seedThreadRNG(int workerCount) {
rng = malloc(workerCount * sizeof(pcg32_random_t));
checkMallocFailed(rng);
uint64_t initstate = getSysRNG();
for (int i = 0; i < workerCount; i++) {
// argument 1 determines the starting RNG value
// argument 2 determines the RNG sequence
// See https://www.pcg-random.org/using-pcg-c-basic.html
uint64_t initseq = (intptr_t)(rng) + i;
pcg32_srandom_r(rng + i, initstate, initseq);
}
}
/*-------------------------------------------------------------------
* Function : applyJumpStorageFramePenalty
*
* Looks at the node's Cook data. If the item is autoplaced, then add
* a penalty for not tossing the item. Adjust framesTaken and
* totalFramesTaken to reflect this change.
-------------------------------------------------------------------*/
void applyJumpStorageFramePenalty(BranchPath *node) {
Cook* pCook = (Cook*)node->description.data;
if (pCook->handleOutput == Autoplace) {
node->description.framesTaken += JUMP_STORAGE_NO_TOSS_FRAMES;
node->description.totalFramesTaken += JUMP_STORAGE_NO_TOSS_FRAMES;
}
}
/*-------------------------------------------------------------------
* Function : createChapter5Struct
*
* Compartmentalization of setting CH5 attributes
* lateSort tracks whether we performed the sort before or after the
* Keel Mango, for printing purposes
-------------------------------------------------------------------*/
ABSL_MUST_USE_RESULT CH5 *createChapter5Struct(CH5_Eval eval, int lateSort) {
CH5 *ch5 = malloc(sizeof(CH5));
checkMallocFailed(ch5);
ch5->indexDriedBouquet = eval.DB_place_index;
ch5->indexCoconut = eval.CO_place_index;
ch5->ch5Sort = eval.sort;
ch5->indexKeelMango = eval.KM_place_index;
ch5->indexCourageShell = eval.CS_place_index;
ch5->indexThunderRage = eval.TR_use_index;
ch5->lateSort = lateSort;
return ch5;
}
/*-------------------------------------------------------------------
* Function : createCookDescription
*
* Compartmentalization of generating a MoveDescription struct
* based on various parameters dependent on what recipe we're cooking
-------------------------------------------------------------------*/
MoveDescription createCookDescription(const BranchPath *node, Recipe recipe, ItemCombination combo, Inventory *tempInventory, int viableItems) {
MoveDescription useDescription;
useDescription.action = ECook;
int ingredientLoc[2];
// Determine the locations of both ingredients
ingredientLoc[0] = indexOfItemInInventory(*tempInventory, combo.item1);
if (combo.numItems == 1) {
createCookDescription1Item(node, recipe, combo, tempInventory, ingredientLoc, viableItems, &useDescription);
}
else {
ingredientLoc[1] = indexOfItemInInventory(*tempInventory, combo.item2);
createCookDescription2Items(node, recipe, combo, tempInventory, ingredientLoc, viableItems, &useDescription);
}
return useDescription;
}
/*-------------------------------------------------------------------
* Function : createCookDescription1Item
*
* Handles inventory management and frame calculation for recipes of
* length 1. Generates Cook structure and points to this structure
* in useDescription.
-------------------------------------------------------------------*/
void createCookDescription1Item(const BranchPath *node, Recipe recipe, ItemCombination combo, Inventory *tempInventory, int *ingredientLoc, int viableItems, MoveDescription *useDescription) {
// This is a potentially viable recipe with 1 ingredient
// Determine how many frames will be needed to select that item
int framesTaken = invFrames[viableItems - 1][ingredientLoc[0] - tempInventory->nulls];
// Modify the inventory if the ingredient was in the first 10 slots
if (ingredientLoc[0] < 10) {
// Shift the inventory towards the front of the array to fill the null
*tempInventory = removeItem(*tempInventory, ingredientLoc[0]);
}
generateCook(useDescription, combo, recipe, ingredientLoc);
generateFramesTaken(useDescription, node, framesTaken);
}
/*-------------------------------------------------------------------
* Function : createCookDescription2Items
*
* Handles inventory management and frame calculation for recipes of
* length 2. Swaps items if it's faster to choose the second item first.
* Generates Cook structure and points to this structure in useDescription.
-------------------------------------------------------------------*/
void createCookDescription2Items(const BranchPath *node, Recipe recipe, ItemCombination combo, Inventory *tempInventory, int *ingredientLoc, int viableItems, MoveDescription *useDescription) {
// This is a potentially viable recipe with 2 ingredients
//Baseline frames based on how many times we need to access the menu
int framesTaken = CHOOSE_2ND_INGREDIENT_FRAMES;
// Swap ingredient order if necessary. There are some configurations where
// it is 2 frames faster to pick the ingredients in the reverse order or
// only one order is possible.
if (selectSecondItemFirst(ingredientLoc, tempInventory->nulls, viableItems)) {
swapItems(ingredientLoc, &combo);
}
int visibleLoc0 = ingredientLoc[0] - tempInventory->nulls;
int visibleLoc1 = ingredientLoc[1] - tempInventory->nulls;
// Add the frames to choose the first ingredient.
framesTaken += invFrames[viableItems - 1][visibleLoc0];
// Depending on the first ingredient's position and the state of the
// inventory, it or another item could be hidden during the second
// ingredient selection.
if (ingredientLoc[0] < 10) {
--viableItems;
// If the second ingredient comes after the first, its position will be
// 1 less.
if (ingredientLoc[0] < ingredientLoc[1]) {
--visibleLoc1;
}
}
else if (visibleLoc0 >= 10) {
--viableItems;
// If there are nulls in this case, the wrong item is hidden. If the
// second ingredient comes after the hidden item, its position will be
// 1 less.
if (visibleLoc0 < ingredientLoc[1]) {
--visibleLoc1;
}
}
// Add the frames to choose the second ingredient.
framesTaken += invFrames[viableItems - 1][visibleLoc1];
// Set each inventory index to null if the item was in the first 10 slots
// To reduce complexity, remove the items in ascending order of index
if (ingredientLoc[0] < ingredientLoc[1]) {
if (ingredientLoc[0] < 10) {
*tempInventory = removeItem(*tempInventory, ingredientLoc[0]);
}
if (ingredientLoc[1] < 10) {
*tempInventory = removeItem(*tempInventory, ingredientLoc[1]);
}
}
else {
if (ingredientLoc[1] < 10) {
*tempInventory = removeItem(*tempInventory, ingredientLoc[1]);
}
if (ingredientLoc[0] < 10) {
*tempInventory = removeItem(*tempInventory, ingredientLoc[0]);
}
}
// Describe what items were used
generateCook(useDescription, combo, recipe, ingredientLoc);
generateFramesTaken(useDescription, node, framesTaken);
}
/*-------------------------------------------------------------------
* Function : createLegalMove
*
* Given the input parameters, allocate and set attributes for a
* legalMove node, as well as add it to the parent's list of legal moves.
-------------------------------------------------------------------*/
BranchPath *createLegalMove(BranchPath *node, Inventory inventory, MoveDescription description, const outputCreatedArray_t outputsFulfilled, int numOutputsFulfilled) {
BranchPath *newLegalMove = malloc(sizeof(BranchPath));
checkMallocFailed(newLegalMove);
newLegalMove->moves = node->moves + 1;
newLegalMove->inventory = inventory;
newLegalMove->description = description;
newLegalMove->prev = node;
newLegalMove->next = NULL;
copyOutputsFulfilled(newLegalMove->outputCreated, outputsFulfilled);
newLegalMove->numOutputsCreated = numOutputsFulfilled;
newLegalMove->legalMoves = NULL;
newLegalMove->numLegalMoves = 0;
if (description.action >= ESort_Alpha_Asc && description.action <= ESort_Type_Des) {
newLegalMove->totalSorts = node->totalSorts + 1;
}
else {
newLegalMove->totalSorts = node->totalSorts;
}
return newLegalMove;
}
/*-------------------------------------------------------------------
* Function : filterOut2Ingredients
*
* For the first node's legal moves, we cannot cook a recipe which
* contains two items. Thus, we need to remove any legal moves
* which require two ingredients
-------------------------------------------------------------------*/
void filterOut2Ingredients(BranchPath *node) {
for (int i = 0; i < node->numLegalMoves; i++) {
if (node->legalMoves[i]->description.action == ECook) {
Cook *cook = node->legalMoves[i]->description.data;
if (cook->numItems == 2)
freeAndShiftLegalMove(node, i--);
}
}
}
/*-------------------------------------------------------------------
* Function : finalizeChapter5Eval
*
* Given input parameters, construct a new legal move to represent CH5
-------------------------------------------------------------------*/
void finalizeChapter5Eval(BranchPath *node, Inventory inventory, CH5 *ch5Data, int temp_frame_sum, const outputCreatedArray_t outputsFulfilled, int numOutputsFulfilled) {
// Get the index of where to insert this legal move to
int insertIndex = getInsertionIndex(node, temp_frame_sum);
MoveDescription description;
description.action = ECh5;
description.data = ch5Data;
description.framesTaken = temp_frame_sum;
description.totalFramesTaken = node->description.totalFramesTaken + temp_frame_sum;
// Create the legalMove node
BranchPath *legalMove = createLegalMove(node, inventory, description, outputsFulfilled, numOutputsFulfilled);
// Apend the legal move
insertIntoLegalMoves(insertIndex, legalMove, node);
}
/*-------------------------------------------------------------------
* Function : finalizeLegalMove
*
* Given input parameters, construct a new legal move to represent
* a valid recipe move. Also checks to see if the legal move exceeds
* the frame limit
-------------------------------------------------------------------*/
void finalizeLegalMove(BranchPath *node, MoveDescription useDescription, Inventory tempInventory, const outputCreatedArray_t tempOutputsFulfilled, int numOutputsFulfilled, enum HandleOutput tossType, enum Type_Sort toss, int tossIndex) {
// Determine if the legal move exceeds the frame limit. If so, return out
if (useDescription.totalFramesTaken > getLocalRecord() + BUFFER_SEARCH_FRAMES)
return;
// Determine where to insert this legal move into the list of legal moves (sorted by frames taken)
int insertIndex = getInsertionIndex(node, useDescription.framesTaken);
Cook *cookNew = malloc(sizeof(Cook));
checkMallocFailed(cookNew);
*cookNew = *((Cook*)useDescription.data);
cookNew->handleOutput = tossType;
cookNew->toss = toss;
cookNew->indexToss = tossIndex;
useDescription.data = cookNew;
// Create the legalMove node
BranchPath *newLegalMove = createLegalMove(node, tempInventory, useDescription, tempOutputsFulfilled, numOutputsFulfilled);
// Insert this new move into the current node's legalMove array
insertIntoLegalMoves(insertIndex, newLegalMove, node);
}
/*-------------------------------------------------------------------
* Function : freeAllNodes
*
* We've reached the iteration limit, so free all nodes in the roadmap
* We additionally need to delete node from the previous node's list of
* legalMoves to prevent a double-free. Don't cache serials, as we haven't
* traversed all legal moves.
-------------------------------------------------------------------*/
void freeAllNodes(BranchPath *node) {
BranchPath *prevNode = NULL;
do {
prevNode = node->prev;
freeNode(node);
// Delete node in nextNode's list of legal moves to prevent a double free
if (prevNode != NULL && prevNode->legalMoves != NULL) {
prevNode->legalMoves[0] = NULL;
prevNode->numLegalMoves--;
shiftUpLegalMoves(prevNode, 1);
}
// Traverse to the previous node
node = prevNode;
} while (node != NULL);
}
/*-------------------------------------------------------------------
* Function : freeLegalMove
*
* Free the legal move at index in the node's array of legal moves,
* but unlike freeAndShiftLegalMove(), this does NOT shift the existing
* legal moves to fill the gap. This is useful in cases where the
* caller can assure such consistency is not needed (For example,
* freeing the last legal move or freeing all legal moves).
-------------------------------------------------------------------*/
static void freeLegalMove(BranchPath *node, int index) {
freeNode(node->legalMoves[index]);
node->legalMoves[index] = NULL;
node->numLegalMoves--;
node->next = NULL;
}
/*-------------------------------------------------------------------
* Function : freeAndShiftLegalMove
*
* Free the legal move at index in the node's array of legal moves,
* and shift the existing legal moves after the index to fill the gap.
-------------------------------------------------------------------*/
void freeAndShiftLegalMove(BranchPath *node, int index) {
freeLegalMove(node, index);
shiftUpLegalMoves(node, index + 1);
}
/*-------------------------------------------------------------------
* Function : freeNode
*
* Free the current node and all legal moves within the node
-------------------------------------------------------------------*/
void freeNode(BranchPath *node) {
if (node->description.data != NULL) {
free(node->description.data);
}
if (node->legalMoves != NULL) {
const int max = node->numLegalMoves;
int i = 0;
while (i < max) {
// Don't need to worry about shifting up when we do this.
// Or resetting slots to NULL.
// We are blowing it all away anyways.
freeLegalMove(node, i++);
}
free(node->legalMoves);
}
free(node);
}
/*-------------------------------------------------------------------
* Function : fulfillChapter5
*
* Count up frames from Hot Dog and Mousse Cake, then determine how
* to continue evaluating Chapter 5 based on null count.
-------------------------------------------------------------------*/
void fulfillChapter5(BranchPath *curNode) {
// Create an outputs chart but with the Dried Bouquet collected
// to ensure that the produced inventory can fulfill all remaining recipes
outputCreatedArray_t tempOutputsFulfilled;
copyOutputsFulfilled(tempOutputsFulfilled, curNode->outputCreated);
tempOutputsFulfilled[getOutputIndex(Dried_Bouquet)] = true;
int numOutputsFulfilled = curNode->numOutputsCreated + 1;
Inventory newInventory = curNode->inventory;
int mousse_cake_index = indexOfItemInInventory(newInventory, Mousse_Cake);
// Create the CH5 eval struct
CH5_Eval eval;
// Explicit int casts are to silence warnings.
int viableItems = (int)newInventory.length - newInventory.nulls - min((int)newInventory.length - 10, newInventory.nulls);
// Calculate frames it takes the navigate to the Mousse Cake and the Hot Dog for the trade
eval.frames_at_HD = 2 * invFrames[viableItems - 1][indexOfItemInInventory(newInventory, Hot_Dog) - newInventory.nulls];
eval.frames_at_MC = eval.frames_at_HD
+ invFrames[viableItems - 1][mousse_cake_index - newInventory.nulls];
// If the Mousse Cake is in the first 10 slots, change it to NULL
if (mousse_cake_index < 10) {
newInventory = removeItem(newInventory, mousse_cake_index);
}
// Handle allocation of the first 2 CH5 items (Dried Bouquet and Coconut)
switch (newInventory.nulls) {
case 0 :
handleDBCOAllocation0Nulls(curNode, newInventory, tempOutputsFulfilled, numOutputsFulfilled, eval);
break;
case 1 :
handleDBCOAllocation1Null(curNode, newInventory, tempOutputsFulfilled, numOutputsFulfilled, eval);
break;
default :
handleDBCOAllocation2Nulls(curNode, newInventory, tempOutputsFulfilled, numOutputsFulfilled, eval);
}
}
/*-------------------------------------------------------------------
* Function : fulfillRecipes
*
* Iterate through all possible combinations of cooking different
* recipes and create legal moves for them
-------------------------------------------------------------------*/
void fulfillRecipes(BranchPath *curNode) {
// Only evaluate the 57th recipe (Mistake) when it's the last recipe to fulfill
// This is because it is relatively easy to craft this output with many of the previous outputs, and will take minimal frames
int upperOutputLimit = (curNode->numOutputsCreated == NUM_RECIPES - 1) ? NUM_RECIPES : (NUM_RECIPES - 1);
// Iterate through all recipe ingredient combos
for (int recipeIndex = 0; recipeIndex < upperOutputLimit; recipeIndex++) {
// Only want recipes that haven't been fulfilled
if (curNode->outputCreated[recipeIndex]) {
continue;
}
// Dried Bouquet (Recipe index 56) represents the Chapter 5 intermission
// Don't actually use the specified recipe, as it is handled later
if (recipeIndex == getOutputIndex(Dried_Bouquet)) {
continue;
}
// Only want ingredient combos that can be fulfilled right now!
Recipe recipe = recipeList[recipeIndex];
ItemCombination *combos = recipe.combos;
for (int comboIndex = 0; comboIndex < recipe.countCombos; comboIndex++) {
ItemCombination combo = combos[comboIndex];
if (!itemComboInInventory(combo, curNode->inventory)) {
continue;
}
// This is a recipe that can be fulfilled right now!
// Copy the inventory
Inventory newInventory = curNode->inventory;
// Mark that this output has been fulfilled for viability determination
outputCreatedArray_t tempOutputsFulfilled;
copyOutputsFulfilled(tempOutputsFulfilled, curNode->outputCreated);
tempOutputsFulfilled[recipeIndex] = 1;
int numOutputsFulfilled = curNode->numOutputsCreated + 1;
// How many items there are to choose from (Not NULL or hidden)
int viableItems = newInventory.length - newInventory.nulls - min(newInventory.length - 10, newInventory.nulls);
MoveDescription useDescription = createCookDescription(curNode, recipe, combo, &newInventory, viableItems);
// Store the base useDescription's cook pointer to be freed later
Cook *cookBase = (Cook *)useDescription.data;
// Handle allocation of the output
handleRecipeOutput(curNode, newInventory, useDescription, tempOutputsFulfilled, numOutputsFulfilled, recipe.output, viableItems);
free(cookBase);
// We know tempOutputsFulfilled does not escape this scope, so safe to be unallocated on return.
}
}
}
/*-------------------------------------------------------------------
* Function : generateCook
*
* Given input parameters, generate Cook structure to represent
* what was cooked and how.
-------------------------------------------------------------------*/
void generateCook(MoveDescription *description, const ItemCombination combo, const Recipe recipe, const int *ingredientLoc) {
Cook *cook = malloc(sizeof(Cook));
checkMallocFailed(cook);
description->action = ECook;
cook->numItems = combo.numItems;
cook->item1 = combo.item1;
cook->item2 = combo.item2;
cook->itemIndex1 = ingredientLoc[0];
cook->itemIndex2 = ingredientLoc[1];
cook->output = recipe.output;
description->data = cook;
}
/*-------------------------------------------------------------------
* Function : generateFramesTaken
*
* Assign frame duration to description structure and reference the
* previous node to find the total frame duration for the roadmap thus far
-------------------------------------------------------------------*/
void generateFramesTaken(MoveDescription *description, const BranchPath *node, int framesTaken) {
description->framesTaken = framesTaken;
description->totalFramesTaken = node->description.totalFramesTaken + framesTaken;
}
/*-------------------------------------------------------------------
* Function : getInsertionIndex
*
* Based on the frames it takes to complete a new legal move, find out
* where to insert it in the current node's array of legal moves, which
* is ordered based on frame count ascending
-------------------------------------------------------------------*/
int getInsertionIndex(const BranchPath *curNode, int frames) {
if (curNode->legalMoves == NULL) {
return 0;
}
int tempIndex = 0;
while (tempIndex < curNode->numLegalMoves && frames > curNode->legalMoves[tempIndex]->description.framesTaken) {
tempIndex++;
}
return tempIndex;
}
/*-------------------------------------------------------------------
* Function : getSortFrames
*
* Depending on the type of sort, return the corresponding frame cost.
-------------------------------------------------------------------*/
int getSortFrames(enum Action action) {
switch (action) {
case ESort_Alpha_Asc:
return ALPHA_ASC_SORT_FRAMES;
case ESort_Alpha_Des:
return ALPHA_DESC_SORT_FRAMES;
case ESort_Type_Asc:
return TYPE_ASC_SORT_FRAMES;
case ESort_Type_Des:
return TYPE_DESC_SORT_FRAMES;
default:
// Critical error if we reach this point...
// action should be some type of sort
exit(-2);
}
}
/*-------------------------------------------------------------------
* Function : outputOrderIsSlower
*
* In a case where an output is manually placed, if the item it
* replaces has not been used since the placement of a previous
* output, then the items the outputs replaced can be swapped.
* As outputs are placed at the beginning, the lower index would be
* changed by 1, so there can be a time difference of 2 frames.
* This function determines whether the current order is slower and
* the outputs should be swapped. If the orders take the same time
* (possible when the inventory length is even and less than 20),
* this will still return 1 for one order and 0 for the other.
-------------------------------------------------------------------*/
int outputOrderIsSlower(int location_1, int location_2, int inventoryLength) {
int middle = inventoryLength / 2;
if (location_1 < middle) {
// The first location will be selected by going down, so we want
// to minimize its position.
return location_1 >= location_2;
}
if (location_2 > middle) {
// The second location will be selected by going up, so we want
// to maximize its position.
return location_2 > location_1;
}
return 1;
}
/*-------------------------------------------------------------------
* Function : handleChapter5EarlySortEndItems
*
* A sort already occurred right after placing the Coconut. Evaluate
* each combination of Keel Mango and Courage Shell placements,
* handle using the Thunder Rage on Smorg,, and if everything is valid,
* create the move and insert it.
-------------------------------------------------------------------*/
void handleChapter5EarlySortEndItems(BranchPath *node, Inventory inventory, const outputCreatedArray_t outputsFulfilled, int numOutputsFulfilled, CH5_Eval eval) {
for (eval.KM_place_index = 0; eval.KM_place_index < 10; eval.KM_place_index++) {
// Don't allow a move that will be invalid.
if (inventory.inventory[eval.KM_place_index] == Thunder_Rage
|| inventory.inventory[eval.KM_place_index] == Dried_Bouquet) {
continue;
}
// Replace the chosen item with the Keel Mango
Inventory km_temp_inventory = replaceItem(inventory, eval.KM_place_index, Keel_Mango);
// Calculate the frames for this action
eval.frames_at_KM = eval.frames_at_sort + TOSS_FRAMES
+ invFrames[inventory.length][eval.KM_place_index + 1];
for (eval.CS_place_index = 1; eval.CS_place_index < 10; eval.CS_place_index++) {
// Don't allow a move that will be invalid or needlessly slower.
if (km_temp_inventory.inventory[eval.CS_place_index] == Thunder_Rage
|| km_temp_inventory.inventory[eval.CS_place_index] == Dried_Bouquet
|| outputOrderIsSlower(eval.KM_place_index, eval.CS_place_index, km_temp_inventory.length)) {
continue;
}
// Replace the chosen item with the Courage Shell
Inventory kmcs_temp_inventory = replaceItem(km_temp_inventory, eval.CS_place_index, Courage_Shell);
// Calculate the frames for this action
eval.frames_at_CS = eval.frames_at_KM + TOSS_FRAMES
+ invFrames[kmcs_temp_inventory.length][eval.CS_place_index + 1];
// The next event is using the Thunder Rage item before resuming the 2nd session of recipe fulfillment
eval.TR_use_index = indexOfItemInInventory(kmcs_temp_inventory, Thunder_Rage);
if (eval.TR_use_index < 10) {
kmcs_temp_inventory = removeItem(kmcs_temp_inventory, eval.TR_use_index);
}
// Calculate the frames for this action
eval.frames_at_TR = eval.frames_at_CS
+ invFrames[kmcs_temp_inventory.length - 1][eval.TR_use_index];
// Determine if the remaining inventory is sufficient to fulfill all remaining recipes
if (stateOK(kmcs_temp_inventory, outputsFulfilled, recipeList)) {
CH5 *ch5Data = createChapter5Struct(eval, 0);
finalizeChapter5Eval(node, kmcs_temp_inventory, ch5Data, eval.frames_at_TR, outputsFulfilled, numOutputsFulfilled);
}
}
}
}
/*-------------------------------------------------------------------
* Function : handleChapter5Eval
*
* Branch into early and late sort scenarios. For late sort, handle
* Keel Mango placement here. Otherwise, defer to other functions.
-------------------------------------------------------------------*/
void handleChapter5Eval(BranchPath *node, Inventory inventory, const outputCreatedArray_t outputsFulfilled, int numOutputsFulfilled, CH5_Eval eval) {
// Evaluate sorting before the Keel Mango
// Use -1 to identify that we are not collecting the Keel Mango until after the sort
eval.KM_place_index = -1;
handleChapter5Sorts(node, inventory, outputsFulfilled, numOutputsFulfilled, eval);
// Place the Keel Mango in a null spot if one is available.
if (inventory.nulls >= 1) {
// Making a copy of the temp inventory for what it looks like after the allocation of the KM
Inventory km_temp_inventory = addItem(inventory, Keel_Mango);
eval.frames_at_KM = eval.frames_at_CO;
eval.KM_place_index = 0;
// Perform all sorts
handleChapter5Sorts(node, km_temp_inventory, outputsFulfilled, numOutputsFulfilled, eval);
}
else {
// Place the Keel Mango starting after the other placed items.
for (eval.KM_place_index = 2; eval.KM_place_index < 10; eval.KM_place_index++) {
// Don't allow a move that will be invalid.
if (inventory.inventory[eval.KM_place_index] == Thunder_Rage) {
continue;
}
// Making a copy of the temp inventory for what it looks like after the allocation of the KM
Inventory km_temp_inventory = replaceItem(inventory, eval.KM_place_index, Keel_Mango);
// Calculate the frames for this action
eval.frames_at_KM = eval.frames_at_CO + TOSS_FRAMES
+ invFrames[inventory.length][eval.KM_place_index + 1];
// Perform all sorts
handleChapter5Sorts(node, km_temp_inventory, outputsFulfilled, numOutputsFulfilled, eval);
}
}
}
/*-------------------------------------------------------------------
* Function : handleChapter5LateSortEndItems
*
* A sort already occurred right after placing the Keel Mango.
* Evaluate each Courage Shell placement, handle using the Thunder
* Rage, and if everything is valid, create the move and insert it.
-------------------------------------------------------------------*/
void handleChapter5LateSortEndItems(BranchPath *node, Inventory inventory, const outputCreatedArray_t outputsFulfilled, int numOutputsFulfilled, CH5_Eval eval) {
// Place the Courage Shell
for (eval.CS_place_index = 0; eval.CS_place_index < 10; eval.CS_place_index++) {
// Don't allow a move that will be invalid.
if (inventory.inventory[eval.CS_place_index] == Dried_Bouquet
|| inventory.inventory[eval.CS_place_index] == Keel_Mango
|| inventory.inventory[eval.CS_place_index] == Thunder_Rage) {
continue;
}
// Replace the chosen item with the Courage Shell
Inventory cs_temp_inventory = replaceItem(inventory, eval.CS_place_index, Courage_Shell);
// Calculate the frames for this action
eval.frames_at_CS = eval.frames_at_sort + TOSS_FRAMES
+ invFrames[cs_temp_inventory.length][eval.CS_place_index + 1];
// The next event is using the Thunder Rage
eval.TR_use_index = indexOfItemInInventory(cs_temp_inventory, Thunder_Rage);
// Using the Thunder Rage in slots 1-10 will remove it
if (eval.TR_use_index < 10) {
cs_temp_inventory = removeItem(cs_temp_inventory, eval.TR_use_index);
}
// Calculate the frames for this action
eval.frames_at_TR = eval.frames_at_CS
+ invFrames[cs_temp_inventory.length - 1][eval.TR_use_index];
if (stateOK(cs_temp_inventory, outputsFulfilled, recipeList)) {
CH5 *ch5Data = createChapter5Struct(eval, 1);
finalizeChapter5Eval(node, cs_temp_inventory, ch5Data, eval.frames_at_TR, outputsFulfilled, numOutputsFulfilled);
}
}
}
/*-------------------------------------------------------------------
* Function : handleChapter5Sorts
*
* Evaluate each sorting method to make sure Coconut will be
* duplicated, and then branch to the appropriate end items function
* based on whether Keel Mango has already been placed or not.
-------------------------------------------------------------------*/
void handleChapter5Sorts(BranchPath *node, Inventory inventory, const outputCreatedArray_t outputsFulfilled, int numOutputsFulfilled, CH5_Eval eval) {
for (eval.sort = ESort_Alpha_Asc; eval.sort <= ESort_Type_Des; eval.sort++) {
Inventory sorted_inventory = getSortedInventory(inventory, eval.sort);
// Only bother with further evaluation if the sort placed the Coconut in the latter half of the inventory
// because the Coconut is needed for duplication
if (indexOfItemInInventory(sorted_inventory, Coconut) < 10) {
continue;
}
// Count the frames this sort takes.
int sort_frames = getSortFrames(eval.sort);
// Evaluate final items, including Keel Mango if necessary.
if (eval.KM_place_index == -1) {
eval.frames_at_sort = eval.frames_at_CO + sort_frames;
handleChapter5EarlySortEndItems(node, sorted_inventory, outputsFulfilled, numOutputsFulfilled, eval);
continue;
}
eval.frames_at_sort = eval.frames_at_KM + sort_frames;
handleChapter5LateSortEndItems(node, sorted_inventory, outputsFulfilled, numOutputsFulfilled, eval);
}
}
/*-------------------------------------------------------------------
* Function : handleDBCOAllocation0Nulls
*
* There are no nulls, so neither Dried Bouquet nor Coconut will be
* autoplaced. Evaluate each combination of placements for them, and
* then proceed to the early/late sort decision.
-------------------------------------------------------------------*/
void handleDBCOAllocation0Nulls(BranchPath *curNode, Inventory tempInventory, const outputCreatedArray_t tempOutputsFulfilled, int numOutputsFulfilled, CH5_Eval eval) {
// Place the Dried Bouquet.
for (eval.DB_place_index = 0; eval.DB_place_index < 10; eval.DB_place_index++) {
// Don't allow a move that will be invalid.
if (tempInventory.inventory[eval.DB_place_index] == Thunder_Rage) {
continue;
}
// Replace the chosen item with the Dried Bouquet
Inventory db_temp_inventory = replaceItem(tempInventory, eval.DB_place_index, Dried_Bouquet);
// Calculate the frames for this action
eval.frames_at_DB = eval.frames_at_MC + TOSS_FRAMES
+ invFrames[tempInventory.length][eval.DB_place_index + 1];
// Place the Coconut after the Dried Bouquet.
for (eval.CO_place_index = 1; eval.CO_place_index < 10; eval.CO_place_index++) {
// Don't allow a move that will be invalid or needlessly slower.
if (db_temp_inventory.inventory[eval.CO_place_index] == Thunder_Rage
|| outputOrderIsSlower(eval.DB_place_index, eval.CO_place_index, db_temp_inventory.length)) {
continue;
}
// Replace the chosen item with the Coconut
Inventory dbco_temp_inventory = replaceItem(db_temp_inventory, eval.CO_place_index, Coconut);
// Calculate the frames of this action
eval.frames_at_CO = eval.frames_at_DB + TOSS_FRAMES
+ invFrames[tempInventory.length][eval.CO_place_index + 1];
// Handle the allocation of the Coconut sort, Keel Mango, and Courage Shell
handleChapter5Eval(curNode, dbco_temp_inventory, tempOutputsFulfilled, numOutputsFulfilled, eval);
}
}
}
/*-------------------------------------------------------------------
* Function : handleDBCOAllocation1Null
*
* There is 1 null, so Dried Bouquet will be autoplaced. Evaluate
* each Coconut placement, and then proceed to the early/late sort
* decision.
-------------------------------------------------------------------*/
void handleDBCOAllocation1Null(BranchPath *curNode, Inventory tempInventory, const outputCreatedArray_t tempOutputsFulfilled, int numOutputsFulfilled, CH5_Eval eval) {
// The Dried Bouquet gets auto-placed in the 1st slot,
// and everything else gets shifted down one to fill the first NULL
tempInventory = addItem(tempInventory, Dried_Bouquet);
eval.DB_place_index = 0;
eval.frames_at_DB = eval.frames_at_MC;
// Dried Bouquet will always be in the first slot
for (eval.CO_place_index = 1; eval.CO_place_index < 10; eval.CO_place_index++) {
// Don't allow a move that will be invalid.
if (tempInventory.inventory[eval.CO_place_index] == Thunder_Rage) {
continue;
}
// Replace the item with the Coconut
Inventory co_temp_inventory = replaceItem(tempInventory, eval.CO_place_index, Coconut);
// Calculate the number of frames needed to pick this slot for replacement
eval.frames_at_CO = eval.frames_at_DB + TOSS_FRAMES
+ invFrames[tempInventory.length][eval.CO_place_index + 1];
// Handle the allocation of the Coconut sort, Keel Mango, and Courage Shell
handleChapter5Eval(curNode, co_temp_inventory, tempOutputsFulfilled, numOutputsFulfilled, eval);
}
}
/*-------------------------------------------------------------------
* Function : handleDBCOAllocation2Nulls
*
* There are at least 2 nulls, so both Dried Bouquet and Coconut
* will be autoplaced. Proceed to the early/late sort decision.
-------------------------------------------------------------------*/
void handleDBCOAllocation2Nulls(BranchPath *curNode, Inventory tempInventory, const outputCreatedArray_t tempOutputsFulfilled, int numOutputsFulfilled, CH5_Eval eval) {
// The Dried Bouquet gets auto-placed due to having nulls
tempInventory = addItem(tempInventory, Dried_Bouquet);
eval.DB_place_index = 0;
eval.frames_at_DB = eval.frames_at_MC;
// The Coconut gets auto-placed due to having nulls
tempInventory = addItem(tempInventory, Coconut);
eval.CO_place_index = 0;
eval.frames_at_CO = eval.frames_at_DB;
// Handle the allocation of the Coconut, Sort, Keel Mango, and Courage Shell
handleChapter5Eval(curNode, tempInventory, tempOutputsFulfilled, numOutputsFulfilled, eval);
}
/*-------------------------------------------------------------------
* Function : handleRecipeOutput
*
* After detecting that a recipe can be satisfied, see how we can handle
* the output (either tossing the output, auto-placing it if there is a
* null slot, or tossing a different item in the inventory)
-------------------------------------------------------------------*/
void handleRecipeOutput(BranchPath *curNode, Inventory tempInventory, MoveDescription useDescription, const outputCreatedArray_t tempOutputsFulfilled, int numOutputsFulfilled, enum Type_Sort output, int viableItems) {
// Options vary by whether there are NULLs within the inventory
if (tempInventory.nulls >= 1) {
tempInventory = addItem(tempInventory, ((Cook*)useDescription.data)->output);
// Check to see if this state is viable
if(stateOK(tempInventory, tempOutputsFulfilled, recipeList)) {
finalizeLegalMove(curNode, useDescription, tempInventory, tempOutputsFulfilled, numOutputsFulfilled, Autoplace, -1, -1);
}
}
else {
// There are no NULLs in the inventory. Something must be tossed
// Total number of frames increased by forcing to toss something
useDescription.framesTaken += TOSS_FRAMES;
useDescription.totalFramesTaken += TOSS_FRAMES;
// Evaluate the viability of tossing all current inventory items
// Assumed that it is impossible to toss and replace any items in the last 10 positions
tryTossInventoryItem(curNode, tempInventory, useDescription, tempOutputsFulfilled, numOutputsFulfilled, output, viableItems);
// Evaluate viability of tossing the output item itself
if (stateOK(tempInventory, tempOutputsFulfilled, recipeList)) {
finalizeLegalMove(curNode, useDescription, tempInventory, tempOutputsFulfilled, numOutputsFulfilled, Toss, output, -1);
}
}
}
/*-------------------------------------------------------------------
* Function : handleLegalMoveSelection
*
* Using the given method, select a legal move to explore next and
* place it at the beginning of the array.
-------------------------------------------------------------------*/
void handleLegalMoveSelection(BranchPath *curNode, enum SelectionMethod method) {
// Somewhat random process of picking the quicker moves to recurse down
// Arbitrarily skip over the fastest legal move with a given probability
if (method == Exponential && curNode->moves < 55 && curNode->numLegalMoves > 0) {
int nextMoveIndex = 0;
while (nextMoveIndex < curNode->numLegalMoves - 1 && pcg32_random_r(&rng[omp_get_thread_num()]) % 2) {
nextMoveIndex++;
}
// Take the legal move at nextMoveIndex and move it to the front of the array
BranchPath *nextMove = curNode->legalMoves[nextMoveIndex];
curNode->legalMoves[nextMoveIndex] = NULL;
shiftDownLegalMoves(curNode, 0, nextMoveIndex);
curNode->legalMoves[0] = nextMove;
}
// When opting for randomization, shuffle the entire list of legal moves