Welcome to mirror list, hosted at ThFree Co, Russian Federation.

image.cc « intern « blenkernel « blender « source - git.blender.org/blender.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 75e3e22afa7a05b5cc378a5536f3d3474d31a7d5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
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
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
/* SPDX-License-Identifier: GPL-2.0-or-later
 * Copyright 2001-2002 NaN Holding BV. All rights reserved. */

/** \file
 * \ingroup bke
 */

#include <cctype>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <ctime>
#include <fcntl.h>
#ifndef WIN32
#  include <unistd.h>
#else
#  include <io.h>
#endif

#include <regex>
#include <string>

#include "BLI_array.hh"

#include "CLG_log.h"

#include "MEM_guardedalloc.h"

#include "IMB_colormanagement.h"
#include "IMB_imbuf.h"
#include "IMB_imbuf_types.h"
#include "IMB_metadata.h"
#include "IMB_moviecache.h"
#include "IMB_openexr.h"

/* Allow using deprecated functionality for .blend file I/O. */
#define DNA_DEPRECATED_ALLOW

#include "DNA_brush_types.h"
#include "DNA_camera_types.h"
#include "DNA_defaults.h"
#include "DNA_light_types.h"
#include "DNA_material_types.h"
#include "DNA_mesh_types.h"
#include "DNA_meshdata_types.h"
#include "DNA_object_types.h"
#include "DNA_packedFile_types.h"
#include "DNA_scene_types.h"
#include "DNA_sequence_types.h"
#include "DNA_simulation_types.h"
#include "DNA_world_types.h"

#include "BLI_blenlib.h"
#include "BLI_math_vector.h"
#include "BLI_mempool.h"
#include "BLI_system.h"
#include "BLI_task.h"
#include "BLI_threads.h"
#include "BLI_timecode.h" /* For stamp time-code format. */
#include "BLI_utildefines.h"

#include "BLT_translation.h"

#include "BKE_bpath.h"
#include "BKE_colortools.h"
#include "BKE_global.h"
#include "BKE_icons.h"
#include "BKE_idtype.h"
#include "BKE_image.h"
#include "BKE_image_format.h"
#include "BKE_lib_id.h"
#include "BKE_main.h"
#include "BKE_node.h"
#include "BKE_node_tree_update.h"
#include "BKE_packedFile.h"
#include "BKE_report.h"
#include "BKE_scene.h"
#include "BKE_workspace.h"

#include "BLF_api.h"

#include "PIL_time.h"

#include "RE_pipeline.h"

#include "SEQ_utils.h" /* SEQ_get_topmost_sequence() */

#include "GPU_material.h"
#include "GPU_texture.h"

#include "BLI_sys_types.h" /* for intptr_t support */

#include "DEG_depsgraph.h"
#include "DEG_depsgraph_query.h"

#include "BLO_read_write.h"

/* for image user iteration */
#include "DNA_node_types.h"
#include "DNA_screen_types.h"
#include "DNA_space_types.h"
#include "DNA_view3d_types.h"

using blender::Array;

static CLG_LogRef LOG = {"bke.image"};

static void image_init(Image *ima, short source, short type);
static void image_free_packedfiles(Image *ima);
static void copy_image_packedfiles(ListBase *lb_dst, const ListBase *lb_src);

/* -------------------------------------------------------------------- */
/** \name Image #IDTypeInfo API
 * \{ */

/** Reset runtime image fields when data-block is being initialized. */
static void image_runtime_reset(struct Image *image)
{
  memset(&image->runtime, 0, sizeof(image->runtime));
  image->runtime.cache_mutex = MEM_mallocN(sizeof(ThreadMutex), "image runtime cache_mutex");
  BLI_mutex_init(static_cast<ThreadMutex *>(image->runtime.cache_mutex));
}

/** Reset runtime image fields when data-block is being copied. */
static void image_runtime_reset_on_copy(struct Image *image)
{
  image->runtime.cache_mutex = MEM_mallocN(sizeof(ThreadMutex), "image runtime cache_mutex");
  BLI_mutex_init(static_cast<ThreadMutex *>(image->runtime.cache_mutex));

  image->runtime.partial_update_register = nullptr;
  image->runtime.partial_update_user = nullptr;
}

static void image_runtime_free_data(struct Image *image)
{
  BLI_mutex_end(static_cast<ThreadMutex *>(image->runtime.cache_mutex));
  MEM_freeN(image->runtime.cache_mutex);
  image->runtime.cache_mutex = nullptr;

  if (image->runtime.partial_update_user != nullptr) {
    BKE_image_partial_update_free(image->runtime.partial_update_user);
    image->runtime.partial_update_user = nullptr;
  }
  BKE_image_partial_update_register_free(image);
}

static void image_init_data(ID *id)
{
  Image *image = (Image *)id;

  if (image != nullptr) {
    image_init(image, IMA_SRC_GENERATED, IMA_TYPE_UV_TEST);
  }
}

static void image_copy_data(Main * /*bmain*/, ID *id_dst, const ID *id_src, const int flag)
{
  Image *image_dst = (Image *)id_dst;
  const Image *image_src = (const Image *)id_src;

  BKE_color_managed_colorspace_settings_copy(&image_dst->colorspace_settings,
                                             &image_src->colorspace_settings);

  copy_image_packedfiles(&image_dst->packedfiles, &image_src->packedfiles);

  image_dst->stereo3d_format = static_cast<Stereo3dFormat *>(
      MEM_dupallocN(image_src->stereo3d_format));
  BLI_duplicatelist(&image_dst->views, &image_src->views);

  /* Cleanup stuff that cannot be copied. */
  image_dst->cache = nullptr;
  image_dst->rr = nullptr;

  BLI_duplicatelist(&image_dst->renderslots, &image_src->renderslots);
  LISTBASE_FOREACH (RenderSlot *, slot, &image_dst->renderslots) {
    slot->render = nullptr;
  }

  BLI_listbase_clear(&image_dst->anims);

  BLI_duplicatelist(&image_dst->tiles, &image_src->tiles);

  for (int eye = 0; eye < 2; eye++) {
    for (int i = 0; i < TEXTARGET_COUNT; i++) {
      image_dst->gputexture[i][eye] = nullptr;
    }
  }

  if ((flag & LIB_ID_COPY_NO_PREVIEW) == 0) {
    BKE_previewimg_id_copy(&image_dst->id, &image_src->id);
  }
  else {
    image_dst->preview = nullptr;
  }

  image_runtime_reset_on_copy(image_dst);
}

static void image_free_data(ID *id)
{
  Image *image = (Image *)id;

  /* Also frees animations (#Image.anims list). */
  BKE_image_free_buffers(image);

  image_free_packedfiles(image);

  LISTBASE_FOREACH (RenderSlot *, slot, &image->renderslots) {
    if (slot->render) {
      RE_FreeRenderResult(slot->render);
      slot->render = nullptr;
    }
  }
  BLI_freelistN(&image->renderslots);

  BKE_image_free_views(image);
  MEM_SAFE_FREE(image->stereo3d_format);

  BKE_icon_id_delete(&image->id);
  BKE_previewimg_free(&image->preview);

  BLI_freelistN(&image->tiles);

  image_runtime_free_data(image);
}

static void image_foreach_cache(ID *id,
                                IDTypeForeachCacheFunctionCallback function_callback,
                                void *user_data)
{
  Image *image = (Image *)id;
  IDCacheKey key;
  key.id_session_uuid = id->session_uuid;
  key.offset_in_ID = offsetof(Image, cache);
  function_callback(id, &key, (void **)&image->cache, 0, user_data);

  auto gputexture_offset = [image](int target, int eye) {
    constexpr size_t base_offset = offsetof(Image, gputexture);
    struct GPUTexture **first = &image->gputexture[0][0];
    const size_t array_offset = sizeof(*first) * (&image->gputexture[target][eye] - first);
    return base_offset + array_offset;
  };

  for (int eye = 0; eye < 2; eye++) {
    for (int a = 0; a < TEXTARGET_COUNT; a++) {
      GPUTexture *texture = image->gputexture[a][eye];
      if (texture == nullptr) {
        continue;
      }
      key.offset_in_ID = gputexture_offset(a, eye);
      function_callback(id, &key, (void **)&image->gputexture[a][eye], 0, user_data);
    }
  }

  key.offset_in_ID = offsetof(Image, rr);
  function_callback(id, &key, (void **)&image->rr, 0, user_data);

  LISTBASE_FOREACH (RenderSlot *, slot, &image->renderslots) {
    key.offset_in_ID = size_t(BLI_ghashutil_strhash_p(slot->name));
    function_callback(id, &key, (void **)&slot->render, 0, user_data);
  }
}

static void image_foreach_path(ID *id, BPathForeachPathData *bpath_data)
{
  Image *ima = (Image *)id;
  const eBPathForeachFlag flag = bpath_data->flag;

  if (BKE_image_has_packedfile(ima) && (flag & BKE_BPATH_FOREACH_PATH_SKIP_PACKED) != 0) {
    return;
  }
  /* Skip empty file paths, these are typically from generated images and
   * don't make sense to add directories to until the image has been saved
   * once to give it a meaningful value. */
  /* TODO re-assess whether this behavior is desired in the new generic code context. */
  if (!ELEM(ima->source, IMA_SRC_FILE, IMA_SRC_MOVIE, IMA_SRC_SEQUENCE, IMA_SRC_TILED) ||
      ima->filepath[0] == '\0') {
    return;
  }

  /* If this is a tiled image, and we're asked to resolve the tokens in the virtual
   * filepath, use the first tile to generate a concrete path for use during processing. */
  bool result = false;
  if (ima->source == IMA_SRC_TILED && (flag & BKE_BPATH_FOREACH_PATH_RESOLVE_TOKEN) != 0) {
    char temp_path[FILE_MAX], orig_file[FILE_MAXFILE];
    BLI_strncpy(temp_path, ima->filepath, sizeof(temp_path));
    BLI_split_file_part(temp_path, orig_file, sizeof(orig_file));

    eUDIM_TILE_FORMAT tile_format;
    char *udim_pattern = BKE_image_get_tile_strformat(temp_path, &tile_format);
    BKE_image_set_filepath_from_tile_number(
        temp_path, udim_pattern, tile_format, ((ImageTile *)ima->tiles.first)->tile_number);
    MEM_SAFE_FREE(udim_pattern);

    result = BKE_bpath_foreach_path_fixed_process(bpath_data, temp_path);
    if (result) {
      /* Put the filepath back together using the new directory and the original file name. */
      char new_dir[FILE_MAXDIR];
      BLI_split_dir_part(temp_path, new_dir, sizeof(new_dir));
      BLI_path_join(ima->filepath, sizeof(ima->filepath), new_dir, orig_file);
    }
  }
  else {
    result = BKE_bpath_foreach_path_fixed_process(bpath_data, ima->filepath);
  }

  if (result) {
    if (flag & BKE_BPATH_FOREACH_PATH_RELOAD_EDITED) {
      if (!BKE_image_has_packedfile(ima) &&
          /* Image may have been painted onto (and not saved, T44543). */
          !BKE_image_is_dirty(ima)) {
        BKE_image_signal(bpath_data->bmain, ima, nullptr, IMA_SIGNAL_RELOAD);
      }
    }
  }
}

static void image_blend_write(BlendWriter *writer, ID *id, const void *id_address)
{
  Image *ima = (Image *)id;
  const bool is_undo = BLO_write_is_undo(writer);

  /* Clear all data that isn't read to reduce false detection of changed image during memfile undo.
   */
  ima->lastused = 0;
  ima->cache = nullptr;
  ima->gpuflag = 0;
  BLI_listbase_clear(&ima->anims);
  ima->runtime.partial_update_register = nullptr;
  ima->runtime.partial_update_user = nullptr;
  for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 2; j++) {
      ima->gputexture[i][j] = nullptr;
    }
  }

  ImagePackedFile *imapf;

  BLI_assert(ima->packedfile == nullptr);
  if (!is_undo) {
    /* Do not store packed files in case this is a library override ID. */
    if (ID_IS_OVERRIDE_LIBRARY(ima)) {
      BLI_listbase_clear(&ima->packedfiles);
    }
    else {
      /* Some trickery to keep forward compatibility of packed images. */
      if (ima->packedfiles.first != nullptr) {
        imapf = static_cast<ImagePackedFile *>(ima->packedfiles.first);
        ima->packedfile = imapf->packedfile;
      }
    }
  }

  /* write LibData */
  BLO_write_id_struct(writer, Image, id_address, &ima->id);
  BKE_id_blend_write(writer, &ima->id);

  for (imapf = static_cast<ImagePackedFile *>(ima->packedfiles.first); imapf;
       imapf = imapf->next) {
    BLO_write_struct(writer, ImagePackedFile, imapf);
    BKE_packedfile_blend_write(writer, imapf->packedfile);
  }

  BKE_previewimg_blend_write(writer, ima->preview);

  LISTBASE_FOREACH (ImageView *, iv, &ima->views) {
    BLO_write_struct(writer, ImageView, iv);
  }
  BLO_write_struct(writer, Stereo3dFormat, ima->stereo3d_format);

  BLO_write_struct_list(writer, ImageTile, &ima->tiles);

  ima->packedfile = nullptr;

  BLO_write_struct_list(writer, RenderSlot, &ima->renderslots);
}

static void image_blend_read_data(BlendDataReader *reader, ID *id)
{
  Image *ima = (Image *)id;
  BLO_read_list(reader, &ima->tiles);

  BLO_read_list(reader, &(ima->renderslots));
  if (!BLO_read_data_is_undo(reader)) {
    /* We reset this last render slot index only when actually reading a file, not for undo. */
    ima->last_render_slot = ima->render_slot;
  }

  BLO_read_list(reader, &(ima->views));
  BLO_read_list(reader, &(ima->packedfiles));

  if (ima->packedfiles.first) {
    LISTBASE_FOREACH (ImagePackedFile *, imapf, &ima->packedfiles) {
      BKE_packedfile_blend_read(reader, &imapf->packedfile);
    }
    ima->packedfile = nullptr;
  }
  else {
    BKE_packedfile_blend_read(reader, &ima->packedfile);
  }

  BLI_listbase_clear(&ima->anims);
  BLO_read_data_address(reader, &ima->preview);
  BKE_previewimg_blend_read(reader, ima->preview);
  BLO_read_data_address(reader, &ima->stereo3d_format);

  ima->lastused = 0;
  ima->gpuflag = 0;

  image_runtime_reset(ima);
}

static void image_blend_read_lib(BlendLibReader * /*reader*/, ID *id)
{
  Image *ima = (Image *)id;
  /* Images have some kind of 'main' cache, when null we should also clear all others. */
  /* Needs to be done *after* cache pointers are restored (call to
   * `foreach_cache`/`blo_cache_storage_entry_restore_in_new`), easier for now to do it in
   * lib_link... */
  if (ima->cache == nullptr) {
    BKE_image_free_buffers(ima);
  }
}

constexpr IDTypeInfo get_type_info()
{
  IDTypeInfo info{};
  info.id_code = ID_IM;
  info.id_filter = FILTER_ID_IM;
  info.main_listbase_index = INDEX_ID_IM;
  info.struct_size = sizeof(Image);
  info.name = "Image";
  info.name_plural = "images";
  info.translation_context = BLT_I18NCONTEXT_ID_IMAGE;
  info.flags = IDTYPE_FLAGS_NO_ANIMDATA | IDTYPE_FLAGS_APPEND_IS_REUSABLE;
  info.asset_type_info = nullptr;

  info.init_data = image_init_data;
  info.copy_data = image_copy_data;
  info.free_data = image_free_data;
  info.make_local = nullptr;
  info.foreach_id = nullptr;
  info.foreach_cache = image_foreach_cache;
  info.foreach_path = image_foreach_path;
  info.owner_pointer_get = nullptr;

  info.blend_write = image_blend_write;
  info.blend_read_data = image_blend_read_data;
  info.blend_read_lib = image_blend_read_lib;
  info.blend_read_expand = nullptr;

  info.blend_read_undo_preserve = nullptr;

  info.lib_override_apply_post = nullptr;
  return info;
}
IDTypeInfo IDType_ID_IM = get_type_info();

/* prototypes */
static int image_num_viewfiles(Image *ima);
static ImBuf *image_load_image_file(
    Image *ima, ImageUser *iuser, int entry, int cfra, bool is_sequence);
static ImBuf *image_acquire_ibuf(Image *ima, ImageUser *iuser, void **r_lock);
static void image_update_views_format(Image *ima, ImageUser *iuser);
static void image_add_view(Image *ima, const char *viewname, const char *filepath);

/* max int, to indicate we don't store sequences in ibuf */
#define IMA_NO_INDEX 0x7FEFEFEF

/* quick lookup: supports 1 million entries, thousand passes */
#define IMA_MAKE_INDEX(entry, index) (((entry) << 10) + (index))
#define IMA_INDEX_ENTRY(index) ((index) >> 10)
#if 0
#  define IMA_INDEX_PASS(index) (index & ~1023)
#endif

/** \} */

/* -------------------------------------------------------------------- */
/** \name Image Cache
 * \{ */

struct ImageCacheKey {
  int index;
};

static uint imagecache_hashhash(const void *key_v)
{
  const ImageCacheKey *key = static_cast<const ImageCacheKey *>(key_v);
  return key->index;
}

static bool imagecache_hashcmp(const void *a_v, const void *b_v)
{
  const ImageCacheKey *a = static_cast<const ImageCacheKey *>(a_v);
  const ImageCacheKey *b = static_cast<const ImageCacheKey *>(b_v);

  return (a->index != b->index);
}

static void imagecache_keydata(void *userkey, int *framenr, int *proxy, int *render_flags)
{
  ImageCacheKey *key = static_cast<ImageCacheKey *>(userkey);

  *framenr = IMA_INDEX_ENTRY(key->index);
  *proxy = IMB_PROXY_NONE;
  *render_flags = 0;
}

static void imagecache_put(Image *image, int index, ImBuf *ibuf)
{
  ImageCacheKey key;

  if (image->cache == nullptr) {
    // char cache_name[64];
    // SNPRINTF(cache_name, "Image Datablock %s", image->id.name);

    image->cache = IMB_moviecache_create(
        "Image Datablock Cache", sizeof(ImageCacheKey), imagecache_hashhash, imagecache_hashcmp);
    IMB_moviecache_set_getdata_callback(image->cache, imagecache_keydata);
  }

  key.index = index;

  IMB_moviecache_put(image->cache, &key, ibuf);
}

static void imagecache_remove(Image *image, int index)
{
  if (image->cache == nullptr) {
    return;
  }

  ImageCacheKey key;
  key.index = index;
  IMB_moviecache_remove(image->cache, &key);
}

static struct ImBuf *imagecache_get(Image *image, int index, bool *r_is_cached_empty)
{
  if (image->cache) {
    ImageCacheKey key;
    key.index = index;
    return IMB_moviecache_get(image->cache, &key, r_is_cached_empty);
  }

