File: MapMerging.cpp

package info (click to toggle)
darkradiant 3.9.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 41,080 kB
  • sloc: cpp: 264,743; ansic: 10,659; python: 1,852; xml: 1,650; sh: 92; makefile: 21
file content (2645 lines) | stat: -rw-r--r-- 127,094 bytes parent folder | download | duplicates (2)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
#include "RadiantTest.h"

#include "icommandsystem.h"
#include "itransformable.h"
#include "ibrush.h"
#include "imapresource.h"
#include "ipatch.h"
#include "icomparablenode.h"
#include "algorithm/Scene.h"
#include "registry/registry.h"
#include "scenelib.h"
#include "scene/merge/GraphComparer.h"
#include "scene/merge/MergeOperation.h"
#include "scene/merge/ThreeWayMergeOperation.h"
#include "scene/merge/SelectionGroupMerger.h"
#include "scene/merge/ThreeWaySelectionGroupMerger.h"
#include "scene/merge/ThreeWayLayerMerger.h"
#include "scene/merge/LayerMerger.h"

namespace test
{

using MapMergeTest = RadiantTest;
using SelectionGroupMergeTest = RadiantTest;
using LayerMergeTest = RadiantTest;
using ThreeWayMergeTest = RadiantTest;
using ThreeWaySelectionGroupMergeTest = RadiantTest;
using ThreeWayLayerMergeTest = RadiantTest;

TEST_F(MapMergeTest, BrushFingerprint)
{
    GlobalCommandSystem().executeCommand("OpenMap", cmd::Argument("maps/fingerprinting.mapx"));

    auto originalMaterial = "textures/numbers/1";
    auto brush = std::dynamic_pointer_cast<IBrushNode>(algorithm::findFirstBrushWithMaterial(
        GlobalMapModule().findOrInsertWorldspawn(), originalMaterial));

    auto comparable = std::dynamic_pointer_cast<scene::IComparableNode>(brush);
    EXPECT_TRUE(comparable) << "BrushNode is not implementing IComparableNode";

    auto originalFingerprint = comparable->getFingerprint();

    EXPECT_FALSE(originalFingerprint.empty()); // shouldn't be empty

    // Calling it twice shouldn't change the value
    EXPECT_EQ(comparable->getFingerprint(), originalFingerprint);

    // Change the material of this brush, the fingerprint should change now
    brush->getIBrush().setShader("textures/somethingelse");
    EXPECT_NE(comparable->getFingerprint(), originalFingerprint);

    // Change it back
    brush->getIBrush().setShader(originalMaterial);
    EXPECT_EQ(comparable->getFingerprint(), originalFingerprint);

    // Change the contents flags, fingerprint should change
    brush->getIBrush().setDetailFlag(IBrush::Detail);
    EXPECT_NE(comparable->getFingerprint(), originalFingerprint);

    // Change it back
    brush->getIBrush().setDetailFlag(IBrush::Structural);
    EXPECT_EQ(comparable->getFingerprint(), originalFingerprint);

    // Get the first face and tinker with it
    auto& face = brush->getIBrush().getFace(0);

    auto lastFingerprint = comparable->getFingerprint();

    // Changing the texture should modify the fingerprint
    face.flipTexture(0);
    EXPECT_NE(comparable->getFingerprint(), lastFingerprint);
    lastFingerprint = comparable->getFingerprint();

    // Disable texture lock
    registry::setValue(RKEY_ENABLE_TEXTURE_LOCK, false);

    // Changing the planes
    auto transformable = std::dynamic_pointer_cast<ITransformable>(brush);
    transformable->setTranslation(Vector3(10,0,0));
    transformable->freezeTransform();

    EXPECT_NE(comparable->getFingerprint(), lastFingerprint);
    lastFingerprint = comparable->getFingerprint();
}

TEST_F(MapMergeTest, PatchFingerprint)
{
    GlobalCommandSystem().executeCommand("OpenMap", cmd::Argument("maps/fingerprinting.mapx"));

    auto originalMaterial = "textures/numbers/1";
    auto patch = std::dynamic_pointer_cast<IPatchNode>(algorithm::findFirstPatchWithMaterial(
        GlobalMapModule().findOrInsertWorldspawn(), originalMaterial));

    auto comparable = std::dynamic_pointer_cast<scene::IComparableNode>(patch);
    EXPECT_TRUE(comparable) << "PatchNode is not implementing IComparableNode";

    auto originalFingerprint = comparable->getFingerprint();

    EXPECT_FALSE(originalFingerprint.empty()); // shouldn't be empty

    // Calling it twice shouldn't change the value
    EXPECT_EQ(comparable->getFingerprint(), originalFingerprint);

    // Change the material of this patch, the fingerprint should change now
    patch->getPatch().setShader("textures/somethingelse");
    EXPECT_NE(comparable->getFingerprint(), originalFingerprint);

    // Change it back
    patch->getPatch().setShader(originalMaterial);
    EXPECT_EQ(comparable->getFingerprint(), originalFingerprint);

    // Change a single control vertex
    auto& control = patch->getPatch().ctrlAt(0, 0);

    auto lastFingerprint = comparable->getFingerprint();

    // Change a 3D coordinate
    control.vertex.x() += 0.1;
    EXPECT_NE(comparable->getFingerprint(), lastFingerprint);
    lastFingerprint = comparable->getFingerprint();

    // Change a 2D component
    control.texcoord.x() += 0.1;
    EXPECT_NE(comparable->getFingerprint(), lastFingerprint);
    lastFingerprint = comparable->getFingerprint();

    // Append vertices
    patch->getPatch().appendPoints(true, false);
    EXPECT_NE(comparable->getFingerprint(), lastFingerprint);
}

TEST_F(MapMergeTest, EntityFingerprint)
{
    GlobalCommandSystem().executeCommand("OpenMap", cmd::Argument("maps/fingerprinting.mapx"));

    auto entityNode = algorithm::getEntityByName(GlobalMapModule().getRoot(), "func_static_1");

    auto comparable = std::dynamic_pointer_cast<scene::IComparableNode>(entityNode);
    EXPECT_TRUE(comparable) << "EntityNode is not implementing IComparableNode";

    auto entity = std::dynamic_pointer_cast<IEntityNode>(entityNode);
    auto originalFingerprint = comparable->getFingerprint();

    EXPECT_FALSE(originalFingerprint.empty()); // shouldn't be empty

    // Calling it twice shouldn't change the value
    EXPECT_EQ(comparable->getFingerprint(), originalFingerprint);

    // Change a spawnarg slightly
    auto oldOrigin = entity->getEntity().getKeyValue("origin");

    entity->getEntity().setKeyValue("origin", "96 -32 53");
    EXPECT_NE(comparable->getFingerprint(), originalFingerprint);

    // Change it back
    entity->getEntity().setKeyValue("origin", oldOrigin);
    EXPECT_EQ(comparable->getFingerprint(), originalFingerprint);

    // Add a new spawnarg
    entity->getEntity().setKeyValue("origin22", "whatever");
    EXPECT_NE(comparable->getFingerprint(), originalFingerprint);

    // Change it back
    entity->getEntity().setKeyValue("origin22", "");
    EXPECT_EQ(comparable->getFingerprint(), originalFingerprint);

    // Remove a spawnarg, this alters the order of keyvalues
    auto originalValue = entity->getEntity().getKeyValue("dummyspawnarg");

    entity->getEntity().setKeyValue("dummyspawnarg", "");
    EXPECT_NE(comparable->getFingerprint(), originalFingerprint);

    // Change it back, even though the order is different, the fingerprint should be the same
    entity->getEntity().setKeyValue("dummyspawnarg", originalValue);
    EXPECT_EQ(comparable->getFingerprint(), originalFingerprint);
}

TEST_F(MapMergeTest, EntityFingerprintConsidersChildNodes)
{
    GlobalCommandSystem().executeCommand("OpenMap", cmd::Argument("maps/fingerprinting.mapx"));

    auto entityNode = algorithm::getEntityByName(GlobalMapModule().getRoot(), "func_static_1");

    auto comparable = std::dynamic_pointer_cast<scene::IComparableNode>(entityNode);
    EXPECT_TRUE(comparable) << "EntityNode is not implementing IComparableNode";

    auto entity = std::dynamic_pointer_cast<IEntityNode>(entityNode);
    auto originalFingerprint = comparable->getFingerprint();

    // Add a child patch
    auto patchNode = GlobalPatchModule().createPatch(patch::PatchDefType::Def3);
    std::dynamic_pointer_cast<IPatchNode>(patchNode)->getPatch().setDims(3, 3);
    scene::addNodeToContainer(patchNode, entityNode);
    EXPECT_NE(comparable->getFingerprint(), originalFingerprint);

    // Remove the patch again
    scene::removeNodeFromParent(patchNode);
    EXPECT_EQ(comparable->getFingerprint(), originalFingerprint);
}

TEST_F(MapMergeTest, EntityFingerprintInsensitiveToChildOrder)
{
    GlobalCommandSystem().executeCommand("OpenMap", cmd::Argument("maps/fingerprinting.mapx"));

    auto entityNode = algorithm::getEntityByName(GlobalMapModule().getRoot(), "func_static_1");

    auto comparable = std::dynamic_pointer_cast<scene::IComparableNode>(entityNode);
    EXPECT_TRUE(comparable) << "EntityNode is not implementing IComparableNode";

    auto entity = std::dynamic_pointer_cast<IEntityNode>(entityNode);
    auto originalFingerprint = comparable->getFingerprint();

    // Find the first brush of this func_static
    scene::INodePtr firstChild;
    std::size_t numChildren = 0;
    entity->foreachNode([&](const scene::INodePtr& node) 
    { 
        numChildren++;
        if (!firstChild)
        {
            firstChild = node;
        }

        return true;
    });
    EXPECT_TRUE(firstChild) << "func_static doesn't have any child nodes";
    EXPECT_GT(numChildren, 1) << "We need to have more than one child node in this func_static";

    // Remove it from the parent
    scene::removeNodeFromParent(firstChild);
    EXPECT_NE(comparable->getFingerprint(), originalFingerprint);

    // Adding it back to the entity will change the order of children,
    scene::addNodeToContainer(firstChild, entityNode);
    // Hash should stay the same
    EXPECT_EQ(comparable->getFingerprint(), originalFingerprint);
}

using namespace scene::merge;

inline ComparisonResult::Ptr performComparison(const std::string& targetMap, const std::string& sourceMapPath)
{
    GlobalCommandSystem().executeCommand("OpenMap", cmd::Argument(targetMap));

    auto resource = GlobalMapResourceManager().createFromPath(sourceMapPath);
    EXPECT_TRUE(resource->load()) << "Test map not found in path " << sourceMapPath;

    return GraphComparer::Compare(resource->getRootNode(), GlobalMapModule().getRoot());
}

inline std::size_t countPrimitiveDifference(const ComparisonResult::EntityDifference& diff, 
    const ComparisonResult::PrimitiveDifference::Type type)
{
    std::size_t count = 0;

    for (const auto& difference : diff.differingChildren)
    {
        if (difference.type == type)
        {
            ++count;
        }
    }

    return count;
}

inline bool hasKeyValueDifference(const ComparisonResult::EntityDifference& diff, 
    const std::string& key, const std::string& value, ComparisonResult::KeyValueDifference::Type type)
{
    for (const auto& difference : diff.differingKeyValues)
    {
        if (difference.type == type && difference.key == key && difference.value == value)
        {
            return true;
        }
    }

    return false;
}

inline ComparisonResult::EntityDifference getEntityDifference(const ComparisonResult::Ptr& result, const std::string& name)
{
    for (const auto& difference : result->differingEntities)
    {
        if (difference.entityName == name)
        {
            return difference;
        }
    }

    return ComparisonResult::EntityDifference();
}

TEST_F(MapMergeTest, DetectMissingEntities)
{
    auto result = performComparison("maps/fingerprinting.mapx", _context.getTestProjectPath() + "maps/fingerprinting_2.mapx");

    // The player start has been removed in the changed map
    auto diff = getEntityDifference(result, "info_player_start_1");
    
    EXPECT_EQ(diff.type, ComparisonResult::EntityDifference::Type::EntityMissingInSource);
    EXPECT_TRUE(diff.baseNode);
    EXPECT_FALSE(diff.sourceNode); // source node is missing, so it must be empty
}

TEST_F(MapMergeTest, DetectAddedEntities)
{
    auto result = performComparison("maps/fingerprinting.mapx", _context.getTestProjectPath() + "maps/fingerprinting_2.mapx");

    // light_3 start has been added to the changed map
    auto diff = getEntityDifference(result, "light_3");

    EXPECT_EQ(diff.type, ComparisonResult::EntityDifference::Type::EntityMissingInBase);
    EXPECT_TRUE(diff.sourceNode);
    EXPECT_FALSE(diff.baseNode); // base node is missing, so it must be empty

    diff = getEntityDifference(result, "func_static_2");
    EXPECT_EQ(diff.type, ComparisonResult::EntityDifference::Type::EntityMissingInBase);
    EXPECT_TRUE(diff.sourceNode);
    EXPECT_FALSE(diff.baseNode); // base node is missing, so it must be empty
}

TEST_F(MapMergeTest, DetectAddedKeyValues)
{
    auto result = performComparison("maps/fingerprinting.mapx", _context.getTestProjectPath() + "maps/fingerprinting_2.mapx");

    // light_1 has different key values, dist_check_period = 40 has been added
    auto diff = getEntityDifference(result, "light_1");

    EXPECT_EQ(diff.type, ComparisonResult::EntityDifference::Type::EntityPresentButDifferent);
    EXPECT_TRUE(hasKeyValueDifference(diff, "dist_check_period", "40", ComparisonResult::KeyValueDifference::Type::KeyValueAdded));
}

TEST_F(MapMergeTest, DetectRemovedKeyValues)
{
    auto result = performComparison("maps/fingerprinting.mapx", _context.getTestProjectPath() + "maps/fingerprinting_2.mapx");

    // light_1 has different key values, break = 1 has been removed
    auto diff = getEntityDifference(result, "light_1");

    EXPECT_EQ(diff.type, ComparisonResult::EntityDifference::Type::EntityPresentButDifferent);
    EXPECT_TRUE(hasKeyValueDifference(diff, "break", "1", ComparisonResult::KeyValueDifference::Type::KeyValueRemoved));
}

TEST_F(MapMergeTest, DetectChangedKeyValues)
{
    auto result = performComparison("maps/fingerprinting.mapx", _context.getTestProjectPath() + "maps/fingerprinting_2.mapx");

    // light_1 has different key values, "ai_see" has been changed to "1"
    auto diff = getEntityDifference(result, "light_1");

    EXPECT_EQ(diff.type, ComparisonResult::EntityDifference::Type::EntityPresentButDifferent);
    EXPECT_TRUE(hasKeyValueDifference(diff, "ai_see", "1", ComparisonResult::KeyValueDifference::Type::KeyValueChanged));

    // light_2 has a different origin
    diff = getEntityDifference(result, "light_2");
    EXPECT_EQ(diff.type, ComparisonResult::EntityDifference::Type::EntityPresentButDifferent);
    EXPECT_TRUE(hasKeyValueDifference(diff, "origin", "280 160 0", ComparisonResult::KeyValueDifference::Type::KeyValueChanged));
}

TEST_F(MapMergeTest, DetectChildPrimitiveChanges)
{
    auto result = performComparison("maps/fingerprinting.mapx", _context.getTestProjectPath() + "maps/fingerprinting_2.mapx");

    // func_static_30 has changed primitives
    auto diff = getEntityDifference(result, "func_static_30");

    EXPECT_EQ(diff.type, ComparisonResult::EntityDifference::Type::EntityPresentButDifferent);
    EXPECT_EQ(diff.differingChildren.size(), 1);
    EXPECT_EQ(diff.differingChildren.front().type, ComparisonResult::PrimitiveDifference::Type::PrimitiveAdded);
    EXPECT_EQ(diff.differingChildren.front().node->getNodeType(), scene::INode::Type::Brush);

    // func_static_1 has 2 additions and 1 removal (== 1 addition, 1 replacement)
    diff = getEntityDifference(result, "func_static_1");

    EXPECT_EQ(diff.type, ComparisonResult::EntityDifference::Type::EntityPresentButDifferent);
    EXPECT_EQ(countPrimitiveDifference(diff, ComparisonResult::PrimitiveDifference::Type::PrimitiveAdded), 2);
    EXPECT_EQ(countPrimitiveDifference(diff, ComparisonResult::PrimitiveDifference::Type::PrimitiveRemoved), 1);

    // worldspawn has a couple of changes
    diff = getEntityDifference(result, "worldspawn");

    EXPECT_EQ(diff.type, ComparisonResult::EntityDifference::Type::EntityPresentButDifferent);
    EXPECT_EQ(countPrimitiveDifference(diff, ComparisonResult::PrimitiveDifference::Type::PrimitiveAdded), 3);
    EXPECT_EQ(countPrimitiveDifference(diff, ComparisonResult::PrimitiveDifference::Type::PrimitiveRemoved), 3);
}

template<typename T>
std::shared_ptr<T> findAction(const IMergeOperation::Ptr& operation, const std::function<bool(const std::shared_ptr<T>&)>& predicate)
{
    std::shared_ptr<T> foundAction;

    operation->foreachAction([&](const IMergeAction::Ptr& action)
    {
        if (foundAction) return;

        auto derivedAction = std::dynamic_pointer_cast<T>(action);

        if (!derivedAction || !predicate(derivedAction)) return;

        foundAction = derivedAction;
    });

    return foundAction;
}

template<typename T>
std::size_t countActions(const IMergeOperation::Ptr& operation, const std::function<bool(const std::shared_ptr<T>&)>& predicate)
{
    std::size_t count = 0;

    operation->foreachAction([&](const IMergeAction::Ptr& action)
    {
        auto derivedAction = std::dynamic_pointer_cast<T>(action);

        if (!derivedAction || !predicate(derivedAction)) return;

        ++count;
    });

    return count;
}

TEST_F(MapMergeTest, MergeActionsForMissingEntities)
{
    auto result = performComparison("maps/fingerprinting.mapx", _context.getTestProjectPath() + "maps/fingerprinting_2.mapx");
    auto operation = MergeOperation::CreateFromComparisonResult(*result);

    // light_3
    auto action = findAction<AddEntityAction>(operation, [](const std::shared_ptr<AddEntityAction>& action)
    {
        auto sourceEntity = Node_getEntity(action->getSourceNodeToAdd());
        return sourceEntity->getKeyValue("name") == "light_3";
    });

    EXPECT_TRUE(action) << "No merge action found for missing entity";

    // Check pre-requisites and apply the action
    auto entityNode = algorithm::getEntityByName(result->getBaseRootNode(), "light_3");
    EXPECT_FALSE(entityNode);

    action->applyChanges();

    entityNode = algorithm::getEntityByName(result->getBaseRootNode(), "light_3");
    EXPECT_TRUE(entityNode);

    // func_static_2
    action = findAction<AddEntityAction>(operation, [](const std::shared_ptr<AddEntityAction>& action)
    {
        auto sourceEntity = Node_getEntity(action->getSourceNodeToAdd());
        return sourceEntity->getKeyValue("name") == "func_static_2";
    });

    EXPECT_TRUE(action) << "No merge action found for missing entity";

    // Check pre-requisites and apply the action
    entityNode = algorithm::getEntityByName(result->getBaseRootNode(), "func_static_2");
    EXPECT_FALSE(entityNode);

    action->applyChanges();

    entityNode = algorithm::getEntityByName(result->getBaseRootNode(), "func_static_2");
    EXPECT_TRUE(entityNode);

    // Assume the child primitives have been added too
    EXPECT_TRUE(scene::hasChildPrimitives(entityNode));
}

TEST_F(MapMergeTest, MergeActionsForRemovedEntities)
{
    auto result = performComparison("maps/fingerprinting.mapx", _context.getTestProjectPath() + "maps/fingerprinting_2.mapx");
    auto operation = MergeOperation::CreateFromComparisonResult(*result);

    auto action = findAction<RemoveEntityAction>(operation, [](const std::shared_ptr<RemoveEntityAction>& action)
    {
        auto entity = Node_getEntity(action->getNodeToRemove());
        return entity->getKeyValue("name") == "info_player_start_1";
    });

    EXPECT_TRUE(action) << "No merge action found for removed entity";

    // Check pre-requisites and apply the action
    auto entityNode = algorithm::getEntityByName(result->getBaseRootNode(), "info_player_start_1");
    EXPECT_TRUE(entityNode);

    action->applyChanges();

    entityNode = algorithm::getEntityByName(result->getBaseRootNode(), "info_player_start_1");
    EXPECT_FALSE(entityNode);
}

TEST_F(MapMergeTest, MergeActionsForAddedKeyValues)
{
    auto result = performComparison("maps/fingerprinting.mapx", _context.getTestProjectPath() + "maps/fingerprinting_2.mapx");
    auto operation = MergeOperation::CreateFromComparisonResult(*result);

    auto action = findAction<AddEntityKeyValueAction>(operation, [](const std::shared_ptr<AddEntityKeyValueAction>& action)
    {
        auto entity = Node_getEntity(action->getEntityNode());
        return entity->getKeyValue("name") == "light_1" && action->getKey() == "dist_check_period" && action->getValue() == "40";
    });

    EXPECT_TRUE(action) << "No merge action found for added key value";

    // Check pre-requisites and apply the action
    auto entityNode = algorithm::getEntityByName(result->getBaseRootNode(), "light_1");
    EXPECT_EQ(Node_getEntity(entityNode)->getKeyValue("dist_check_period"), "");

    action->applyChanges();

    entityNode = algorithm::getEntityByName(result->getBaseRootNode(), "light_1");
    EXPECT_EQ(Node_getEntity(entityNode)->getKeyValue("dist_check_period"), "40");
}

TEST_F(MapMergeTest, MergeActionsForRemovedKeyValues)
{
    auto result = performComparison("maps/fingerprinting.mapx", _context.getTestProjectPath() + "maps/fingerprinting_2.mapx");
    auto operation = MergeOperation::CreateFromComparisonResult(*result);

    auto action = findAction<RemoveEntityKeyValueAction>(operation, [](const std::shared_ptr<RemoveEntityKeyValueAction>& action)
    {
        auto entity = Node_getEntity(action->getEntityNode());
        return entity->getKeyValue("name") == "light_1" && action->getKey() == "break" && action->getValue().empty();
    });

    EXPECT_TRUE(action) << "No merge action found for removed key value";

    // Check pre-requisites and apply the action
    auto entityNode = algorithm::getEntityByName(result->getBaseRootNode(), "light_1");
    EXPECT_EQ(Node_getEntity(entityNode)->getKeyValue("break"), "1");

    action->applyChanges();

    entityNode = algorithm::getEntityByName(result->getBaseRootNode(), "light_1");
    EXPECT_EQ(Node_getEntity(entityNode)->getKeyValue("break"), "");
}

TEST_F(MapMergeTest, MergeActionsForChangedKeyValues)
{
    auto result = performComparison("maps/fingerprinting.mapx", _context.getTestProjectPath() + "maps/fingerprinting_2.mapx");
    auto operation = MergeOperation::CreateFromComparisonResult(*result);

    auto action = findAction<ChangeEntityKeyValueAction>(operation, [](const std::shared_ptr<ChangeEntityKeyValueAction>& action)
    {
        auto entity = Node_getEntity(action->getEntityNode());
        return entity->getKeyValue("name") == "light_1" && action->getKey() == "ai_see" && action->getValue() == "1";
    });

    EXPECT_TRUE(action) << "No merge action found for changed key value";

    // Check pre-requisites and apply the action
    auto entityNode = algorithm::getEntityByName(result->getBaseRootNode(), "light_1");
    EXPECT_EQ(Node_getEntity(entityNode)->getKeyValue("ai_see"), "0");

    action->applyChanges();

    entityNode = algorithm::getEntityByName(result->getBaseRootNode(), "light_1");
    EXPECT_EQ(Node_getEntity(entityNode)->getKeyValue("ai_see"), "1");

    action = findAction<ChangeEntityKeyValueAction>(operation, [](const std::shared_ptr<ChangeEntityKeyValueAction>& action)
    {
        auto entity = Node_getEntity(action->getEntityNode());
        return entity->getKeyValue("name") == "light_2" && action->getKey() == "origin" && action->getValue() == "280 160 0";
    });

    EXPECT_TRUE(action) << "No merge action found for changed key value";

    // Check pre-requisites and apply the action
    entityNode = algorithm::getEntityByName(result->getBaseRootNode(), "light_2");
    EXPECT_NE(Node_getEntity(entityNode)->getKeyValue("origin"), "280 160 0");

    action->applyChanges();

    entityNode = algorithm::getEntityByName(result->getBaseRootNode(), "light_2");
    EXPECT_EQ(Node_getEntity(entityNode)->getKeyValue("origin"), "280 160 0");
}

inline std::size_t getChildPrimitiveCount(const scene::INodePtr& node)
{
    std::size_t count = 0;
    node->foreachNode([&](const scene::INodePtr& node)
    {
        if (Node_isPrimitive(node))
        {
            ++count;
        }

        return true;
    });

    return count;
}

TEST_F(MapMergeTest, MergeActionsForChangedPrimitives)
{
    auto result = performComparison("maps/fingerprinting.mapx", _context.getTestProjectPath() + "maps/fingerprinting_2.mapx");
    auto operation = MergeOperation::CreateFromComparisonResult(*result);

    auto addAction = findAction<AddChildAction>(operation, [](const std::shared_ptr<AddChildAction>& action)
    {
        auto entity = Node_getEntity(action->getParent());
        return entity->getKeyValue("name") == "func_static_30" && action->getSourceNodeToAdd()->getNodeType() == scene::INode::Type::Brush;
    });

    EXPECT_TRUE(addAction) << "No merge action found for added child node";

    // func_static_1 has 2 additions and 1 removal (== 1 addition, 1 replacement)
    auto addActionCount = countActions<AddChildAction>(operation, [](const std::shared_ptr<AddChildAction>& action)
    {
        auto entity = Node_getEntity(action->getParent());
        return entity->getKeyValue("name") == "func_static_1";
    });
    auto removeActionCount = countActions<RemoveChildAction>(operation, [](const std::shared_ptr<RemoveChildAction>& action)
    {
        auto entity = Node_getEntity(action->getNodeToRemove()->getParent());
        return entity->getKeyValue("name") == "func_static_1";
    });

    EXPECT_EQ(addActionCount, 2) << "No merge action found for added child node";
    EXPECT_EQ(removeActionCount, 1) << "No merge action found for removed child node";

    addActionCount = countActions<AddChildAction>(operation, [](const std::shared_ptr<AddChildAction>& action)
    {
        auto entity = Node_getEntity(action->getParent());
        return entity->isWorldspawn();
    });
    removeActionCount = countActions<RemoveChildAction>(operation, [](const std::shared_ptr<RemoveChildAction>& action)
    {
        auto entity = Node_getEntity(action->getNodeToRemove()->getParent());
        return entity->isWorldspawn();
    });

    EXPECT_EQ(addActionCount, 3) << "No merge action found for added child node";
    EXPECT_EQ(removeActionCount, 3) << "No merge action found for removed child node";

    // func_static_1 should have 3 brushes after execution of the actions
    // Check prerequisites and execute action
    auto entityNode = algorithm::getEntityByName(result->getBaseRootNode(), "func_static_1");
    EXPECT_EQ(getChildPrimitiveCount(entityNode), 2);

    operation->applyActions();

    entityNode = algorithm::getEntityByName(result->getBaseRootNode(), "func_static_1");
    EXPECT_EQ(getChildPrimitiveCount(entityNode), 3);
}

TEST_F(MapMergeTest, ApplyMergeOperation)
{
    GlobalCommandSystem().executeCommand("OpenMap", cmd::Argument("maps/fingerprinting.mapx"));

    auto changedMap = _context.getTestProjectPath() + "maps/fingerprinting_2.mapx";
    auto resource = GlobalMapResourceManager().createFromPath(changedMap);
    EXPECT_TRUE(resource->load()) << "Test map not found in path " << changedMap;

    auto result = GraphComparer::Compare(resource->getRootNode(), GlobalMapModule().getRoot());

    // The result should have differences
    EXPECT_FALSE(result->differingEntities.empty());

    auto operation = MergeOperation::CreateFromComparisonResult(*result);
    operation->applyActions();

    auto resultAfterExecution = GraphComparer::Compare(resource->getRootNode(), GlobalMapModule().getRoot());

    // The result should not list any differences anymore
    EXPECT_TRUE(resultAfterExecution->differingEntities.empty());
}

TEST_F(MapMergeTest, DeactivatedAddEntityAction)
{
    auto result = performComparison("maps/fingerprinting.mapx", _context.getTestProjectPath() + "maps/fingerprinting_2.mapx");
    auto operation = MergeOperation::CreateFromComparisonResult(*result);

    auto action = findAction<AddEntityAction>(operation, [](const std::shared_ptr<AddEntityAction>& action)
    {
        auto sourceEntity = Node_getEntity(action->getSourceNodeToAdd());
        return sourceEntity->getKeyValue("name") == "light_3";
    });

    // Check pre-requisites and apply the action
    auto entityNode = algorithm::getEntityByName(result->getBaseRootNode(), "light_3");
    EXPECT_FALSE(entityNode);

    action->deactivate();
    action->applyChanges();

    entityNode = algorithm::getEntityByName(result->getBaseRootNode(), "light_3");
    EXPECT_FALSE(entityNode); // must still be missing
}

TEST_F(MapMergeTest, DeactivatedRemoveEntityAction)
{
    auto result = performComparison("maps/fingerprinting.mapx", _context.getTestProjectPath() + "maps/fingerprinting_2.mapx");
    auto operation = MergeOperation::CreateFromComparisonResult(*result);

    auto action = findAction<RemoveEntityAction>(operation, [](const std::shared_ptr<RemoveEntityAction>& action)
    {
        auto entity = Node_getEntity(action->getNodeToRemove());
        return entity->getKeyValue("name") == "info_player_start_1";
    });

    // Check pre-requisites and apply the action
    auto entityNode = algorithm::getEntityByName(result->getBaseRootNode(), "info_player_start_1");
    EXPECT_TRUE(entityNode);

    action->deactivate();
    action->applyChanges();

    entityNode = algorithm::getEntityByName(result->getBaseRootNode(), "info_player_start_1");
    EXPECT_TRUE(entityNode); // must still be here
}

TEST_F(MapMergeTest, DeactivatedAddEntityKeyValueAction)
{
    auto result = performComparison("maps/fingerprinting.mapx", _context.getTestProjectPath() + "maps/fingerprinting_2.mapx");
    auto operation = MergeOperation::CreateFromComparisonResult(*result);

    auto action = findAction<AddEntityKeyValueAction>(operation, [](const std::shared_ptr<AddEntityKeyValueAction>& action)
    {
        auto entity = Node_getEntity(action->getEntityNode());
        return entity->getKeyValue("name") == "light_1" && action->getKey() == "dist_check_period" && action->getValue() == "40";
    });

    // Check pre-requisites and apply the action
    auto entityNode = algorithm::getEntityByName(result->getBaseRootNode(), "light_1");
    EXPECT_EQ(Node_getEntity(entityNode)->getKeyValue("dist_check_period"), "");

    action->deactivate();
    action->applyChanges();

    entityNode = algorithm::getEntityByName(result->getBaseRootNode(), "light_1");
    EXPECT_EQ(Node_getEntity(entityNode)->getKeyValue("dist_check_period"), ""); // must still be unchanged
}

TEST_F(MapMergeTest, DeactivatedRemoveEntityKeyValueAction)
{
    auto result = performComparison("maps/fingerprinting.mapx", _context.getTestProjectPath() + "maps/fingerprinting_2.mapx");
    auto operation = MergeOperation::CreateFromComparisonResult(*result);

    auto action = findAction<RemoveEntityKeyValueAction>(operation, [](const std::shared_ptr<RemoveEntityKeyValueAction>& action)
    {
        auto entity = Node_getEntity(action->getEntityNode());
        return entity->getKeyValue("name") == "light_1" && action->getKey() == "break" && action->getValue().empty();
    });

    // Check pre-requisites and apply the action
    auto entityNode = algorithm::getEntityByName(result->getBaseRootNode(), "light_1");
    EXPECT_EQ(Node_getEntity(entityNode)->getKeyValue("break"), "1");

    action->deactivate();
    action->applyChanges();

    entityNode = algorithm::getEntityByName(result->getBaseRootNode(), "light_1");
    EXPECT_EQ(Node_getEntity(entityNode)->getKeyValue("break"), "1"); // must be unchanged
}

TEST_F(MapMergeTest, DeactivatedChangeEntityKeyValueAction)
{
    auto result = performComparison("maps/fingerprinting.mapx", _context.getTestProjectPath() + "maps/fingerprinting_2.mapx");
    auto operation = MergeOperation::CreateFromComparisonResult(*result);

    auto action = findAction<ChangeEntityKeyValueAction>(operation, [](const std::shared_ptr<ChangeEntityKeyValueAction>& action)
    {
        auto entity = Node_getEntity(action->getEntityNode());
        return entity->getKeyValue("name") == "light_1" && action->getKey() == "ai_see" && action->getValue() == "1";
    });

    // Check pre-requisites and apply the action
    auto entityNode = algorithm::getEntityByName(result->getBaseRootNode(), "light_1");
    EXPECT_EQ(Node_getEntity(entityNode)->getKeyValue("ai_see"), "0");

    action->deactivate();
    action->applyChanges();

    entityNode = algorithm::getEntityByName(result->getBaseRootNode(), "light_1");
    EXPECT_EQ(Node_getEntity(entityNode)->getKeyValue("ai_see"), "0");
}

TEST_F(MapMergeTest, DeactivatedChangePrimitiveActions)
{
    auto result = performComparison("maps/fingerprinting.mapx", _context.getTestProjectPath() + "maps/fingerprinting_2.mapx");
    auto operation = MergeOperation::CreateFromComparisonResult(*result);

    // func_static_1 has 2 additions and 1 removal (== 1 addition, 1 replacement)
    operation->foreachAction([&](const IMergeAction::Ptr& action)
    {
        auto addChildAction = std::dynamic_pointer_cast<AddChildAction>(action);

        if (addChildAction && Node_isEntity(addChildAction->getParent()) && 
            Node_getEntity(addChildAction->getParent())->getKeyValue("name") == "func_static_1")
        {
            addChildAction->deactivate();
        }

        auto removeChildAction = std::dynamic_pointer_cast<RemoveChildAction>(action);

        if (removeChildAction && Node_isEntity(removeChildAction->getNodeToRemove()->getParent()) &&
            Node_getEntity(removeChildAction->getNodeToRemove()->getParent())->getKeyValue("name") == "func_static_1")
        {
            removeChildAction->deactivate();
        }
    });
    
    // func_static_1 has 2 brushes, this should stay the same
    // Check prerequisites and execute action
    auto entityNode = algorithm::getEntityByName(result->getBaseRootNode(), "func_static_1");
    EXPECT_EQ(getChildPrimitiveCount(entityNode), 2);

    operation->applyActions();

    entityNode = algorithm::getEntityByName(result->getBaseRootNode(), "func_static_1");
    EXPECT_EQ(getChildPrimitiveCount(entityNode), 2);
}

// Start and finish the merge operation through the map module interface
TEST_F(MapMergeTest, StartAndFinishMergeOperation)
{
    GlobalCommandSystem().executeCommand("OpenMap", cmd::Argument("maps/fingerprinting.mapx"));

    auto changedMap = _context.getTestProjectPath() + "maps/fingerprinting_2.mapx";
    auto resource = GlobalMapResourceManager().createFromPath(changedMap);
    EXPECT_TRUE(resource->load()) << "Test map not found in path " << changedMap;

    auto result = GraphComparer::Compare(resource->getRootNode(), GlobalMapModule().getRoot());

    // The result should have differences
    EXPECT_FALSE(result->differingEntities.empty());

    // Start and finish the regular merge operation
    GlobalMapModule().startMergeOperation(changedMap);
    GlobalMapModule().finishMergeOperation();

    auto resultAfterExecution = GraphComparer::Compare(resource->getRootNode(), GlobalMapModule().getRoot());

    // The result should not list any differences anymore
    EXPECT_TRUE(resultAfterExecution->differingEntities.empty());
}

// Finish the merge operation with a few merge action nodes hidden
TEST_F(MapMergeTest, FinishMergeOperationWithHiddenNodes)
{
    GlobalCommandSystem().executeCommand("OpenMap", cmd::Argument("maps/fingerprinting.mapx"));

    auto changedMap = _context.getTestProjectPath() + "maps/fingerprinting_2.mapx";
    auto resource = GlobalMapResourceManager().createFromPath(changedMap);
    EXPECT_TRUE(resource->load()) << "Test map not found in path " << changedMap;

    auto result = GraphComparer::Compare(resource->getRootNode(), GlobalMapModule().getRoot());

    // The result should have differences
    EXPECT_FALSE(result->differingEntities.empty());

    // Start and finish the regular merge operation
    GlobalMapModule().startMergeOperation(changedMap);

    std::vector<scene::INodePtr> mergeNodes;

    // Hide a few merge action nodes
    GlobalMapModule().getRoot()->foreachNode([&](const scene::INodePtr& node)
    {
        if (node->getNodeType() == scene::INode::Type::MergeAction)
        {
            mergeNodes.push_back(node);
        }

        return true;
    });

    EXPECT_NE(mergeNodes.size(), 0) << "No merge action nodes found in the scene";

    // Pick and hide every other node 
    for (auto i = 0; i < mergeNodes.size(); i += 2)
    {
        EXPECT_TRUE(mergeNodes[i]->visible()) << "Node should not be hidden: " << mergeNodes[i]->name();
        Node_setSelected(mergeNodes[i], true);
    }

    GlobalCommandSystem().executeCommand("HideSelected");

    for (auto i = 0; i < mergeNodes.size(); i += 2)
    {
        EXPECT_FALSE(mergeNodes[i]->visible()) << "Node should be hidden: " << mergeNodes[i]->name();
    }

    GlobalMapModule().finishMergeOperation();

    // The hidden merge action nodes should still have their actions applied
    auto resultAfterExecution = GraphComparer::Compare(resource->getRootNode(), GlobalMapModule().getRoot());

    // The result should not list any differences anymore
    EXPECT_TRUE(resultAfterExecution->differingEntities.empty());
}

inline bool hasChange(const std::vector<SelectionGroupMerger::Change>& log, 
    const std::function<bool(const SelectionGroupMerger::Change&)>& predicate)
{
    return std::find_if(log.begin(), log.end(), predicate) != log.end();
}

inline std::size_t changeCountByType(const std::vector<SelectionGroupMerger::Change>& log,
    SelectionGroupMerger::Change::Type type)
{
    return std::count_if(log.begin(), log.end(), [=](const SelectionGroupMerger::Change& change)
    {
        return change.type == type;
    });
}

inline std::unique_ptr<SelectionGroupMerger> setupGroupMerger(const std::string& sourceMap, const std::string& baseMap)
{
    auto originalResource = GlobalMapResourceManager().createFromPath(baseMap);
    EXPECT_TRUE(originalResource->load()) << "Test map not found: " << baseMap;

    auto changedResource = GlobalMapResourceManager().createFromPath(sourceMap);
    EXPECT_TRUE(changedResource->load()) << "Test map not found: " << sourceMap;

    auto result = GraphComparer::Compare(changedResource->getRootNode(), originalResource->getRootNode());
    auto operation = MergeOperation::CreateFromComparisonResult(*result);
    operation->setMergeSelectionGroups(false); // we do this manually
    operation->applyActions();

    return std::make_unique<SelectionGroupMerger>(result->getSourceRootNode(), result->getBaseRootNode());
}

inline bool groupContains(const selection::ISelectionGroupPtr& group, const scene::INodePtr& node)
{
    bool found = false;

    group->foreachNode([&](const scene::INodePtr& member) 
    { 
        if (member == node) found = true; 
    });

    return found;
}

// The group containing the 1 brushes has been dissolved in the changed map
TEST_F(SelectionGroupMergeTest, GroupRemoved)
{
    auto merger = setupGroupMerger("maps/merging_groups_2.mapx", "maps/merging_groups_1.mapx");

    // Worldspawn Brush with "1" should be part of 1 group
    auto brush1 = algorithm::findFirstBrushWithMaterial(algorithm::findWorldspawn(merger->getBaseRoot()), "textures/numbers/1");
    EXPECT_EQ(std::dynamic_pointer_cast<IGroupSelectable>(brush1)->getGroupIds().size(), 2);

    merger->adjustBaseGroups();

    // Worldspawn Brush with "1" should no longer be part of 1 group
    EXPECT_EQ(std::dynamic_pointer_cast<IGroupSelectable>(brush1)->getGroupIds().size(), 1);

    EXPECT_EQ(changeCountByType(merger->getChangeLog(), SelectionGroupMerger::Change::Type::BaseGroupCreated), 0);
    EXPECT_EQ(changeCountByType(merger->getChangeLog(), SelectionGroupMerger::Change::Type::BaseGroupRemoved), 1);

    // Run another merger, it shouldn't find any actions to take
    merger = std::make_unique<SelectionGroupMerger>(merger->getSourceRoot(), merger->getBaseRoot());
    merger->adjustBaseGroups();
    EXPECT_TRUE(merger->getChangeLog().empty());
}

// Brushes 1 & 2 have been grouped together, brushes 15/16/17/18 form a new group
TEST_F(SelectionGroupMergeTest, GroupAdded)
{
    auto merger = setupGroupMerger("maps/merging_groups_3.mapx", "maps/merging_groups_1.mapx");

    auto brush15 = algorithm::findFirstBrushWithMaterial(algorithm::findWorldspawn(merger->getBaseRoot()), "textures/numbers/15");
    auto brush16 = algorithm::findFirstBrushWithMaterial(algorithm::findWorldspawn(merger->getBaseRoot()), "textures/numbers/16");
    auto brush17 = algorithm::findFirstBrushWithMaterial(algorithm::findWorldspawn(merger->getBaseRoot()), "textures/numbers/17");
    auto brush18 = algorithm::findFirstBrushWithMaterial(algorithm::findWorldspawn(merger->getBaseRoot()), "textures/numbers/18");

    EXPECT_EQ(std::dynamic_pointer_cast<IGroupSelectable>(brush15)->getGroupIds().size(), 0);
    EXPECT_EQ(std::dynamic_pointer_cast<IGroupSelectable>(brush16)->getGroupIds().size(), 0);
    EXPECT_EQ(std::dynamic_pointer_cast<IGroupSelectable>(brush17)->getGroupIds().size(), 0);
    EXPECT_EQ(std::dynamic_pointer_cast<IGroupSelectable>(brush18)->getGroupIds().size(), 0);

    // Verify the other targets
    auto brush1 = algorithm::findFirstBrushWithMaterial(algorithm::findWorldspawn(merger->getBaseRoot()), "textures/numbers/1");
    auto brush2 = algorithm::findFirstBrushWithMaterial(algorithm::findWorldspawn(merger->getBaseRoot()), "textures/numbers/2");
    auto funcStatic1 = algorithm::getEntityByName(merger->getBaseRoot(), "func_static_1");
    auto funcStatic2 = algorithm::getEntityByName(merger->getBaseRoot(), "func_static_2");

    EXPECT_EQ(std::dynamic_pointer_cast<IGroupSelectable>(brush1)->getGroupIds().size(), 2); // worldspawn brush has 2 groups
    EXPECT_EQ(std::dynamic_pointer_cast<IGroupSelectable>(brush2)->getGroupIds().size(), 2); // worldspawn brush has 2 groups
    EXPECT_EQ(std::dynamic_pointer_cast<IGroupSelectable>(funcStatic1)->getGroupIds().size(), 1); // func_static has 1 group
    EXPECT_EQ(std::dynamic_pointer_cast<IGroupSelectable>(funcStatic2)->getGroupIds().size(), 1); // func_static has 1 group

    merger->adjustBaseGroups();

    // 2 new groups in this map
    EXPECT_EQ(changeCountByType(merger->getChangeLog(), SelectionGroupMerger::Change::Type::BaseGroupCreated), 2);
    EXPECT_EQ(changeCountByType(merger->getChangeLog(), SelectionGroupMerger::Change::Type::BaseGroupRemoved), 0);
    
    // Brushes 15/16/17/18 are now in a group
    EXPECT_EQ(std::dynamic_pointer_cast<IGroupSelectable>(brush15)->getGroupIds().size(), 1);
    EXPECT_EQ(std::dynamic_pointer_cast<IGroupSelectable>(brush16)->getGroupIds().size(), 1);
    EXPECT_EQ(std::dynamic_pointer_cast<IGroupSelectable>(brush17)->getGroupIds().size(), 1);
    EXPECT_EQ(std::dynamic_pointer_cast<IGroupSelectable>(brush18)->getGroupIds().size(), 1);

    // It must be the same group
    auto groupId = std::dynamic_pointer_cast<IGroupSelectable>(brush15)->getGroupIds().front();
    EXPECT_EQ(std::dynamic_pointer_cast<IGroupSelectable>(brush16)->getGroupIds().front(), groupId);
    EXPECT_EQ(std::dynamic_pointer_cast<IGroupSelectable>(brush17)->getGroupIds().front(), groupId);
    EXPECT_EQ(std::dynamic_pointer_cast<IGroupSelectable>(brush18)->getGroupIds().front(), groupId);

    // Verify the other changed nodes
    EXPECT_EQ(std::dynamic_pointer_cast<IGroupSelectable>(brush1)->getGroupIds().size(), 3); // worldspawn brush now has 3 groups
    EXPECT_EQ(std::dynamic_pointer_cast<IGroupSelectable>(brush2)->getGroupIds().size(), 3); // worldspawn brush now has 3 groups
    EXPECT_EQ(std::dynamic_pointer_cast<IGroupSelectable>(funcStatic1)->getGroupIds().size(), 2); // func_static now has 2 group
    EXPECT_EQ(std::dynamic_pointer_cast<IGroupSelectable>(funcStatic2)->getGroupIds().size(), 2); // func_static now has 2 group

    // Run another merger, it shouldn't find any actions to take
    merger = std::make_unique<SelectionGroupMerger>(merger->getSourceRoot(), merger->getBaseRoot());
    merger->adjustBaseGroups();
    EXPECT_TRUE(merger->getChangeLog().empty());
}

// Base: [[Brush7+Brush7] + func_static_7] => Brushes 7/7 are grouped, and this group in turn forms a group with func_static_7
// Changed map: [[[Brush7+Brush7] + Brush17] + func_static_7] => Intermediate group of B7+B7 with B17
TEST_F(SelectionGroupMergeTest, GroupInsertion)
{
    auto merger = setupGroupMerger("maps/merging_groups_4.mapx", "maps/merging_groups_1.mapx");

    auto brush7 = algorithm::findFirstBrushWithMaterial(algorithm::findWorldspawn(merger->getBaseRoot()), "textures/numbers/7");
    auto brush17 = algorithm::findFirstBrushWithMaterial(algorithm::findWorldspawn(merger->getBaseRoot()), "textures/numbers/17");
    auto funcStatic7 = algorithm::getEntityByName(merger->getBaseRoot(), "func_static_7");

    EXPECT_EQ(std::dynamic_pointer_cast<IGroupSelectable>(brush7)->getGroupIds().size(), 2);
    EXPECT_EQ(std::dynamic_pointer_cast<IGroupSelectable>(brush17)->getGroupIds().size(), 0);
    EXPECT_EQ(std::dynamic_pointer_cast<IGroupSelectable>(funcStatic7)->getGroupIds().size(), 1);

    merger->adjustBaseGroups();

    // 2 new groups in this map, 1 old one removed
    EXPECT_EQ(changeCountByType(merger->getChangeLog(), SelectionGroupMerger::Change::Type::BaseGroupCreated), 2);
    EXPECT_EQ(changeCountByType(merger->getChangeLog(), SelectionGroupMerger::Change::Type::BaseGroupRemoved), 1);

    // Brush 7 now has 3 group memberships
    auto brush7Groups = std::dynamic_pointer_cast<IGroupSelectable>(brush7)->getGroupIds();
    auto brush17Groups = std::dynamic_pointer_cast<IGroupSelectable>(brush17)->getGroupIds();
    auto funcStatic7Groups = std::dynamic_pointer_cast<IGroupSelectable>(funcStatic7)->getGroupIds();

    EXPECT_EQ(brush7Groups.size(), 3);
    EXPECT_EQ(brush17Groups.size(), 2);
    EXPECT_EQ(funcStatic7Groups.size(), 1);

    // Check the exact groups
    auto& baseManager = merger->getBaseRoot()->getSelectionGroupManager();

    auto firstGroup = baseManager.getSelectionGroup(brush7Groups[0]);
    EXPECT_TRUE(groupContains(firstGroup, brush7));
    EXPECT_FALSE(groupContains(firstGroup, brush17));
    EXPECT_FALSE(groupContains(firstGroup, funcStatic7));

    auto secondGroup = baseManager.getSelectionGroup(brush7Groups[1]);
    EXPECT_TRUE(groupContains(secondGroup, brush7));
    EXPECT_TRUE(groupContains(secondGroup, brush17));
    EXPECT_FALSE(groupContains(secondGroup, funcStatic7));

    auto thirdGroup = baseManager.getSelectionGroup(brush7Groups[2]);
    EXPECT_TRUE(groupContains(thirdGroup, brush7));
    EXPECT_TRUE(groupContains(thirdGroup, brush17));
    EXPECT_TRUE(groupContains(thirdGroup, funcStatic7));
    
    // Run another merger, it shouldn't find any actions to take
    merger = std::make_unique<SelectionGroupMerger>(merger->getSourceRoot(), merger->getBaseRoot());
    merger->adjustBaseGroups();
    EXPECT_TRUE(merger->getChangeLog().empty());
}

// Changed map introduces light_2 and expandable1
// Groups: [[light_2+expandable1] + [light_1+expandable]]
TEST_F(SelectionGroupMergeTest, NewEntitiesWithGroups)
{
    auto merger = setupGroupMerger("maps/merging_groups_5.mapx", "maps/merging_groups_1.mapx");

    auto light_1 = algorithm::getEntityByName(merger->getBaseRoot(), "light_1");
    auto light_2 = algorithm::getEntityByName(merger->getBaseRoot(), "light_2");
    auto expandable = algorithm::getEntityByName(merger->getBaseRoot(), "expandable");
    auto expandable1 = algorithm::getEntityByName(merger->getBaseRoot(), "expandable1");

    EXPECT_EQ(std::dynamic_pointer_cast<IGroupSelectable>(light_1)->getGroupIds().size(), 1);
    EXPECT_EQ(std::dynamic_pointer_cast<IGroupSelectable>(expandable)->getGroupIds().size(), 1);

    // Groups of the new nodes haven't been imported yet
    EXPECT_EQ(std::dynamic_pointer_cast<IGroupSelectable>(light_2)->getGroupIds().size(), 0);
    EXPECT_EQ(std::dynamic_pointer_cast<IGroupSelectable>(expandable1)->getGroupIds().size(), 0);

    merger->adjustBaseGroups();

    // 2 new groups in this map
    EXPECT_EQ(changeCountByType(merger->getChangeLog(), SelectionGroupMerger::Change::Type::BaseGroupCreated), 2);
    EXPECT_EQ(changeCountByType(merger->getChangeLog(), SelectionGroupMerger::Change::Type::BaseGroupRemoved), 0);

    // Check the new group membership counts
    auto light1Groups = std::dynamic_pointer_cast<IGroupSelectable>(light_1)->getGroupIds();
    auto light2Groups = std::dynamic_pointer_cast<IGroupSelectable>(light_2)->getGroupIds();
    auto expandableGroups = std::dynamic_pointer_cast<IGroupSelectable>(expandable)->getGroupIds();
    auto expandable1Groups = std::dynamic_pointer_cast<IGroupSelectable>(expandable1)->getGroupIds();

    EXPECT_EQ(light1Groups.size(), 2);
    EXPECT_EQ(light2Groups.size(), 2);
    EXPECT_EQ(expandableGroups.size(), 2);
    EXPECT_EQ(expandable1Groups.size(), 2);

    // Check the exact groups of light_2
    auto& baseManager = merger->getBaseRoot()->getSelectionGroupManager();

    auto firstGroup = baseManager.getSelectionGroup(light2Groups[0]);
    EXPECT_TRUE(groupContains(firstGroup, light_2));
    EXPECT_TRUE(groupContains(firstGroup, expandable1));
    EXPECT_FALSE(groupContains(firstGroup, light_1));
    EXPECT_FALSE(groupContains(firstGroup, expandable));

    auto secondGroup = baseManager.getSelectionGroup(light2Groups[1]);
    EXPECT_TRUE(groupContains(secondGroup, light_1));
    EXPECT_TRUE(groupContains(secondGroup, expandable));
    EXPECT_TRUE(groupContains(secondGroup, light_2));
    EXPECT_TRUE(groupContains(secondGroup, expandable1));

    // Check the exact groups of light_1
    firstGroup = baseManager.getSelectionGroup(light1Groups[0]);
    EXPECT_TRUE(groupContains(firstGroup, light_1));
    EXPECT_TRUE(groupContains(firstGroup, expandable));
    EXPECT_FALSE(groupContains(firstGroup, light_2));
    EXPECT_FALSE(groupContains(firstGroup, expandable1));

    secondGroup = baseManager.getSelectionGroup(light1Groups[1]);
    EXPECT_TRUE(groupContains(secondGroup, light_1));
    EXPECT_TRUE(groupContains(secondGroup, expandable));
    EXPECT_TRUE(groupContains(secondGroup, light_2));
    EXPECT_TRUE(groupContains(secondGroup, expandable1));

    // Run another merger, it shouldn't find any actions to take
    merger = std::make_unique<SelectionGroupMerger>(merger->getSourceRoot(), merger->getBaseRoot());
    merger->adjustBaseGroups();
    EXPECT_TRUE(merger->getChangeLog().empty());
}

// Group of [[Brush8+Brush8]+func_static_8] has been dissolved
// [Brush8+Brush8] have been deleted, but have been kept by the user during merge
// func_static_8 has been grouped with [[Brush7+Brush7]+func_static_7]
TEST_F(SelectionGroupMergeTest, BrushesKeptDuringMerge)
{
    auto originalResource = GlobalMapResourceManager().createFromPath("maps/merging_groups_1.mapx");
    EXPECT_TRUE(originalResource->load()) << "Test map not found: " << "maps/merging_groups_1.mapx";

    auto changedResource = GlobalMapResourceManager().createFromPath("maps/merging_groups_6.mapx");
    EXPECT_TRUE(changedResource->load()) << "Test map not found: " << "maps/merging_groups_6.mapx";

    auto result = GraphComparer::Compare(changedResource->getRootNode(), originalResource->getRootNode());
    auto operation = MergeOperation::CreateFromComparisonResult(*result);

    // Deactivate the action removing the two brushes
    std::size_t deactivationCount = 0;
    operation->foreachAction([&](const scene::merge::IMergeAction::Ptr& action)
    {
        auto brush = Node_getIBrush(action->getAffectedNode());
        
        if (brush && brush->hasShader("textures/numbers/8"))
        {
            action->deactivate();
            deactivationCount++;
        }
    });
    EXPECT_EQ(deactivationCount, 2);

    operation->setMergeSelectionGroups(false); // we do this manually
    operation->applyActions();

    auto merger = std::make_unique<SelectionGroupMerger>(result->getSourceRootNode(), result->getBaseRootNode());

    auto func_static_7 = algorithm::getEntityByName(merger->getBaseRoot(), "func_static_7");
    auto func_static_8 = algorithm::getEntityByName(merger->getBaseRoot(), "func_static_8");
    auto brush7 = algorithm::findFirstBrushWithMaterial(algorithm::findWorldspawn(merger->getBaseRoot()), "textures/numbers/7");
    auto brush8 = algorithm::findFirstBrushWithMaterial(algorithm::findWorldspawn(merger->getBaseRoot()), "textures/numbers/8");

    EXPECT_EQ(std::dynamic_pointer_cast<IGroupSelectable>(brush7)->getGroupIds().size(), 2);
    EXPECT_EQ(std::dynamic_pointer_cast<IGroupSelectable>(brush8)->getGroupIds().size(), 2);
    EXPECT_EQ(std::dynamic_pointer_cast<IGroupSelectable>(func_static_7)->getGroupIds().size(), 1);
    EXPECT_EQ(std::dynamic_pointer_cast<IGroupSelectable>(func_static_8)->getGroupIds().size(), 1);

    merger->adjustBaseGroups();

    // 1 added group
    EXPECT_EQ(changeCountByType(merger->getChangeLog(), SelectionGroupMerger::Change::Type::BaseGroupCreated), 1);
    EXPECT_EQ(changeCountByType(merger->getChangeLog(), SelectionGroupMerger::Change::Type::BaseGroupRemoved), 0);

    // Check the new group membership counts
    auto funcStatic7Groups = std::dynamic_pointer_cast<IGroupSelectable>(func_static_7)->getGroupIds();
    auto funcStatic8Groups = std::dynamic_pointer_cast<IGroupSelectable>(func_static_8)->getGroupIds();
    auto brush7Groups = std::dynamic_pointer_cast<IGroupSelectable>(brush7)->getGroupIds();
    auto brush8Groups = std::dynamic_pointer_cast<IGroupSelectable>(brush8)->getGroupIds();

    EXPECT_EQ(funcStatic7Groups.size(), 2); // has been grouped with func_static_8 (had one group before)
    EXPECT_EQ(funcStatic8Groups.size(), 1); // has been grouped with func_static_7
    EXPECT_EQ(brush7Groups.size(), 3); // one additional group with func_static_8
    // The 2 groups brush8 was a member of has been been merged down to 1, so the count is 1
    EXPECT_EQ(brush8Groups.size(), 1); // one group remaining, with the second brush8.

    auto& baseManager = merger->getBaseRoot()->getSelectionGroupManager();

    // Check the exact groups of func_static_7
    auto firstGroup = baseManager.getSelectionGroup(funcStatic7Groups[0]);
    EXPECT_TRUE(groupContains(firstGroup, func_static_7));
    EXPECT_TRUE(groupContains(firstGroup, brush7));
    EXPECT_FALSE(groupContains(firstGroup, brush8));
    EXPECT_FALSE(groupContains(firstGroup, func_static_8));

    auto secondGroup = baseManager.getSelectionGroup(funcStatic7Groups[1]);
    EXPECT_TRUE(groupContains(secondGroup, func_static_7));
    EXPECT_TRUE(groupContains(secondGroup, brush7));
    EXPECT_TRUE(groupContains(secondGroup, func_static_8));
    EXPECT_FALSE(groupContains(secondGroup, brush8));

    // Check the exact groups of func_static_8
    firstGroup = baseManager.getSelectionGroup(funcStatic8Groups[0]);
    EXPECT_TRUE(groupContains(firstGroup, func_static_8));
    EXPECT_TRUE(groupContains(firstGroup, func_static_7));
    EXPECT_TRUE(groupContains(firstGroup, brush7));
    EXPECT_FALSE(groupContains(firstGroup, brush8));

    // Check the exact groups of brush "8"
    firstGroup = baseManager.getSelectionGroup(brush8Groups[0]);
    EXPECT_TRUE(groupContains(firstGroup, brush8));
    EXPECT_FALSE(groupContains(firstGroup, brush7));
    EXPECT_FALSE(groupContains(firstGroup, func_static_7));
    EXPECT_FALSE(groupContains(firstGroup, func_static_8));

    // Run another merger, it shouldn't find any actions to take
    merger = std::make_unique<SelectionGroupMerger>(merger->getSourceRoot(), merger->getBaseRoot());
    merger->adjustBaseGroups();
    EXPECT_TRUE(merger->getChangeLog().empty());
}

// Checks that setting the flag "merge selection groups" in the MergeOperation is working
TEST_F(SelectionGroupMergeTest, MergeSelectionGroupsFlagSet)
{
    auto originalResource = GlobalMapResourceManager().createFromPath("maps/merging_groups_1.mapx");
    EXPECT_TRUE(originalResource->load()) << "Test map not found: " << "maps/merging_groups_1.mapx";

    auto changedResource = GlobalMapResourceManager().createFromPath("maps/merging_groups_6.mapx");
    EXPECT_TRUE(changedResource->load()) << "Test map not found: " << "maps/merging_groups_6.mapx";

    auto result = GraphComparer::Compare(changedResource->getRootNode(), originalResource->getRootNode());
    auto operation = MergeOperation::CreateFromComparisonResult(*result);
    
    operation->setMergeSelectionGroups(true);
    operation->applyActions();

    // Set up a merger class, it should find nothing to do
    auto merger = std::make_unique<SelectionGroupMerger>(result->getSourceRootNode(), result->getBaseRootNode());
    merger->adjustBaseGroups();
    EXPECT_TRUE(merger->getChangeLog().empty());
}

TEST_F(SelectionGroupMergeTest, MergeSelectionGroupsFlagNotSet)
{
    auto originalResource = GlobalMapResourceManager().createFromPath("maps/merging_groups_1.mapx");
    EXPECT_TRUE(originalResource->load()) << "Test map not found: " << "maps/merging_groups_1.mapx";

    auto changedResource = GlobalMapResourceManager().createFromPath("maps/merging_groups_6.mapx");
    EXPECT_TRUE(changedResource->load()) << "Test map not found: " << "maps/merging_groups_6.mapx";

    auto result = GraphComparer::Compare(changedResource->getRootNode(), originalResource->getRootNode());
    auto operation = MergeOperation::CreateFromComparisonResult(*result);

    operation->setMergeSelectionGroups(false);
    operation->applyActions();

    // Set up a merger class, it should do something
    auto merger = std::make_unique<SelectionGroupMerger>(result->getSourceRootNode(), result->getBaseRootNode());
    merger->adjustBaseGroups();
    EXPECT_FALSE(merger->getChangeLog().empty());
}

std::unique_ptr<LayerMerger> setupLayerMerger(const std::string& sourceMap, const std::string& baseMap)
{
    auto originalResource = GlobalMapResourceManager().createFromPath(baseMap);
    EXPECT_TRUE(originalResource->load()) << "Test map not found: " << baseMap;

    auto changedResource = GlobalMapResourceManager().createFromPath(sourceMap);
    EXPECT_TRUE(changedResource->load()) << "Test map not found: " << sourceMap;

    auto result = GraphComparer::Compare(changedResource->getRootNode(), originalResource->getRootNode());
    auto operation = MergeOperation::CreateFromComparisonResult(*result);

    operation->setMergeLayers(false); // we do this manually
    operation->applyActions();

    return std::make_unique<LayerMerger>(result->getSourceRootNode(), result->getBaseRootNode());
}

// Returns true if this node is (at least) member of all the given layers
bool nodeIsMemberOfLayer(const scene::INodePtr& node, const std::set<std::string>& layerNames)
{
    auto& layerManager = node->getRootNode()->getLayerManager();
    
    std::set<std::string> nodeLayerNames;

    for (auto layerId : node->getLayers())
    {
        nodeLayerNames.emplace(layerManager.getLayerName(layerId));
    }
    
    return std::includes(nodeLayerNames.begin(), nodeLayerNames.end(), layerNames.begin(), layerNames.end());
}

inline std::size_t changeCountByType(const std::vector<LayerMerger::Change>& log,
    LayerMerger::Change::Type type)
{
    return std::count_if(log.begin(), log.end(), [=](const LayerMerger::Change& change)
    {
        return change.type == type;
    });
}

// Merge operation against the same map shouldn't detect any changes
TEST_F(LayerMergeTest, UnchangedMap)
{
    auto merger = setupLayerMerger("maps/merging_layers_1.mapx", "maps/merging_layers_1.mapx");

    merger->adjustBaseLayers();
    EXPECT_TRUE(merger->getChangeLog().empty());
}

// A new layer has been introduced with both new and existing nodes as members
// func_static_6/7/8 has been added to "New Layer"
// new_func_static, brush 0 and brush 11 have been moved to "New Layer" (all of these are new nodes)
// func_static_6/7/8 are still members of "Shared" and "6", "7" and "8", respectively.
TEST_F(LayerMergeTest, AddedLayer)
{
    auto merger = setupLayerMerger("maps/merging_layers_2.mapx", "maps/merging_layers_1.mapx");

    auto func_static_6 = algorithm::getEntityByName(merger->getBaseRoot(), "func_static_6");
    auto func_static_7 = algorithm::getEntityByName(merger->getBaseRoot(), "func_static_7");
    auto func_static_8 = algorithm::getEntityByName(merger->getBaseRoot(), "func_static_8");
    auto new_func_static = algorithm::getEntityByName(merger->getBaseRoot(), "new_func_static");
    auto brush11 = algorithm::findFirstBrushWithMaterial(algorithm::findWorldspawn(merger->getBaseRoot()), "textures/numbers/11");
    auto brush0 = algorithm::findFirstBrushWithMaterial(algorithm::findWorldspawn(merger->getBaseRoot()), "textures/numbers/0");

    EXPECT_TRUE(nodeIsMemberOfLayer(func_static_6, { "Shared", "6" }));
    EXPECT_TRUE(nodeIsMemberOfLayer(func_static_7, { "Shared", "7" }));
    EXPECT_TRUE(nodeIsMemberOfLayer(func_static_8, { "Shared", "8" }));
    EXPECT_TRUE(nodeIsMemberOfLayer(brush11, { "Default" }));
    EXPECT_TRUE(nodeIsMemberOfLayer(brush0, { "Default" }));
    EXPECT_TRUE(nodeIsMemberOfLayer(new_func_static, { "Default" }));

    EXPECT_EQ(new_func_static->getLayers().size(), 1); // only part of the active layer
    EXPECT_EQ(brush0->getLayers().size(), 1); // only part of the active layer

    merger->adjustBaseLayers();
    
    EXPECT_FALSE(merger->getChangeLog().empty());

    // 1 created layer
    EXPECT_EQ(changeCountByType(merger->getChangeLog(), LayerMerger::Change::Type::BaseLayerCreated), 1);
    EXPECT_EQ(changeCountByType(merger->getChangeLog(), LayerMerger::Change::Type::BaseLayerRemoved), 0);

    // The "New Layer" must exist now
    EXPECT_NE(merger->getBaseRoot()->getLayerManager().getLayerID("New Layer"), -1);

    EXPECT_TRUE(nodeIsMemberOfLayer(func_static_6, { "Shared", "6", "New Layer" }));
    EXPECT_TRUE(nodeIsMemberOfLayer(func_static_7, { "Shared", "7", "New Layer" }));
    EXPECT_TRUE(nodeIsMemberOfLayer(func_static_8, { "Shared", "8", "New Layer" }));
    EXPECT_TRUE(nodeIsMemberOfLayer(brush11, { "New Layer" }));
    EXPECT_TRUE(nodeIsMemberOfLayer(brush0, { "New Layer" }));
    EXPECT_TRUE(nodeIsMemberOfLayer(new_func_static, { "New Layer" }));

    EXPECT_EQ(new_func_static->getLayers().size(), 1); // only part of "New Layer"
    EXPECT_EQ(brush0->getLayers().size(), 1); // only part of "New Layer"
    EXPECT_EQ(brush11->getLayers().size(), 1); // only part of "New Layer"

    // Finally run another merger across the scene, it shouldn't find anything to do
    merger = std::make_unique<LayerMerger>(merger->getSourceRoot(), merger->getBaseRoot());
    merger->adjustBaseLayers();
    EXPECT_TRUE(merger->getChangeLog().empty());
}

// The layer "8" has been removed from the changed map, the brushes with texture "8" now are part of layer "Shared" only
TEST_F(LayerMergeTest, RemovedLayer)
{
    auto merger = setupLayerMerger("maps/merging_layers_3.mapx", "maps/merging_layers_1.mapx");

    auto func_static_8 = algorithm::getEntityByName(merger->getBaseRoot(), "func_static_8");
    auto brush8 = algorithm::findFirstBrushWithMaterial(algorithm::findWorldspawn(merger->getBaseRoot()), "textures/numbers/8");

    EXPECT_TRUE(nodeIsMemberOfLayer(func_static_8, { "Shared", "8" }));
    EXPECT_TRUE(nodeIsMemberOfLayer(brush8, { "Shared", "8" }));

    EXPECT_EQ(func_static_8->getLayers().size(), 2); // only these two layers
    EXPECT_EQ(brush8->getLayers().size(), 2); // only these two layers

    merger->adjustBaseLayers();

    EXPECT_FALSE(merger->getChangeLog().empty());

    // 1 removed layer
    EXPECT_EQ(changeCountByType(merger->getChangeLog(), LayerMerger::Change::Type::BaseLayerCreated), 0);
    EXPECT_EQ(changeCountByType(merger->getChangeLog(), LayerMerger::Change::Type::BaseLayerRemoved), 1);

    // The "8" must be gone now
    EXPECT_EQ(merger->getBaseRoot()->getLayerManager().getLayerID("8"), -1);

    EXPECT_TRUE(nodeIsMemberOfLayer(func_static_8, { "Shared" }));
    EXPECT_TRUE(nodeIsMemberOfLayer(brush8, { "Shared" }));

    EXPECT_EQ(func_static_8->getLayers().size(), 1); // only part of "Shared"
    EXPECT_EQ(brush8->getLayers().size(), 1); // only part of "Shared"

    // Finally run another merger across the scene, it shouldn't find anything to do
    merger = std::make_unique<LayerMerger>(merger->getSourceRoot(), merger->getBaseRoot());
    merger->adjustBaseLayers();
    EXPECT_TRUE(merger->getChangeLog().empty());
}

// Brushes with texture "8" and the corresponding layer "8" have been removed from the changed map
// The user chose to keep the "8" brushes, and that's why the layer "8" should be preserved too.
TEST_F(LayerMergeTest, KeptNodesInRemovedLayer)
{
    auto originalResource = GlobalMapResourceManager().createFromPath("maps/merging_layers_1.mapx");
    EXPECT_TRUE(originalResource->load()) << "Test map not found: " << "maps/merging_layers_1.mapx";

    auto changedResource = GlobalMapResourceManager().createFromPath("maps/merging_layers_4.mapx");
    EXPECT_TRUE(changedResource->load()) << "Test map not found: " << "maps/merging_layers_4.mapx";

    auto result = GraphComparer::Compare(changedResource->getRootNode(), originalResource->getRootNode());
    auto operation = MergeOperation::CreateFromComparisonResult(*result);

    // Deactivate the action removing the two "8" brushes
    std::size_t deactivationCount = 0;
    operation->foreachAction([&](const scene::merge::IMergeAction::Ptr& action)
    {
        auto brush = Node_getIBrush(action->getAffectedNode());

        if (brush && brush->hasShader("textures/numbers/8"))
        {
            action->deactivate();
            deactivationCount++;
        }
    });
    EXPECT_EQ(deactivationCount, 2);

    operation->setMergeLayers(false); // we do this manually
    operation->applyActions();

    auto merger = std::make_unique<LayerMerger>(result->getSourceRootNode(), result->getBaseRootNode());

    auto func_static_8 = algorithm::getEntityByName(merger->getBaseRoot(), "func_static_8");
    auto brush8 = algorithm::findFirstBrushWithMaterial(algorithm::findWorldspawn(merger->getBaseRoot()), "textures/numbers/8");

    EXPECT_FALSE(func_static_8); // func_static_8 is gone
    EXPECT_TRUE(nodeIsMemberOfLayer(brush8, { "Shared", "8" }));

    EXPECT_EQ(brush8->getLayers().size(), 2); // only these two layers

    merger->adjustBaseLayers();

    // We expect no changes, since nothing else apart of the two brushes has changed
    // The presence of the "8" brushes preserve the "8" layer, and therefore no change is registered
    EXPECT_TRUE(merger->getChangeLog().empty());

    // No removed layers
    EXPECT_EQ(changeCountByType(merger->getChangeLog(), LayerMerger::Change::Type::BaseLayerCreated), 0);
    EXPECT_EQ(changeCountByType(merger->getChangeLog(), LayerMerger::Change::Type::BaseLayerRemoved), 0);

    // The "8" must still be there
    EXPECT_NE(merger->getBaseRoot()->getLayerManager().getLayerID("8"), -1);

    // The 8 brush must be part of this layer, and the "Shared" one too
    EXPECT_TRUE(nodeIsMemberOfLayer(brush8, { "Shared", "8" }));
    EXPECT_EQ(brush8->getLayers().size(), 2); // still part of "8" and "Shared"
}

// Layer "8" has been renamed to "8 renamed"
// func_static_8 has been removed from "8 renamed", brush 18 has been added
TEST_F(LayerMergeTest, LayerRenamedAndModified)
{
    auto merger = setupLayerMerger("maps/merging_layers_5.mapx", "maps/merging_layers_1.mapx");

    auto func_static_8 = algorithm::getEntityByName(merger->getBaseRoot(), "func_static_8");
    auto brush8 = algorithm::findFirstBrushWithMaterial(algorithm::findWorldspawn(merger->getBaseRoot()), "textures/numbers/8");
    auto brush18 = algorithm::findFirstBrushWithMaterial(algorithm::findWorldspawn(merger->getBaseRoot()), "textures/numbers/18");

    EXPECT_TRUE(nodeIsMemberOfLayer(brush8, { "Shared", "8" }));
    EXPECT_TRUE(nodeIsMemberOfLayer(func_static_8, { "Shared", "8" }));
    EXPECT_FALSE(nodeIsMemberOfLayer(brush18, { "8" }));

    merger->adjustBaseLayers();

    EXPECT_FALSE(merger->getChangeLog().empty());

    // A rename results in 1 removal and 1 addition
    EXPECT_EQ(changeCountByType(merger->getChangeLog(), LayerMerger::Change::Type::BaseLayerCreated), 1);
    EXPECT_EQ(changeCountByType(merger->getChangeLog(), LayerMerger::Change::Type::BaseLayerRemoved), 1);

    // The "8" must be gone, "8 renamed" should be here
    EXPECT_EQ(merger->getBaseRoot()->getLayerManager().getLayerID("8"), -1);
    EXPECT_NE(merger->getBaseRoot()->getLayerManager().getLayerID("8 renamed"), -1);

    // The 8 brush must be part of this new layer, and the "Shared" one too
    EXPECT_TRUE(nodeIsMemberOfLayer(brush8, { "Shared", "8 renamed" }));
    EXPECT_EQ(brush8->getLayers().size(), 2); // only part of "8" and "Shared"

    EXPECT_TRUE(nodeIsMemberOfLayer(func_static_8, { "Shared" }));
    EXPECT_EQ(func_static_8->getLayers().size(), 1); // only part of "Shared"

    // The 18 brush must be part of this new layer
    EXPECT_TRUE(nodeIsMemberOfLayer(brush18, { "Default", "8 renamed" }));
    EXPECT_EQ(brush18->getLayers().size(), 2); // only part of "8" and "Default"

    // Finally run another merger across the scene, it shouldn't find anything to do
    merger = std::make_unique<LayerMerger>(merger->getSourceRoot(), merger->getBaseRoot());
    merger->adjustBaseLayers();
    EXPECT_TRUE(merger->getChangeLog().empty());
}

TEST_F(LayerMergeTest, MergeLayersFlagSet)
{
    auto originalResource = GlobalMapResourceManager().createFromPath("maps/merging_layers_1.mapx");
    EXPECT_TRUE(originalResource->load()) << "Test map not found: " << "maps/merging_layers_1.mapx";

    auto changedResource = GlobalMapResourceManager().createFromPath("maps/merging_layers_2.mapx");
    EXPECT_TRUE(changedResource->load()) << "Test map not found: " << "maps/merging_layers_2.mapx";

    auto result = GraphComparer::Compare(changedResource->getRootNode(), originalResource->getRootNode());
    auto operation = MergeOperation::CreateFromComparisonResult(*result);

    operation->setMergeLayers(true);
    operation->applyActions();

    // Set up a merger class, it shouldn't find anything to do
    auto merger = std::make_unique<LayerMerger>(result->getSourceRootNode(), result->getBaseRootNode());
    merger->adjustBaseLayers();
    EXPECT_TRUE(merger->getChangeLog().empty());
}

TEST_F(LayerMergeTest, MergeLayersFlagNotSet)
{
    auto originalResource = GlobalMapResourceManager().createFromPath("maps/merging_layers_1.mapx");
    EXPECT_TRUE(originalResource->load()) << "Test map not found: " << "maps/merging_layers_1.mapx";

    auto changedResource = GlobalMapResourceManager().createFromPath("maps/merging_layers_2.mapx");
    EXPECT_TRUE(changedResource->load()) << "Test map not found: " << "maps/merging_layers_2.mapx";

    auto result = GraphComparer::Compare(changedResource->getRootNode(), originalResource->getRootNode());
    auto operation = MergeOperation::CreateFromComparisonResult(*result);

    operation->setMergeLayers(false);
    operation->applyActions();

    auto new_func_static = algorithm::getEntityByName(originalResource->getRootNode(), "new_func_static");

    // New objects go into default (which is the active layer here)
    EXPECT_TRUE(nodeIsMemberOfLayer(new_func_static, { "Default" }));
    EXPECT_EQ(new_func_static->getLayers().size(), 1); // only part of the active layer

    // Set up a merger class, it should do something
    auto merger = std::make_unique<LayerMerger>(result->getSourceRootNode(), result->getBaseRootNode());
    merger->adjustBaseLayers();
    EXPECT_FALSE(merger->getChangeLog().empty());
}

// Map changelog of source and target against their base (threeway_merge_base.mapx), used in several test cases below:
// 
// Source (threeway_merge_source_1.mapx):
// - light_2 has been added
// - brush 16 added to worldspawn
// - brush_8 in func_static_8 retextured to brush 9
// - entity expandable got a new spawnarg: "source_spawnarg" => "source_value"
// - entity expandable got a spawnarg removed: "extra1"
// - entity expandable got a spawnarg modified: "extra3" => "value3_changed"
// - both brush_6 have been deleted from worldspawn
// - func_static_5 had two brush_5 added (were part of worldspawn before)
// - brush_11 got moved to the left
// 
// Target Map (threeway_merge_target_1.mapx):
// - light_3 has been added
// - brush_17 been added to worldspawn
// - brush_7 in func_static_7 retextured to brush 9
// - entity expandable got a new spawnarg: "target_spawnarg" => "target_value"
// - entity expandable got a spawnarg removed: "extra2"
// - entity expandable got a spawnarg modified: "origin" => "-100 350 32"
// - both brush_4 have been deleted from worldspawn
// - func_static_3 had two brush_3 added (were part of worldspawn before)
// - brush_12 got moved to the left

ThreeWayMergeOperation::Ptr setupThreeWayMergeOperation(const std::string& basePath, const std::string& targetPath, const std::string& sourcePath)
{
    auto baseResource = GlobalMapResourceManager().createFromPath(basePath);
    EXPECT_TRUE(baseResource->load()) << "Test map not found: " << basePath;

    auto targetResource = GlobalMapResourceManager().createFromPath(targetPath);
    EXPECT_TRUE(targetResource->load()) << "Test map not found: " << targetPath;

    auto sourceResource = GlobalMapResourceManager().createFromPath(sourcePath);
    EXPECT_TRUE(sourceResource->load()) << "Test map not found: " << sourcePath;

    return ThreeWayMergeOperation::Create(baseResource->getRootNode(), sourceResource->getRootNode(), targetResource->getRootNode());
}

// Asserts that the changes to the target map have not been reverted
void verifyTargetChanges1(const scene::IMapRootNodePtr& targetRoot)
{
    EXPECT_TRUE(algorithm::getEntityByName(targetRoot, "light_3")); // light_3 has been added
    EXPECT_TRUE(algorithm::findFirstBrushWithMaterial(algorithm::findWorldspawn(targetRoot), "textures/numbers/17")); // brush_17 been added to worldspawn
    auto func_static_7 = algorithm::getEntityByName(targetRoot, "func_static_7");
    EXPECT_TRUE(algorithm::findFirstBrushWithMaterial(func_static_7, "textures/numbers/9")); // brush_7 in func_static_7 retextured to brush 9
    EXPECT_EQ(Node_getEntity(algorithm::getEntityByName(targetRoot, "expandable"))->getKeyValue("target_spawnarg"), "target_value");
    EXPECT_EQ(Node_getEntity(algorithm::getEntityByName(targetRoot, "expandable"))->getKeyValue("extra2"), "");
    EXPECT_EQ(Node_getEntity(algorithm::getEntityByName(targetRoot, "expandable"))->getKeyValue("origin"), "-100 350 32");
    EXPECT_FALSE(algorithm::findFirstBrushWithMaterial(algorithm::findWorldspawn(targetRoot), "textures/numbers/4")); // both brush_4 have been deleted from worldspawn
    EXPECT_FALSE(algorithm::findFirstBrushWithMaterial(algorithm::findWorldspawn(targetRoot), "textures/numbers/3")); // func_static_3 had two brush_3 added (were part of worldspawn before)

    auto func_static_3 = algorithm::getEntityByName(targetRoot, "func_static_3");
    auto func_static_3_childCount = algorithm::getChildCount(func_static_3, algorithm::brushHasMaterial("textures/numbers/3"));
    EXPECT_EQ(func_static_3_childCount, 4);

    EXPECT_TRUE(algorithm::findFirstBrushWithMaterial(algorithm::findWorldspawn(targetRoot), "textures/numbers/12")); // brush_12 got moved to the left

    auto entity_to_be_moved = algorithm::getEntityByName(targetRoot, "entity_to_be_moved");
    EXPECT_EQ(algorithm::getChildCount(entity_to_be_moved), 2) << "entity_to_be_moved should have two child primitives";
    EXPECT_TRUE(algorithm::findFirstBrushWithMaterial(entity_to_be_moved, "textures/numbers/18")); // one brush with texture 18
    EXPECT_TRUE(algorithm::findFirstPatchWithMaterial(entity_to_be_moved, "textures/numbers/18")); // one patch with texture 18
}

TEST_F(ThreeWayMergeTest, NonconflictingEntityAddition)
{
    auto operation = setupThreeWayMergeOperation("maps/threeway_merge_base.mapx", "maps/threeway_merge_target_1.mapx", "maps/threeway_merge_source_1.mapx");

    verifyTargetChanges1(operation->getTargetRoot());

    // light_2 must be added to target
    auto action = findAction<AddEntityAction>(operation, [](const std::shared_ptr<AddEntityAction>& action)
    {
        auto sourceEntity = Node_getEntity(action->getSourceNodeToAdd());
        return sourceEntity->getKeyValue("name") == "light_2";
    });

    EXPECT_TRUE(action) << "No merge action found for missing entity";

    // Check pre-requisites and apply the action
    auto entityNode = algorithm::getEntityByName(operation->getTargetRoot(), "light_2");
    EXPECT_FALSE(entityNode);

    action->applyChanges();

    entityNode = algorithm::getEntityByName(operation->getTargetRoot(), "light_2");
    EXPECT_TRUE(entityNode);

    verifyTargetChanges1(operation->getTargetRoot());
}

TEST_F(ThreeWayMergeTest, NonconflictingWorldspawnPrimitiveAddition)
{
    auto operation = setupThreeWayMergeOperation("maps/threeway_merge_base.mapx", "maps/threeway_merge_target_1.mapx", "maps/threeway_merge_source_1.mapx");

    verifyTargetChanges1(operation->getTargetRoot());

    // brush_16 should be added to worldspawn
    auto action = findAction<AddChildAction>(operation, [](const std::shared_ptr<AddChildAction>& action)
    {
        auto sourceBrush = Node_getIBrush(action->getSourceNodeToAdd());
        return sourceBrush && sourceBrush->hasShader("textures/numbers/16");
    });

    EXPECT_TRUE(action) << "No merge action found for missing brush";

    // Check pre-requisites and apply the action
    EXPECT_FALSE(algorithm::findFirstBrushWithMaterial(algorithm::findWorldspawn(operation->getTargetRoot()), "textures/numbers/16")); // brush_16 not in worldspawn

    action->applyChanges();

    EXPECT_TRUE(algorithm::findFirstBrushWithMaterial(algorithm::findWorldspawn(operation->getTargetRoot()), "textures/numbers/16")); // brush_16 added to worldspawn

    verifyTargetChanges1(operation->getTargetRoot());
}

// A func_static is moved a few units, this results in a new origin spawnarg and all primitives to be removed and re-added
TEST_F(ThreeWayMergeTest, NonConflictingFuncStaticMove)
{
    auto operation = setupThreeWayMergeOperation("maps/threeway_merge_base.mapx", "maps/threeway_merge_target_1.mapx", "maps/threeway_merge_source_1.mapx");

    verifyTargetChanges1(operation->getTargetRoot());

    auto entity_to_be_moved = algorithm::getEntityByName(operation->getTargetRoot(), "entity_to_be_moved");
    EXPECT_EQ(Node_getEntity(entity_to_be_moved)->getKeyValue("origin"), "386 -192 32") << "The entity has an unexpected origin";

    // Check the removals
    auto brushRemovalCount = countActions<RemoveChildAction>(operation, [](const std::shared_ptr<RemoveChildAction>& action)
    {
        return algorithm::brushHasMaterial("textures/numbers/18")(action->getNodeToRemove());
    });
    EXPECT_EQ(brushRemovalCount, 1) << "a brush should be removed from entity_to_be_moved";

    auto patchRemovalCount = countActions<RemoveChildAction>(operation, [](const std::shared_ptr<RemoveChildAction>& action)
    {
        return algorithm::patchHasMaterial("textures/numbers/18")(action->getNodeToRemove());
    });
    EXPECT_EQ(patchRemovalCount, 1) << "a patch should be removed from entity_to_be_moved";

    // Two additions should be scheduled
    auto brushAdditionCount = countActions<AddChildAction>(operation, [&](const std::shared_ptr<AddChildAction>& action)
    {
        return algorithm::brushHasMaterial("textures/numbers/18")(action->getSourceNodeToAdd()) && action->getParent() == entity_to_be_moved;
    });
    EXPECT_EQ(brushAdditionCount, 1) << "A brush should be added to entity_to_be_moved";

    auto patchAdditionCount = countActions<AddChildAction>(operation, [&](const std::shared_ptr<AddChildAction>& action)
    {
        return algorithm::patchHasMaterial("textures/numbers/18")(action->getSourceNodeToAdd()) && action->getParent() == entity_to_be_moved;
    });
    EXPECT_EQ(patchAdditionCount, 1) << "A patch should be added to entity_to_be_moved";

    operation->applyActions();

    // Inspect the entity after the merge
    entity_to_be_moved = algorithm::getEntityByName(operation->getTargetRoot(), "entity_to_be_moved");

    EXPECT_EQ(algorithm::getChildCount(entity_to_be_moved), 2) << "entity_to_be_moved should have two child primitives after the merge";
    EXPECT_EQ(Node_getEntity(entity_to_be_moved)->getKeyValue("origin"), "386 -256 32") << "The entity should have a new origin key value";
    EXPECT_TRUE(algorithm::findFirstBrushWithMaterial(entity_to_be_moved, "textures/numbers/18")); // one brush with texture 18
    EXPECT_TRUE(algorithm::findFirstPatchWithMaterial(entity_to_be_moved, "textures/numbers/18")); // one patch with texture 18

    verifyTargetChanges1(operation->getTargetRoot());
}

TEST_F(ThreeWayMergeTest, NonconflictingWorldspawnPrimitiveRemoval)
{
    auto operation = setupThreeWayMergeOperation("maps/threeway_merge_base.mapx", "maps/threeway_merge_target_1.mapx", "maps/threeway_merge_source_1.mapx");

    verifyTargetChanges1(operation->getTargetRoot());

    // brush_6 should be removed from worldspawn
    auto action = findAction<RemoveChildAction>(operation, [](const std::shared_ptr<RemoveChildAction>& action)
    {
        return algorithm::brushHasMaterial("textures/numbers/6")(action->getNodeToRemove());
    });

    EXPECT_TRUE(action) << "No merge action found for removed brush";

    // Check pre-requisites and apply the action
    EXPECT_TRUE(algorithm::findFirstBrushWithMaterial(algorithm::findWorldspawn(operation->getTargetRoot()), "textures/numbers/6")); // brush_6 in worldspawn

    operation->applyActions();

    EXPECT_FALSE(algorithm::findFirstBrushWithMaterial(algorithm::findWorldspawn(operation->getTargetRoot()), "textures/numbers/6")); // brush_6 not in worldspawn

    verifyTargetChanges1(operation->getTargetRoot());
}

// - func_static_5 had two brush_5 added (were part of worldspawn before)
TEST_F(ThreeWayMergeTest, NonconflictingPrimitiveParentChange)
{
    auto operation = setupThreeWayMergeOperation("maps/threeway_merge_base.mapx", "maps/threeway_merge_target_1.mapx", "maps/threeway_merge_source_1.mapx");

    verifyTargetChanges1(operation->getTargetRoot());

    auto func_static_5 = algorithm::getEntityByName(operation->getTargetRoot(), "func_static_5");
    auto worldspawn = algorithm::findWorldspawn(operation->getTargetRoot());

    // brush_5 should be removed from worldspawn
    auto removeActionCount = countActions<RemoveChildAction>(operation, [](const std::shared_ptr<RemoveChildAction>& action)
    {
        return algorithm::brushHasMaterial("textures/numbers/5")(action->getNodeToRemove());
    });
    auto addActionCount = countActions<AddChildAction>(operation, [&](const std::shared_ptr<AddChildAction>& action)
    {
        return algorithm::brushHasMaterial("textures/numbers/5")(action->getSourceNodeToAdd()) && action->getParent() == func_static_5;
    });

    EXPECT_EQ(removeActionCount, 2) << "No remove action found for reparented brush";
    EXPECT_EQ(addActionCount, 2) << "No add action found for reparented brush";

    auto func_static_5_childCount = algorithm::getChildCount(func_static_5, algorithm::brushHasMaterial("textures/numbers/5"));
    auto worldspawn_childCount = algorithm::getChildCount(worldspawn, algorithm::brushHasMaterial("textures/numbers/5"));
    EXPECT_EQ(func_static_5_childCount, 2);
    EXPECT_EQ(worldspawn_childCount, 2);

    operation->applyActions();

    func_static_5_childCount = algorithm::getChildCount(func_static_5, algorithm::brushHasMaterial("textures/numbers/5"));
    worldspawn_childCount = algorithm::getChildCount(worldspawn, algorithm::brushHasMaterial("textures/numbers/5"));
    EXPECT_EQ(func_static_5_childCount, 4);
    EXPECT_EQ(worldspawn_childCount, 0);

    verifyTargetChanges1(operation->getTargetRoot());
}

TEST_F(ThreeWayMergeTest, NonconflictingFuncStaticPrimitiveAddition)
{
    auto operation = setupThreeWayMergeOperation("maps/threeway_merge_base.mapx", "maps/threeway_merge_target_1.mapx", "maps/threeway_merge_source_1.mapx");

    verifyTargetChanges1(operation->getTargetRoot());

    auto func_static_8 = algorithm::getEntityByName(operation->getTargetRoot(), "func_static_8");

    // brush_9 should be added to func_static_8
    auto action = findAction<AddChildAction>(operation, [](const std::shared_ptr<AddChildAction>& action)
    {
        return algorithm::brushHasMaterial("textures/numbers/9")(action->getSourceNodeToAdd());
    });

    EXPECT_TRUE(action) << "No merge action found for retextured brush";

    // Check pre-requisites and apply the action
    EXPECT_FALSE(algorithm::findFirstBrushWithMaterial(func_static_8, "textures/numbers/9")); // brush_9 not in func_static_8

    action->applyChanges();

    EXPECT_TRUE(algorithm::findFirstBrushWithMaterial(func_static_8, "textures/numbers/9")); // brush_9 added to func_static_8

    verifyTargetChanges1(operation->getTargetRoot());
}

// - entity expandable got a new spawnarg: "source_spawnarg" => "source_value"
// - entity expandable got a spawnarg removed: "extra1"
// - entity expandable got a spawnarg modified: "extra3" => "value3_changed"
TEST_F(ThreeWayMergeTest, NonconflictingSpawnargManipulation)
{
    auto operation = setupThreeWayMergeOperation("maps/threeway_merge_base.mapx", "maps/threeway_merge_target_1.mapx", "maps/threeway_merge_source_1.mapx");

    verifyTargetChanges1(operation->getTargetRoot());

    auto expandable = algorithm::getEntityByName(operation->getTargetRoot(), "expandable");

    // Find the spawnarg actions
    auto addAction = findAction<AddEntityKeyValueAction>(operation, [&](const std::shared_ptr<AddEntityKeyValueAction>& action)
    {
        return action->getKey() == "source_spawnarg" && action->getEntityNode() == expandable;
    });
    auto removeAction = findAction<RemoveEntityKeyValueAction>(operation, [&](const std::shared_ptr<RemoveEntityKeyValueAction>& action)
    {
        return action->getKey() == "extra1" && action->getEntityNode() == expandable;
    });
    auto modifyAction = findAction<ChangeEntityKeyValueAction>(operation, [&](const std::shared_ptr<ChangeEntityKeyValueAction>& action)
    {
        return action->getKey() == "extra3" && action->getEntityNode() == expandable;
    });

    EXPECT_TRUE(addAction) << "No merge action found for adding the spawnarg";
    EXPECT_TRUE(modifyAction) << "No merge action found for modifying the spawnarg";
    EXPECT_TRUE(removeAction) << "No merge action found for removing the spawnarg";

    // Check pre-requisites and apply the action
    EXPECT_NE(Node_getEntity(expandable)->getKeyValue("source_spawnarg"), "source_value");
    EXPECT_NE(Node_getEntity(expandable)->getKeyValue("extra1"), "");
    EXPECT_NE(Node_getEntity(expandable)->getKeyValue("extra3"), "value3_changed");

    addAction->applyChanges();
    EXPECT_EQ(Node_getEntity(expandable)->getKeyValue("source_spawnarg"), "source_value");

    removeAction->applyChanges();
    EXPECT_EQ(Node_getEntity(expandable)->getKeyValue("extra1"), "");
    
    modifyAction->applyChanges();
    EXPECT_EQ(Node_getEntity(expandable)->getKeyValue("extra3"), "value3_changed");

    verifyTargetChanges1(operation->getTargetRoot());
}

TEST_F(ThreeWayMergeTest, NonconflictingPrimitiveMove)
{
    auto operation = setupThreeWayMergeOperation("maps/threeway_merge_base.mapx", "maps/threeway_merge_target_1.mapx", "maps/threeway_merge_source_1.mapx");

    verifyTargetChanges1(operation->getTargetRoot());

    auto worldspawn = algorithm::findWorldspawn(operation->getTargetRoot());

    // one brush_11 should be removed from worldspawn
    auto removeActionCount = countActions<RemoveChildAction>(operation, [](const std::shared_ptr<RemoveChildAction>& action)
    {
        return algorithm::brushHasMaterial("textures/numbers/11")(action->getNodeToRemove());
    });
    // and the moved brush_11 should be added back
    auto addActionCount = countActions<AddChildAction>(operation, [&](const std::shared_ptr<AddChildAction>& action)
    {
        return algorithm::brushHasMaterial("textures/numbers/11")(action->getSourceNodeToAdd()) && action->getParent() == worldspawn;
    });

    EXPECT_EQ(removeActionCount, 1) << "No remove action found for moved brush";
    EXPECT_EQ(addActionCount, 1) << "No add action found for moved brush";

    auto worldspawn_childCount = algorithm::getChildCount(worldspawn, algorithm::brushHasMaterial("textures/numbers/11"));
    EXPECT_EQ(worldspawn_childCount, 1);

    operation->applyActions();

    worldspawn_childCount = algorithm::getChildCount(worldspawn, algorithm::brushHasMaterial("textures/numbers/11"));
    EXPECT_EQ(worldspawn_childCount, 1);

    verifyTargetChanges1(operation->getTargetRoot());
}

// A seemingly trivial case where the source changes and the target changes against their base match up 1:1
TEST_F(ThreeWayMergeTest, SourceAndTargetAreTheSame)
{
    // Load the same map twice as source and target
    auto operation = setupThreeWayMergeOperation("maps/threeway_merge_base.mapx", "maps/threeway_merge_target_1.mapx", "maps/threeway_merge_target_1.mapx");

    verifyTargetChanges1(operation->getTargetRoot());

    auto actionCount = countActions<IMergeAction>(operation, [&](const IMergeAction::Ptr&) { return true; });

    EXPECT_EQ(actionCount, 0);
}

// Map changelog of source and target against their base (threeway_merge_base.mapx), used in several test cases below:
// 
// Source (threeway_merge_source_2.mapx):
// - add all brush "2" to func_static_1 (a subset of the target change)
// - add all brush "4" & "5" to func_static_4
// - add two new nodes with the same name and one in between ("4", "between_4_and_5" and "5")
//   with links from n1->n2->n3->n4->nbetween_4_and_5->n5->n1. The position of n4 and n5 is different from the target.
// - light_1 got a new spawnarg _color (CONFLICT)
// - func_static_8 has been deleted (CONFLICT)
// - func_static_6 changes its origin to 224 180 32 (CONFLICT)
// - expandable entity has its spwnarg "extra3" modified to "value3_changed" (CONFLICT)
// - expandable entity has its spwnarg "extra2" removed (CONFLICT)
// 
// Target Map (threeway_merge_target_2.mapx):
// - add all brush "1" & "2" to func_static_1
// - add all brush "4" to func_static_4 (a subset of the source change)
// - added two new nodes (4 & 5) that are extend the node chain n1->n2->n3->n4->n5->n1
// - light_1 has been removed (CONFLICT)
// - func_static_8 got a new spawnarg "changed_in_target" => "value" (CONFLICT)
// - func_static_6 changes its origin to 224 200 32 (CONFLICT)
// - expandable entity has the spawnarg "extra3" removed (CONFLICT)
// - expandable entity has the spawnarg "extra2" modified to "value2_changed" (CONFLICT)

TEST_F(ThreeWayMergeTest, MergePrimitiveChangesOfSameEntity)
{
    auto operation = setupThreeWayMergeOperation("maps/threeway_merge_base.mapx", "maps/threeway_merge_target_2.mapx", "maps/threeway_merge_source_2.mapx");

    // Expected result would be that func_static_1 will not be changed since it contains
    // all changes of the source map, and more
    // func_static_4 should be changed, but only the missing "5" brushes should be added
    
    auto func_static_1 = algorithm::getEntityByName(operation->getTargetRoot(), "func_static_1");
    auto func_static_4 = algorithm::getEntityByName(operation->getTargetRoot(), "func_static_4");
    auto worldspawn = algorithm::findWorldspawn(operation->getTargetRoot());

    // brush_1 should get no actions, since they are already below func_static_1
    auto brush1ActionCount = countActions<MergeAction>(operation, [](const std::shared_ptr<MergeAction>& action)
    {
        return algorithm::brushHasMaterial("textures/numbers/1")(action->getAffectedNode());
    });
    auto brush5ActionCount = countActions<MergeAction>(operation, [](const std::shared_ptr<MergeAction>& action)
    {
        return algorithm::brushHasMaterial("textures/numbers/5")(action->getAffectedNode());
    });

    EXPECT_EQ(brush1ActionCount, 0) << "Brush 1 should not take any changes";
    EXPECT_EQ(brush5ActionCount, 4) << "Brush 5 should be 2x removed from worldspawn and 2x added to func_static_4";

    EXPECT_EQ(algorithm::getChildCount(func_static_1, algorithm::brushHasMaterial("textures/numbers/1")), 4);
    EXPECT_EQ(algorithm::getChildCount(func_static_4, algorithm::brushHasMaterial("textures/numbers/5")), 0);
    EXPECT_EQ(algorithm::getChildCount(worldspawn, algorithm::brushHasMaterial("textures/numbers/5")), 2);

    operation->applyActions();

    EXPECT_EQ(algorithm::getChildCount(func_static_1, algorithm::brushHasMaterial("textures/numbers/1")), 4); // no change here
    EXPECT_EQ(algorithm::getChildCount(func_static_4, algorithm::brushHasMaterial("textures/numbers/5")), 2); // added to func_static_4
    EXPECT_EQ(algorithm::getChildCount(worldspawn, algorithm::brushHasMaterial("textures/numbers/5")), 0); // removed from worldspawn
}

// Source:
// - add two new nodes with the same name and one in between ("4", "between_4_and_5" and "5")
//   with links from n1->n2->n3->n4->nbetween_4_and_5->n5->n1. The position of n4 and n5 is different from the target.
// Target:
// - added two new nodes (4 & 5) that are extend the node chain n1->n2->n3->n4->n5->n1
TEST_F(ThreeWayMergeTest, MergeEntityNameCollisions)
{
    auto baseResource = GlobalMapResourceManager().createFromPath("maps/threeway_merge_base.mapx");
    EXPECT_TRUE(baseResource->load()) << "Base map not found.";

    auto targetResource = GlobalMapResourceManager().createFromPath("maps/threeway_merge_target_2.mapx");
    EXPECT_TRUE(targetResource->load()) << "Target map not found";

    auto sourceResource = GlobalMapResourceManager().createFromPath("maps/threeway_merge_source_2.mapx");
    EXPECT_TRUE(sourceResource->load()) << "Source map not found";

    // Get the node_4 in the source scene, it will be renamed
    auto sourceNode4 = algorithm::getEntityByName(sourceResource->getRootNode(), "node_4");
    auto sourceNode5 = algorithm::getEntityByName(sourceResource->getRootNode(), "node_5");
    auto sourceNodeBetween4And5 = algorithm::getEntityByName(sourceResource->getRootNode(), "node_between_4_and_5");

    auto operation = ThreeWayMergeOperation::Create(baseResource->getRootNode(), sourceResource->getRootNode(), targetResource->getRootNode());

    // Sources node_4 and node_5 have already been renamed, get the new names
    auto newNode4Name = Node_getEntity(sourceNode4)->getKeyValue("name");
    auto newNode5Name = Node_getEntity(sourceNode5)->getKeyValue("name");
    EXPECT_NE(newNode4Name, "node_4");
    EXPECT_NE(newNode5Name, "node_5");

    EXPECT_EQ(Node_getEntity(sourceNodeBetween4And5)->getKeyValue("name"), "node_between_4_and_5"); // this on is unchanged

    // The expected result is that the three nodes added in the source have their names
    // changed to not conflict with the target map and keep their links intact after import.
    // The nodes n4 and n5 in the target should be preserved including their links.
    // The only conflict occurring here is the target spawnarg on node3, which targets "n4" in the target and "n4renamed" in the source

    // Already present in the target scene
    EXPECT_TRUE(algorithm::getEntityByName(operation->getTargetRoot(), "node_1"));
    EXPECT_TRUE(algorithm::getEntityByName(operation->getTargetRoot(), "node_2"));
    EXPECT_TRUE(algorithm::getEntityByName(operation->getTargetRoot(), "node_3"));
    EXPECT_TRUE(algorithm::getEntityByName(operation->getTargetRoot(), "node_4"));
    EXPECT_TRUE(algorithm::getEntityByName(operation->getTargetRoot(), "node_5"));
    // Not yet present in the target scene
    EXPECT_FALSE(algorithm::getEntityByName(operation->getTargetRoot(), "node_between_4_and_5"));
    EXPECT_FALSE(algorithm::getEntityByName(operation->getTargetRoot(), newNode4Name));
    EXPECT_FALSE(algorithm::getEntityByName(operation->getTargetRoot(), newNode5Name));

    // We should receive three new nodes from the source map, their names should have been changed to not conflict, e.g. node_6 and node_7
    auto numAdditions = countActions<AddEntityAction>(operation, [](const std::shared_ptr<AddEntityAction>& action) { return true; });
    EXPECT_EQ(numAdditions, 3);

    // We expect the one conflict on node_3
    auto keyValueConflict = findAction<EntityKeyValueConflictResolutionAction>(operation,
        [](const std::shared_ptr<EntityKeyValueConflictResolutionAction>& action)
    {
        return Node_getEntity(action->getConflictingSourceEntity())->getKeyValue("name") == "node_3";
    });
    EXPECT_TRUE(keyValueConflict);
    EXPECT_EQ(keyValueConflict->getConflictType(), ConflictType::SettingKeyToDifferentValue);
    EXPECT_EQ(keyValueConflict->getTargetAction()->getType(), scene::merge::ActionType::AddKeyValue);

    EXPECT_EQ(std::dynamic_pointer_cast<AddEntityKeyValueAction>(keyValueConflict->getTargetAction())->getKey(), "target0");
    EXPECT_EQ(std::dynamic_pointer_cast<AddEntityKeyValueAction>(keyValueConflict->getTargetAction())->getValue(), "node_4");

    EXPECT_EQ(keyValueConflict->getSourceAction()->getType(), scene::merge::ActionType::AddKeyValue);
    EXPECT_EQ(std::dynamic_pointer_cast<AddEntityKeyValueAction>(keyValueConflict->getSourceAction())->getKey(), "target0");
    EXPECT_EQ(std::dynamic_pointer_cast<AddEntityKeyValueAction>(keyValueConflict->getSourceAction())->getValue(), newNode4Name);

    operation->applyActions();

    // Were present before in the target scene
    EXPECT_TRUE(algorithm::getEntityByName(operation->getTargetRoot(), "node_1"));
    EXPECT_TRUE(algorithm::getEntityByName(operation->getTargetRoot(), "node_2"));
    EXPECT_TRUE(algorithm::getEntityByName(operation->getTargetRoot(), "node_3"));
    EXPECT_TRUE(algorithm::getEntityByName(operation->getTargetRoot(), "node_4"));
    EXPECT_TRUE(algorithm::getEntityByName(operation->getTargetRoot(), "node_5"));

    // Are now present in the target scene
    EXPECT_TRUE(algorithm::getEntityByName(operation->getTargetRoot(), "node_between_4_and_5"));
    EXPECT_TRUE(algorithm::getEntityByName(operation->getTargetRoot(), newNode4Name));
    EXPECT_TRUE(algorithm::getEntityByName(operation->getTargetRoot(), newNode5Name));

    // Since we didn't resolve the action accepting the source change, the target0 key should still be at "node_4"
    auto node_3 = algorithm::getEntityByName(operation->getTargetRoot(), "node_3");
    EXPECT_EQ(Node_getEntity(node_3)->getKeyValue("target0"), "node_4");

    // Actively resolve the conflict and apply the change
    keyValueConflict->setResolution(ResolutionType::ApplySourceChange);
    keyValueConflict->applyChanges();

    node_3 = algorithm::getEntityByName(operation->getTargetRoot(), "node_3");
    EXPECT_EQ(Node_getEntity(node_3)->getKeyValue("target0"), newNode4Name);
}

// The source map tries to remove an entity that has been modified in target (func_static_8)
TEST_F(ThreeWayMergeTest, RemovalOfModifiedEntity)
{
    auto operation = setupThreeWayMergeOperation("maps/threeway_merge_base.mapx", "maps/threeway_merge_target_2.mapx", "maps/threeway_merge_source_2.mapx");

    // func_static_8 is still present in the target
    EXPECT_TRUE(algorithm::getEntityByName(operation->getTargetRoot(), "func_static_8"));

    auto entityConflict = findAction<EntityConflictResolutionAction>(operation,
        [](const std::shared_ptr<EntityConflictResolutionAction>& action)
    {
        return Node_getEntity(action->getConflictingTargetEntity())->getKeyValue("name") == "func_static_8";
    });
    EXPECT_TRUE(entityConflict) << "Didn't find the conflicting with subject func_static_8";
    EXPECT_EQ(entityConflict->getConflictType(), ConflictType::RemovalOfModifiedEntity);

    operation->applyActions();

    // The entity func_static_8 is still present
    EXPECT_TRUE(algorithm::getEntityByName(operation->getTargetRoot(), "func_static_8"));

    // Now accept the change explicitly
    entityConflict->setResolution(ResolutionType::ApplySourceChange);
    entityConflict->applyChanges();

    // The entity func_static_8 has now been removed in target
    EXPECT_FALSE(algorithm::getEntityByName(operation->getTargetRoot(), "func_static_8"));
}

// The source map tries to modify a spawnarg of the removed entity light_1
TEST_F(ThreeWayMergeTest, ModificationOfRemovedEntity)
{
    auto operation = setupThreeWayMergeOperation("maps/threeway_merge_base.mapx", "maps/threeway_merge_target_2.mapx", "maps/threeway_merge_source_2.mapx");

    EXPECT_FALSE(algorithm::getEntityByName(operation->getTargetRoot(), "light_1"));

    auto entityConflict = findAction<EntityConflictResolutionAction>(operation,
        [](const std::shared_ptr<EntityConflictResolutionAction>& action)
    {
        return action->getConflictingSourceEntity() && action->getConflictingTargetEntity() == nullptr &&
            Node_getEntity(action->getConflictingSourceEntity())->getKeyValue("name") == "light_1";
    });
    EXPECT_TRUE(entityConflict) << "Didn't find the conflicting with subject light_1";
    EXPECT_EQ(entityConflict->getConflictType(), ConflictType::ModificationOfRemovedEntity);

    operation->applyActions();

    // The entity light_1 is still gone
    EXPECT_FALSE(algorithm::getEntityByName(operation->getTargetRoot(), "light_1"));

    // Now accept the change explicitly
    entityConflict->setResolution(ResolutionType::ApplySourceChange);
    entityConflict->applyChanges();

    // The entity light_1 has now been imported to target
    EXPECT_TRUE(algorithm::getEntityByName(operation->getTargetRoot(), "light_1"));
}

TEST_F(ThreeWayMergeTest, SettingKeyValueToConflictingValues)
{
    auto operation = setupThreeWayMergeOperation("maps/threeway_merge_base.mapx", "maps/threeway_merge_target_2.mapx", "maps/threeway_merge_source_2.mapx");

    auto entity = algorithm::getEntityByName(operation->getTargetRoot(), "func_static_6");
    EXPECT_EQ(Node_getEntity(entity)->getKeyValue("origin"), "224 200 32");

    auto valueConflict = findAction<EntityKeyValueConflictResolutionAction>(operation,
        [](const std::shared_ptr<EntityKeyValueConflictResolutionAction>& action)
    {
        return Node_getEntity(action->getConflictingSourceEntity())->getKeyValue("name") == "func_static_6" &&
               Node_getEntity(action->getConflictingTargetEntity())->getKeyValue("name") == "func_static_6";
    });
    EXPECT_TRUE(valueConflict) << "Didn't find the conflicting with subject func_static_6";
    EXPECT_EQ(valueConflict->getConflictType(), ConflictType::SettingKeyToDifferentValue);

    // Verify the source action
    EXPECT_EQ(valueConflict->getSourceAction()->getType(), ActionType::ChangeKeyValue);
    EXPECT_EQ(std::dynamic_pointer_cast<ChangeEntityKeyValueAction>(valueConflict->getSourceAction())->getKey(), "origin");
    EXPECT_EQ(std::dynamic_pointer_cast<ChangeEntityKeyValueAction>(valueConflict->getSourceAction())->getValue(), "224 180 32");

    // Verify the target action
    EXPECT_EQ(valueConflict->getTargetAction()->getType(), ActionType::ChangeKeyValue);
    EXPECT_EQ(std::dynamic_pointer_cast<ChangeEntityKeyValueAction>(valueConflict->getTargetAction())->getKey(), "origin");
    EXPECT_EQ(std::dynamic_pointer_cast<ChangeEntityKeyValueAction>(valueConflict->getTargetAction())->getValue(), "224 200 32");

    operation->applyActions();

    // The key value is still the same
    EXPECT_EQ(Node_getEntity(entity)->getKeyValue("origin"), "224 200 32");

    // Now accept the change explicitly
    valueConflict->setResolution(ResolutionType::ApplySourceChange);
    valueConflict->applyChanges();

    // The changed value has now been imported
    EXPECT_EQ(Node_getEntity(entity)->getKeyValue("origin"), "224 180 32");
}

// Source: expandable entity has its spwnarg "extra3" modified to "value3_changed"
// Target: expandable entity has the spawnarg "extra3" removed
TEST_F(ThreeWayMergeTest, ModificationOfRemovedKeyValue)
{
    auto operation = setupThreeWayMergeOperation("maps/threeway_merge_base.mapx", "maps/threeway_merge_target_2.mapx", "maps/threeway_merge_source_2.mapx");

    auto entity = algorithm::getEntityByName(operation->getTargetRoot(), "expandable");
    EXPECT_EQ(Node_getEntity(entity)->getKeyValue("extra3"), "");

    auto valueConflict = findAction<EntityKeyValueConflictResolutionAction>(operation,
        [](const std::shared_ptr<EntityKeyValueConflictResolutionAction>& action)
    {
        return action->getConflictType() == ConflictType::ModificationOfRemovedKeyValue &&
            Node_getEntity(action->getConflictingSourceEntity())->getKeyValue("name") == "expandable" &&
            Node_getEntity(action->getConflictingTargetEntity())->getKeyValue("name") == "expandable";
    });
    EXPECT_TRUE(valueConflict) << "Didn't find the conflicting with subject expandable";
    EXPECT_EQ(valueConflict->getConflictType(), ConflictType::ModificationOfRemovedKeyValue);

    // Verify the source action
    EXPECT_EQ(valueConflict->getSourceAction()->getType(), ActionType::ChangeKeyValue);
    EXPECT_EQ(std::dynamic_pointer_cast<ChangeEntityKeyValueAction>(valueConflict->getSourceAction())->getKey(), "extra3");
    EXPECT_EQ(std::dynamic_pointer_cast<ChangeEntityKeyValueAction>(valueConflict->getSourceAction())->getValue(), "value3_changed");

    // Verify the target action
    EXPECT_EQ(valueConflict->getTargetAction()->getType(), ActionType::RemoveKeyValue);
    EXPECT_EQ(std::dynamic_pointer_cast<RemoveEntityKeyValueAction>(valueConflict->getTargetAction())->getKey(), "extra3");
    EXPECT_EQ(std::dynamic_pointer_cast<RemoveEntityKeyValueAction>(valueConflict->getTargetAction())->getValue(), "");

    operation->applyActions();

    // The key value is still gone
    EXPECT_EQ(Node_getEntity(entity)->getKeyValue("extra3"), "");

    // Now accept the change explicitly
    valueConflict->setResolution(ResolutionType::ApplySourceChange);
    valueConflict->applyChanges();

    // The changed value has now been imported
    EXPECT_EQ(Node_getEntity(entity)->getKeyValue("extra3"), "value3_changed");
}

// Source: expandable entity has its spwnarg "extra2" removed
// Target: expandable entity has the spawnarg "extra2" modified to "value2_changed"
TEST_F(ThreeWayMergeTest, RemovalOfModifiedKeyValue)
{
    auto operation = setupThreeWayMergeOperation("maps/threeway_merge_base.mapx", "maps/threeway_merge_target_2.mapx", "maps/threeway_merge_source_2.mapx");

    auto entity = algorithm::getEntityByName(operation->getTargetRoot(), "expandable");
    EXPECT_EQ(Node_getEntity(entity)->getKeyValue("extra2"), "value2_changed");

    auto valueConflict = findAction<EntityKeyValueConflictResolutionAction>(operation,
        [](const std::shared_ptr<EntityKeyValueConflictResolutionAction>& action)
    {
        return action->getConflictType() == ConflictType::RemovalOfModifiedKeyValue &&
            Node_getEntity(action->getConflictingSourceEntity())->getKeyValue("name") == "expandable" &&
            Node_getEntity(action->getConflictingTargetEntity())->getKeyValue("name") == "expandable";
    });
    EXPECT_TRUE(valueConflict) << "Didn't find the conflicting with subject expandable";
    EXPECT_EQ(valueConflict->getConflictType(), ConflictType::RemovalOfModifiedKeyValue);

    // Verify the source action
    EXPECT_EQ(valueConflict->getSourceAction()->getType(), ActionType::RemoveKeyValue);
    EXPECT_EQ(std::dynamic_pointer_cast<RemoveEntityKeyValueAction>(valueConflict->getSourceAction())->getKey(), "extra2");
    EXPECT_EQ(std::dynamic_pointer_cast<RemoveEntityKeyValueAction>(valueConflict->getSourceAction())->getValue(), "");

    // Verify the target action
    EXPECT_EQ(valueConflict->getTargetAction()->getType(), ActionType::ChangeKeyValue);
    EXPECT_EQ(std::dynamic_pointer_cast<ChangeEntityKeyValueAction>(valueConflict->getTargetAction())->getKey(), "extra2");
    EXPECT_EQ(std::dynamic_pointer_cast<ChangeEntityKeyValueAction>(valueConflict->getTargetAction())->getValue(), "value2_changed");

    operation->applyActions();

    // The key value is still the same
    EXPECT_EQ(Node_getEntity(entity)->getKeyValue("extra2"), "value2_changed");

    // Now accept the change explicitly
    valueConflict->setResolution(ResolutionType::ApplySourceChange);
    valueConflict->applyChanges();

    // The changed value has now been removed
    EXPECT_EQ(Node_getEntity(entity)->getKeyValue("extra2"), "");
}

inline std::unique_ptr<ThreeWaySelectionGroupMerger> setupThreeWayGroupMerger(const std::string& baseMap,
    const std::string& sourceMap, const std::string& targetMap)
{
    auto baseResource = GlobalMapResourceManager().createFromPath(baseMap);
    EXPECT_TRUE(baseResource->load()) << "Test map not found: " << baseMap;

    auto changedResource = GlobalMapResourceManager().createFromPath(sourceMap);
    EXPECT_TRUE(changedResource->load()) << "Test map not found: " << sourceMap;

    auto targetResource = GlobalMapResourceManager().createFromPath(targetMap);
    EXPECT_TRUE(targetResource->load()) << "Test map not found: " << targetMap;

    auto operation = ThreeWayMergeOperation::Create(baseResource->getRootNode(), changedResource->getRootNode(), targetResource->getRootNode());
    operation->setMergeSelectionGroups(false); // we do this manually
    operation->applyActions();

    return std::make_unique<ThreeWaySelectionGroupMerger>(baseResource->getRootNode(), changedResource->getRootNode(), targetResource->getRootNode());
}

inline std::size_t changeCountByType(const std::vector<ThreeWaySelectionGroupMerger::Change>& log,
    ThreeWaySelectionGroupMerger::Change::Type type)
{
    return std::count_if(log.begin(), log.end(), [=](const ThreeWaySelectionGroupMerger::Change& change)
    {
        return change.type == type;
    });
}

inline bool groupContainsNodes(selection::ISelectionGroup& group, const std::vector<scene::INodePtr>& nodes)
{
    std::set<scene::INodePtr> groupMembers;
    group.foreachNode([&](const scene::INodePtr& node) { groupMembers.insert(node); });

    for (const auto& requiredNode : nodes)
    {
        if (groupMembers.count(requiredNode) != 1)
        {
            return false;
        }
    }

    return !nodes.empty();
}

// Three-Way Selection Group Merge Scenarios
// 
// Base Map Groups:
// N1-N2-N3
// [N1-N2-N3]-L1
// 11-12-13-14
// FS1-FS2
// FS3-FS4
// 1-2
// [1-2]-3
// 5-6
// 
// Target Map Changes:
// L2 deleted
// FS1-FS2 group dissolved
// Added Brushes 15 and 16
// [5-6]-15 group added
// 7-FS7 group added (same as in source)
//
// Source Map Changes:
// [[N1-N2-N3]-L1]-L2 group added
// Brush 14 removed by degeneration 11-12-13 remains
// [5-6]-4 group added
// FS3-FS4 group dissolved
// 7-FS7 group added (same as in target)

void verifyTargetScene(const scene::IMapRootNodePtr& targetRoot)
{
    // FS1 and FS2 no longer form a group
    auto func_static_1 = algorithm::getEntityByName(targetRoot, "func_static_1");
    auto func_static_2 = algorithm::getEntityByName(targetRoot, "func_static_2");

    EXPECT_EQ(std::dynamic_pointer_cast<IGroupSelectable>(func_static_1)->getGroupIds().size(), 0);
    EXPECT_EQ(std::dynamic_pointer_cast<IGroupSelectable>(func_static_2)->getGroupIds().size(), 0);

    // [5-6]-15 group added
    auto brush15 = algorithm::findFirstBrushWithMaterial(algorithm::findWorldspawn(targetRoot), "textures/numbers/15");
    auto brush5 = algorithm::findFirstBrushWithMaterial(algorithm::findWorldspawn(targetRoot), "textures/numbers/5");
    auto brush6 = algorithm::findFirstBrushWithMaterial(algorithm::findWorldspawn(targetRoot), "textures/numbers/6");

    bool foundGroup = false;

    for (auto groupId : std::dynamic_pointer_cast<IGroupSelectable>(brush15)->getGroupIds())
    {
        auto group = targetRoot->getSelectionGroupManager().getSelectionGroup(groupId);

        if (groupContainsNodes(*group, { brush15, brush5, brush6 }))
        {
            foundGroup = true;
            break;
        }
    }

    EXPECT_TRUE(foundGroup) << "Brush 15 does not form a group with brush 5 and 6";

    auto brush11 = algorithm::findFirstBrushWithMaterial(algorithm::findWorldspawn(targetRoot), "textures/numbers/11");
    auto brush12 = algorithm::findFirstBrushWithMaterial(algorithm::findWorldspawn(targetRoot), "textures/numbers/12");
    auto brush13 = algorithm::findFirstBrushWithMaterial(algorithm::findWorldspawn(targetRoot), "textures/numbers/13");

    EXPECT_EQ(std::dynamic_pointer_cast<IGroupSelectable>(brush11)->getGroupIds().size(), 1);
    EXPECT_EQ(std::dynamic_pointer_cast<IGroupSelectable>(brush12)->getGroupIds().size(), 1);
    EXPECT_EQ(std::dynamic_pointer_cast<IGroupSelectable>(brush13)->getGroupIds().size(), 1);

    auto brush11Group = targetRoot->getSelectionGroupManager().getSelectionGroup(
        std::dynamic_pointer_cast<IGroupSelectable>(brush11)->getGroupIds().front());

    EXPECT_TRUE(groupContainsNodes(*brush11Group, { brush11, brush12, brush13 }));

    // brush 7 and func_static_7 form a group
    auto brush7 = algorithm::findFirstBrushWithMaterial(algorithm::findWorldspawn(targetRoot), "textures/numbers/7");
    auto func_static_7 = algorithm::getEntityByName(targetRoot, "func_static_7");

    EXPECT_EQ(std::dynamic_pointer_cast<IGroupSelectable>(brush7)->getGroupIds().size(), 1);
    EXPECT_EQ(std::dynamic_pointer_cast<IGroupSelectable>(func_static_7)->getGroupIds().size(), 1);

    auto brush7Group = targetRoot->getSelectionGroupManager().getSelectionGroup(
        std::dynamic_pointer_cast<IGroupSelectable>(brush7)->getGroupIds().front());

    EXPECT_TRUE(groupContainsNodes(*brush7Group, { brush7, func_static_7 }));
}

TEST_F(ThreeWaySelectionGroupMergeTest, GroupRemoval)
{
    auto merger = setupThreeWayGroupMerger("maps/threeway_merge_groups_base.mapx", "maps/threeway_merge_groups_source_1.mapx", "maps/threeway_merge_groups_target_1.mapx");

    verifyTargetScene(merger->getTargetRoot());

    // FS3 and FS4 still form a group
    auto func_static_3 = algorithm::getEntityByName(merger->getTargetRoot(), "func_static_3");
    auto func_static_4 = algorithm::getEntityByName(merger->getTargetRoot(), "func_static_4");

    EXPECT_EQ(std::dynamic_pointer_cast<IGroupSelectable>(func_static_3)->getGroupIds().size(), 1);
    EXPECT_EQ(std::dynamic_pointer_cast<IGroupSelectable>(func_static_4)->getGroupIds().size(), 1);

    merger->adjustTargetGroups();

    // Target scene tries to add a group with L2 in it, but this node is no longer present
    EXPECT_FALSE(algorithm::getEntityByName(merger->getTargetRoot(), "light_2"));

    // FS3 and FS4 no longer form a group
    func_static_3 = algorithm::getEntityByName(merger->getTargetRoot(), "func_static_3");
    func_static_4 = algorithm::getEntityByName(merger->getTargetRoot(), "func_static_4");

    EXPECT_EQ(std::dynamic_pointer_cast<IGroupSelectable>(func_static_3)->getGroupIds().size(), 0);
    EXPECT_EQ(std::dynamic_pointer_cast<IGroupSelectable>(func_static_4)->getGroupIds().size(), 0);

    EXPECT_EQ(changeCountByType(merger->getChangeLog(), ThreeWaySelectionGroupMerger::Change::Type::TargetGroupRemoved), 1);

    // The rest of the target changes should still be intact
    verifyTargetScene(merger->getTargetRoot());
}

TEST_F(ThreeWaySelectionGroupMergeTest, GroupAddition)
{
    auto merger = setupThreeWayGroupMerger("maps/threeway_merge_groups_base.mapx", "maps/threeway_merge_groups_source_1.mapx", "maps/threeway_merge_groups_target_1.mapx");

    verifyTargetScene(merger->getTargetRoot());

    // Brush 4 is not part of any group yet
    auto brush4 = algorithm::findFirstBrushWithMaterial(algorithm::findWorldspawn(merger->getTargetRoot()), "textures/numbers/4");
    EXPECT_EQ(std::dynamic_pointer_cast<IGroupSelectable>(brush4)->getGroupIds().size(), 0);

    merger->adjustTargetGroups();

    // Target scene tries to add a group with L2 in it, but this node is no longer present
    EXPECT_FALSE(algorithm::getEntityByName(merger->getTargetRoot(), "light_2"));

    // Brushes 5+6 already formed a group, Brush 4 should have been added
    brush4 = algorithm::findFirstBrushWithMaterial(algorithm::findWorldspawn(merger->getTargetRoot()), "textures/numbers/4");
    auto brush5 = algorithm::findFirstBrushWithMaterial(algorithm::findWorldspawn(merger->getTargetRoot()), "textures/numbers/5");
    auto brush6 = algorithm::findFirstBrushWithMaterial(algorithm::findWorldspawn(merger->getTargetRoot()), "textures/numbers/6");
    // Brush 15 was already forming a group with 4 & 5 in the target map, this grouping should still be there
    // The groups [5+6]+4 and [5+6]+15 both are of size 3, so they should have been merged down to one group containing all 4
    auto brush15 = algorithm::findFirstBrushWithMaterial(algorithm::findWorldspawn(merger->getTargetRoot()), "textures/numbers/15");

    EXPECT_EQ(std::dynamic_pointer_cast<IGroupSelectable>(brush4)->getGroupIds().size(), 1);

    auto group = merger->getTargetRoot()->getSelectionGroupManager().getSelectionGroup(std::dynamic_pointer_cast<IGroupSelectable>(brush4)->getGroupIds().front());

    EXPECT_TRUE(groupContainsNodes(*group, { brush4, brush5, brush6, brush15 }));

    // The rest of the target changes should still be intact
    verifyTargetScene(merger->getTargetRoot());
}

// Checks that a source group which has an exact counter-part in the target map is not added as a redundant group
TEST_F(ThreeWaySelectionGroupMergeTest, RedundantGroupNotAdded)
{
    auto merger = setupThreeWayGroupMerger("maps/threeway_merge_groups_base.mapx", "maps/threeway_merge_groups_source_1.mapx", "maps/threeway_merge_groups_target_1.mapx");

    verifyTargetScene(merger->getTargetRoot());

    merger->adjustTargetGroups();

    // Make sure the func_static_7 + brush7 group is not duplicated
    auto brush7 = algorithm::findFirstBrushWithMaterial(algorithm::findWorldspawn(merger->getTargetRoot()), "textures/numbers/7");
    auto func_static_7 = algorithm::getEntityByName(merger->getTargetRoot(), "func_static_7");

    // Only one group with brush7
    EXPECT_EQ(std::dynamic_pointer_cast<IGroupSelectable>(brush7)->getGroupIds().size(), 1);
    EXPECT_EQ(std::dynamic_pointer_cast<IGroupSelectable>(func_static_7)->getGroupIds().size(), 1);

    auto brush7Group = merger->getTargetRoot()->getSelectionGroupManager().getSelectionGroup(
        std::dynamic_pointer_cast<IGroupSelectable>(brush7)->getGroupIds().front());

    EXPECT_TRUE(groupContainsNodes(*brush7Group, { brush7, func_static_7 }));

    // The target changes should still be intact
    verifyTargetScene(merger->getTargetRoot());
}

// Layer Merge Base map: merging_layers1.mapx
// 
// func_static_1 is part of layer 1
// func_static_X is part of layer X
// Shared Layer: all func_static_s, expandable entity and light_1
// Default Layer: brush 11-18, expandable entity and light_1
//
// Layer Merge Source Map: threeway_merge_layers_source_1
// --- Deletions ---
// Layers 6, 7 and 8 deleted
// --- Additions ---
// Layer NewLayer has been added (with expandable and light_1)
// Layer NewLayer2 has been added (with expandable and light_1)
// Layer NewLayer3 has been added (with expandable and light_1)
// --- Modifications ---
// Layer "1": Brush 1 removed, Brush "0" added
// Layer "2": Brush 2 removed, Brush "0" added
// Layer "3": Brush 3 removed (only removals)
// Layer "4": Brush 4 removed, Brush "0" added
// 
// Layer merge Target Map: threeway_merge_layers_target_1
// --- Deletions ---
// Layer 6 was not modified
// Layer 7 got nodes added in target
// Layer 8 got nodes removed in target
// --- Additions ---
// Layer NewLayer has been added (with expandable and brush11)
// Layer NewLayer3 has been added (with expandable and light_1) - exactly the same as in source
// --- Modifications ---
// Layer "1": no changes
// Layer "2": brush 19 (newly created added)
// Layer "3" has been deleted
// Layer "4" has been deleted

std::unique_ptr<ThreeWayLayerMerger> setupThreeWayLayerMerger(const std::string& baseMap, const std::string& sourceMap, const std::string& targetMap)
{
    auto originalResource = GlobalMapResourceManager().createFromPath(baseMap);
    EXPECT_TRUE(originalResource->load()) << "Test map not found: " << baseMap;

    auto targetResource = GlobalMapResourceManager().createFromPath(targetMap);
    EXPECT_TRUE(targetResource->load()) << "Test map not found: " << targetMap;

    auto changedResource = GlobalMapResourceManager().createFromPath(sourceMap);
    EXPECT_TRUE(changedResource->load()) << "Test map not found: " << sourceMap;

    auto operation = ThreeWayMergeOperation::Create(originalResource->getRootNode(), changedResource->getRootNode(), targetResource->getRootNode());
    operation->setMergeLayers(false); // we do this manually
    operation->applyActions();

    return std::make_unique<ThreeWayLayerMerger>(originalResource->getRootNode(), changedResource->getRootNode(), targetResource->getRootNode());
}

TEST_F(ThreeWayLayerMergeTest, LayerRemovedInSource)
{
    auto merger = setupThreeWayLayerMerger("maps/merging_layers_1.mapx", "maps/threeway_merge_layers_source_1.mapx", "maps/threeway_merge_layers_target_1.mapx");

    // Layers 6,7,8 should still be present
    auto& targetManager = merger->getTargetRoot()->getLayerManager();

    EXPECT_NE(targetManager.getLayerID("6"), -1);
    EXPECT_NE(targetManager.getLayerID("7"), -1);
    EXPECT_NE(targetManager.getLayerID("8"), -1);

    merger->adjustTargetLayers();

    // Layer 6 was not modified in target, but removed in source => should be gone
    EXPECT_EQ(targetManager.getLayerID("6"), -1);

    // Layer 7 was modified and got nodes added, should not be removed from target
    EXPECT_NE(targetManager.getLayerID("7"), -1);

    // Check if the layer membership is still intact
    auto brush17 = algorithm::findFirstBrushWithMaterial(algorithm::findWorldspawn(merger->getTargetRoot()), "textures/numbers/17");
    auto brush7 = algorithm::findFirstBrushWithMaterial(algorithm::findWorldspawn(merger->getTargetRoot()), "textures/numbers/7");
    auto func_static_7 = algorithm::getEntityByName(merger->getTargetRoot(), "func_static_7");

    EXPECT_TRUE(nodeIsMemberOfLayer(brush17, { "7" }));
    EXPECT_TRUE(nodeIsMemberOfLayer(brush7, { "7" }));
    EXPECT_TRUE(nodeIsMemberOfLayer(func_static_7, { "7" }));

    // Layer 8 was modified and got nodes removed in target (no additions) => should be gone
    EXPECT_EQ(targetManager.getLayerID("8"), -1);
}

TEST_F(ThreeWayLayerMergeTest, LayerAddedInSource)
{
    auto merger = setupThreeWayLayerMerger("maps/merging_layers_1.mapx", "maps/threeway_merge_layers_source_1.mapx", "maps/threeway_merge_layers_target_1.mapx");

    // Check the base situation in the target map
    auto& targetManager = merger->getTargetRoot()->getLayerManager();

    EXPECT_NE(targetManager.getLayerID("NewLayer"), -1);
    EXPECT_EQ(targetManager.getLayerID("NewLayer2"), -1); // doesn't exist
    EXPECT_NE(targetManager.getLayerID("NewLayer3"), -1);
    EXPECT_EQ(targetManager.getLayerID("NewLayer4"), -1); // doesn't exist

    merger->adjustTargetLayers();

    // After merging, the target map should have two new layers (NewLayer2 and NewLayer4)
    EXPECT_NE(targetManager.getLayerID("NewLayer"), -1);
    EXPECT_NE(targetManager.getLayerID("NewLayer2"), -1);
    EXPECT_NE(targetManager.getLayerID("NewLayer3"), -1);
    EXPECT_NE(targetManager.getLayerID("NewLayer4"), -1);

    // NewLayer5 should never be created, NewLayer3 might be renamed to this if the algorithm doesn't check 100% matches
    EXPECT_EQ(targetManager.getLayerID("NewLayer5"), -1);

    auto brush11 = algorithm::findFirstBrushWithMaterial(algorithm::findWorldspawn(merger->getTargetRoot()), "textures/numbers/11");
    auto expandable = algorithm::getEntityByName(merger->getTargetRoot(), "expandable");
    auto light_1 = algorithm::getEntityByName(merger->getTargetRoot(), "light_1");

    // Brush 11 is still only part of NewLayer
    EXPECT_TRUE(nodeIsMemberOfLayer(brush11, { "NewLayer" }));

    // Expandable entity is part of every created layer
    EXPECT_TRUE(nodeIsMemberOfLayer(expandable, { "NewLayer","NewLayer2", "NewLayer3", "NewLayer4" }));

    // light_1 is now part of NewLayer2, NewLayer3 and NewLayer4 (which originates from NewLayer in source)
    EXPECT_TRUE(nodeIsMemberOfLayer(light_1, { "NewLayer2", "NewLayer3", "NewLayer4" }));
}

TEST_F(ThreeWayLayerMergeTest, LayerModifiedInSource)
{
    auto merger = setupThreeWayLayerMerger("maps/merging_layers_1.mapx", "maps/threeway_merge_layers_source_1.mapx", "maps/threeway_merge_layers_target_1.mapx");

    // Check the base situation in the target map
    auto& targetManager = merger->getTargetRoot()->getLayerManager();

    auto brush0 = algorithm::findFirstBrushWithMaterial(algorithm::findWorldspawn(merger->getTargetRoot()), "textures/numbers/0");
    auto brush1 = algorithm::findFirstBrushWithMaterial(algorithm::findWorldspawn(merger->getTargetRoot()), "textures/numbers/1");
    auto brush2 = algorithm::findFirstBrushWithMaterial(algorithm::findWorldspawn(merger->getTargetRoot()), "textures/numbers/2");
    auto brush3 = algorithm::findFirstBrushWithMaterial(algorithm::findWorldspawn(merger->getTargetRoot()), "textures/numbers/3");
    auto brush4 = algorithm::findFirstBrushWithMaterial(algorithm::findWorldspawn(merger->getTargetRoot()), "textures/numbers/4");
    auto brush19 = algorithm::findFirstBrushWithMaterial(algorithm::findWorldspawn(merger->getTargetRoot()), "textures/numbers/19");
    auto func_static_1 = algorithm::getEntityByName(merger->getTargetRoot(), "func_static_1");
    auto func_static_2 = algorithm::getEntityByName(merger->getTargetRoot(), "func_static_2");
    auto func_static_3 = algorithm::getEntityByName(merger->getTargetRoot(), "func_static_3");
    auto func_static_4 = algorithm::getEntityByName(merger->getTargetRoot(), "func_static_4");

    EXPECT_EQ(targetManager.getLayerID("3"), -1); // doesn't exist
    EXPECT_EQ(targetManager.getLayerID("4"), -1); // doesn't exist

    // Starting layer config

    // Brush 0 is not part of any existing or removed layer
    EXPECT_FALSE(nodeIsMemberOfLayer(brush0, { "1" }));
    EXPECT_FALSE(nodeIsMemberOfLayer(brush0, { "2" }));
    EXPECT_FALSE(nodeIsMemberOfLayer(brush0, { "3" }));
    EXPECT_FALSE(nodeIsMemberOfLayer(brush0, { "4" }));

    // func_static_1 and _2 are still part of "1" and "2"
    EXPECT_TRUE(nodeIsMemberOfLayer(func_static_1, { "1" }));
    EXPECT_TRUE(nodeIsMemberOfLayer(func_static_2, { "2" }));
    EXPECT_FALSE(nodeIsMemberOfLayer(func_static_3, { "3" })); // layer 3 is gone
    EXPECT_FALSE(nodeIsMemberOfLayer(func_static_4, { "4" })); // layer 4 is gone

    // Brushes 1 and 2 have not been removed from layer "1" and "2"
    EXPECT_TRUE(nodeIsMemberOfLayer(brush1, { "1" }));
    EXPECT_TRUE(nodeIsMemberOfLayer(brush2, { "2" }));
    EXPECT_FALSE(nodeIsMemberOfLayer(brush3, { "3" })); // layer 3 is gone
    EXPECT_FALSE(nodeIsMemberOfLayer(brush4, { "4" })); // layer 4 is gone

    // Brush 19 has been added to layer "2"
    EXPECT_TRUE(nodeIsMemberOfLayer(brush19, { "2" }));

    merger->adjustTargetLayers();

    // After merging, the layer 4 should exist again, layer 3 should still be gone
    EXPECT_EQ(targetManager.getLayerID("3"), -1);
    EXPECT_NE(targetManager.getLayerID("4"), -1);

    // Check Layer "1": brush 0 was added, brushes 1 removed
    EXPECT_TRUE(nodeIsMemberOfLayer(brush0, { "1" }));
    EXPECT_TRUE(nodeIsMemberOfLayer(func_static_1, { "1" }));
    EXPECT_FALSE(nodeIsMemberOfLayer(brush1, { "1" }));

    // Check Layer "2": brushes "2" removed, brush "0" added, brush 19 still part of it
    EXPECT_TRUE(nodeIsMemberOfLayer(func_static_2, { "2" }));
    EXPECT_FALSE(nodeIsMemberOfLayer(brush2, { "2" }));
    EXPECT_TRUE(nodeIsMemberOfLayer(brush0, { "2" }));
    EXPECT_TRUE(nodeIsMemberOfLayer(brush19, { "2" }));

    // Layer "3": it's still gone

    // Layer "4": brush 0 and func_static_4 remains in it, as defined by the source
    EXPECT_TRUE(nodeIsMemberOfLayer(brush0, { "4" }));
    EXPECT_TRUE(nodeIsMemberOfLayer(func_static_4, { "4" }));
    EXPECT_FALSE(nodeIsMemberOfLayer(brush4, { "4" }));
}

}