  return nullptr;
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Allocate & Free, Data Managing
 * \{ */

static void image_free_cached_frames(Image *image)
{
  if (image->cache) {
    IMB_moviecache_free(image->cache);
    image->cache = nullptr;
  }
}

static void image_free_packedfiles(Image *ima)
{
  while (ima->packedfiles.last) {
    ImagePackedFile *imapf = static_cast<ImagePackedFile *>(ima->packedfiles.last);
    if (imapf->packedfile) {
      BKE_packedfile_free(imapf->packedfile);
    }
    BLI_remlink(&ima->packedfiles, imapf);
    MEM_freeN(imapf);
  }
}

void BKE_image_free_packedfiles(Image *ima)
{
  image_free_packedfiles(ima);
}

void BKE_image_free_views(Image *image)
{
  BLI_freelistN(&image->views);
}

static void image_free_anims(Image *ima)
{
  while (ima->anims.last) {
    ImageAnim *ia = static_cast<ImageAnim *>(ima->anims.last);
    if (ia->anim) {
      IMB_free_anim(ia->anim);
      ia->anim = nullptr;
    }
    BLI_remlink(&ima->anims, ia);
    MEM_freeN(ia);
  }
}

void BKE_image_free_buffers_ex(Image *ima, bool do_lock)
{
  if (do_lock) {
    BLI_mutex_lock(static_cast<ThreadMutex *>(ima->runtime.cache_mutex));
  }
  image_free_cached_frames(ima);

  image_free_anims(ima);

  if (ima->rr) {
    RE_FreeRenderResult(ima->rr);
    ima->rr = nullptr;
  }

  BKE_image_free_gputextures(ima);

  if (do_lock) {
    BLI_mutex_unlock(static_cast<ThreadMutex *>(ima->runtime.cache_mutex));
  }
}

void BKE_image_free_buffers(Image *ima)
{
  BKE_image_free_buffers_ex(ima, false);
}

void BKE_image_free_data(Image *ima)
{
  image_free_data(&ima->id);
}

static ImageTile *imagetile_alloc(int tile_number)
{
  ImageTile *tile = MEM_cnew<ImageTile>("Image Tile");
  tile->tile_number = tile_number;
  tile->gen_x = 1024;
  tile->gen_y = 1024;
  tile->gen_type = IMA_GENTYPE_GRID;
  return tile;
}

/* only image block itself */
static void image_init(Image *ima, short source, short type)
{
  BLI_assert(MEMCMP_STRUCT_AFTER_IS_ZERO(ima, id));

  MEMCPY_STRUCT_AFTER(ima, DNA_struct_default_get(Image), id);

  ima->source = source;
  ima->type = type;

  if (source == IMA_SRC_VIEWER) {
    ima->flag |= IMA_VIEW_AS_RENDER;
  }

  ImageTile *tile = imagetile_alloc(1001);
  BLI_addtail(&ima->tiles, tile);

  if (type == IMA_TYPE_R_RESULT) {
    for (int i = 0; i < 8; i++) {
      BKE_image_add_renderslot(ima, nullptr);
    }
  }

  image_runtime_reset(ima);

  BKE_color_managed_colorspace_settings_init(&ima->colorspace_settings);
  ima->stereo3d_format = MEM_cnew<Stereo3dFormat>("Image Stereo Format");
}

static Image *image_alloc(Main *bmain, const char *name, short source, short type)
{
  Image *ima;

  ima = static_cast<Image *>(BKE_libblock_alloc(bmain, ID_IM, name, 0));
  if (ima) {
    image_init(ima, source, type);
  }

  return ima;
}

/**
 * Get the ibuf from an image cache by its index and entry.
 * Local use here only.
 *
 * \returns referenced image buffer if it exists, callee is to call #IMB_freeImBuf
 * to de-reference the image buffer after it's done handling it.
 */
static ImBuf *image_get_cached_ibuf_for_index_entry(Image *ima,
                                                    int index,
                                                    int entry,
                                                    bool *r_is_cached_empty)
{
  if (index != IMA_NO_INDEX) {
    index = IMA_MAKE_INDEX(entry, index);
  }

  return imagecache_get(ima, index, r_is_cached_empty);
}

static void image_assign_ibuf(Image *ima, ImBuf *ibuf, int index, int entry)
{
  if (index != IMA_NO_INDEX) {
    index = IMA_MAKE_INDEX(entry, index);
  }

  imagecache_put(ima, index, ibuf);
}

static void image_remove_ibuf(Image *ima, int index, int entry)
{
  if (index != IMA_NO_INDEX) {
    index = IMA_MAKE_INDEX(entry, index);
  }
  imagecache_remove(ima, index);
}

static void copy_image_packedfiles(ListBase *lb_dst, const ListBase *lb_src)
{
  const ImagePackedFile *imapf_src;

  BLI_listbase_clear(lb_dst);
  for (imapf_src = static_cast<const ImagePackedFile *>(lb_src->first); imapf_src;
       imapf_src = imapf_src->next) {
    ImagePackedFile *imapf_dst = static_cast<ImagePackedFile *>(
        MEM_mallocN(sizeof(ImagePackedFile), "Image Packed Files (copy)"));

    imapf_dst->view = imapf_src->view;
    imapf_dst->tile_number = imapf_src->tile_number;
    STRNCPY(imapf_dst->filepath, imapf_src->filepath);

    if (imapf_src->packedfile) {
      imapf_dst->packedfile = BKE_packedfile_duplicate(imapf_src->packedfile);
    }

    BLI_addtail(lb_dst, imapf_dst);
  }
}

void BKE_image_merge(Main *bmain, Image *dest, Image *source)
{
  /* sanity check */
  if (dest && source && dest != source) {
    BLI_mutex_lock(static_cast<ThreadMutex *>(source->runtime.cache_mutex));
    BLI_mutex_lock(static_cast<ThreadMutex *>(dest->runtime.cache_mutex));

    if (source->cache != nullptr) {
      struct MovieCacheIter *iter;
      iter = IMB_moviecacheIter_new(source->cache);
      while (!IMB_moviecacheIter_done(iter)) {
        ImBuf *ibuf = IMB_moviecacheIter_getImBuf(iter);
        ImageCacheKey *key = static_cast<ImageCacheKey *>(IMB_moviecacheIter_getUserKey(iter));
        imagecache_put(dest, key->index, ibuf);
        IMB_moviecacheIter_step(iter);
      }
      IMB_moviecacheIter_free(iter);
    }

    BLI_mutex_unlock(static_cast<ThreadMutex *>(dest->runtime.cache_mutex));
    BLI_mutex_unlock(static_cast<ThreadMutex *>(source->runtime.cache_mutex));

    BKE_id_free(bmain, source);
  }
}

bool BKE_image_scale(Image *image, int width, int height)
{
  /* NOTE: We could be clever and scale all imbuf's
   * but since some are mipmaps its not so simple. */

  ImBuf *ibuf;
  void *lock;

  ibuf = BKE_image_acquire_ibuf(image, nullptr, &lock);

  if (ibuf) {
    IMB_scaleImBuf(ibuf, width, height);
    BKE_image_mark_dirty(image, ibuf);
  }

  BKE_image_release_ibuf(image, ibuf, lock);

  return (ibuf != nullptr);
}

bool BKE_image_has_opengl_texture(Image *ima)
{
  for (int eye = 0; eye < 2; eye++) {
    for (int i = 0; i < TEXTARGET_COUNT; i++) {
      if (ima->gputexture[i][eye] != nullptr) {
        return true;
      }
    }
  }
  return false;
}

static int image_get_tile_number_from_iuser(const Image *ima, const ImageUser *iuser)
{
  BLI_assert(ima != nullptr && ima->tiles.first);
  ImageTile *tile = static_cast<ImageTile *>(ima->tiles.first);
  return (iuser && iuser->tile) ? iuser->tile : tile->tile_number;
}

ImageTile *BKE_image_get_tile(Image *ima, int tile_number)
{
  if (ima == nullptr) {
    return nullptr;
  }

  /* Tiles 0 and 1001 are a special case and refer to the first tile, typically
   * coming from non-UDIM-aware code. */
  if (ELEM(tile_number, 0, 1001)) {
    return static_cast<ImageTile *>(ima->tiles.first);
  }

  /* Must have a tiled image and a valid tile number at this point. */
  if (ima->source != IMA_SRC_TILED || tile_number < 1001 || tile_number > IMA_UDIM_MAX) {
    return nullptr;
  }

  LISTBASE_FOREACH (ImageTile *, tile, &ima->tiles) {
    if (tile->tile_number == tile_number) {
      return tile;
    }
  }

  return nullptr;
}

ImageTile *BKE_image_get_tile_from_iuser(Image *ima, const ImageUser *iuser)
{
  return BKE_image_get_tile(ima, image_get_tile_number_from_iuser(ima, iuser));
}

int BKE_image_get_tile_from_pos(Image *ima, const float uv[2], float r_uv[2], float r_ofs[2])
{
  float local_ofs[2];
  if (r_ofs == nullptr) {
    r_ofs = local_ofs;
  }

  copy_v2_v2(r_uv, uv);
  zero_v2(r_ofs);

  if ((ima->source != IMA_SRC_TILED) || uv[0] < 0.0f || uv[1] < 0.0f || uv[0] >= 10.0f) {
    return 0;
  }

  int ix = int(uv[0]);
  int iy = int(uv[1]);
  int tile_number = 1001 + 10 * iy + ix;

  if (BKE_image_get_tile(ima, tile_number) == nullptr) {
    return 0;
  }
  r_ofs[0] = ix;
  r_ofs[1] = iy;
  sub_v2_v2(r_uv, r_ofs);

  return tile_number;
}

void BKE_image_get_tile_uv(const Image *ima, const int tile_number, float r_uv[2])
{
  if (ima->source != IMA_SRC_TILED) {
    zero_v2(r_uv);
  }
  else {
    const int tile_index = tile_number - 1001;
    r_uv[0] = float(tile_index % 10);
    r_uv[1] = float(tile_index / 10);
  }
}

/** Linear distance between #x and the unit interval. */
static float distance_to_unit_interval(float x)
{
  /* The unit interval is between 0 and 1.
   * Within the interval, return 0.
   * Outside the interval, return the distance to the nearest boundary.
   * Intuitively, the function looks like:
   *  \ |   | /
   * __\|___|/__
   *    0   1
   */

  if (x <= 0.0f) {
    return -x; /* Distance to left border. */
  }
  if (x <= 1.0f) {
    return 0.0f; /* Inside unit interval. */
  }
  return x - 1.0f; /* Distance to right border. */
}

/** Distance squared between #co and the unit square with lower-left starting at #udim. */
static float distance_squared_to_udim(const float co[2], const float udim[2])
{
  float delta[2];
  sub_v2_v2v2(delta, co, udim);
  delta[0] = distance_to_unit_interval(delta[0]);
  delta[1] = distance_to_unit_interval(delta[1]);
  return len_squared_v2(delta);
}

static bool nearest_udim_tile_tie_break(const float best_dist_sq,
                                        const float best_uv[2],
                                        const float dist_sq,
                                        const float uv[2])
{
  if (best_dist_sq == dist_sq) {   /* Exact same distance? Tie-break. */
    if (best_uv[0] == uv[0]) {     /* Exact same U? Tie-break. */
      return (uv[1] > best_uv[1]); /* Higher than previous candidate? */
    }
    return (uv[0] > best_uv[0]); /* Further right than previous candidate? */
  }
  return (dist_sq < best_dist_sq); /* Closer than previous candidate? */
}

int BKE_image_find_nearest_tile_with_offset(const Image *image,
                                            const float co[2],
                                            float r_uv_offset[2])
{
  /* NOTE: If the co-ordinates are integers, take special care to break ties. */

  zero_v2(r_uv_offset);
  int tile_number_best = -1;

  if (!image || image->source != IMA_SRC_TILED) {
    return tile_number_best;
  }

  /* Distance squared to the closest UDIM tile. */
  float dist_best_sq = FLT_MAX;

  LISTBASE_FOREACH (const ImageTile *, tile, &image->tiles) {
    float uv_offset[2];
    BKE_image_get_tile_uv(image, tile->tile_number, uv_offset);

    /* Distance squared between #co and closest point on UDIM tile. */
    const float dist_sq = distance_squared_to_udim(co, uv_offset);

    if (dist_sq == 0) { /* Either inside in the UDIM, or on its boundary. */
      if (floorf(co[0]) == uv_offset[0] && floorf(co[1]) == uv_offset[1]) {
        /* Within the half-open interval of the UDIM. */
        copy_v2_v2(r_uv_offset, uv_offset);
        return tile_number_best;
      }
    }

    if (nearest_udim_tile_tie_break(dist_best_sq, r_uv_offset, dist_sq, uv_offset)) {
      /* Tile is better than previous best, update. */
      dist_best_sq = dist_sq;
      copy_v2_v2(r_uv_offset, uv_offset);
      tile_number_best = tile->tile_number;
    }
  }
  return tile_number_best;
}

int BKE_image_find_nearest_tile(const struct Image *image, const float co[2])
{
  float uv_offset_dummy[2];
  return BKE_image_find_nearest_tile_with_offset(image, co, uv_offset_dummy);
}

static void image_init_color_management(Image *ima)
{
  ImBuf *ibuf;
  char name[FILE_MAX];

  BKE_image_user_file_path(nullptr, ima, name);

  /* Will set input color space to image format default's. */
  ibuf = IMB_loadiffname(name, IB_test | IB_alphamode_detect, ima->colorspace_settings.name);

  if (ibuf) {
    if (ibuf->flags & IB_alphamode_premul) {
      ima->alpha_mode = IMA_ALPHA_PREMUL;
    }
    else if (ibuf->flags & IB_alphamode_channel_packed) {
      ima->alpha_mode = IMA_ALPHA_CHANNEL_PACKED;
    }
    else if (ibuf->flags & IB_alphamode_ignore) {
      ima->alpha_mode = IMA_ALPHA_IGNORE;
    }
    else {
      ima->alpha_mode = IMA_ALPHA_STRAIGHT;
    }

    IMB_freeImBuf(ibuf);
  }
}

char BKE_image_alpha_mode_from_extension_ex(const char *filepath)
{
  if (BLI_path_extension_check_n(filepath, ".exr", ".cin", ".dpx", ".hdr", nullptr)) {
    return IMA_ALPHA_PREMUL;
  }

  return IMA_ALPHA_STRAIGHT;
}

void BKE_image_alpha_mode_from_extension(Image *image)
{
  image->alpha_mode = BKE_image_alpha_mode_from_extension_ex(image->filepath);
}

Image *BKE_image_load(Main *bmain, const char *filepath)
{
  Image *ima;
  int file;
  char str[FILE_MAX];

  STRNCPY(str, filepath);
  BLI_path_abs(str, BKE_main_blendfile_path(bmain));

  /* exists? */
  file = BLI_open(str, O_BINARY | O_RDONLY, 0);
  if (file == -1) {
    if (!BKE_image_tile_filepath_exists(str)) {
      return nullptr;
    }
  }
  else {
    close(file);
  }

  ima = image_alloc(bmain, BLI_path_basename(filepath), IMA_SRC_FILE, IMA_TYPE_IMAGE);
  STRNCPY(ima->filepath, filepath);

  if (BLI_path_extension_check_array(filepath, imb_ext_movie)) {
    ima->source = IMA_SRC_MOVIE;
  }

  image_init_color_management(ima);

  return ima;
}

Image *BKE_image_load_exists_ex(Main *bmain, const char *filepath, bool *r_exists)
{
  Image *ima;
  char str[FILE_MAX], strtest[FILE_MAX];

  STRNCPY(str, filepath);
  BLI_path_abs(str, bmain->filepath);

  /* first search an identical filepath */
  for (ima = static_cast<Image *>(bmain->images.first); ima;
       ima = static_cast<Image *>(ima->id.next)) {
    if (!ELEM(ima->source, IMA_SRC_VIEWER, IMA_SRC_GENERATED)) {
      STRNCPY(strtest, ima->filepath);
      BLI_path_abs(strtest, ID_BLEND_PATH(bmain, &ima->id));

      if (BLI_path_cmp(strtest, str) == 0) {
        if ((BKE_image_has_anim(ima) == false) || (ima->id.us == 0)) {
          id_us_plus(&ima->id); /* officially should not, it doesn't link here! */
          if (r_exists) {
            *r_exists = true;
          }
          return ima;
        }
      }
    }
  }

  if (r_exists) {
    *r_exists = false;
  }
  return BKE_image_load(bmain, filepath);
}

Image *BKE_image_load_exists(Main *bmain, const char *filepath)
{
  return BKE_image_load_exists_ex(bmain, filepath, nullptr);
}

struct ImageFillData {
  short gen_type;
  uint width;
  uint height;
  uchar *rect;
  float *rect_float;
  float fill_color[4];
};

static void image_buf_fill_isolated(void *usersata_v)
{
  ImageFillData *usersata = static_cast<ImageFillData *>(usersata_v);

  const short gen_type = usersata->gen_type;
  const uint width = usersata->width;
  const uint height = usersata->height;

  uchar *rect = usersata->rect;
  float *rect_float = usersata->rect_float;

  switch (gen_type) {
    case IMA_GENTYPE_GRID:
      BKE_image_buf_fill_checker(rect, rect_float, width, height);
      break;
    case IMA_GENTYPE_GRID_COLOR:
      BKE_image_buf_fill_checker_color(rect, rect_float, width, height);
      break;
    default:
      BKE_image_buf_fill_color(rect, rect_float, width, height, usersata->fill_color);
      break;
  }
}

static ImBuf *add_ibuf_for_tile(Image *ima, ImageTile *tile)
{
  ImBuf *ibuf;
  uchar *rect = nullptr;
  float *rect_float = nullptr;
  float fill_color[4];

  const bool floatbuf = (tile->gen_flag & IMA_GEN_FLOAT) != 0;
  if (floatbuf) {
    ibuf = IMB_allocImBuf(tile->gen_x, tile->gen_y, tile->gen_depth, IB_rectfloat);

    if (ima->colorspace_settings.name[0] == '\0') {
      const char *colorspace = IMB_colormanagement_role_colorspace_name_get(
          COLOR_ROLE_DEFAULT_FLOAT);

      STRNCPY(ima->colorspace_settings.name, colorspace);
    }

    if (ibuf != nullptr) {
      rect_float = ibuf->rect_float;
      IMB_colormanagement_check_is_data(ibuf, ima->colorspace_settings.name);
    }

    if (IMB_colormanagement_space_name_is_data(ima->colorspace_settings.name)) {
      copy_v4_v4(fill_color, tile->gen_color);
    }
    else {
      /* The input color here should ideally be linear already, but for now
       * we just convert and postpone breaking the API for later. */
      srgb_to_linearrgb_v4(fill_color, tile->gen_color);
    }
  }
  else {
    ibuf = IMB_allocImBuf(tile->gen_x, tile->gen_y, tile->gen_depth, IB_rect);

    if (ima->colorspace_settings.name[0] == '\0') {
      const char *colorspace = IMB_colormanagement_role_colorspace_name_get(
          COLOR_ROLE_DEFAULT_BYTE);

      STRNCPY(ima->colorspace_settings.name, colorspace);
    }

    if (ibuf != nullptr) {
      rect = (uchar *)ibuf->rect;
      IMB_colormanagement_assign_rect_colorspace(ibuf, ima->colorspace_settings.name);
    }

    copy_v4_v4(fill_color, tile->gen_color);
  }

  if (!ibuf) {
    return nullptr;
  }

  STRNCPY(ibuf->name, ima->filepath);

  /* Mark the tile itself as having been generated. */
  tile->gen_flag |= IMA_GEN_TILE;

  ImageFillData data;

  data.gen_type = tile->gen_type;
  data.width = tile->gen_x;
  data.height = tile->gen_y;
  data.rect = rect;
  data.rect_float = rect_float;
  copy_v4_v4(data.fill_color, fill_color);

  BLI_task_isolate(image_buf_fill_isolated, &data);

  return ibuf;
}

Image *BKE_image_add_generated(Main *bmain,
                               uint width,
                               uint height,
                               const char *name,
                               int depth,
                               int floatbuf,
                               short gen_type,
                               const float color[4],
                               const bool stereo3d,
                               const bool is_data,
                               const bool tiled)
{
  /* Saving the image changes it's #Image.source to #IMA_SRC_FILE (leave as generated here). */
  Image *ima;
  if (tiled) {
    ima = image_alloc(bmain, name, IMA_SRC_TILED, IMA_TYPE_IMAGE);
  }
  else {
    ima = image_alloc(bmain, name, IMA_SRC_GENERATED, IMA_TYPE_UV_TEST);
  }
  if (ima == nullptr) {
    return nullptr;
  }

  int view_id;
  const char *names[2] = {STEREO_LEFT_NAME, STEREO_RIGHT_NAME};

  /* NOTE: leave `ima->filepath` unset,
   * setting it to a dummy value may write to an invalid file-path. */

  /* The generation info is always stored in the tiles. The first tile
   * will be used for non-tiled images. */
  ImageTile *tile = static_cast<ImageTile *>(ima->tiles.first);
  tile->gen_x = width;
  tile->gen_y = height;
  tile->gen_type = gen_type;
  tile->gen_flag |= (floatbuf ? IMA_GEN_FLOAT : 0);
  tile->gen_depth = depth;
  copy_v4_v4(tile->gen_color, color);

  if (is_data) {
    STRNCPY(ima->colorspace_settings.name,
            IMB_colormanagement_role_colorspace_name_get(COLOR_ROLE_DATA));
  }

  for (view_id = 0; view_id < 2; view_id++) {
    ImBuf *ibuf;
    ibuf = add_ibuf_for_tile(ima, tile);
    int index = tiled ? 0 : IMA_NO_INDEX;
    int entry = tiled ? 1001 : 0;
    image_assign_ibuf(ima, ibuf, stereo3d ? view_id : index, entry);

    /* #image_assign_ibuf puts buffer to the cache, which increments user counter. */
    IMB_freeImBuf(ibuf);
    if (!stereo3d) {
      break;
    }

    image_add_view(ima, names[view_id], "");
  }

  return ima;
}

static void image_colorspace_from_imbuf(Image *image, const ImBuf *ibuf)
{
  const char *colorspace_name = nullptr;

  if (ibuf->rect_float) {
    if (ibuf->float_colorspace) {
      colorspace_name = IMB_colormanagement_colorspace_get_name(ibuf->float_colorspace);
    }
    else {
      colorspace_name = IMB_colormanagement_role_colorspace_name_get(COLOR_ROLE_DEFAULT_FLOAT);
    }
  }

  if (ibuf->rect && !colorspace_name) {
    if (ibuf->rect_colorspace) {
      colorspace_name = IMB_colormanagement_colorspace_get_name(ibuf->rect_colorspace);
    }
    else {
      colorspace_name = IMB_colormanagement_role_colorspace_name_get(COLOR_ROLE_DEFAULT_BYTE);
    }
  }

  if (colorspace_name) {
    STRNCPY(image->colorspace_settings.name, colorspace_name);
  }
}

Image *BKE_image_add_from_imbuf(Main *bmain, ImBuf *ibuf, const char *name)
{
  if (name == nullptr) {
    name = BLI_path_basename(ibuf->name);
  }

  /* When the image buffer has valid path create a new image with "file" source and copy the path
   * from the image buffer.
   * Otherwise create "generated" image, avoiding invalid configuration with an empty file path. */
  const eImageSource source = ibuf->name[0] != '\0' ? IMA_SRC_FILE : IMA_SRC_GENERATED;

  Image *ima = image_alloc(bmain, name, source, IMA_TYPE_IMAGE);

  if (!ima) {
    return nullptr;
  }

  BKE_image_replace_imbuf(ima, ibuf);

  return ima;
}

void BKE_image_replace_imbuf(Image *image, ImBuf *ibuf)
{
  BLI_assert(image->type == IMA_TYPE_IMAGE &&
             ELEM(image->source, IMA_SRC_FILE, IMA_SRC_GENERATED));

  BKE_image_free_buffers(image);

  image_assign_ibuf(image, ibuf, IMA_NO_INDEX, 0);
  image_colorspace_from_imbuf(image, ibuf);

  /* Keep generated image type flags consistent with the image buffer. */
  if (image->source == IMA_SRC_GENERATED) {
    if (ibuf->rect_float) {
      image->gen_flag |= IMA_GEN_FLOAT;
    }
    else {
      image->gen_flag &= ~IMA_GEN_FLOAT;
    }

    image->gen_x = ibuf->x;
    image->gen_y = ibuf->y;
  }

  /* Consider image dirty since its content can not be re-created unless the image is explicitly
   * saved. */
  BKE_image_mark_dirty(image, ibuf);
}

/** Pack image buffer to memory as PNG or EXR. */
static bool image_memorypack_imbuf(
    Image *ima, ImBuf *ibuf, int view, int tile_number, const char *filepath)
{
  ibuf->ftype = (ibuf->rect_float) ? IMB_FTYPE_OPENEXR : IMB_FTYPE_PNG;

  IMB_saveiff(ibuf, filepath, IB_rect | IB_mem);

  if (ibuf->encodedbuffer == nullptr) {
    CLOG_STR_ERROR(&LOG, "memory save for pack error");
    IMB_freeImBuf(ibuf);
    image_free_packedfiles(ima);
    return false;
  }

  ImagePackedFile *imapf;
  PackedFile *pf = MEM_cnew<PackedFile>("PackedFile");

  pf->data = ibuf->encodedbuffer;
  pf->size = ibuf->encodedsize;

  imapf = static_cast<ImagePackedFile *>(MEM_mallocN(sizeof(ImagePackedFile), "Image PackedFile"));
  STRNCPY(imapf->filepath, filepath);
  imapf->packedfile = pf;
  imapf->view = view;
  imapf->tile_number = tile_number;
  BLI_addtail(&ima->packedfiles, imapf);

  ibuf->encodedbuffer = nullptr;
  ibuf->encodedsize = 0;
  ibuf->userflags &= ~IB_BITMAPDIRTY;

  return true;
}

bool BKE_image_memorypack(Image *ima)
{
  bool ok = true;

  image_free_packedfiles(ima);

  const int tot_viewfiles = image_num_viewfiles(ima);
  const bool is_tiled = (ima->source == IMA_SRC_TILED);
  const bool is_multiview = BKE_image_is_multiview(ima);

  ImageUser iuser{};
  BKE_imageuser_default(&iuser);
  char tiled_filepath[FILE_MAX];

  for (int view = 0; view < tot_viewfiles; view++) {
    LISTBASE_FOREACH (ImageTile *, tile, &ima->tiles) {
      int index = (is_multiview || is_tiled) ? view : IMA_NO_INDEX;
      int entry = is_tiled ? tile->tile_number : 0;
      ImBuf *ibuf = image_get_cached_ibuf_for_index_entry(ima, index, entry, nullptr);
      if (!ibuf) {
        ok = false;
        break;
      }

      const char *filepath = ibuf->name;
      if (is_tiled) {
        iuser.tile = tile->tile_number;
        BKE_image_user_file_path(&iuser, ima, tiled_filepath);
        filepath = tiled_filepath;
      }
      else if (is_multiview) {
        ImageView *iv = static_cast<ImageView *>(BLI_findlink(&ima->views, view));
        /* if the image was a R_IMF_VIEWS_STEREO_3D we force _L, _R suffices */
        if (ima->views_format == R_IMF_VIEWS_STEREO_3D) {
          const char *suffix[2] = {STEREO_LEFT_SUFFIX, STEREO_RIGHT_SUFFIX};
          BLI_path_suffix(iv->filepath, FILE_MAX, suffix[view], "");
        }
        filepath = iv->filepath;
      }

      ok = ok && image_memorypack_imbuf(ima, ibuf, view, tile->tile_number, filepath);
      IMB_freeImBuf(ibuf);
    }
  }

  if (is_multiview) {
    ima->views_format = R_IMF_VIEWS_INDIVIDUAL;
  }

  if (ok && ima->source == IMA_SRC_GENERATED) {
    ima->source = IMA_SRC_FILE;
    ima->type = IMA_TYPE_IMAGE;
  }

  return ok;
}

void BKE_image_packfiles(ReportList *reports, Image *ima, const char *basepath)
{
  const int tot_viewfiles = image_num_viewfiles(ima);

  ImageUser iuser{};
  BKE_imageuser_default(&iuser);
  for (int view = 0; view < tot_viewfiles; view++) {
    iuser.view = view;
    LISTBASE_FOREACH (ImageTile *, tile, &ima->tiles) {
      iuser.tile = tile->tile_number;
      char filepath[FILE_MAX];
      BKE_image_user_file_path(&iuser, ima, filepath);

      ImagePackedFile *imapf = static_cast<ImagePackedFile *>(
          MEM_mallocN(sizeof(ImagePackedFile), "Image packed file"));
      BLI_addtail(&ima->packedfiles, imapf);

      imapf->packedfile = BKE_packedfile_new(reports, filepath, basepath);
      imapf->view = view;
      imapf->tile_number = tile->tile_number;
      if (imapf->packedfile) {
        STRNCPY(imapf->filepath, filepath);
      }
      else {
        BLI_freelinkN(&ima->packedfiles, imapf);
      }
    }
  }
}

void BKE_image_packfiles_from_mem(ReportList *reports,
                                  Image *ima,
                                  char *data,
                                  const size_t data_len)
{
  const int tot_viewfiles = image_num_viewfiles(ima);

  if (tot_viewfiles != 1) {
    BKE_report(reports, RPT_ERROR, "Cannot pack multiview images from raw data currently...");
  }
  else if (ima->source == IMA_SRC_TILED) {
    BKE_report(reports, RPT_ERROR, "Cannot pack tiled images from raw data currently...");
  }
  else {
    ImagePackedFile *imapf = static_cast<ImagePackedFile *>(
        MEM_mallocN(sizeof(ImagePackedFile), __func__));
    BLI_addtail(&ima->packedfiles, imapf);
    imapf->packedfile = BKE_packedfile_new_from_memory(data, data_len);
    imapf->view = 0;
    imapf->tile_number = 1001;
    STRNCPY(imapf->filepath, ima->filepath);
  }
}

void BKE_image_tag_time(Image *ima)
{
  ima->lastused = PIL_check_seconds_timer_i();
}

static uintptr_t image_mem_size(Image *image)
{
  uintptr_t size = 0;

  /* viewers have memory depending on other rules, has no valid rect pointer */
  if (image->source == IMA_SRC_VIEWER) {
    return 0;
  }

  BLI_mutex_lock(static_cast<ThreadMutex *>(image->runtime.cache_mutex));

  if (image->cache != nullptr) {
    struct MovieCacheIter *iter = IMB_moviecacheIter_new(image->cache);

    while (!IMB_moviecacheIter_done(iter)) {
      ImBuf *ibuf = IMB_moviecacheIter_getImBuf(iter);
      IMB_moviecacheIter_step(iter);
      if (ibuf == nullptr) {
        continue;
      }
      ImBuf *ibufm;
      int level;

      if (ibuf->rect) {
        size += MEM_allocN_len(ibuf->rect);
      }
      if (ibuf->rect_float) {
        size += MEM_allocN_len(ibuf->rect_float);
      }

      for (level = 0; level < IMB_MIPMAP_LEVELS; level++) {
        ibufm = ibuf->mipmap[level];
        if (ibufm) {
          if (ibufm->rect) {
            size += MEM_allocN_len(ibufm->rect);
          }
          if (ibufm->rect_float) {
            size += MEM_allocN_len(ibufm->rect_float);
          }
        }
      }
    }
    IMB_moviecacheIter_free(iter);
  }

  BLI_mutex_unlock(static_cast<ThreadMutex *>(image->runtime.cache_mutex));

  return size;
}

void BKE_image_print_memlist(Main *bmain)
{
  Image *ima;
  uintptr_t size, totsize = 0;

  for (ima = static_cast<Image *>(bmain->images.first); ima;
       ima = static_cast<Image *>(ima->id.next)) {
    totsize += image_mem_size(ima);
  }

  printf("\ntotal image memory len: %.3f MB\n", double(totsize) / double(1024 * 1024));

  for (ima = static_cast<Image *>(bmain->images.first); ima;
       ima = static_cast<Image *>(ima->id.next)) {
    size = image_mem_size(ima);

    if (size) {
      printf("%s len: %.3f MB\n", ima->id.name + 2, double(size) / double(1024 * 1024));
    }
  }
}

static bool imagecache_check_dirty(ImBuf *ibuf, void * /*userkey*/, void * /*userdata*/)
{
  if (ibuf == nullptr) {
    return false;
  }
  return (ibuf->userflags & IB_BITMAPDIRTY) == 0;
}

void BKE_image_free_all_textures(Main *bmain)
{
#undef CHECK_FREED_SIZE

  Tex *tex;
  Image *ima;
#ifdef CHECK_FREED_SIZE
  uintptr_t tot_freed_size = 0;
#endif

  for (ima = static_cast<Image *>(bmain->images.first); ima;
       ima = static_cast<Image *>(ima->id.next)) {
    ima->id.tag &= ~LIB_TAG_DOIT;
  }

  for (tex = static_cast<Tex *>(bmain->textures.first); tex;
       tex = static_cast<Tex *>(tex->id.next)) {
    if (tex->ima) {
      tex->ima->id.tag |= LIB_TAG_DOIT;
    }
  }

  for (ima = static_cast<Image *>(bmain->images.first); ima;
       ima = static_cast<Image *>(ima->id.next)) {
    if (ima->cache && (ima->id.tag & LIB_TAG_DOIT)) {
#ifdef CHECK_FREED_SIZE
      uintptr_t old_size = image_mem_size(ima);
#endif

      IMB_moviecache_cleanup(ima->cache, imagecache_check_dirty, nullptr);

#ifdef CHECK_FREED_SIZE
      tot_freed_size += old_size - image_mem_size(ima);
#endif
    }
  }
#ifdef CHECK_FREED_SIZE
  printf("%s: freed total %lu MB\n", __func__, tot_freed_size / (1024 * 1024));
#endif
}

static bool imagecache_check_free_anim(ImBuf *ibuf, void * /*userkey*/, void *userdata)
{
  if (ibuf == nullptr) {
    return true;
  }
  int except_frame = *(int *)userdata;
  return (ibuf->userflags & IB_BITMAPDIRTY) == 0 && (ibuf->index != IMA_NO_INDEX) &&
         (except_frame != IMA_INDEX_ENTRY(ibuf->index));
}

void BKE_image_free_anim_ibufs(Image *ima, int except_frame)
{
  BLI_mutex_lock(static_cast<ThreadMutex *>(ima->runtime.cache_mutex));
  if (ima->cache != nullptr) {
    IMB_moviecache_cleanup(ima->cache, imagecache_check_free_anim, &except_frame);
  }
  BLI_mutex_unlock(static_cast<ThreadMutex *>(ima->runtime.cache_mutex));
}

void BKE_image_all_free_anim_ibufs(Main *bmain, int cfra)
{
  Image *ima;

  for (ima = static_cast<Image *>(bmain->images.first); ima;
       ima = static_cast<Image *>(ima->id.next)) {
    if (BKE_image_is_animated(ima)) {
      BKE_image_free_anim_ibufs(ima, cfra);
    }
  }
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Read and Write
 * \{ */

#define STAMP_NAME_SIZE ((MAX_ID_NAME - 2) + 16)
/* could allow access externally - 512 is for long names,
 * STAMP_NAME_SIZE is for id names, allowing them some room for description */
struct StampDataCustomField {
  struct StampDataCustomField *next, *prev;
  /* TODO(sergey): Think of better size here, maybe dynamically allocated even. */
  char key[512];
  char *value;
  /* TODO(sergey): Support non-string values. */
};

struct StampData {
  char file[512];
  char note[512];
  char date[512];
  char marker[512];
  char time[512];
  char frame[512];
  char frame_range[512];
  char camera[STAMP_NAME_SIZE];
  char cameralens[STAMP_NAME_SIZE];
  char scene[STAMP_NAME_SIZE];
  char strip[STAMP_NAME_SIZE];
  char rendertime[STAMP_NAME_SIZE];
  char memory[STAMP_NAME_SIZE];
  char hostname[512];

  /* Custom fields are used to put extra meta information header from render
   * engine to the result image.
   *
   * NOTE: This fields are not stamped onto the image. At least for now.
   */
  ListBase custom_fields;
};
#undef STAMP_NAME_SIZE

/**
 * \param do_prefix: Include a label like "File ", "Date ", etc. in the stamp data strings.
 * \param use_dynamic: Also include data that can change on a per-frame basis.
 */
static void stampdata(
    const Scene *scene, Object *camera, StampData *stamp_data, int do_prefix, bool use_dynamic)
{
  char text[256];
  struct tm *tl;
  time_t t;

  if (scene->r.stamp & R_STAMP_FILENAME) {
    const char *blendfile_path = BKE_main_blendfile_path_from_global();
    SNPRINTF(stamp_data->file,
             do_prefix ? "File %s" : "%s",
             (blendfile_path[0] != '\0') ? blendfile_path : "<untitled>");
  }
  else {
    stamp_data->file[0] = '\0';
  }

  if (scene->r.stamp & R_STAMP_NOTE) {
    /* Never do prefix for Note */
    SNPRINTF(stamp_data->note, "%s", scene->r.stamp_udata);
  }
  else {
    stamp_data->note[0] = '\0';
  }

  if (scene->r.stamp & R_STAMP_DATE) {
    t = time(nullptr);
    tl = localtime(&t);
    SNPRINTF(text,
             "%04d/%02d/%02d %02d:%02d:%02d",
             tl->tm_year + 1900,
             tl->tm_mon + 1,
             tl->tm_mday,
             tl->tm_hour,
             tl->tm_min,
             tl->tm_sec);
    SNPRINTF(stamp_data->date, do_prefix ? "Date %s" : "%s", text);
  }
  else {
    stamp_data->date[0] = '\0';
  }

  if (use_dynamic && scene->r.stamp & R_STAMP_MARKER) {
    const char *name = BKE_scene_find_last_marker_name(scene, scene->r.cfra);

    if (name) {
      STRNCPY(text, name);
    }
    else {
      STRNCPY(text, "<none>");
    }

    SNPRINTF(stamp_data->marker, do_prefix ? "Marker %s" : "%s", text);
  }
  else {
    stamp_data->marker[0] = '\0';
  }

  if (use_dynamic && scene->r.stamp & R_STAMP_TIME) {
    const short timecode_style = USER_TIMECODE_SMPTE_FULL;
    BLI_timecode_string_from_time(
        text, sizeof(text), 0, FRA2TIME(scene->r.cfra), FPS, timecode_style);
    SNPRINTF(stamp_data->time, do_prefix ? "Timecode %s" : "%s", text);
  }
  else {
    stamp_data->time[0] = '\0';
  }

  if (use_dynamic && scene->r.stamp & R_STAMP_FRAME) {
    char fmtstr[32];
    int digits = 1;

    if (scene->r.efra > 9) {
      digits = integer_digits_i(scene->r.efra);
    }

    SNPRINTF(fmtstr, do_prefix ? "Frame %%0%di" : "%%0%di", digits);
    SNPRINTF(stamp_data->frame, fmtstr, scene->r.cfra);
  }
  else {
    stamp_data->frame[0] = '\0';
  }

  if (scene->r.stamp & R_STAMP_FRAME_RANGE) {
    SNPRINTF(stamp_data->frame_range,
             do_prefix ? "Frame Range %d:%d" : "%d:%d",
             scene->r.sfra,
             scene->r.efra);
  }
  else {
    stamp_data->frame_range[0] = '\0';
  }

  if (use_dynamic && scene->r.stamp & R_STAMP_CAMERA) {
    SNPRINTF(stamp_data->camera,
             do_prefix ? "Camera %s" : "%s",
             camera ? camera->id.name + 2 : "<none>");
  }
  else {
    stamp_data->camera[0] = '\0';
  }

  if (use_dynamic && scene->r.stamp & R_STAMP_CAMERALENS) {
    if (camera && camera->type == OB_CAMERA) {
      SNPRINTF(text, "%.2f", ((Camera *)camera->data)->lens);
    }
    else {
      STRNCPY(text, "<none>");
    }

    SNPRINTF(stamp_data->cameralens, do_prefix ? "Lens %s" : "%s", text);
  }
  else {
    stamp_data->cameralens[0] = '\0';
  }

  if (scene->r.stamp & R_STAMP_SCENE) {
    SNPRINTF(stamp_data->scene, do_prefix ? "Scene %s" : "%s", scene->id.name + 2);
  }
  else {
    stamp_data->scene[0] = '\0';
  }

  if (use_dynamic && scene->r.stamp & R_STAMP_SEQSTRIP) {
    const Sequence *seq = SEQ_get_topmost_sequence(scene, scene->r.cfra);

    if (seq) {
      STRNCPY(text, seq->name + 2);
    }
    else {
      STRNCPY(text, "<none>");
    }

    SNPRINTF(stamp_data->strip, do_prefix ? "Strip %s" : "%s", text);
  }
  else {
    stamp_data->strip[0] = '\0';
  }

  {
    Render *re = RE_GetSceneRender(scene);
    RenderStats *stats = re ? RE_GetStats(re) : nullptr;

    if (use_dynamic && stats && (scene->r.stamp & R_STAMP_RENDERTIME)) {
      BLI_timecode_string_from_time_simple(text, sizeof(text), stats->lastframetime);

      SNPRINTF(stamp_data->rendertime, do_prefix ? "RenderTime %s" : "%s", text);
    }
    else {
      stamp_data->rendertime[0] = '\0';
    }

    if (use_dynamic && stats && (scene->r.stamp & R_STAMP_MEMORY)) {
      SNPRINTF(stamp_data->memory, do_prefix ? "Peak Memory %.2fM" : "%.2fM", stats->mem_peak);
    }
    else {
      stamp_data->memory[0] = '\0';
    }
  }
  if (scene->r.stamp & R_STAMP_FRAME_RANGE) {
    SNPRINTF(stamp_data->frame_range,
             do_prefix ? "Frame Range %d:%d" : "%d:%d",
             scene->r.sfra,
             scene->r.efra);
  }
  else {
    stamp_data->frame_range[0] = '\0';
  }

  if (scene->r.stamp & R_STAMP_HOSTNAME) {
    char hostname[500]; /* sizeof(stamp_data->hostname) minus some bytes for a label. */
    BLI_hostname_get(hostname, sizeof(hostname));
    SNPRINTF(stamp_data->hostname, do_prefix ? "Hostname %s" : "%s", hostname);
  }
  else {
    stamp_data->hostname[0] = '\0';
  }
}

static void stampdata_from_template(StampData *stamp_data,
                                    const Scene *scene,
                                    const StampData *stamp_data_template,
                                    bool do_prefix)
{
  if (scene->r.stamp & R_STAMP_FILENAME) {
    SNPRINTF(stamp_data->file, do_prefix ? "File %s" : "%s", stamp_data_template->file);
  }
  else {
    stamp_data->file[0] = '\0';
  }
  if (scene->r.stamp & R_STAMP_NOTE) {
    STRNCPY(stamp_data->note, stamp_data_template->note);
  }
  else {
    stamp_data->note[0] = '\0';
  }
  if (scene->r.stamp & R_STAMP_DATE) {
    SNPRINTF(stamp_data->date, do_prefix ? "Date %s" : "%s", stamp_data_template->date);
  }
  else {
    stamp_data->date[0] = '\0';
  }
  if (scene->r.stamp & R_STAMP_MARKER) {
    SNPRINTF(stamp_data->marker, do_prefix ? "Marker %s" : "%s", stamp_data_template->marker);
  }
  else {
    stamp_data->marker[0] = '\0';
  }
  if (scene->r.stamp & R_STAMP_TIME) {
    SNPRINTF(stamp_data->time, do_prefix ? "Timecode %s" : "%s", stamp_data_template->time);
  }
  else {
    stamp_data->time[0] = '\0';
  }
  if (scene->r.stamp & R_STAMP_FRAME) {
    SNPRINTF(stamp_data->frame, do_prefix ? "Frame %s" : "%s", stamp_data_template->frame);
  }
  else {
    stamp_data->frame[0] = '\0';
  }
  if (scene->r.stamp & R_STAMP_CAMERA) {
    SNPRINTF(stamp_data->camera, do_prefix ? "Camera %s" : "%s", stamp_data_template->camera);
  }
  else {
    stamp_data->camera[0] = '\0';
  }
  if (scene->r.stamp & R_STAMP_CAMERALENS) {
    SNPRINTF(
        stamp_data->cameralens, do_prefix ? "Lens %s" : "%s", stamp_data_template->cameralens);
  }
  else {
    stamp_data->cameralens[0] = '\0';
  }
  if (scene->r.stamp & R_STAMP_SCENE) {
    SNPRINTF(stamp_data->scene, do_prefix ? "Scene %s" : "%s", stamp_data_template->scene);
  }
  else {
    stamp_data->scene[0] = '\0';
  }
  if (scene->r.stamp & R_STAMP_SEQSTRIP) {
    SNPRINTF(stamp_data->strip, do_prefix ? "Strip %s" : "%s", stamp_data_template->strip);
  }
  else {
    stamp_data->strip[0] = '\0';
  }
  if (scene->r.stamp & R_STAMP_RENDERTIME) {
    SNPRINTF(stamp_data->rendertime,
             do_prefix ? "RenderTime %s" : "%s",
             stamp_data_template->rendertime);
  }
  else {
    stamp_data->rendertime[0] = '\0';
  }
  if (scene->r.stamp & R_STAMP_MEMORY) {
    SNPRINTF(stamp_data->memory, do_prefix ? "Peak Memory %s" : "%s", stamp_data_template->memory);
  }
  else {
    stamp_data->memory[0] = '\0';
  }
  if (scene->r.stamp & R_STAMP_HOSTNAME) {
    SNPRINTF(
        stamp_data->hostname, do_prefix ? "Hostname %s" : "%s", stamp_data_template->hostname);
  }
  else {
    stamp_data->hostname[0] = '\0';
  }
}

void BKE_image_stamp_buf(Scene *scene,
                         Object *camera,
                         const StampData *stamp_data_template,
                         uchar *rect,
                         float *rectf,
                         int width,
                         int height,
                         int channels)
{
  struct StampData stamp_data;
  int w, h, pad;
  int x, y, y_ofs;
  int h_fixed;
  const int mono = blf_mono_font_render; /* XXX */
  struct ColorManagedDisplay *display;
  const char *display_device;

  /* vars for calculating wordwrap */
  struct {
    struct ResultBLF info;
    rcti rect;
  } wrap;

  /* this could be an argument if we want to operate on non linear float imbuf's
   * for now though this is only used for renders which use scene settings */

#define TEXT_SIZE_CHECK(str, w, h) \
  ((str[0]) && ((void)(h = h_fixed), (w = int(BLF_width(mono, str, sizeof(str))))))

  /* must enable BLF_WORD_WRAP before using */
#define TEXT_SIZE_CHECK_WORD_WRAP(str, w, h) \
  ((str[0]) && (BLF_boundbox_ex(mono, str, sizeof(str), &wrap.rect, &wrap.info), \
                (void)(h = h_fixed * wrap.info.lines), \
                (w = BLI_rcti_size_x(&wrap.rect))))

#define BUFF_MARGIN_X 2
#define BUFF_MARGIN_Y 1

  if (!rect && !rectf) {
    return;
  }

  display_device = scene->display_settings.display_device;
  display = IMB_colormanagement_display_get_named(display_device);

  bool do_prefix = (scene->r.stamp & R_STAMP_HIDE_LABELS) == 0;
  if (stamp_data_template == nullptr) {
    stampdata(scene, camera, &stamp_data, do_prefix, true);
  }
  else {
    stampdata_from_template(&stamp_data, scene, stamp_data_template, do_prefix);
  }

  /* TODO: do_versions. */
  if (scene->r.stamp_font_id < 8) {
    scene->r.stamp_font_id = 12;
  }

  /* set before return */
  BLF_size(mono, scene->r.stamp_font_id);
  BLF_wordwrap(mono, width - (BUFF_MARGIN_X * 2));

  BLF_buffer(mono, rectf, rect, width, height, channels, display);
  BLF_buffer_col(mono, scene->r.fg_stamp);
  pad = BLF_width_max(mono);

  /* use 'h_fixed' rather than 'h', aligns better */
  h_fixed = BLF_height_max(mono);
  y_ofs = -BLF_descender(mono);

  x = 0;
  y = height;

  if (TEXT_SIZE_CHECK(stamp_data.file, w, h)) {
    /* Top left corner */
    y -= h;

    /* also a little of space to the background. */
    buf_rectfill_area(rect,
                      rectf,
                      width,
                      height,
                      scene->r.bg_stamp,
                      display,
                      x - BUFF_MARGIN_X,
                      y - BUFF_MARGIN_Y,
                      w + BUFF_MARGIN_X,
                      y + h + BUFF_MARGIN_Y);

    /* and draw the text. */
    BLF_position(mono, x, y + y_ofs, 0.0);
    BLF_draw_buffer(mono, stamp_data.file, sizeof(stamp_data.file));

    /* the extra pixel for background. */
    y -= BUFF_MARGIN_Y * 2;
  }

  /* Top left corner, below File */
  if (TEXT_SIZE_CHECK(stamp_data.date, w, h)) {
    y -= h;

    /* and space for background. */
    buf_rectfill_area(rect,
                      rectf,
                      width,
                      height,
                      scene->r.bg_stamp,
                      display,
                      0,
                      y - BUFF_MARGIN_Y,
                      w + BUFF_MARGIN_X,
                      y + h + BUFF_MARGIN_Y);

    BLF_position(mono, x, y + y_ofs, 0.0);
    BLF_draw_buffer(mono, stamp_data.date, sizeof(stamp_data.date));

    /* the extra pixel for background. */
    y -= BUFF_MARGIN_Y * 2;
  }

  /* Top left corner, below File, Date */
  if (TEXT_SIZE_CHECK(stamp_data.rendertime, w, h)) {
    y -= h;

    /* and space for background. */
    buf_rectfill_area(rect,
                      rectf,
                      width,
                      height,
                      scene->r.bg_stamp,
                      display,
                      0,
                      y - BUFF_MARGIN_Y,
                      w + BUFF_MARGIN_X,
                      y + h + BUFF_MARGIN_Y);

    BLF_position(mono, x, y + y_ofs, 0.0);
    BLF_draw_buffer(mono, stamp_data.rendertime, sizeof(stamp_data.rendertime));

    /* the extra pixel for background. */
    y -= BUFF_MARGIN_Y * 2;
  }

  /* Top left corner, below File, Date, Render-time */
  if (TEXT_SIZE_CHECK(stamp_data.memory, w, h)) {
    y -= h;

    /* and space for background. */
    buf_rectfill_area(rect,
                      rectf,
                      width,
                      height,
                      scene->r.bg_stamp,
                      display,
                      0,
                      y - BUFF_MARGIN_Y,
                      w + BUFF_MARGIN_X,
                      y + h + BUFF_MARGIN_Y);

    BLF_position(mono, x, y + y_ofs, 0.0);
    BLF_draw_buffer(mono, stamp_data.memory, sizeof(stamp_data.memory));

    /* the extra pixel for background. */
    y -= BUFF_MARGIN_Y * 2;
  }

  /* Top left corner, below: File, Date, Render-time, Memory. */
  if (TEXT_SIZE_CHECK(stamp_data.hostname, w, h)) {
    y -= h;

    /* and space for background. */
    buf_rectfill_area(rect,
                      rectf,
                      width,
                      height,
                      scene->r.bg_stamp,
                      display,
                      0,
                      y - BUFF_MARGIN_Y,
                      w + BUFF_MARGIN_X,
                      y + h + BUFF_MARGIN_Y);

    BLF_position(mono, x, y + y_ofs, 0.0);
    BLF_draw_buffer(mono, stamp_data.hostname, sizeof(stamp_data.hostname));

    /* the extra pixel for background. */
    y -= BUFF_MARGIN_Y * 2;
  }

  /* Top left corner, below: File, Date, Memory, Render-time, Host-name. */
  BLF_enable(mono, BLF_WORD_WRAP);
  if (TEXT_SIZE_CHECK_WORD_WRAP(stamp_data.note, w, h)) {
    y -= h;

    /* and space for background. */
    buf_rectfill_area(rect,
                      rectf,
                      width,
                      height,
                      scene->r.bg_stamp,
                      display,
                      0,
                      y - BUFF_MARGIN_Y,
                      w + BUFF_MARGIN_X,
                      y + h + BUFF_MARGIN_Y);

    BLF_position(mono, x, y + y_ofs + (h - h_fixed), 0.0);
    BLF_draw_buffer(mono, stamp_data.note, sizeof(stamp_data.note));
  }
  BLF_disable(mono, BLF_WORD_WRAP);

  x = 0;
  y = 0;

  /* Bottom left corner, leaving space for timing */
  if (TEXT_SIZE_CHECK(stamp_data.marker, w, h)) {

    /* extra space for background. */
    buf_rectfill_area(rect,
                      rectf,
                      width,
                      height,
                      scene->r.bg_stamp,
                      display,
                      x - BUFF_MARGIN_X,
                      y - BUFF_MARGIN_Y,
                      w + BUFF_MARGIN_X,
                      y + h + BUFF_MARGIN_Y);

    /* and pad the text. */
    BLF_position(mono, x, y + y_ofs, 0.0);
    BLF_draw_buffer(mono, stamp_data.marker, sizeof(stamp_data.marker));

    /* space width. */
    x += w + pad;
  }

  /* Left bottom corner */
  if (TEXT_SIZE_CHECK(stamp_data.time, w, h)) {

    /* extra space for background */
    buf_rectfill_area(rect,
                      rectf,
                      width,
                      height,
                      scene->r.bg_stamp,
                      display,
                      x - BUFF_MARGIN_X,
                      y,
                      x + w + BUFF_MARGIN_X,
                      y + h + BUFF_MARGIN_Y);

    /* and pad the text. */
    BLF_position(mono, x, y + y_ofs, 0.0);
    BLF_draw_buffer(mono, stamp_data.time, sizeof(stamp_data.time));

    /* space width. */
    x += w + pad;
  }

  if (TEXT_SIZE_CHECK(stamp_data.frame, w, h)) {

    /* extra space for background. */
    buf_rectfill_area(rect,
                      rectf,
                      width,
                      height,
                      scene->r.bg_stamp,
                      display,
                      x - BUFF_MARGIN_X,
                      y - BUFF_MARGIN_Y,
                      x + w + BUFF_MARGIN_X,
                      y + h + BUFF_MARGIN_Y);

    /* and pad the text. */
    BLF_position(mono, x, y + y_ofs, 0.0);
    BLF_draw_buffer(mono, stamp_data.frame, sizeof(stamp_data.frame));

    /* space width. */
    x += w + pad;
  }

  if (TEXT_SIZE_CHECK(stamp_data.camera, w, h)) {

    /* extra space for background. */
    buf_rectfill_area(rect,
                      rectf,
                      width,
                      height,
                      scene->r.bg_stamp,
                      display,
                      x - BUFF_MARGIN_X,
                      y - BUFF_MARGIN_Y,
                      x + w + BUFF_MARGIN_X,
                      y + h + BUFF_MARGIN_Y);
    BLF_position(mono, x, y + y_ofs, 0.0);
    BLF_draw_buffer(mono, stamp_data.camera, sizeof(stamp_data.camera));

    /* space width. */
    x += w + pad;
  }

  if (TEXT_SIZE_CHECK(stamp_data.cameralens, w, h)) {

    /* extra space for background. */
    buf_rectfill_area(rect,
                      rectf,
                      width,
                      height,
                      scene->r.bg_stamp,
                      display,
                      x - BUFF_MARGIN_X,
                      y - BUFF_MARGIN_Y,
                      x + w + BUFF_MARGIN_X,
                      y + h + BUFF_MARGIN_Y);
    BLF_position(mono, x, y + y_ofs, 0.0);
    BLF_draw_buffer(mono, stamp_data.cameralens, sizeof(stamp_data.cameralens));
  }

  if (TEXT_SIZE_CHECK(stamp_data.scene, w, h)) {

    /* Bottom right corner, with an extra space because the BLF API is too strict! */
    x = width - w - 2;

    /* extra space for background. */
    buf_rectfill_area(rect,
                      rectf,
                      width,
                      height,
                      scene->r.bg_stamp,
                      display,
                      x - BUFF_MARGIN_X,
                      y - BUFF_MARGIN_Y,
                      x + w + BUFF_MARGIN_X,
                      y + h + BUFF_MARGIN_Y);

    /* and pad the text. */
    BLF_position(mono, x, y + y_ofs, 0.0);
    BLF_draw_buffer(mono, stamp_data.scene, sizeof(stamp_data.scene));
  }

  if (TEXT_SIZE_CHECK(stamp_data.strip, w, h)) {

    /* Top right corner, with an extra space because the BLF API is too strict! */
    x = width - w - pad;
    y = height - h;

    /* extra space for background. */
    buf_rectfill_area(rect,
                      rectf,
                      width,
                      height,
                      scene->r.bg_stamp,
                      display,
                      x - BUFF_MARGIN_X,
                      y - BUFF_MARGIN_Y,
                      x + w + BUFF_MARGIN_X,
                      y + h + BUFF_MARGIN_Y);

    BLF_position(mono, x, y + y_ofs, 0.0);
    BLF_draw_buffer(mono, stamp_data.strip, sizeof(stamp_data.strip));
  }

  /* cleanup the buffer. */
  BLF_buffer(mono, nullptr, nullptr, 0, 0, 0, nullptr);
  BLF_wordwrap(mono, 0);

#undef TEXT_SIZE_CHECK
#undef TEXT_SIZE_CHECK_WORD_WRAP
#undef BUFF_MARGIN_X
#undef BUFF_MARGIN_Y
}

void BKE_render_result_stamp_info(Scene *scene,
                                  Object *camera,
                                  struct RenderResult *rr,
                                  bool allocate_only)
{
  struct StampData *stamp_data;

  if (!(scene && (scene->r.stamp & R_STAMP_ALL)) && !allocate_only) {
    return;
  }

  if (!rr->stamp_data) {
    stamp_data = MEM_cnew<StampData>("RenderResult.stamp_data");
  }
  else {
    stamp_data = rr->stamp_data;
  }

  if (!allocate_only) {
    stampdata(scene, camera, stamp_data, 0, true);
  }

  if (!rr->stamp_data) {
    rr->stamp_data = stamp_data;
  }
}

struct StampData *BKE_stamp_info_from_scene_static(const Scene *scene)
{
  struct StampData *stamp_data;

  if (!(scene && (scene->r.stamp & R_STAMP_ALL))) {
    return nullptr;
  }

  /* Memory is allocated here (instead of by the caller) so that the caller
   * doesn't have to know the size of the StampData struct. */
  stamp_data = MEM_cnew<StampData>(__func__);
  stampdata(scene, nullptr, stamp_data, 0, false);

  return stamp_data;
}

static const char *stamp_metadata_fields[] = {
    "File",
    "Note",
    "Date",
    "Marker",
    "Time",
    "Frame",
    "FrameRange",
    "Camera",
    "Lens",
    "Scene",
    "Strip",
    "RenderTime",
    "Memory",
    "Hostname",
    nullptr,
};

bool BKE_stamp_is_known_field(const char *field_name)
{
  int i = 0;
  while (stamp_metadata_fields[i] != nullptr) {
    if (STREQ(field_name, stamp_metadata_fields[i])) {
      return true;
    }
    i++;
  }
  return false;
}

void BKE_stamp_info_callback(void *data,
                             struct StampData *stamp_data,
                             StampCallback callback,
                             bool noskip)
{
  if ((callback == nullptr) || (stamp_data == nullptr)) {
    return;
  }

#define CALL(member, value_str) \
  if (noskip || stamp_data->member[0]) { \
    callback(data, value_str, stamp_data->member, sizeof(stamp_data->member)); \
  } \
  ((void)0)

  /* TODO(sergey): Use stamp_metadata_fields somehow, or make it more generic
   * meta information to avoid duplication. */
  CALL(file, "File");
  CALL(note, "Note");
  CALL(date, "Date");
  CALL(marker, "Marker");
  CALL(time, "Time");
  CALL(frame, "Frame");
  CALL(frame_range, "FrameRange");
  CALL(camera, "Camera");
  CALL(cameralens, "Lens");
  CALL(scene, "Scene");
  CALL(strip, "Strip");
  CALL(rendertime, "RenderTime");
  CALL(memory, "Memory");
  CALL(hostname, "Hostname");

  LISTBASE_FOREACH (StampDataCustomField *, custom_field, &stamp_data->custom_fields) {
    if (noskip || custom_field->value[0]) {
      callback(data, custom_field->key, custom_field->value, strlen(custom_field->value) + 1);
    }
  }

#undef CALL
}

void BKE_render_result_stamp_data(RenderResult *rr, const char *key, const char *value)
{
  StampData *stamp_data;
  if (rr->stamp_data == nullptr) {
    rr->stamp_data = MEM_cnew<StampData>("RenderResult.stamp_data");
  }
  stamp_data = rr->stamp_data;
  StampDataCustomField *field = static_cast<StampDataCustomField *>(
      MEM_mallocN(sizeof(StampDataCustomField), "StampData Custom Field"));
  STRNCPY(field->key, key);
  field->value = BLI_strdup(value);
  BLI_addtail(&stamp_data->custom_fields, field);
}

StampData *BKE_stamp_data_copy(const StampData *stamp_data)
{
  if (stamp_data == nullptr) {
    return nullptr;
  }

  StampData *stamp_datan = static_cast<StampData *>(MEM_dupallocN(stamp_data));
  BLI_duplicatelist(&stamp_datan->custom_fields, &stamp_data->custom_fields);

  LISTBASE_FOREACH (StampDataCustomField *, custom_fieldn, &stamp_datan->custom_fields) {
    custom_fieldn->value = static_cast<char *>(MEM_dupallocN(custom_fieldn->value));
  }

  return stamp_datan;
}

void BKE_stamp_data_free(StampData *stamp_data)
{
  if (stamp_data == nullptr) {
    return;
  }
  LISTBASE_FOREACH (StampDataCustomField *, custom_field, &stamp_data->custom_fields) {
    MEM_freeN(custom_field->value);
  }
  BLI_freelistN(&stamp_data->custom_fields);
  MEM_freeN(stamp_data);
}

/* wrap for callback only */
static void metadata_set_field(void *data, const char *propname, char *propvalue, int /*len*/)
{
  /* We know it is an ImBuf* because that's what we pass to BKE_stamp_info_callback. */
  ImBuf *imbuf = static_cast<ImBuf *>(data);
  IMB_metadata_set_field(imbuf->metadata, propname, propvalue);
}

static void metadata_get_field(void *data, const char *propname, char *propvalue, int len)
{
  /* We know it is an ImBuf* because that's what we pass to BKE_stamp_info_callback. */
  ImBuf *imbuf = static_cast<ImBuf *>(data);
  IMB_metadata_get_field(imbuf->metadata, propname, propvalue, len);
}

void BKE_imbuf_stamp_info(const RenderResult *rr, ImBuf *ibuf)
{
  StampData *stamp_data = const_cast<StampData *>(rr->stamp_data);
  IMB_metadata_ensure(&ibuf->metadata);
  BKE_stamp_info_callback(ibuf, stamp_data, metadata_set_field, false);
}

static void metadata_copy_custom_fields(const char *field, const char *value, void *rr_v)
{
  if (BKE_stamp_is_known_field(field)) {
    return;
  }
  RenderResult *rr = (RenderResult *)rr_v;
  BKE_render_result_stamp_data(rr, field, value);
}

void BKE_stamp_info_from_imbuf(RenderResult *rr, ImBuf *ibuf)
{
  if (rr->stamp_data == nullptr) {
    rr->stamp_data = MEM_cnew<StampData>("RenderResult.stamp_data");
  }
  StampData *stamp_data = rr->stamp_data;
  IMB_metadata_ensure(&ibuf->metadata);
  BKE_stamp_info_callback(ibuf, stamp_data, metadata_get_field, true);
  /* Copy render engine specific settings. */
  IMB_metadata_foreach(ibuf, metadata_copy_custom_fields, rr);
}

bool BKE_imbuf_alpha_test(ImBuf *ibuf)
{
  int tot;
  if (ibuf->rect_float) {
    const float *buf = ibuf->rect_float;
    for (tot = ibuf->x * ibuf->y; tot--; buf += 4) {
      if (buf[3] < 1.0f) {
        return true;
      }
    }
  }
  else if (ibuf->rect) {
    uchar *buf = (uchar *)ibuf->rect;
    for (tot = ibuf->x * ibuf->y; tot--; buf += 4) {
      if (buf[3] != 255) {
        return true;
      }
    }
  }

  return false;
}

int BKE_imbuf_write(ImBuf *ibuf, const char *name, const ImageFormatData *imf)
{
  BKE_image_format_to_imbuf(ibuf, imf);

  BLI_make_existing_file(name);

  const bool ok = IMB_saveiff(ibuf, name, IB_rect | IB_zbuf | IB_zbuffloat);
  if (ok == 0) {
    perror(name);
  }

  return ok;
}

int BKE_imbuf_write_as(ImBuf *ibuf,
                       const char *name,
                       const ImageFormatData *imf,
                       const bool save_copy)
{
  ImBuf ibuf_back = *ibuf;
  int ok;

  /* All data is RGBA anyway, this just controls how to save for some formats. */
  ibuf->planes = imf->planes;

  ok = BKE_imbuf_write(ibuf, name, imf);

  if (save_copy) {
    /* note that we are not restoring _all_ settings */
    ibuf->planes = ibuf_back.planes;
    ibuf->ftype = ibuf_back.ftype;
    ibuf->foptions = ibuf_back.foptions;
  }

  return ok;
}

int BKE_imbuf_write_stamp(const Scene *scene,
                          const struct RenderResult *rr,
                          ImBuf *ibuf,
                          const char *name,
                          const struct ImageFormatData *imf)
{
  if (scene && scene->r.stamp & R_STAMP_ALL) {
    BKE_imbuf_stamp_info(rr, ibuf);
  }

  return BKE_imbuf_write(ibuf, name, imf);
}

struct anim *openanim_noload(const char *name,
                             int flags,
                             int streamindex,
                             char colorspace[IMA_MAX_SPACE])
{
  struct anim *anim;

  anim = IMB_open_anim(name, flags, streamindex, colorspace);
  return anim;
}

struct anim *openanim(const char *name, int flags, int streamindex, char colorspace[IMA_MAX_SPACE])
{
  struct anim *anim;
  struct ImBuf *ibuf;

  anim = IMB_open_anim(name, flags, streamindex, colorspace);
  if (anim == nullptr) {
    return nullptr;
  }

  ibuf = IMB_anim_absolute(anim, 0, IMB_TC_NONE, IMB_PROXY_NONE);
  if (ibuf == nullptr) {
    if (BLI_exists(name)) {
      printf("not an anim: %s\n", name);
    }
    else {
      printf("anim file doesn't exist: %s\n", name);
    }
    IMB_free_anim(anim);
    return nullptr;
  }
  IMB_freeImBuf(ibuf);

  return anim;
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name New Image API
 * \{ */

/* Notes about Image storage
 * - packedfile
 *   -> written in .blend
 * - filename
 *   -> written in .blend
 * - movie
 *   -> comes from packedfile or filename
 * - renderresult
 *   -> comes from packedfile or filename
 * - listbase
 *   -> ibufs from EXR-handle.
 * - flip-book array
 *   -> ibufs come from movie, temporary renderresult or sequence
 * - ibuf
 *   -> comes from packedfile or filename or generated
 */

Image *BKE_image_ensure_viewer(Main *bmain, int type, const char *name)
{
  Image *ima;

  for (ima = static_cast<Image *>(bmain->images.first); ima;
       ima = static_cast<Image *>(ima->id.next)) {
    if (ima->source == IMA_SRC_VIEWER) {
      if (ima->type == type) {
        break;
      }
    }
  }

  if (ima == nullptr) {
    ima = image_alloc(bmain, name, IMA_SRC_VIEWER, type);
  }

  /* Happens on reload, image-window cannot be image user when hidden. */
  if (ima->id.us == 0) {
    id_us_ensure_real(&ima->id);
  }

  return ima;
}

static void image_viewer_create_views(const RenderData *rd, Image *ima)
{
  if ((rd->scemode & R_MULTIVIEW) == 0) {
    image_add_view(ima, "", "");
  }
  else {
    for (SceneRenderView *srv = static_cast<SceneRenderView *>(rd->views.first); srv;
         srv = srv->next) {
      if (BKE_scene_multiview_is_render_view_active(rd, srv) == false) {
        continue;
      }
      image_add_view(ima, srv->name, "");
    }
  }
}

void BKE_image_ensure_viewer_views(const RenderData *rd, Image *ima, ImageUser *iuser)
{
  bool do_reset;
  const bool is_multiview = (rd->scemode & R_MULTIVIEW) != 0;

  BLI_thread_lock(LOCK_DRAW_IMAGE);

  if (!BKE_scene_multiview_is_stereo3d(rd)) {
    iuser->flag &= ~IMA_SHOW_STEREO;
  }

  /* see if all scene render views are in the image view list */
  do_reset = (BKE_scene_multiview_num_views_get(rd) != BLI_listbase_count(&ima->views));

  /* multiview also needs to be sure all the views are synced */
  if (is_multiview && !do_reset) {
    SceneRenderView *srv;
    ImageView *iv;

    for (iv = static_cast<ImageView *>(ima->views.first); iv; iv = iv->next) {
      srv = static_cast<SceneRenderView *>(
          BLI_findstring(&rd->views, iv->name, offsetof(SceneRenderView, name)));
      if ((srv == nullptr) || (BKE_scene_multiview_is_render_view_active(rd, srv) == false)) {
        do_reset = true;
        break;
      }
    }
  }

  if (do_reset) {
    BLI_mutex_lock(static_cast<ThreadMutex *>(ima->runtime.cache_mutex));

    image_free_cached_frames(ima);
    BKE_image_free_views(ima);

    /* add new views */
    image_viewer_create_views(rd, ima);

    BLI_mutex_unlock(static_cast<ThreadMutex *>(ima->runtime.cache_mutex));
  }

  BLI_thread_unlock(LOCK_DRAW_IMAGE);
}

static void image_walk_ntree_all_users(
    bNodeTree *ntree,
    ID *id,
    void *customdata,
    void callback(Image *ima, ID *iuser_id, ImageUser *iuser, void *customdata))
{
  switch (ntree->type) {
    case NTREE_SHADER:
      LISTBASE_FOREACH (bNode *, node, &ntree->nodes) {
        if (node->id) {
          if (node->type == SH_NODE_TEX_IMAGE) {
            NodeTexImage *tex = static_cast<NodeTexImage *>(node->storage);
            Image *ima = (Image *)node->id;
            callback(ima, id, &tex->iuser, customdata);
          }
          if (node->type == SH_NODE_TEX_ENVIRONMENT) {
            NodeTexImage *tex = static_cast<NodeTexImage *>(node->storage);
            Image *ima = (Image *)node->id;
            callback(ima, id, &tex->iuser, customdata);
          }
        }
      }
      break;
    case NTREE_TEXTURE:
      LISTBASE_FOREACH (bNode *, node, &ntree->nodes) {
        if (node->id && node->type == TEX_NODE_IMAGE) {
          Image *ima = (Image *)node->id;
          ImageUser *iuser = static_cast<ImageUser *>(node->storage);
          callback(ima, id, iuser, customdata);
        }
      }
      break;
    case NTREE_COMPOSIT:
      LISTBASE_FOREACH (bNode *, node, &ntree->nodes) {
        if (node->id && node->type == CMP_NODE_IMAGE) {
          Image *ima = (Image *)node->id;
          ImageUser *iuser = static_cast<ImageUser *>(node->storage);
          callback(ima, id, iuser, customdata);
        }
      }
      break;
  }
}

static void image_walk_gpu_materials(
    ID *id,
    ListBase *gpu_materials,
    void *customdata,
    void callback(Image *ima, ID *iuser_id, ImageUser *iuser, void *customdata))
{
  LISTBASE_FOREACH (LinkData *, link, gpu_materials) {
    GPUMaterial *gpu_material = (GPUMaterial *)link->data;
    ListBase textures = GPU_material_textures(gpu_material);
    LISTBASE_FOREACH (GPUMaterialTexture *, gpu_material_texture, &textures) {
      if (gpu_material_texture->iuser_available) {
        callback(gpu_material_texture->ima, id, &gpu_material_texture->iuser, customdata);
      }
    }
  }
}

static void image_walk_id_all_users(
    ID *id,
    bool skip_nested_nodes,
    void *customdata,
    void callback(Image *ima, ID *iuser_id, ImageUser *iuser, void *customdata))
{
  switch (GS(id->name)) {
    case ID_OB: {
      Object *ob = (Object *)id;
      if (ob->empty_drawtype == OB_EMPTY_IMAGE && ob->data) {
        callback(static_cast<Image *>(ob->data), &ob->id, ob->iuser, customdata);
      }
      break;
    }
    case ID_MA: {
      Material *ma = (Material *)id;
      if (ma->nodetree && ma->use_nodes && !skip_nested_nodes) {
        image_walk_ntree_all_users(ma->nodetree, &ma->id, customdata, callback);
      }
      image_walk_gpu_materials(id, &ma->gpumaterial, customdata, callback);
      break;
    }
    case ID_LA: {
      Light *light = (Light *)id;
      if (light->nodetree && light->use_nodes && !skip_nested_nodes) {
        image_walk_ntree_all_users(light->nodetree, &light->id, customdata, callback);
      }
      break;
    }
    case ID_WO: {
      World *world = (World *)id;
      if (world->nodetree && world->use_nodes && !skip_nested_nodes) {
        image_walk_ntree_all_users(world->nodetree, &world->id, customdata, callback);
      }
      image_walk_gpu_materials(id, &world->gpumaterial, customdata, callback);
      break;
    }
    case ID_TE: {
      Tex *tex = (Tex *)id;
      if (tex->type == TEX_IMAGE && tex->ima) {
        callback(tex->ima, &tex->id, &tex->iuser, customdata);
      }
      if (tex->nodetree && tex->use_nodes && !skip_nested_nodes) {
        image_walk_ntree_all_users(tex->nodetree, &tex->id, customdata, callback);
      }
      break;
    }
    case ID_NT: {
      bNodeTree *ntree = (bNodeTree *)id;
      image_walk_ntree_all_users(ntree, &ntree->id, customdata, callback);
      break;
    }
    case ID_CA: {
      Camera *cam = (Camera *)id;
      LISTBASE_FOREACH (CameraBGImage *, bgpic, &cam->bg_images) {
        callback(bgpic->ima, nullptr, &bgpic->iuser, customdata);
      }
      break;
    }
    case ID_WM: {
      wmWindowManager *wm = (wmWindowManager *)id;
      LISTBASE_FOREACH (wmWindow *, win, &wm->windows) {
        const bScreen *screen = BKE_workspace_active_screen_get(win->workspace_hook);

        LISTBASE_FOREACH (ScrArea *, area, &screen->areabase) {
          if (area->spacetype == SPACE_IMAGE) {
            SpaceImage *sima = static_cast<SpaceImage *>(area->spacedata.first);
            callback(sima->image, nullptr, &sima->iuser, customdata);
          }
        }
      }
      break;
    }
    case ID_SCE: {
      Scene *scene = (Scene *)id;
      if (scene->nodetree && scene->use_nodes && !skip_nested_nodes) {
        image_walk_ntree_all_users(scene->nodetree, &scene->id, customdata, callback);
      }
      break;
    }
    case ID_SIM: {
      Simulation *simulation = (Simulation *)id;
      image_walk_ntree_all_users(simulation->nodetree, &simulation->id, customdata, callback);
      break;
    }
    default:
      break;
  }
}

void BKE_image_walk_all_users(
    const Main *mainp,
    void *customdata,
    void callback(Image *ima, ID *iuser_id, ImageUser *iuser, void *customdata))
{
  for (Scene *scene = static_cast<Scene *>(mainp->scenes.first); scene;
       scene = static_cast<Scene *>(scene->id.next)) {
    image_walk_id_all_users(&scene->id, false, customdata, callback);
  }

  for (Object *ob = static_cast<Object *>(mainp->objects.first); ob;
       ob = static_cast<Object *>(ob->id.next)) {
    image_walk_id_all_users(&ob->id, false, customdata, callback);
  }

  for (bNodeTree *ntree = static_cast<bNodeTree *>(mainp->nodetrees.first); ntree;
       ntree = static_cast<bNodeTree *>(ntree->id.next)) {
    image_walk_id_all_users(&ntree->id, false, customdata, callback);
  }

  for (Material *ma = static_cast<Material *>(mainp->materials.first); ma;
       ma = static_cast<Material *>(ma->id.next)) {
    image_walk_id_all_users(&ma->id, false, customdata, callback);
  }

  for (Light *light = static_cast<Light *>(mainp->materials.first); light;
       light = static_cast<Light *>(light->id.next)) {
    image_walk_id_all_users(&light->id, false, customdata, callback);
  }

  for (World *world = static_cast<World *>(mainp->materials.first); world;
       world = static_cast<World *>(world->id.next)) {
    image_walk_id_all_users(&world->id, false, customdata, callback);
  }

  for (Tex *tex = static_cast<Tex *>(mainp->textures.first); tex;
       tex = static_cast<Tex *>(tex->id.next)) {
    image_walk_id_all_users(&tex->id, false, customdata, callback);
  }

  for (Camera *cam = static_cast<Camera *>(mainp->cameras.first); cam;
       cam = static_cast<Camera *>(cam->id.next)) {
    image_walk_id_all_users(&cam->id, false, customdata, callback);
  }

  for (wmWindowManager *wm = static_cast<wmWindowManager *>(mainp->wm.first); wm;
       wm = static_cast<wmWindowManager *>(wm->id.next)) { /* only 1 wm */
    image_walk_id_all_users(&wm->id, false, customdata, callback);
  }
}

static void image_tag_frame_recalc(Image *ima, ID *iuser_id, ImageUser *iuser, void *customdata)
{
  Image *changed_image = static_cast<Image *>(customdata);

  if (ima == changed_image && BKE_image_is_animated(ima)) {
    iuser->flag |= IMA_NEED_FRAME_RECALC;

    if (iuser_id) {
      /* Must copy image user changes to CoW data-block. */
      DEG_id_tag_update(iuser_id, ID_RECALC_COPY_ON_WRITE);
    }
  }
}

static void image_tag_reload(Image *ima, ID *iuser_id, ImageUser *iuser, void *customdata)
{
  Image *changed_image = static_cast<Image *>(customdata);

  if (ima == changed_image) {
    if (iuser->scene) {
      image_update_views_format(ima, iuser);
    }
    if (iuser_id) {
      /* Must copy image user changes to CoW data-block. */
      DEG_id_tag_update(iuser_id, ID_RECALC_COPY_ON_WRITE);
    }
    BKE_image_partial_update_mark_full_update(ima);
  }
}

void BKE_imageuser_default(ImageUser *iuser)
{
  memset(iuser, 0, sizeof(ImageUser));
  iuser->frames = 100;
  iuser->sfra = 1;
}

void BKE_image_init_imageuser(Image *ima, ImageUser *iuser)
{
  RenderResult *rr = ima->rr;

  iuser->multi_index = 0;
  iuser->layer = iuser->pass = iuser->view = 0;

  if (rr) {
    BKE_image_multilayer_index(rr, iuser);
  }
}

static void image_free_tile(Image *ima, ImageTile *tile)
{
  for (int i = 0; i < TEXTARGET_COUNT; i++) {
    /* Only two textures depends on all tiles, so if this is a secondary tile we can keep the other
     * two. */
    if (tile != ima->tiles.first && !ELEM(i, TEXTARGET_2D_ARRAY, TEXTARGET_TILE_MAPPING)) {
      continue;
    }

    for (int eye = 0; eye < 2; eye++) {
      if (ima->gputexture[i][eye] != nullptr) {
        GPU_texture_free(ima->gputexture[i][eye]);
        ima->gputexture[i][eye] = nullptr;
      }
    }
  }
  BKE_image_partial_update_mark_full_update(ima);

  if (BKE_image_is_multiview(ima)) {
    const int totviews = BLI_listbase_count(&ima->views);
    for (int i = 0; i < totviews; i++) {
      image_remove_ibuf(ima, i, tile->tile_number);
    }
  }
  else {
    image_remove_ibuf(ima, 0, tile->tile_number);
  }
}

static bool image_remove_tile(Image *ima, ImageTile *tile)
{
  if (BLI_listbase_is_single(&ima->tiles)) {
    /* Can't remove the last remaining tile. */
    return false;
  }

  image_free_tile(ima, tile);
  BLI_remlink(&ima->tiles, tile);
  MEM_freeN(tile);

  return true;
}

static void image_remove_all_tiles(Image *ima)
{
  /* Remove all but the final tile. */
  while (image_remove_tile(ima, static_cast<ImageTile *>(ima->tiles.last))) {
    ;
  }
}

void BKE_image_signal(Main *bmain, Image *ima, ImageUser *iuser, int signal)
{
  if (ima == nullptr) {
    return;
  }

  BLI_mutex_lock(static_cast<ThreadMutex *>(ima->runtime.cache_mutex));

  switch (signal) {
    case IMA_SIGNAL_FREE:
      BKE_image_free_buffers(ima);

      if (iuser) {
        if (iuser->scene) {
          image_update_views_format(ima, iuser);
        }
      }
      break;
    case IMA_SIGNAL_SRC_CHANGE:
      if (ima->type == IMA_TYPE_UV_TEST) {
        if (ima->source != IMA_SRC_GENERATED) {
          ima->type = IMA_TYPE_IMAGE;
        }
      }

      if (ima->source == IMA_SRC_GENERATED) {
        ImageTile *base_tile = BKE_image_get_tile(ima, 0);
        if (base_tile->gen_x == 0 || base_tile->gen_y == 0) {
          ImBuf *ibuf = image_get_cached_ibuf_for_index_entry(ima, IMA_NO_INDEX, 0, nullptr);
          if (ibuf) {
            base_tile->gen_x = ibuf->x;
            base_tile->gen_y = ibuf->y;
            IMB_freeImBuf(ibuf);
          }
        }

        /* Changing source type to generated will likely change file format
         * used by generated image buffer. Saving different file format to
         * the old name might confuse other applications.
         *
         * Here we ensure original image path wouldn't be used when saving
         * generated image.
         */
        ima->filepath[0] = '\0';
      }

      if (ima->source != IMA_SRC_TILED) {
        /* Free all but the first tile. */
        image_remove_all_tiles(ima);

        /* If this used to be a UDIM image, get the concrete filepath associated
         * with the remaining tile and use that as the new filepath. */
        ImageTile *base_tile = BKE_image_get_tile(ima, 0);
        if (BKE_image_is_filename_tokenized(ima->filepath)) {
          const bool was_relative = BLI_path_is_rel(ima->filepath);

          eUDIM_TILE_FORMAT tile_format;
          char *udim_pattern = BKE_image_get_tile_strformat(ima->filepath, &tile_format);
          BKE_image_set_filepath_from_tile_number(
              ima->filepath, udim_pattern, tile_format, base_tile->tile_number);
          MEM_freeN(udim_pattern);

          if (was_relative) {
            const char *relbase = ID_BLEND_PATH(bmain, &ima->id);
            BLI_path_rel(ima->filepath, relbase);
          }
        }

        /* If the remaining tile was not number 1001, we need to reassign it so that
         * ibuf lookups from the cache still succeed. */
        base_tile->tile_number = 1001;
      }
      else {
        /* When changing to UDIM, attempt to tokenize the filepath. */
        char *filename = (char *)BLI_path_basename(ima->filepath);
        BKE_image_ensure_tile_token(filename);
      }

      /* image buffers for non-sequence multilayer will share buffers with RenderResult,
       * however sequence multilayer will own buffers. Such logic makes switching from
       * single multilayer file to sequence completely unstable
       * since changes in nodes seems this workaround isn't needed anymore, all sockets
       * are nicely detecting anyway, but freeing buffers always here makes multilayer
       * sequences behave stable
       */
      BKE_image_free_buffers(ima);

      if (iuser) {
        image_tag_frame_recalc(ima, nullptr, iuser, ima);
      }
      BKE_image_walk_all_users(bmain, ima, image_tag_frame_recalc);
      BKE_image_partial_update_mark_full_update(ima);

      break;

    case IMA_SIGNAL_RELOAD:
      /* try to repack file */
      if (BKE_image_has_packedfile(ima)) {
        const int tot_viewfiles = image_num_viewfiles(ima);
        const int tot_files = tot_viewfiles * BLI_listbase_count(&ima->tiles);

        if (tot_files != BLI_listbase_count_at_most(&ima->packedfiles, tot_files + 1)) {
          /* in case there are new available files to be loaded */
          image_free_packedfiles(ima);
          BKE_image_packfiles(nullptr, ima, ID_BLEND_PATH(bmain, &ima->id));
        }
        else {
          ImagePackedFile *imapf;
          for (imapf = static_cast<ImagePackedFile *>(ima->packedfiles.first); imapf;
               imapf = imapf->next) {
            PackedFile *pf;
            pf = BKE_packedfile_new(nullptr, imapf->filepath, ID_BLEND_PATH(bmain, &ima->id));
            if (pf) {
              BKE_packedfile_free(imapf->packedfile);
              imapf->packedfile = pf;
            }
            else {
              printf("ERROR: Image \"%s\" not available. Keeping packed image\n", imapf->filepath);
            }
          }
        }

        if (BKE_image_has_packedfile(ima)) {
          BKE_image_free_buffers(ima);
        }
      }
      else {
        BKE_image_free_buffers(ima);
      }

      if (ima->source == IMA_SRC_TILED) {
        ListBase new_tiles = {nullptr, nullptr};
        int new_start, new_range;

        char filepath[FILE_MAX];
        BLI_strncpy(filepath, ima->filepath, sizeof(filepath));
        BLI_path_abs(filepath, ID_BLEND_PATH_FROM_GLOBAL(&ima->id));
        bool result = BKE_image_get_tile_info(filepath, &new_tiles, &new_start, &new_range);
        if (result) {
          /* Because the prior and new list of tiles are both sparse sequences, we need to be sure
           * to account for how the two sets might or might not overlap. To be complete, we start
           * the refresh process by clearing all existing tiles, stopping when there's only 1 tile
           * left. */
          image_remove_all_tiles(ima);

          ImageTile *base_tile = BKE_image_get_tile(ima, 0);
          int remaining_tile_number = base_tile->tile_number;
          bool needs_final_cleanup = true;

          /* Add in all the new tiles. As the image is proven to be on disk at this point, remove
           * the generation flag from the remaining tile in case this was previously a generated
           * image. */
          base_tile->gen_flag &= ~IMA_GEN_TILE;
          LISTBASE_FOREACH (LinkData *, new_tile, &new_tiles) {
            int new_tile_number = POINTER_AS_INT(new_tile->data);
            BKE_image_add_tile(ima, new_tile_number, nullptr);
            if (new_tile_number == remaining_tile_number) {
              needs_final_cleanup = false;
            }
          }

          /* Final cleanup if the prior remaining tile was never encountered in the new list. */
          if (needs_final_cleanup) {
            BKE_image_remove_tile(ima, BKE_image_get_tile(ima, remaining_tile_number));
          }
        }
        BLI_freelistN(&new_tiles);
      }
      else if (ima->filepath[0] != '\0') {
        /* If the filepath is set at this point remove the generation flag. */
        ImageTile *base_tile = BKE_image_get_tile(ima, 0);
        base_tile->gen_flag &= ~IMA_GEN_TILE;
      }

      if (iuser) {
        image_tag_reload(ima, nullptr, iuser, ima);
      }
      BKE_image_walk_all_users(bmain, ima, image_tag_reload);
      break;
    case IMA_SIGNAL_USER_NEW_IMAGE:
      if (iuser) {
        if (ELEM(ima->source, IMA_SRC_FILE, IMA_SRC_SEQUENCE, IMA_SRC_TILED)) {
          if (ima->type == IMA_TYPE_MULTILAYER) {
            BKE_image_init_imageuser(ima, iuser);
          }
        }
      }
      break;
    case IMA_SIGNAL_COLORMANAGE:
      BKE_image_free_buffers(ima);
      break;
  }

  BLI_mutex_unlock(static_cast<ThreadMutex *>(ima->runtime.cache_mutex));

  BKE_ntree_update_tag_id_changed(bmain, &ima->id);
  BKE_ntree_update_main(bmain, nullptr);
}

/**
 * \return render-pass for a given pass index and active view.
 * fallback to available if there are missing passes for active view.
 */
static RenderPass *image_render_pass_get(RenderLayer *rl,
                                         const int pass,
                                         const int view,
                                         int *r_passindex)
{
  RenderPass *rpass_ret = nullptr;
  RenderPass *rpass;

  int rp_index = 0;
  const char *rp_name = "";

  for (rpass = static_cast<RenderPass *>(rl->passes.first); rpass;
       rpass = rpass->next, rp_index++) {
    if (rp_index == pass) {
      rpass_ret = rpass;
      if (view == 0) {
        /* no multiview or left eye */
        break;
      }

      rp_name = rpass->name;
    }
    /* multiview */
    else if (rp_name[0] && STREQ(rpass->name, rp_name) && (rpass->view_id == view)) {
      rpass_ret = rpass;
      break;
    }
  }

  /* fallback to the first pass in the layer */
  if (rpass_ret == nullptr) {
    rp_index = 0;
    rpass_ret = static_cast<RenderPass *>(rl->passes.first);
  }

  if (r_passindex) {
    *r_passindex = (rpass == rpass_ret ? rp_index : pass);
  }

  return rpass_ret;
}

void BKE_image_get_tile_label(Image *ima, ImageTile *tile, char *label, int len_label)
{
  label[0] = '\0';
  if (ima == nullptr || tile == nullptr) {
    return;
  }

  if (tile->label[0]) {
    BLI_strncpy(label, tile->label, len_label);
  }
  else {
    BLI_snprintf(label, len_label, "%d", tile->tile_number);
  }
}

bool BKE_image_get_tile_info(char *filepath, ListBase *tiles, int *r_tile_start, int *r_tile_range)
{
  char filename[FILE_MAXFILE], dirname[FILE_MAXDIR];
  BLI_split_dirfile(filepath, dirname, filename, sizeof(dirname), sizeof(filename));

  if (!BKE_image_is_filename_tokenized(filename)) {
    BKE_image_ensure_tile_token(filename);
  }

  eUDIM_TILE_FORMAT tile_format;
  char *udim_pattern = BKE_image_get_tile_strformat(filename, &tile_format);

  bool all_valid_udim = true;
  int min_udim = IMA_UDIM_MAX + 1;
  int max_udim = 0;
  int id;

  struct direntry *dirs;
  const uint dirs_num = BLI_filelist_dir_contents(dirname, &dirs);
  for (int i = 0; i < dirs_num; i++) {
    if (!(dirs[i].type & S_IFREG)) {
      continue;
    }

    if (!BKE_image_get_tile_number_from_filepath(
            dirs[i].relname, udim_pattern, tile_format, &id)) {
      continue;
    }

    if (id < 1001 || id > IMA_UDIM_MAX) {
      all_valid_udim = false;
      break;
    }

    BLI_addtail(tiles, BLI_genericNodeN(POINTER_FROM_INT(id)));
    min_udim = min_ii(min_udim, id);
    max_udim = max_ii(max_udim, id);
  }
  BLI_filelist_free(dirs, dirs_num);
  MEM_SAFE_FREE(udim_pattern);

  if (all_valid_udim && min_udim <= IMA_UDIM_MAX) {
    BLI_path_join(filepath, FILE_MAX, dirname, filename);

    *r_tile_start = min_udim;
    *r_tile_range = max_udim - min_udim + 1;
    return true;
  }
  return false;
}

ImageTile *BKE_image_add_tile(struct Image *ima, int tile_number, const char *label)
{
  if (ima->source != IMA_SRC_TILED) {
    return nullptr;
  }

  if (tile_number < 1001 || tile_number > IMA_UDIM_MAX) {
    return nullptr;
  }

  /* Search the first tile that has a higher number.
   * We then insert before that to keep the list sorted. */
  ImageTile *next_tile;
  for (next_tile = static_cast<ImageTile *>(ima->tiles.first); next_tile;
       next_tile = next_tile->next) {
    if (next_tile->tile_number == tile_number) {
      /* Tile already exists. */
      return nullptr;
    }
    if (next_tile->tile_number > tile_number) {
      break;
    }
  }

  ImageTile *tile = imagetile_alloc(tile_number);

  if (next_tile) {
    BLI_insertlinkbefore(&ima->tiles, next_tile, tile);
  }
  else {
    BLI_addtail(&ima->tiles, tile);
  }

  if (label) {
    BLI_strncpy(tile->label, label, sizeof(tile->label));
  }

  for (int eye = 0; eye < 2; eye++) {
    /* Reallocate GPU tile array. */
    if (ima->gputexture[TEXTARGET_2D_ARRAY][eye] != nullptr) {
      GPU_texture_free(ima->gputexture[TEXTARGET_2D_ARRAY][eye]);
      ima->gputexture[TEXTARGET_2D_ARRAY][eye] = nullptr;
    }
    if (ima->gputexture[TEXTARGET_TILE_MAPPING][eye] != nullptr) {
      GPU_texture_free(ima->gputexture[TEXTARGET_TILE_MAPPING][eye]);
      ima->gputexture[TEXTARGET_TILE_MAPPING][eye] = nullptr;
    }
  }
  BKE_image_partial_update_mark_full_update(ima);

  return tile;
}

bool BKE_image_remove_tile(struct Image *ima, ImageTile *tile)
{
  if (ima == nullptr || tile == nullptr || ima->source != IMA_SRC_TILED) {
    return false;
  }

  return image_remove_tile(ima, tile);
}

void BKE_image_reassign_tile(struct Image *ima, ImageTile *tile, int new_tile_number)
{
  if (ima == nullptr || tile == nullptr || ima->source != IMA_SRC_TILED) {
    return;
  }

  if (new_tile_number < 1001 || new_tile_number > IMA_UDIM_MAX) {
    return;
  }

  const int old_tile_number = tile->tile_number;
  tile->tile_number = new_tile_number;

  if (BKE_image_is_multiview(ima)) {
    const int totviews = BLI_listbase_count(&ima->views);
    for (int i = 0; i < totviews; i++) {
      ImBuf *ibuf = image_get_cached_ibuf_for_index_entry(ima, i, old_tile_number, nullptr);
      image_remove_ibuf(ima, i, old_tile_number);
      image_assign_ibuf(ima, ibuf, i, new_tile_number);
      IMB_freeImBuf(ibuf);
    }
  }
  else {
    ImBuf *ibuf = image_get_cached_ibuf_for_index_entry(ima, 0, old_tile_number, nullptr);
    image_remove_ibuf(ima, 0, old_tile_number);
    image_assign_ibuf(ima, ibuf, 0, new_tile_number);
    IMB_freeImBuf(ibuf);
  }

  for (int eye = 0; eye < 2; eye++) {
    /* Reallocate GPU tile array. */
    if (ima->gputexture[TEXTARGET_2D_ARRAY][eye] != nullptr) {
      GPU_texture_free(ima->gputexture[TEXTARGET_2D_ARRAY][eye]);
      ima->gputexture[TEXTARGET_2D_ARRAY][eye] = nullptr;
    }
    if (ima->gputexture[TEXTARGET_TILE_MAPPING][eye] != nullptr) {
      GPU_texture_free(ima->gputexture[TEXTARGET_TILE_MAPPING][eye]);
      ima->gputexture[TEXTARGET_TILE_MAPPING][eye] = nullptr;
    }
  }
  BKE_image_partial_update_mark_full_update(ima);
}

static int tile_sort_cb(const void *a, const void *b)
{
  const ImageTile *tile_a = static_cast<const ImageTile *>(a);
  const ImageTile *tile_b = static_cast<const ImageTile *>(b);
  return (tile_a->tile_number > tile_b->tile_number) ? 1 : 0;
}

void BKE_image_sort_tiles(struct Image *ima)
{
  if (ima == nullptr || ima->source != IMA_SRC_TILED) {
    return;
  }

  BLI_listbase_sort(&ima->tiles, tile_sort_cb);
}

bool BKE_image_fill_tile(struct Image *ima, ImageTile *tile)
{
  if (ima == nullptr || tile == nullptr || ima->source != IMA_SRC_TILED) {
    return false;
  }

  image_free_tile(ima, tile);

  ImBuf *tile_ibuf = add_ibuf_for_tile(ima, tile);

  if (tile_ibuf != nullptr) {
    image_assign_ibuf(ima, tile_ibuf, 0, tile->tile_number);
    BKE_image_release_ibuf(ima, tile_ibuf, nullptr);
    return true;
  }
  return false;
}

bool BKE_image_is_filename_tokenized(char *filepath)
{
  const char *filename = BLI_path_basename(filepath);
  return strstr(filename, "<UDIM>") != nullptr || strstr(filename, "<UVTILE>") != nullptr;
}

void BKE_image_ensure_tile_token(char *filename)
{
  BLI_assert_msg(BLI_path_slash_find(filename) == nullptr,
                 "Only the file-name component should be used!");

  if (BKE_image_is_filename_tokenized(filename)) {
    return;
  }

  std::string path(filename);
  std::smatch match;

  /* General 4-digit "udim" pattern. As this format is susceptible to ambiguity
   * with other digit sequences, we can leverage the supported range of roughly
   * 1000 through 2000 to provide better detection. */
  std::regex pattern(R"((.*[._-])([12]\d{3})([._-].*))");
  if (std::regex_search(path, match, pattern)) {
    BLI_strncpy(filename, match.format("$1<UDIM>$3").c_str(), FILE_MAX);
    return;
  }

  /* General `u##_v###` `uvtile` pattern. */
  pattern = std::regex(R"((.*)(u\d{1,2}_v\d{1,3})(\D.*))");
  if (std::regex_search(path, match, pattern)) {
    BLI_strncpy(filename, match.format("$1<UVTILE>$3").c_str(), FILE_MAX);
    return;
  }
}

bool BKE_image_tile_filepath_exists(const char *filepath)
{
  BLI_assert(!BLI_path_is_rel(filepath));

  char dirname[FILE_MAXDIR];
  BLI_split_dir_part(filepath, dirname, sizeof(dirname));

  eUDIM_TILE_FORMAT tile_format;
  char *udim_pattern = BKE_image_get_tile_strformat(filepath, &tile_format);

  bool found = false;
  struct direntry *dirs;
  const uint dirs_num = BLI_filelist_dir_contents(dirname, &dirs);
  for (int i = 0; i < dirs_num; i++) {
    if (!(dirs[i].type & S_IFREG)) {
      continue;
    }

    int id;
    if (!BKE_image_get_tile_number_from_filepath(dirs[i].path, udim_pattern, tile_format, &id)) {
      continue;
    }

    if (id < 1001 || id > IMA_UDIM_MAX) {
      continue;
    }

    found = true;
    break;
  }
  BLI_filelist_free(dirs, dirs_num);
  MEM_SAFE_FREE(udim_pattern);

  return found;
}

char *BKE_image_get_tile_strformat(const char *filepath, eUDIM_TILE_FORMAT *r_tile_format)
{
  if (filepath == nullptr || r_tile_format == nullptr) {
    return nullptr;
  }

  if (strstr(filepath, "<UDIM>") != nullptr) {
    *r_tile_format = UDIM_TILE_FORMAT_UDIM;
    return BLI_str_replaceN(filepath, "<UDIM>", "%d");
  }
  if (strstr(filepath, "<UVTILE>") != nullptr) {
    *r_tile_format = UDIM_TILE_FORMAT_UVTILE;
    return BLI_str_replaceN(filepath, "<UVTILE>", "u%d_v%d");
  }

  *r_tile_format = UDIM_TILE_FORMAT_NONE;
  return nullptr;
}

bool BKE_image_get_tile_number_from_filepath(const char *filepath,
                                             const char *pattern,
                                             eUDIM_TILE_FORMAT tile_format,
                                             int *r_tile_number)
{
  if (filepath == nullptr || pattern == nullptr || r_tile_number == nullptr) {
    return false;
  }

  int u, v;
  bool result = false;

  if (tile_format == UDIM_TILE_FORMAT_UDIM) {
    if (sscanf(filepath, pattern, &u) == 1) {
      *r_tile_number = u;
      result = true;
    }
  }
  else if (tile_format == UDIM_TILE_FORMAT_UVTILE) {
    if (sscanf(filepath, pattern, &u, &v) == 2) {
      *r_tile_number = 1001 + (u - 1) + ((v - 1) * 10);
      result = true;
    }
  }

  return result;
}

void BKE_image_set_filepath_from_tile_number(char *filepath,
                                             const char *pattern,
                                             eUDIM_TILE_FORMAT tile_format,
                                             int tile_number)
{
  if (filepath == nullptr || pattern == nullptr) {
    return;
  }

  if (tile_format == UDIM_TILE_FORMAT_UDIM) {
    BLI_sprintf(filepath, pattern, tile_number);
  }
  else if (tile_format == UDIM_TILE_FORMAT_UVTILE) {
    int u = ((tile_number - 1001) % 10);
    int v = ((tile_number - 1001) / 10);
    BLI_sprintf(filepath, pattern, u + 1, v + 1);
  }
}

/* if layer or pass changes, we need an index for the imbufs list */
/* note it is called for rendered results, but it doesn't use the index! */
RenderPass *BKE_image_multilayer_index(RenderResult *rr, ImageUser *iuser)
{
  RenderLayer *rl;
  RenderPass *rpass = nullptr;

  if (rr == nullptr) {
    return nullptr;
  }

  if (iuser) {
    short index = 0, rv_index, rl_index = 0;
    bool is_stereo = (iuser->flag & IMA_SHOW_STEREO) && RE_RenderResult_is_stereo(rr);

    rv_index = is_stereo ? iuser->multiview_eye : iuser->view;
    if (RE_HasCombinedLayer(rr)) {
      rl_index += 1;
    }

    for (rl = static_cast<RenderLayer *>(rr->layers.first); rl; rl = rl->next, rl_index++) {
      if (iuser->layer == rl_index) {
        int rp_index;
        rpass = image_render_pass_get(rl, iuser->pass, rv_index, &rp_index);
        iuser->multi_index = index + rp_index;
        break;
      }

      index += BLI_listbase_count(&rl->passes);
    }
  }

  return rpass;
}

void BKE_image_multiview_index(const Image *ima, ImageUser *iuser)
{
  if (iuser) {
    bool is_stereo = BKE_image_is_stereo(ima) && (iuser->flag & IMA_SHOW_STEREO);
    if (is_stereo) {
      iuser->multi_index = iuser->multiview_eye;
    }
    else {
      if ((iuser->view < 0) ||
          (iuser->view >= BLI_listbase_count_at_most(&ima->views, iuser->view + 1))) {
        iuser->multi_index = iuser->view = 0;
      }
      else {
        iuser->multi_index = iuser->view;
      }
    }
  }
}

/* if layer or pass changes, we need an index for the imbufs list */
/* note it is called for rendered results, but it doesn't use the index! */
bool BKE_image_is_multilayer(const Image *ima)
{
  if (ELEM(ima->source, IMA_SRC_FILE, IMA_SRC_SEQUENCE, IMA_SRC_TILED)) {
    if (ima->type == IMA_TYPE_MULTILAYER) {
      return true;
    }
  }
  else if (ima->source == IMA_SRC_VIEWER) {
    if (ima->type == IMA_TYPE_R_RESULT) {
      return true;
    }
  }
  return false;
}

bool BKE_image_is_multiview(const Image *ima)
{
  ImageView *view = static_cast<ImageView *>(ima->views.first);
  return (view && (view->next || view->name[0]));
}

bool BKE_image_is_stereo(const Image *ima)
{
  return BKE_image_is_multiview(ima) &&
         (BLI_findstring(&ima->views, STEREO_LEFT_NAME, offsetof(ImageView, name)) &&
          BLI_findstring(&ima->views, STEREO_RIGHT_NAME, offsetof(ImageView, name)));
}

static void image_init_multilayer_multiview(Image *ima, RenderResult *rr)
{
  /* update image views from render views, but only if they actually changed,
   * to avoid invalid memory access during render. ideally these should always
   * be acquired with a mutex along with the render result, but there are still
   * some places with just an image pointer that need to access views */
  if (rr && BLI_listbase_count(&ima->views) == BLI_listbase_count(&rr->views)) {
    ImageView *iv = static_cast<ImageView *>(ima->views.first);
    RenderView *rv = static_cast<RenderView *>(rr->views.first);
    bool modified = false;
    for (; rv; rv = rv->next, iv = iv->next) {
      modified |= !STREQ(rv->name, iv->name);
    }
    if (!modified) {
      return;
    }
  }

  BKE_image_free_views(ima);

  if (rr) {
    LISTBASE_FOREACH (RenderView *, rv, &rr->views) {
      ImageView *iv = MEM_cnew<ImageView>("Viewer Image View");
      STRNCPY(iv->name, rv->name);
      BLI_addtail(&ima->views, iv);
    }
  }
}

RenderResult *BKE_image_acquire_renderresult(Scene *scene, Image *ima)
{
  RenderResult *rr = nullptr;
  if (ima->rr) {
    rr = ima->rr;
  }
  else if (ima->type == IMA_TYPE_R_RESULT) {
    if (ima->render_slot == ima->last_render_slot) {
      rr = RE_AcquireResultRead(RE_GetSceneRender(scene));
    }
    else {
      rr = BKE_image_get_renderslot(ima, ima->render_slot)->render;
      BKE_image_partial_update_mark_full_update(ima);
    }

    /* set proper views */
    image_init_multilayer_multiview(ima, rr);
  }

  return rr;
}

void BKE_image_release_renderresult(Scene *scene, Image *ima)
{
  if (ima->rr) {
    /* pass */
  }
  else if (ima->type == IMA_TYPE_R_RESULT) {
    if (ima->render_slot == ima->last_render_slot) {
      RE_ReleaseResult(RE_GetSceneRender(scene));
    }
  }
}

bool BKE_image_is_openexr(struct Image *ima)
{
#ifdef WITH_OPENEXR
  if (ELEM(ima->source, IMA_SRC_FILE, IMA_SRC_SEQUENCE, IMA_SRC_TILED)) {
    return BLI_path_extension_check(ima->filepath, ".exr");
  }
#else
  UNUSED_VARS(ima);
#endif
  return false;
}

void BKE_image_backup_render(Scene *scene, Image *ima, bool free_current_slot)
{
  /* called right before rendering, ima->renderslots contains render
   * result pointers for everything but the current render */
  Render *re = RE_GetSceneRender(scene);

  /* Ensure we always have a valid render slot. */
  if (!ima->renderslots.first) {
    BKE_image_add_renderslot(ima, nullptr);
    ima->render_slot = 0;
    ima->last_render_slot = 0;
  }
  else if (ima->render_slot >= BLI_listbase_count(&ima->renderslots)) {
    ima->render_slot = 0;
    ima->last_render_slot = 0;
  }

  RenderSlot *last_slot = BKE_image_get_renderslot(ima, ima->last_render_slot);
  RenderSlot *cur_slot = BKE_image_get_renderslot(ima, ima->render_slot);

  if (last_slot && ima->render_slot != ima->last_render_slot) {
    last_slot->render = nullptr;
    RE_SwapResult(re, &last_slot->render);

    if (cur_slot->render) {
      if (free_current_slot) {
        BKE_image_clear_renderslot(ima, nullptr, ima->render_slot);
      }
      else {
        RE_SwapResult(re, &cur_slot->render);
      }
    }
  }

  ima->last_render_slot = ima->render_slot;
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Multiview Load OpenEXR
 * \{ */

static void image_add_view(Image *ima, const char *viewname, const char *filepath)
{
  ImageView *iv;

  iv = static_cast<ImageView *>(MEM_mallocN(sizeof(ImageView), "Viewer Image View"));
  STRNCPY(iv->name, viewname);
  STRNCPY(iv->filepath, filepath);

  /* For stereo drawing we need to ensure:
   * STEREO_LEFT_NAME  == STEREO_LEFT_ID and
   * STEREO_RIGHT_NAME == STEREO_RIGHT_ID */

  if (STREQ(viewname, STEREO_LEFT_NAME)) {
    BLI_addhead(&ima->views, iv);
  }
  else if (STREQ(viewname, STEREO_RIGHT_NAME)) {
    ImageView *left_iv = static_cast<ImageView *>(
        BLI_findstring(&ima->views, STEREO_LEFT_NAME, offsetof(ImageView, name)));

    if (left_iv == nullptr) {
      BLI_addhead(&ima->views, iv);
    }
    else {
      BLI_insertlinkafter(&ima->views, left_iv, iv);
    }
  }
  else {
    BLI_addtail(&ima->views, iv);
  }
}

/* After imbuf load, OpenEXR type can return with a EXR-handle open
 * in that case we have to build a render-result. */
#ifdef WITH_OPENEXR
static void image_create_multilayer(Image *ima, ImBuf *ibuf, int framenr)
{
  const char *colorspace = ima->colorspace_settings.name;
  bool predivide = (ima->alpha_mode == IMA_ALPHA_PREMUL);

  /* only load rr once for multiview */
  if (!ima->rr) {
    ima->rr = RE_MultilayerConvert(ibuf->userdata, colorspace, predivide, ibuf->x, ibuf->y);
  }

  IMB_exr_close(ibuf->userdata);

  ibuf->userdata = nullptr;
  if (ima->rr != nullptr) {
    ima->rr->framenr = framenr;
    BKE_stamp_info_from_imbuf(ima->rr, ibuf);
  }

  /* set proper views */
  image_init_multilayer_multiview(ima, ima->rr);
}
#endif /* WITH_OPENEXR */

/** Common stuff to do with images after loading. */
static void image_init_after_load(Image *ima, ImageUser *iuser, ImBuf * /*ibuf*/)
{
  /* Preview is null when it has never been used as an icon before.
   * Never handle previews/icons outside of main thread. */
  if (G.background == 0 && ima->preview == nullptr && BLI_thread_is_main()) {
    BKE_icon_changed(BKE_icon_id_ensure(&ima->id));
  }

  /* timer */
  BKE_image_tag_time(ima);

  ImageTile *tile = BKE_image_get_tile_from_iuser(ima, iuser);
  /* Images should never get loaded if the corresponding tile does not exist,
   * but we should at least not crash if it happens due to a bug elsewhere. */
  BLI_assert(tile != nullptr);
  UNUSED_VARS_NDEBUG(tile);
}

static int imbuf_alpha_flags_for_image(Image *ima)
{
  switch (ima->alpha_mode) {
    case IMA_ALPHA_STRAIGHT:
      return 0;
    case IMA_ALPHA_PREMUL:
      return IB_alphamode_premul;
    case IMA_ALPHA_CHANNEL_PACKED:
      return IB_alphamode_channel_packed;
    case IMA_ALPHA_IGNORE:
      return IB_alphamode_ignore;
  }

  return 0;
}

/**
 * \return the number of files will vary according to the stereo format.
 */
static int image_num_viewfiles(Image *ima)
{
  const bool is_multiview = BKE_image_is_multiview(ima);

  if (!is_multiview) {
    return 1;
  }
  if (ima->views_format == R_IMF_VIEWS_STEREO_3D) {
    return 1;
  }
  /* R_IMF_VIEWS_INDIVIDUAL */

  return BLI_listbase_count(&ima->views);
}

static ImBuf *image_load_sequence_multilayer(Image *ima, ImageUser *iuser, int entry, int frame)
{
  struct ImBuf *ibuf = nullptr;

  /* either we load from RenderResult, or we have to load a new one */

  /* check for new RenderResult */
  if (ima->rr == nullptr || frame != ima->rr->framenr) {
    if (ima->rr) {
      /* Cached image buffers shares pointers with render result,
       * need to ensure there's no image buffers are hanging around
       * with dead links after freeing the render result.
       */
      image_free_cached_frames(ima);
      RE_FreeRenderResult(ima->rr);
      ima->rr = nullptr;
    }

    ibuf = image_load_image_file(ima, iuser, entry, frame, true);

    if (ibuf) { /* actually an error */
      ima->type = IMA_TYPE_IMAGE;
      printf("error, multi is normal image\n");
    }
  }
  if (ima->rr) {
    RenderPass *rpass = BKE_image_multilayer_index(ima->rr, iuser);

    if (rpass) {
      // printf("load from pass %s\n", rpass->name);
      /* since we free  render results, we copy the rect */
      ibuf = IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0);
      ibuf->rect_float = static_cast<float *>(MEM_dupallocN(rpass->rect));
      ibuf->flags |= IB_rectfloat;
      ibuf->mall = IB_rectfloat;
      ibuf->channels = rpass->channels;

      BKE_imbuf_stamp_info(ima->rr, ibuf);

      image_init_after_load(ima, iuser, ibuf);
      image_assign_ibuf(ima, ibuf, iuser ? iuser->multi_index : 0, entry);
    }
    // else printf("pass not found\n");
  }

  return ibuf;
}

static ImBuf *load_movie_single(Image *ima, ImageUser *iuser, int frame, const int view_id)
{
  struct ImBuf *ibuf = nullptr;
  ImageAnim *ia;

  ia = static_cast<ImageAnim *>(BLI_findlink(&ima->anims, view_id));

  if (ia->anim == nullptr) {
    char str[FILE_MAX];
    int flags = IB_rect;
    ImageUser iuser_t{};

    if (ima->flag & IMA_DEINTERLACE) {
      flags |= IB_animdeinterlace;
    }

    if (iuser) {
      iuser_t = *iuser;
    }

    iuser_t.view = view_id;

    BKE_image_user_file_path(&iuser_t, ima, str);

    /* FIXME: make several stream accessible in image editor, too. */
    ia->anim = openanim(str, flags, 0, ima->colorspace_settings.name);

    /* let's initialize this user */
    if (ia->anim && iuser && iuser->frames == 0) {
      iuser->frames = IMB_anim_get_duration(ia->anim, IMB_TC_RECORD_RUN);
    }
  }

  if (ia->anim) {
    int dur = IMB_anim_get_duration(ia->anim, IMB_TC_RECORD_RUN);
    int fra = frame - 1;

    if (fra < 0) {
      fra = 0;
    }
    if (fra > (dur - 1)) {
      fra = dur - 1;
    }
    ibuf = IMB_makeSingleUser(IMB_anim_absolute(ia->anim, fra, IMB_TC_RECORD_RUN, IMB_PROXY_NONE));

    if (ibuf) {
      image_init_after_load(ima, iuser, ibuf);
    }
  }

  return ibuf;
}

static ImBuf *image_load_movie_file(Image *ima, ImageUser *iuser, int frame)
{
  struct ImBuf *ibuf = nullptr;
  const bool is_multiview = BKE_image_is_multiview(ima);
  const int tot_viewfiles = image_num_viewfiles(ima);

  if (tot_viewfiles != BLI_listbase_count_at_most(&ima->anims, tot_viewfiles + 1)) {
    image_free_anims(ima);

    for (int i = 0; i < tot_viewfiles; i++) {
      /* allocate the ImageAnim */
      ImageAnim *ia = MEM_cnew<ImageAnim>("Image Anim");
      BLI_addtail(&ima->anims, ia);
    }
  }

  if (!is_multiview) {
    ibuf = load_movie_single(ima, iuser, frame, 0);
    image_assign_ibuf(ima, ibuf, 0, frame);
  }
  else {
    const int totviews = BLI_listbase_count(&ima->views);
    Array<ImBuf *> ibuf_arr(totviews);

    for (int i = 0; i < tot_viewfiles; i++) {
      ibuf_arr[i] = load_movie_single(ima, iuser, frame, i);
    }

    if (BKE_image_is_stereo(ima) && ima->views_format == R_IMF_VIEWS_STEREO_3D) {
      IMB_ImBufFromStereo3d(ima->stereo3d_format, ibuf_arr[0], ibuf_arr.data(), &ibuf_arr[1]);
    }

    for (int i = 0; i < totviews; i++) {
      image_assign_ibuf(ima, ibuf_arr[i], i, frame);
    }

    /* return the original requested ImBuf */
    ibuf = ibuf_arr[(iuser ? iuser->multi_index : 0)];

    /* "remove" the others (decrease their refcount) */
    for (int i = 0; i < totviews; i++) {
      if (ibuf_arr[i] != ibuf) {
        IMB_freeImBuf(ibuf_arr[i]);
      }
    }
  }

  return ibuf;
}

static ImBuf *load_image_single(Image *ima,
                                ImageUser *iuser,
                                int cfra,
                                const int view_id,
                                const bool has_packed,
                                const bool is_sequence,
                                bool *r_cache_ibuf)
{
  char filepath[FILE_MAX];
  struct ImBuf *ibuf = nullptr;
  int flag = IB_rect | IB_multilayer;

  *r_cache_ibuf = true;
  const int tile_number = image_get_tile_number_from_iuser(ima, iuser);

  /* is there a PackedFile with this image ? */
  if (has_packed && !is_sequence) {
    flag |= imbuf_alpha_flags_for_image(ima);

    LISTBASE_FOREACH (ImagePackedFile *, imapf, &ima->packedfiles) {
      if (imapf->view == view_id && imapf->tile_number == tile_number) {
        if (imapf->packedfile) {
          ibuf = IMB_ibImageFromMemory((uchar *)imapf->packedfile->data,
                                       imapf->packedfile->size,
                                       flag,
                                       ima->colorspace_settings.name,
                                       "<packed data>");
        }
        break;
      }
    }
  }
  else {
    if (is_sequence) {
      ima->lastframe = cfra;
    }

    /* get the correct filepath */
    const bool is_tiled = (ima->source == IMA_SRC_TILED);
    if (!(is_sequence || is_tiled)) {
      BKE_image_user_frame_calc(ima, iuser, cfra);
    }

    ImageUser iuser_t{};
    if (iuser) {
      iuser_t = *iuser;
    }
    else {
      iuser_t.framenr = ima->lastframe;
    }

    iuser_t.view = view_id;

    BKE_image_user_file_path(&iuser_t, ima, filepath);

    /* read ibuf */
    flag |= IB_metadata;
    flag |= imbuf_alpha_flags_for_image(ima);
    ibuf = IMB_loadiffname(filepath, flag, ima->colorspace_settings.name);
  }

  if (ibuf) {
#ifdef WITH_OPENEXR
    if (ibuf->ftype == IMB_FTYPE_OPENEXR && ibuf->userdata) {
      /* Handle multilayer and multiview cases, don't assign ibuf here.
       * will be set layer in BKE_image_acquire_ibuf from ima->rr. */
      if (IMB_exr_has_multilayer(ibuf->userdata)) {
        image_create_multilayer(ima, ibuf, cfra);
        ima->type = IMA_TYPE_MULTILAYER;
        IMB_freeImBuf(ibuf);
        ibuf = nullptr;
        /* Null ibuf in the cache means the image failed to load. However for multilayer we load
         * pixels into RenderResult instead and intentionally leave ibuf null. */
        *r_cache_ibuf = false;
      }
    }
    else
#endif
    {
      image_init_after_load(ima, iuser, ibuf);

      /* Make packed file for auto-pack. */
      if (!is_sequence && (has_packed == false) && (G.fileflags & G_FILE_AUTOPACK)) {
        ImagePackedFile *imapf = static_cast<ImagePackedFile *>(
            MEM_mallocN(sizeof(ImagePackedFile), "Image Pack-file"));
        BLI_addtail(&ima->packedfiles, imapf);

        STRNCPY(imapf->filepath, filepath);
        imapf->view = view_id;
        imapf->tile_number = tile_number;
        imapf->packedfile = BKE_packedfile_new(
            nullptr, filepath, ID_BLEND_PATH_FROM_GLOBAL(&ima->id));
      }
    }
  }

  return ibuf;
}

/* warning, 'iuser' can be null
 * NOTE: Image->views was already populated (in image_update_views_format)
 */
static ImBuf *image_load_image_file(
    Image *ima, ImageUser *iuser, int entry, int cfra, bool is_sequence)
{
  struct ImBuf *ibuf = nullptr;
  const bool is_multiview = BKE_image_is_multiview(ima);
  const bool is_tiled = (ima->source == IMA_SRC_TILED);
  const int tot_viewfiles = image_num_viewfiles(ima);
  bool has_packed = BKE_image_has_packedfile(ima);

  if (!(is_sequence || is_tiled)) {
    /* ensure clean ima */
    BKE_image_free_buffers(ima);
  }

  /* this should never happen, but just playing safe */
  if (!is_sequence && has_packed) {
    const int totfiles = tot_viewfiles * BLI_listbase_count(&ima->tiles);
    if (totfiles != BLI_listbase_count_at_most(&ima->packedfiles, totfiles + 1)) {
      image_free_packedfiles(ima);
      has_packed = false;
    }
  }

  if (!is_multiview) {
    bool put_in_cache;
    ibuf = load_image_single(ima, iuser, cfra, 0, has_packed, is_sequence, &put_in_cache);
    if (put_in_cache) {
      const int index = (is_sequence || is_tiled) ? 0 : IMA_NO_INDEX;
      image_assign_ibuf(ima, ibuf, index, entry);
    }
  }
  else {
    const int totviews = BLI_listbase_count(&ima->views);
    BLI_assert(totviews > 0);

    Array<ImBuf *> ibuf_arr(totviews);
    Array<bool> cache_ibuf_arr(totviews);

    for (int i = 0; i < tot_viewfiles; i++) {
      ibuf_arr[i] = load_image_single(
          ima, iuser, cfra, i, has_packed, is_sequence, &cache_ibuf_arr[i]);
    }

    /* multi-views/multi-layers OpenEXR files directly populate ima, and return null ibuf... */
    if (BKE_image_is_stereo(ima) && ima->views_format == R_IMF_VIEWS_STEREO_3D && ibuf_arr[0] &&
        tot_viewfiles == 1 && totviews >= 2) {
      IMB_ImBufFromStereo3d(ima->stereo3d_format, ibuf_arr[0], ibuf_arr.data(), &ibuf_arr[1]);
    }

    /* return the original requested ImBuf */
    const int ibuf_index = (iuser && iuser->multi_index < totviews) ? iuser->multi_index : 0;
    ibuf = ibuf_arr[ibuf_index];

    for (int i = 0; i < totviews; i++) {
      if (cache_ibuf_arr[i]) {
        image_assign_ibuf(ima, ibuf_arr[i], i, entry);
      }
    }

    /* "remove" the others (decrease their refcount) */
    for (int i = 0; i < totviews; i++) {
      if (ibuf_arr[i] != ibuf) {
        IMB_freeImBuf(ibuf_arr[i]);
      }
    }
  }

  return ibuf;
}

static ImBuf *image_get_ibuf_multilayer(Image *ima, ImageUser *iuser)
{
  ImBuf *ibuf = nullptr;

  if (ima->rr == nullptr) {
    ibuf = image_load_image_file(ima, iuser, 0, 0, false);
    if (ibuf) { /* actually an error */
      ima->type = IMA_TYPE_IMAGE;
      return ibuf;
    }
  }
  if (ima->rr) {
    RenderPass *rpass = BKE_image_multilayer_index(ima->rr, iuser);

    if (rpass) {
      ibuf = IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0);

      image_init_after_load(ima, iuser, ibuf);

      ibuf->rect_float = rpass->rect;
      ibuf->flags |= IB_rectfloat;
      ibuf->channels = rpass->channels;

      BKE_imbuf_stamp_info(ima->rr, ibuf);

      image_assign_ibuf(ima, ibuf, iuser ? iuser->multi_index : IMA_NO_INDEX, 0);
    }
  }

  return ibuf;
}

/* showing RGBA result itself (from compo/sequence) or
 * like exr, using layers etc */
/* always returns a single ibuf, also during render progress */
static ImBuf *image_get_render_result(Image *ima, ImageUser *iuser, void **r_lock)
{
  Render *re;
  RenderView *rv;
  float *rectf, *rectz;
  uint *rect;
  float dither;
  int channels, layer, pass;
  ImBuf *ibuf;
  int from_render = (ima->render_slot == ima->last_render_slot);
  int actview;

  if (!(iuser && iuser->scene)) {
    return nullptr;
  }

  /* if we the caller is not going to release the lock, don't give the image */
  if (!r_lock) {
    return nullptr;
  }

  re = RE_GetSceneRender(iuser->scene);

  channels = 4;
  layer = iuser->layer;
  pass = iuser->pass;
  actview = iuser->view;

  if (BKE_image_is_stereo(ima) && (iuser->flag & IMA_SHOW_STEREO)) {
    actview = iuser->multiview_eye;
  }

  RenderResult rres{};
  RenderSlot *slot;
  if (from_render) {
    RE_AcquireResultImage(re, &rres, actview);
  }
  else if ((slot = BKE_image_get_renderslot(ima, ima->render_slot))->render) {
    rres = *(slot->render);
    rres.have_combined = ((RenderView *)rres.views.first)->rectf != nullptr;
  }

  if (!(rres.rectx > 0 && rres.recty > 0)) {
    if (from_render) {
      RE_ReleaseResultImage(re);
    }
    return nullptr;
  }

  /* release is done in BKE_image_release_ibuf using r_lock */
  if (from_render) {
    BLI_thread_lock(LOCK_VIEWER);
    *r_lock = re;
    rv = nullptr;
  }
  else {
    rv = static_cast<RenderView *>(BLI_findlink(&rres.views, actview));
    if (rv == nullptr) {
      rv = static_cast<RenderView *>(rres.views.first);
    }
  }

  /* this gives active layer, composite or sequence result */
  if (rv == nullptr) {
    rect = (uint *)rres.rect32;
    rectf = rres.rectf;
    rectz = rres.rectz;
  }
  else {
    rect = (uint *)rv->rect32;
    rectf = rv->rectf;
    rectz = rv->rectz;
  }

  dither = iuser->scene->r.dither_intensity;

  /* combined layer gets added as first layer */
  if (rres.have_combined && layer == 0) {
    /* pass */
  }
  else if (rect && layer == 0) {
    /* rect32 is set when there's a Sequence pass, this pass seems
     * to have layer=0 (this is from image_buttons.c)
     * in this case we ignore float buffer, because it could have
     * hung from previous pass which was float
     */
    rectf = nullptr;
  }
  else if (rres.layers.first) {
    RenderLayer *rl = static_cast<RenderLayer *>(
        BLI_findlink(&rres.layers, layer - (rres.have_combined ? 1 : 0)));
    if (rl) {
      RenderPass *rpass = image_render_pass_get(rl, pass, actview, nullptr);
      if (rpass) {
        rectf = rpass->rect;
        if (pass != 0) {
          channels = rpass->channels;
          dither = 0.0f; /* don't dither passes */
        }
      }

      for (rpass = static_cast<RenderPass *>(rl->passes.first); rpass; rpass = rpass->next) {
        if (STREQ(rpass->name, RE_PASSNAME_Z) && rpass->view_id == actview) {
          rectz = rpass->rect;
        }
      }
    }
  }

  ibuf = image_get_cached_ibuf_for_index_entry(ima, IMA_NO_INDEX, 0, nullptr);

  /* make ibuf if needed, and initialize it */
  if (ibuf == nullptr) {
    ibuf = IMB_allocImBuf(rres.rectx, rres.recty, 32, 0);
    image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
  }

  /* Set color space settings for a byte buffer.
   *
   * This is mainly to make it so color management treats byte buffer
   * from render result with Save Buffers enabled as final display buffer
   * and doesn't apply any color management on it.
   *
   * For other cases we need to be sure it stays to default byte buffer space.
   */
  if (ibuf->rect != rect) {
    const char *colorspace = IMB_colormanagement_role_colorspace_name_get(COLOR_ROLE_DEFAULT_BYTE);
    IMB_colormanagement_assign_rect_colorspace(ibuf, colorspace);
  }

  /* invalidate color managed buffers if render result changed */
  BLI_thread_lock(LOCK_COLORMANAGE);
  if (ibuf->x != rres.rectx || ibuf->y != rres.recty || ibuf->rect_float != rectf) {
    ibuf->userflags |= IB_DISPLAY_BUFFER_INVALID;
  }

  ibuf->x = rres.rectx;
  ibuf->y = rres.recty;

  if (rect) {
    imb_freerectImBuf(ibuf);
    ibuf->rect = rect;
  }
  else {
    /* byte buffer of render result has been freed, make sure image buffers
     * does not reference to this buffer anymore
     * need check for whether byte buffer was allocated and owned by image itself
     * or if it's reusing buffer from render result
     */
    if ((ibuf->mall & IB_rect) == 0) {
      ibuf->rect = nullptr;
    }
  }

  if (rectf) {
    ibuf->rect_float = rectf;
    ibuf->flags |= IB_rectfloat;
    ibuf->channels = channels;
  }
  else {
    ibuf->rect_float = nullptr;
    ibuf->flags &= ~IB_rectfloat;
  }

  if (rectz) {
    ibuf->zbuf_float = rectz;
    ibuf->flags |= IB_zbuffloat;
  }
  else {
    ibuf->zbuf_float = nullptr;
    ibuf->flags &= ~IB_zbuffloat;
  }

  /* TODO(sergey): Make this faster by either simply referencing the stamp
   * or by changing both ImBug and RenderResult to use same data type to
   * store metadata. */
  if (ibuf->metadata != nullptr) {
    IMB_metadata_free(ibuf->metadata);
    ibuf->metadata = nullptr;
  }
  BKE_imbuf_stamp_info(&rres, ibuf);

  BLI_thread_unlock(LOCK_COLORMANAGE);

  ibuf->dither = dither;

  return ibuf;
}

static int image_get_multiview_index(Image *ima, ImageUser *iuser)
{
  const bool is_multilayer = BKE_image_is_multilayer(ima);
  const bool is_backdrop = (ima->source == IMA_SRC_VIEWER) && (ima->type == IMA_TYPE_COMPOSITE) &&
                           (iuser == nullptr);
  int index = BKE_image_has_multiple_ibufs(ima) ? 0 : IMA_NO_INDEX;

  if (is_multilayer) {
    return iuser ? iuser->multi_index : index;
  }
  if (is_backdrop) {
    if (BKE_image_is_stereo(ima)) {
      /* Backdrop hack / workaround (since there is no `iuser`). */
      return ima->eye;
    }
  }
  else if (BKE_image_is_multiview(ima)) {
    return iuser ? iuser->multi_index : index;
  }

  return index;
}

static void image_get_entry_and_index(Image *ima, ImageUser *iuser, int *r_entry, int *r_index)
{
  int frame = 0, index = image_get_multiview_index(ima, iuser);

  /* see if we already have an appropriate ibuf, with image source and type */
  if (ima->source == IMA_SRC_MOVIE) {
    frame = iuser ? iuser->framenr : ima->lastframe;
  }
  else if (ima->source == IMA_SRC_SEQUENCE) {
    if (ima->type == IMA_TYPE_IMAGE) {
      frame = iuser ? iuser->framenr : ima->lastframe;
    }
    else if (ima->type == IMA_TYPE_MULTILAYER) {
      frame = iuser ? iuser->framenr : ima->lastframe;
    }
  }
  else if (ima->source == IMA_SRC_TILED) {
    frame = image_get_tile_number_from_iuser(ima, iuser);
  }

  *r_entry = frame;
  *r_index = index;
}

/* Get the ibuf from an image cache for a given image user.
 *
 * Returns referenced image buffer if it exists, callee is to
 * call IMB_freeImBuf to de-reference the image buffer after
 * it's done handling it.
 */
static ImBuf *image_get_cached_ibuf(
    Image *ima, ImageUser *iuser, int *r_entry, int *r_index, bool *r_is_cached_empty)
{
  ImBuf *ibuf = nullptr;
  int entry = 0, index = image_get_multiview_index(ima, iuser);

  /* see if we already have an appropriate ibuf, with image source and type */
  if (ima->source == IMA_SRC_MOVIE) {
    entry = iuser ? iuser->framenr : ima->lastframe;
    ibuf = image_get_cached_ibuf_for_index_entry(ima, index, entry, r_is_cached_empty);
    ima->lastframe = entry;
  }
  else if (ima->source == IMA_SRC_SEQUENCE) {
    if (ima->type == IMA_TYPE_IMAGE) {
      entry = iuser ? iuser->framenr : ima->lastframe;
      ibuf = image_get_cached_ibuf_for_index_entry(ima, index, entry, r_is_cached_empty);
      ima->lastframe = entry;
    }
    else if (ima->type == IMA_TYPE_MULTILAYER) {
      entry = iuser ? iuser->framenr : ima->lastframe;
      ibuf = image_get_cached_ibuf_for_index_entry(ima, index, entry, r_is_cached_empty);
    }
  }
  else if (ima->source == IMA_SRC_FILE) {
    if (ima->type == IMA_TYPE_IMAGE) {
      ibuf = image_get_cached_ibuf_for_index_entry(ima, index, 0, r_is_cached_empty);
    }
    else if (ima->type == IMA_TYPE_MULTILAYER) {
      ibuf = image_get_cached_ibuf_for_index_entry(ima, index, 0, r_is_cached_empty);
    }
  }
  else if (ima->source == IMA_SRC_GENERATED) {
    ibuf = image_get_cached_ibuf_for_index_entry(ima, index, 0, r_is_cached_empty);
  }
  else if (ima->source == IMA_SRC_VIEWER) {
    /* always verify entirely, not that this shouldn't happen
     * as part of texture sampling in rendering anyway, so not
     * a big bottleneck */
  }
  else if (ima->source == IMA_SRC_TILED) {
    if (ELEM(ima->type, IMA_TYPE_IMAGE, IMA_TYPE_MULTILAYER)) {
      entry = image_get_tile_number_from_iuser(ima, iuser);
      ibuf = image_get_cached_ibuf_for_index_entry(ima, index, entry, r_is_cached_empty);
    }
  }

  if (r_entry) {
    *r_entry = entry;
  }

  if (r_index) {
    *r_index = index;
  }

  return ibuf;
}

BLI_INLINE bool image_quick_test(Image *ima, const ImageUser *iuser)
{
  if (ima == nullptr) {
    return false;
  }

  ImageTile *tile = BKE_image_get_tile_from_iuser(ima, iuser);
  if (tile == nullptr) {
    return false;
  }

  return true;
}

/**
 * Checks optional #ImageUser and verifies/creates #ImBuf.
 *
 * \warning Not thread-safe, so callee should worry about thread locks.
 */
static ImBuf *image_acquire_ibuf(Image *ima, ImageUser *iuser, void **r_lock)
{
  ImBuf *ibuf = nullptr;
  int entry = 0, index = 0;

  if (r_lock) {
    *r_lock = nullptr;
  }

  /* quick reject tests */
  if (!image_quick_test(ima, iuser)) {
    return nullptr;
  }

  bool is_cached_empty = false;
  ibuf = image_get_cached_ibuf(ima, iuser, &entry, &index, &is_cached_empty);
  if (is_cached_empty) {
    return nullptr;
  }

  if (ibuf == nullptr) {
    /* We are sure we have to load the ibuf, using source and type. */
    if (ima->source == IMA_SRC_MOVIE) {
      /* Source is from single file, use flip-book to store ibuf. */
      ibuf = image_load_movie_file(ima, iuser, entry);
    }
    else if (ima->source == IMA_SRC_SEQUENCE) {
      if (ima->type == IMA_TYPE_IMAGE) {
        /* Regular files, ibufs in flip-book, allows saving. */
        ibuf = image_load_image_file(ima, iuser, entry, entry, true);
      }
      /* no else; on load the ima type can change */
      if (ima->type == IMA_TYPE_MULTILAYER) {
        /* Only 1 layer/pass stored in imbufs, no EXR-handle anim storage, no saving. */
        ibuf = image_load_sequence_multilayer(ima, iuser, entry, entry);
      }
    }
    else if (ima->source == IMA_SRC_TILED) {
      /* Nothing was cached. Check to see if the tile should be generated. */
      ImageTile *tile = BKE_image_get_tile(ima, entry);
      if ((tile->gen_flag & IMA_GEN_TILE) != 0) {
        ibuf = add_ibuf_for_tile(ima, tile);
        image_assign_ibuf(ima, ibuf, 0, entry);
      }
      else {
        if (ima->type == IMA_TYPE_IMAGE) {
          /* Regular files, ibufs in flip-book, allows saving */
          ibuf = image_load_image_file(ima, iuser, entry, 0, false);
        }
        /* no else; on load the ima type can change */
        if (ima->type == IMA_TYPE_MULTILAYER) {
          /* Only 1 layer/pass stored in imbufs, no EXR-handle anim storage, no saving. */
          ibuf = image_load_sequence_multilayer(ima, iuser, entry, 0);
        }
      }
    }
    else if (ima->source == IMA_SRC_FILE) {

      if (ima->type == IMA_TYPE_IMAGE) {
        ibuf = image_load_image_file(
            ima, iuser, 0, entry, false); /* cfra only for '#', this global is OK */
      }
      /* no else; on load the ima type can change */
      if (ima->type == IMA_TYPE_MULTILAYER) {
        /* keeps render result, stores ibufs in listbase, allows saving */
        ibuf = image_get_ibuf_multilayer(ima, iuser);
      }
    }
    else if (ima->source == IMA_SRC_GENERATED) {
      /* Generated is: `ibuf` is allocated dynamically. */
      /* UV test-grid or black or solid etc. */
      ImageTile *base_tile = BKE_image_get_tile(ima, 0);
      if (base_tile->gen_x == 0) {
        base_tile->gen_x = 1024;
      }
      if (base_tile->gen_y == 0) {
        base_tile->gen_y = 1024;
      }
      if (base_tile->gen_depth == 0) {
        base_tile->gen_depth = 24;
      }
      ibuf = add_ibuf_for_tile(ima, base_tile);
      image_assign_ibuf(ima, ibuf, index, 0);
    }
    else if (ima->source == IMA_SRC_VIEWER) {
      if (ima->type == IMA_TYPE_R_RESULT) {
        /* always verify entirely, and potentially
         * returns pointer to release later */
        ibuf = image_get_render_result(ima, iuser, r_lock);
      }
      else if (ima->type == IMA_TYPE_COMPOSITE) {
        /* requires lock/unlock, otherwise don't return image */
        if (r_lock) {
          /* unlock in BKE_image_release_ibuf */
          BLI_thread_lock(LOCK_VIEWER);
          *r_lock = ima;

          /* XXX anim play for viewer nodes not yet supported */
          entry = 0;  // XXX iuser ? iuser->framenr : 0;
          ibuf = image_get_cached_ibuf_for_index_entry(ima, index, entry, nullptr);

          if (!ibuf) {
            /* Composite Viewer, all handled in compositor */
            /* fake ibuf, will be filled in compositor */
            ibuf = IMB_allocImBuf(256, 256, 32, IB_rect | IB_rectfloat);
            image_assign_ibuf(ima, ibuf, index, entry);
          }
        }
      }
    }

    /* We only want movies and sequences to be memory limited. */
    if (ibuf != nullptr && !ELEM(ima->source, IMA_SRC_MOVIE, IMA_SRC_SEQUENCE)) {
      ibuf->userflags |= IB_PERSISTENT;
    }
  }

  BKE_image_tag_time(ima);

  return ibuf;
}

ImBuf *BKE_image_acquire_ibuf(Image *ima, ImageUser *iuser, void **r_lock)
{
  /* NOTE: same as #image_acquire_ibuf, but can be used to retrieve images being rendered in
   * a thread safe way, always call both acquire and release. */

  if (ima == nullptr) {
    return nullptr;
  }

  ImBuf *ibuf;

  BLI_mutex_lock(static_cast<ThreadMutex *>(ima->runtime.cache_mutex));

  ibuf = image_acquire_ibuf(ima, iuser, r_lock);

  BLI_mutex_unlock(static_cast<ThreadMutex *>(ima->runtime.cache_mutex));

  return ibuf;
}

void BKE_image_release_ibuf(Image *ima, ImBuf *ibuf, void *lock)
{
  if (lock != nullptr) {
    /* for getting image during threaded render / compositing, need to release */
    if (lock == ima) {
      BLI_thread_unlock(LOCK_VIEWER); /* viewer image */
    }
    else {
      RE_ReleaseResultImage(static_cast<Render *>(lock)); /* render result */
      BLI_thread_unlock(LOCK_VIEWER);                     /* view image imbuf */
    }
  }

  if (ibuf) {
    BLI_mutex_lock(static_cast<ThreadMutex *>(ima->runtime.cache_mutex));
    IMB_freeImBuf(ibuf);
    BLI_mutex_unlock(static_cast<ThreadMutex *>(ima->runtime.cache_mutex));
  }
}

bool BKE_image_has_ibuf(Image *ima, ImageUser *iuser)
{
  ImBuf *ibuf;

  /* quick reject tests */
  if (!image_quick_test(ima, iuser)) {
    return false;
  }

  BLI_mutex_lock(static_cast<ThreadMutex *>(ima->runtime.cache_mutex));

  ibuf = image_get_cached_ibuf(ima, iuser, nullptr, nullptr, nullptr);

  if (!ibuf) {
    ibuf = image_acquire_ibuf(ima, iuser, nullptr);
  }

  BLI_mutex_unlock(static_cast<ThreadMutex *>(ima->runtime.cache_mutex));

  IMB_freeImBuf(ibuf);

  return ibuf != nullptr;
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Pool for Image Buffers
 * \{ */

struct ImagePoolItem {
  struct ImagePoolItem *next, *prev;
  Image *image;
  ImBuf *ibuf;
  int index;
  int entry;
};

struct ImagePool {
  ListBase image_buffers;
  BLI_mempool *memory_pool;
  ThreadMutex mutex;
};

ImagePool *BKE_image_pool_new(void)
{
  ImagePool *pool = MEM_cnew<ImagePool>("Image Pool");
  pool->memory_pool = BLI_mempool_create(sizeof(ImagePoolItem), 0, 128, BLI_MEMPOOL_NOP);

  BLI_mutex_init(&pool->mutex);

  return pool;
}

void BKE_image_pool_free(ImagePool *pool)
{
  /* Use single lock to dereference all the image buffers. */
  BLI_mutex_lock(&pool->mutex);
  for (ImagePoolItem *item = static_cast<ImagePoolItem *>(pool->image_buffers.first);
       item != nullptr;
       item = item->next) {
    if (item->ibuf != nullptr) {
      BLI_mutex_lock(static_cast<ThreadMutex *>(item->image->runtime.cache_mutex));
      IMB_freeImBuf(item->ibuf);
      BLI_mutex_unlock(static_cast<ThreadMutex *>(item->image->runtime.cache_mutex));
    }
  }
  BLI_mutex_unlock(&pool->mutex);

  BLI_mempool_destroy(pool->memory_pool);

  BLI_mutex_end(&pool->mutex);

  MEM_freeN(pool);
}

BLI_INLINE ImBuf *image_pool_find_item(
    ImagePool *pool, Image *image, int entry, int index, bool *found)
{
  ImagePoolItem *item;

  *found = false;

  for (item = static_cast<ImagePoolItem *>(pool->image_buffers.first); item; item = item->next) {
    if (item->image == image && item->entry == entry && item->index == index) {
      *found = true;
      return item->ibuf;
    }
  }

  return nullptr;
}

ImBuf *BKE_image_pool_acquire_ibuf(Image *ima, ImageUser *iuser, ImagePool *pool)
{
  ImBuf *ibuf;
  int index, entry;
  bool found;

  if (!image_quick_test(ima, iuser)) {
    return nullptr;
  }

  if (pool == nullptr) {
    /* Pool could be null, in this case use general acquire function. */
    return BKE_image_acquire_ibuf(ima, iuser, nullptr);
  }

  image_get_entry_and_index(ima, iuser, &entry, &index);

  /* Use double-checked locking, to avoid locking when the requested image buffer is already in the
   * pool. */

  ibuf = image_pool_find_item(pool, ima, entry, index, &found);
  if (found) {
    return ibuf;
  }

  /* Lock the pool, to allow thread-safe modification of the content of the pool. */
  BLI_mutex_lock(&pool->mutex);

  ibuf = image_pool_find_item(pool, ima, entry, index, &found);

  /* Will also create item even in cases image buffer failed to load,
   * prevents trying to load the same buggy file multiple times. */
  if (!found) {
    ImagePoolItem *item;

    /* Thread-safe acquisition of an image buffer from the image.
     * The acquisition does not use image pools, so there is no risk of recursive or out-of-order
     * mutex locking. */
    ibuf = BKE_image_acquire_ibuf(ima, iuser, nullptr);

    item = static_cast<ImagePoolItem *>(BLI_mempool_alloc(pool->memory_pool));
    item->image = ima;
    item->entry = entry;
    item->index = index;
    item->ibuf = ibuf;

    BLI_addtail(&pool->image_buffers, item);
  }

  BLI_mutex_unlock(&pool->mutex);

  return ibuf;
}

void BKE_image_pool_release_ibuf(Image *ima, ImBuf *ibuf, ImagePool *pool)
{
  /* if pool wasn't actually used, use general release stuff,
   * for pools image buffers will be dereferenced on pool free
   */
  if (pool == nullptr) {
    BKE_image_release_ibuf(ima, ibuf, nullptr);
  }
}

int BKE_image_user_frame_get(const ImageUser *iuser, int cfra, bool *r_is_in_range)
{
  const int len = iuser->frames;

  if (r_is_in_range) {
    *r_is_in_range = false;
  }

  if (len == 0) {
    return 0;
  }

  int framenr;
  cfra = cfra - iuser->sfra + 1;

  /* cyclic */
  if (iuser->cycl) {
    cfra = ((cfra) % len);
    if (cfra < 0) {
      cfra += len;
    }
    if (cfra == 0) {
      cfra = len;
    }

    if (r_is_in_range) {
      *r_is_in_range = true;
    }
  }

  if (cfra < 0) {
    cfra = 0;
  }
  else if (cfra > len) {
    cfra = len;
  }
  else {
    if (r_is_in_range) {
      *r_is_in_range = true;
    }
  }

  /* transform to images space */
  framenr = cfra;
  if (framenr > iuser->frames) {
    framenr = iuser->frames;
  }

  if (iuser->cycl) {
    framenr = ((framenr) % len);
    while (framenr < 0) {
      framenr += len;
    }
    if (framenr == 0) {
      framenr = len;
    }
  }

  /* important to apply after else we can't loop on frames 100 - 110 for eg. */
  framenr += iuser->offset;

  return framenr;
}

void BKE_image_user_frame_calc(Image *ima, ImageUser *iuser, int cfra)
{
  if (iuser) {
    if (ima && BKE_image_is_animated(ima)) {
      /* Compute current frame for animated image. */
      bool is_in_range;
      const int framenr = BKE_image_user_frame_get(iuser, cfra, &is_in_range);

      if (is_in_range) {
        iuser->flag |= IMA_USER_FRAME_IN_RANGE;
      }
      else {
        iuser->flag &= ~IMA_USER_FRAME_IN_RANGE;
      }

      iuser->framenr = framenr;
    }
    else {
      /* Set fixed frame number for still image. */
      iuser->framenr = 0;
      iuser->flag |= IMA_USER_FRAME_IN_RANGE;
    }

    if (ima && ima->gpuframenr != iuser->framenr) {
      /* NOTE: a single texture and refresh doesn't really work when
       * multiple image users may use different frames, this is to
       * be improved with perhaps a GPU texture cache. */
      BKE_image_partial_update_mark_full_update(ima);
      ima->gpuframenr = iuser->framenr;
    }

    iuser->flag &= ~IMA_NEED_FRAME_RECALC;
  }
}

/* goes over all ImageUsers, and sets frame numbers if auto-refresh is set */
static void image_editors_update_frame(Image *ima,
                                       ID * /*iuser_id*/,
                                       ImageUser *iuser,
                                       void *customdata)
{
  if (ima && BKE_image_is_animated(ima)) {
    if ((iuser->flag & IMA_ANIM_ALWAYS) || (iuser->flag & IMA_NEED_FRAME_RECALC)) {
      int cfra = *(int *)customdata;

      BKE_image_user_frame_calc(ima, iuser, cfra);
    }
  }
}

void BKE_image_editors_update_frame(const Main *bmain, int cfra)
{
  /* This only updates images used by the user interface. For others the
   * dependency graph will call BKE_image_user_id_eval_animation. */
  wmWindowManager *wm = static_cast<wmWindowManager *>(bmain->wm.first);
  image_walk_id_all_users(&wm->id, false, &cfra, image_editors_update_frame);
}

static void image_user_id_has_animation(Image *ima,
                                        ID * /*iuser_id*/,
                                        ImageUser * /*iuser*/,
                                        void *customdata)
{
  if (ima && BKE_image_is_animated(ima)) {
    *(bool *)customdata = true;
  }
}

bool BKE_image_user_id_has_animation(ID *id)
{
  /* For the dependency graph, this does not consider nested node
   * trees as these are handled as their own data-block. */
  bool has_animation = false;
  bool skip_nested_nodes = true;
  image_walk_id_all_users(id, skip_nested_nodes, &has_animation, image_user_id_has_animation);
  return has_animation;
}

static void image_user_id_eval_animation(Image *ima,
                                         ID * /*iduser_id*/,
                                         ImageUser *iuser,
                                         void *customdata)
{
  if (ima && BKE_image_is_animated(ima)) {
    Depsgraph *depsgraph = (Depsgraph *)customdata;

    if ((iuser->flag & IMA_ANIM_ALWAYS) || (iuser->flag & IMA_NEED_FRAME_RECALC) ||
        (DEG_get_mode(depsgraph) == DAG_EVAL_RENDER)) {
      float cfra = DEG_get_ctime(depsgraph);

      BKE_image_user_frame_calc(ima, iuser, cfra);
    }
  }
}

void BKE_image_user_id_eval_animation(Depsgraph *depsgraph, ID *id)
{
  /* This is called from the dependency graph to update the image
   * users in data-blocks. It computes the current frame number
   * and tags the image to be refreshed.
   * This does not consider nested node trees as these are handled
   * as their own data-block. */
  bool skip_nested_nodes = true;
  image_walk_id_all_users(id, skip_nested_nodes, depsgraph, image_user_id_eval_animation);
}

void BKE_image_user_file_path(const ImageUser *iuser, const Image *ima, char *filepath)
{
  BKE_image_user_file_path_ex(G_MAIN, iuser, ima, filepath, true, true);
}

void BKE_image_user_file_path_ex(const Main *bmain,
                                 const ImageUser *iuser,
                                 const Image *ima,
                                 char *filepath,
                                 const bool resolve_udim,
                                 const bool resolve_multiview)
{
  if (resolve_multiview && BKE_image_is_multiview(ima)) {
    ImageView *iv = static_cast<ImageView *>(BLI_findlink(&ima->views, iuser->view));
    if (iv->filepath[0]) {
      BLI_strncpy(filepath, iv->filepath, FILE_MAX);
    }
    else {
      BLI_strncpy(filepath, ima->filepath, FILE_MAX);
    }
  }
  else {
    BLI_strncpy(filepath, ima->filepath, FILE_MAX);
  }

  if (ELEM(ima->source, IMA_SRC_SEQUENCE, IMA_SRC_TILED)) {
    char head[FILE_MAX], tail[FILE_MAX];
    ushort numlen;

    int index;
    if (ima->source == IMA_SRC_SEQUENCE) {
      index = iuser ? iuser->framenr : ima->lastframe;
      BLI_path_sequence_decode(filepath, head, tail, &numlen);
      BLI_path_sequence_encode(filepath, head, tail, numlen, index);
    }
    else if (resolve_udim) {
      index = image_get_tile_number_from_iuser(ima, iuser);

      eUDIM_TILE_FORMAT tile_format;
      char *udim_pattern = BKE_image_get_tile_strformat(filepath, &tile_format);
      BKE_image_set_filepath_from_tile_number(filepath, udim_pattern, tile_format, index);
      MEM_SAFE_FREE(udim_pattern);
    }
  }

  BLI_path_abs(filepath, ID_BLEND_PATH(bmain, &ima->id));
}

bool BKE_image_has_alpha(Image *image)
{
  void *lock;
  ImBuf *ibuf = BKE_image_acquire_ibuf(image, nullptr, &lock);
  const int planes = (ibuf ? ibuf->planes : 0);
  BKE_image_release_ibuf(image, ibuf, lock);

  if (ELEM(planes, 32, 16)) {
    return true;
  }

  return false;
}

void BKE_image_get_size(Image *image, ImageUser *iuser, int *r_width, int *r_height)
{
  ImBuf *ibuf = nullptr;
  void *lock;

  if (image != nullptr) {
    ibuf = BKE_image_acquire_ibuf(image, iuser, &lock);
  }

  if (ibuf && ibuf->x > 0 && ibuf->y > 0) {
    *r_width = ibuf->x;
    *r_height = ibuf->y;
  }
  else if (image != nullptr && image->type == IMA_TYPE_R_RESULT && iuser != nullptr &&
           iuser->scene != nullptr) {
    BKE_render_resolution(&iuser->scene->r, true, r_width, r_height);
  }
  else {
    *r_width = IMG_SIZE_FALLBACK;
    *r_height = IMG_SIZE_FALLBACK;
  }

  if (image != nullptr) {
    BKE_image_release_ibuf(image, ibuf, lock);
  }
}

void BKE_image_get_size_fl(Image *image, ImageUser *iuser, float r_size[2])
{
  int width, height;
  BKE_image_get_size(image, iuser, &width, &height);

  r_size[0] = float(width);
  r_size[1] = float(height);
}

void BKE_image_get_aspect(Image *image, float *r_aspx, float *r_aspy)
{
  *r_aspx = 1.0;

  /* x is always 1 */
  if (image) {
    *r_aspy = image->aspy / image->aspx;
  }
  else {
    *r_aspy = 1.0f;
  }
}

uchar *BKE_image_get_pixels_for_frame(struct Image *image, int frame, int tile)
{
  ImageUser iuser;
  BKE_imageuser_default(&iuser);
  void *lock;
  ImBuf *ibuf;
  uchar *pixels = nullptr;

  iuser.framenr = frame;
  iuser.tile = tile;

  ibuf = BKE_image_acquire_ibuf(image, &iuser, &lock);

  if (ibuf) {
    pixels = (uchar *)ibuf->rect;

    if (pixels) {
      pixels = static_cast<uchar *>(MEM_dupallocN(pixels));
    }

    BKE_image_release_ibuf(image, ibuf, lock);
  }

  if (!pixels) {
    return nullptr;
  }

  return pixels;
}

float *BKE_image_get_float_pixels_for_frame(struct Image *image, int frame, int tile)
{
  ImageUser iuser;
  BKE_imageuser_default(&iuser);
  void *lock;
  ImBuf *ibuf;
  float *pixels = nullptr;

  iuser.framenr = frame;
  iuser.tile = tile;

  ibuf = BKE_image_acquire_ibuf(image, &iuser, &lock);

  if (ibuf) {
    pixels = ibuf->rect_float;

    if (pixels) {
      pixels = static_cast<float *>(MEM_dupallocN(pixels));
    }

    BKE_image_release_ibuf(image, ibuf, lock);
  }

  if (!pixels) {
    return nullptr;
  }

  return pixels;
}

int BKE_image_sequence_guess_offset(Image *image)
{
  return BLI_path_sequence_decode(image->filepath, nullptr, nullptr, nullptr);
}

bool BKE_image_has_anim(Image *ima)
{
  return (BLI_listbase_is_empty(&ima->anims) == false);
}

bool BKE_image_has_packedfile(const Image *ima)
{
  return (BLI_listbase_is_empty(&ima->packedfiles) == false);
}

bool BKE_image_has_filepath(const Image *ima)
{
  /* This could be improved to detect cases like //../../, currently path
   * remapping empty file paths empty. */
  return ima->filepath[0] != '\0';
}

bool BKE_image_is_animated(Image *image)
{
  return ELEM(image->source, IMA_SRC_MOVIE, IMA_SRC_SEQUENCE);
}

bool BKE_image_has_multiple_ibufs(Image *image)
{
  return ELEM(image->source, IMA_SRC_MOVIE, IMA_SRC_SEQUENCE, IMA_SRC_TILED);
}

bool BKE_image_is_dirty_writable(Image *image, bool *r_is_writable)
{
  bool is_dirty = false;
  bool is_writable = false;

  BLI_mutex_lock(static_cast<ThreadMutex *>(image->runtime.cache_mutex));
  if (image->cache != nullptr) {
    struct MovieCacheIter *iter = IMB_moviecacheIter_new(image->cache);

    while (!IMB_moviecacheIter_done(iter)) {
      ImBuf *ibuf = IMB_moviecacheIter_getImBuf(iter);
      if (ibuf != nullptr && ibuf->userflags & IB_BITMAPDIRTY) {
        is_writable = BKE_image_buffer_format_writable(ibuf);
        is_dirty = true;
        break;
      }
      IMB_moviecacheIter_step(iter);
    }
    IMB_moviecacheIter_free(iter);
  }
  BLI_mutex_unlock(static_cast<ThreadMutex *>(image->runtime.cache_mutex));

  if (r_is_writable) {
    *r_is_writable = is_writable;
  }

  return is_dirty;
}

bool BKE_image_is_dirty(Image *image)
{
  return BKE_image_is_dirty_writable(image, nullptr);
}

void BKE_image_mark_dirty(Image * /*image*/, ImBuf *ibuf)
{
  ibuf->userflags |= IB_BITMAPDIRTY;
}

bool BKE_image_buffer_format_writable(ImBuf *ibuf)
{
  ImageFormatData im_format;
  ImbFormatOptions options_dummy;
  BKE_image_format_from_imbuf(&im_format, ibuf);
  return (BKE_imtype_to_ftype(im_format.imtype, &options_dummy) == ibuf->ftype);
}

void BKE_image_file_format_set(Image *image, int ftype, const ImbFormatOptions *options)
{
  BLI_mutex_lock(static_cast<ThreadMutex *>(image->runtime.cache_mutex));
  if (image->cache != nullptr) {
    struct MovieCacheIter *iter = IMB_moviecacheIter_new(image->cache);

    while (!IMB_moviecacheIter_done(iter)) {
      ImBuf *ibuf = IMB_moviecacheIter_getImBuf(iter);
      if (ibuf != nullptr) {
        ibuf->ftype = static_cast<eImbFileType>(ftype);
        ibuf->foptions = *options;
      }
      IMB_moviecacheIter_step(iter);
    }
    IMB_moviecacheIter_free(iter);
  }
  BLI_mutex_unlock(static_cast<ThreadMutex *>(image->runtime.cache_mutex));
}

bool BKE_image_has_loaded_ibuf(Image *image)
{
  bool has_loaded_ibuf = false;

  BLI_mutex_lock(static_cast<ThreadMutex *>(image->runtime.cache_mutex));
  if (image->cache != nullptr) {
    struct MovieCacheIter *iter = IMB_moviecacheIter_new(image->cache);

    while (!IMB_moviecacheIter_done(iter)) {
      ImBuf *ibuf = IMB_moviecacheIter_getImBuf(iter);
      if (ibuf != nullptr) {
        has_loaded_ibuf = true;
        break;
      }
      IMB_moviecacheIter_step(iter);
    }
    IMB_moviecacheIter_free(iter);
  }
  BLI_mutex_unlock(static_cast<ThreadMutex *>(image->runtime.cache_mutex));

  return has_loaded_ibuf;
}

ImBuf *BKE_image_get_ibuf_with_name(Image *image, const char *name)
{
  ImBuf *ibuf = nullptr;

  BLI_mutex_lock(static_cast<ThreadMutex *>(image->runtime.cache_mutex));
  if (image->cache != nullptr) {
    struct MovieCacheIter *iter = IMB_moviecacheIter_new(image->cache);

    while (!IMB_moviecacheIter_done(iter)) {
      ImBuf *current_ibuf = IMB_moviecacheIter_getImBuf(iter);
      if (current_ibuf != nullptr && STREQ(current_ibuf->name, name)) {
        ibuf = current_ibuf;
        IMB_refImBuf(ibuf);
        break;
      }
      IMB_moviecacheIter_step(iter);
    }
    IMB_moviecacheIter_free(iter);
  }
  BLI_mutex_unlock(static_cast<ThreadMutex *>(image->runtime.cache_mutex));

  return ibuf;
}

ImBuf *BKE_image_get_first_ibuf(Image *image)
{
  ImBuf *ibuf = nullptr;

  BLI_mutex_lock(static_cast<ThreadMutex *>(image->runtime.cache_mutex));
  if (image->cache != nullptr) {
    struct MovieCacheIter *iter = IMB_moviecacheIter_new(image->cache);

    while (!IMB_moviecacheIter_done(iter)) {
      ibuf = IMB_moviecacheIter_getImBuf(iter);
      if (ibuf != nullptr) {
        IMB_refImBuf(ibuf);
      }
      break;
    }
    IMB_moviecacheIter_free(iter);
  }
  BLI_mutex_unlock(static_cast<ThreadMutex *>(image->runtime.cache_mutex));

  return ibuf;
}

static void image_update_views_format(Image *ima, ImageUser *iuser)
{
  SceneRenderView *srv;
  ImageView *iv;
  Scene *scene = iuser->scene;
  const bool is_multiview = ((scene->r.scemode & R_MULTIVIEW) != 0) &&
                            ((ima->flag & IMA_USE_VIEWS) != 0);

  /* reset the image views */
  BKE_image_free_views(ima);

  if (!is_multiview) {
    /* nothing to do */
  }
  else if (ima->views_format == R_IMF_VIEWS_STEREO_3D) {
    const char *names[2] = {STEREO_LEFT_NAME, STEREO_RIGHT_NAME};

    for (int i = 0; i < 2; i++) {
      image_add_view(ima, names[i], ima->filepath);
    }
    return;
  }
  else {
    /* R_IMF_VIEWS_INDIVIDUAL */
    char prefix[FILE_MAX] = {'\0'};
    char *name = ima->filepath;
    const char *ext = nullptr;

    BKE_scene_multiview_view_prefix_get(scene, name, prefix, &ext);

    if (prefix[0] == '\0') {
      BKE_image_free_views(ima);
      return;
    }

    /* create all the image views */
    for (srv = static_cast<SceneRenderView *>(scene->r.views.first); srv; srv = srv->next) {
      if (BKE_scene_multiview_is_render_view_active(&scene->r, srv)) {
        char filepath[FILE_MAX];
        SNPRINTF(filepath, "%s%s%s", prefix, srv->suffix, ext);
        image_add_view(ima, srv->name, filepath);
      }
    }

    /* check if the files are all available */
    iv = static_cast<ImageView *>(ima->views.last);
    while (iv) {
      int file;
      char str[FILE_MAX];

      STRNCPY(str, iv->filepath);
      BLI_path_abs(str, ID_BLEND_PATH_FROM_GLOBAL(&ima->id));

      /* exists? */
      file = BLI_open(str, O_BINARY | O_RDONLY, 0);
      if (file == -1) {
        ImageView *iv_del = iv;
        iv = iv->prev;
        BLI_remlink(&ima->views, iv_del);
        MEM_freeN(iv_del);
      }
      else {
        iv = iv->prev;
        close(file);
      }
    }

    /* all good */
    if (!BKE_image_is_multiview(ima)) {
      BKE_image_free_views(ima);
    }
  }
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Render Slots
 * \{ */

RenderSlot *BKE_image_add_renderslot(Image *ima, const char *name)
{
  RenderSlot *slot = MEM_cnew<RenderSlot>("Image new Render Slot");
  if (name && name[0]) {
    BLI_strncpy(slot->name, name, sizeof(slot->name));
  }
  else {
    int n = BLI_listbase_count(&ima->renderslots) + 1;
    BLI_snprintf(slot->name, sizeof(slot->name), DATA_("Slot %d"), n);
  }
  BLI_addtail(&ima->renderslots, slot);
  return slot;
}

bool BKE_image_remove_renderslot(Image *ima, ImageUser *iuser, int slot)
{
  if (slot == ima->last_render_slot) {
    /* Don't remove render slot while rendering to it. */
    if (G.is_rendering) {
      return false;
    }
  }

  int num_slots = BLI_listbase_count(&ima->renderslots);
  if (slot >= num_slots || num_slots == 1) {
    return false;
  }

  RenderSlot *remove_slot = static_cast<RenderSlot *>(BLI_findlink(&ima->renderslots, slot));
  RenderSlot *current_slot = static_cast<RenderSlot *>(
      BLI_findlink(&ima->renderslots, ima->render_slot));
  RenderSlot *current_last_slot = static_cast<RenderSlot *>(
      BLI_findlink(&ima->renderslots, ima->last_render_slot));

  RenderSlot *next_slot;
  if (current_slot == remove_slot) {
    next_slot = static_cast<RenderSlot *>(
        BLI_findlink(&ima->renderslots, (slot == num_slots - 1) ? slot - 1 : slot + 1));
  }
  else {
    next_slot = current_slot;
  }

  /* If the slot to be removed is the slot with the last render,
   * make another slot the last render slot. */
  if (remove_slot == current_last_slot) {
    /* Choose the currently selected slot unless that one is being removed,
     * in that case take the next one. */
    RenderSlot *next_last_slot;
    if (current_slot == remove_slot) {
      next_last_slot = next_slot;
    }
    else {
      next_last_slot = current_slot;
    }

    if (iuser == nullptr || iuser->scene == nullptr) {
      return false;
    }
    Render *re = RE_GetSceneRender(iuser->scene);
    if (re != nullptr) {
      RE_SwapResult(re, &current_last_slot->render);
      RE_SwapResult(re, &next_last_slot->render);
    }
    current_last_slot = next_last_slot;
  }

  current_slot = next_slot;

  BLI_remlink(&ima->renderslots, remove_slot);

  ima->render_slot = BLI_findindex(&ima->renderslots, current_slot);
  ima->last_render_slot = BLI_findindex(&ima->renderslots, current_last_slot);

  if (remove_slot->render) {
    RE_FreeRenderResult(remove_slot->render);
  }
  MEM_freeN(remove_slot);

  return true;
}

bool BKE_image_clear_renderslot(Image *ima, ImageUser *iuser, int slot)
{
  if (slot == ima->last_render_slot) {
    if (!iuser) {
      return false;
    }
    if (G.is_rendering) {
      return false;
    }
    Render *re = RE_GetSceneRender(iuser->scene);
    if (!re) {
      return false;
    }
    RE_ClearResult(re);
    return true;
  }

  RenderSlot *render_slot = static_cast<RenderSlot *>(BLI_findlink(&ima->renderslots, slot));
  if (!render_slot) {
    return false;
  }
  if (render_slot->render) {
    RE_FreeRenderResult(render_slot->render);
    render_slot->render = nullptr;
  }
  return true;
}

RenderSlot *BKE_image_get_renderslot(Image *ima, int index)
{
  /* Can be null for images without render slots. */
  return static_cast<RenderSlot *>(BLI_findlink(&ima->renderslots, index));
}

/** \} */