コミットを比較
| 作成者 | SHA1 | 日付 | |
|---|---|---|---|
|
|
96558947ed
|
||
|
|
d9fcd6fcfc
|
||
|
|
b3703e1afc
|
||
|
|
20e19a9d9f
|
||
|
|
64e5799493
|
||
|
|
87c861bc16
|
||
|
|
9e8fd2d897
|
||
|
|
50b21ccb01
|
||
|
|
8fe4a86246
|
||
|
|
cce60990e2
|
||
|
|
cf62a6ef5d
|
||
|
|
8d4f771f8d
|
||
|
|
dc2e015b1a
|
||
|
|
b0a0c5cc8f
|
||
|
|
40f1322042
|
||
|
|
d1b0439611
|
||
|
|
30d6f62d15
|
||
|
|
ac3a1e350e
|
||
|
|
0a7a2c7d40
|
||
|
|
1a97536bc5
|
||
|
|
8f954c7a2e
|
||
|
|
20509b19c9
|
||
|
|
e4bdf0df19
|
||
|
|
1f421dd158
|
||
|
|
e56a2d85d7
|
||
|
|
969cf52299
|
||
|
|
01785267fc
|
||
|
|
206001888c
|
||
|
|
7c8776dd05
|
||
|
|
d6756ad3c8
|
||
|
|
57c3b346d8
|
||
|
|
55dde273ae
|
||
|
|
a6a9963c85
|
||
|
|
fb7614d6fb
|
||
|
|
a7a8c6b117
|
||
|
|
8b59897992
|
||
|
|
0d8f1e5102
|
||
|
|
e6165ca5a3
|
||
|
|
2bd54674c1
|
||
|
|
9a733807e8
|
||
|
|
f14c689353
|
||
|
|
d4443a1eef
|
||
|
|
b618a3093b
|
||
|
|
a03ba45f2a
|
||
|
|
56c38b2891
|
||
|
|
68b730e6d2
|
||
|
|
ce7b15121c
|
||
|
|
50b20e3060
|
||
|
|
c1f4fa2dc5
|
||
|
|
af9c5af173
|
||
|
|
406a4c1a1b
|
||
|
|
b732dd1b90
|
||
|
|
1e93df21ef
|
||
|
|
3bd6133bef
|
||
|
|
0c05fe2198
|
||
|
|
775791d1e1
|
||
|
|
a291d66567
|
||
|
|
31d26c0a70
|
||
|
|
88b95cc09a
|
||
|
|
9ff328d03a
|
||
|
|
481bce261e
|
||
|
|
421acf1a6a
|
||
|
|
1d01e9d275
|
||
|
|
1a3394b8f5
|
||
|
|
52bbff8284
|
||
|
|
b150970f83
|
||
|
|
6ce23d486a
|
||
|
|
024723a029
|
||
|
|
4746f01134
|
||
|
|
f2ea36ba49
|
||
|
|
adf47608d2
|
||
|
|
f916c810dc
|
||
|
|
9b86a3cb10
|
||
|
|
0fd1194596
|
||
|
|
72aa5d7351
|
||
|
|
a68c0fedd6
|
||
|
|
c5ed30bc72
|
||
|
|
6f44e30fa1
|
||
|
|
3db40f07cb
|
||
|
|
ff8791d086
|
||
|
|
f7f445bd3d
|
||
|
|
68af14bbf8
|
||
|
|
7a23318be3
|
||
|
|
4072d9b117
|
||
|
|
bc366a0af2
|
||
|
|
0c896d44ee
|
||
|
|
9a9acc4b85
|
||
|
|
a7e2285691
|
||
|
|
093e16feec
|
||
|
|
70b1b79fc2
|
||
|
|
995e1bc1aa
|
||
|
|
1120373e67
|
||
|
|
43b3ed7077
|
||
|
|
04ab6b111b
|
||
|
|
5d6787e7d6
|
||
|
|
6960406965
|
||
|
|
9454310988
|
||
|
|
d3118d20af
|
||
|
|
78337c06dd
|
||
|
|
85fc0f8e9f
|
||
|
|
c19ae507cf
|
||
|
|
004041b342
|
||
|
|
08f69cf76d
|
||
|
|
e10bfbe406
|
||
|
|
1a46a76b59
|
||
|
|
e2f32a6722
|
||
|
|
5a23f4329e
|
||
|
|
f5fd6cebdb
|
||
|
|
48f6711f1a
|
||
|
|
859046f5aa
|
||
|
|
7c7a60807f
|
||
|
|
1b23b2937e
|
||
|
|
4135f52499
|
||
|
|
8fda0bfec5
|
||
|
|
7e353053c7
|
||
|
|
d744d218fb
|
||
|
|
772fa6b678
|
||
|
|
154bc6a5c0
|
||
|
|
593939c2d4
|
||
|
|
6730c8ce70
|
||
|
|
b6a1e6e43c
|
||
|
|
fd06fdafe7
|
||
|
|
20a119c6c8
|
||
|
|
cfa8141424
|
||
|
|
7a2a7e5593
|
||
|
|
1a61091ec2
|
||
|
|
bbb1bd3562
|
||
|
|
db8017a8ce
|
||
|
|
bc69ec5681
|
||
|
|
8f6c3105ef
|
||
|
|
de6c1b8b44
|
||
|
|
ffd57fabd0
|
||
|
|
a80d5dec88
|
||
|
|
8bccf5ed01
|
||
|
|
7c831441fc
|
||
|
|
7cd54ff3e8
|
||
|
|
3c3f5aed69
|
||
|
|
913e1a8643
|
||
|
|
f6c7dac970
|
||
|
|
95db23f253
|
||
|
|
62044a3351
|
||
|
|
694b50d375
|
||
|
|
122d85068d
|
||
|
|
620670915f
|
||
|
|
10974242aa
|
||
|
|
36b2ada16a
|
||
|
|
8428057eb4
|
||
|
|
1133daf764
|
||
|
|
b09070e8df
|
||
|
|
cde0b8f498
|
||
|
|
916dd278b2
|
||
|
|
d6d0792207
|
||
|
|
a7bae506a7
|
||
|
|
d05906de7b
|
||
|
|
a8300041e3
|
||
|
|
8bd0d2bc0e
|
||
|
|
cf5f4acf72
|
||
|
|
0d6709d518
|
||
|
|
12bd10164b
|
||
|
|
6287e74fe5
|
||
|
|
8956b7c8d5
|
||
|
|
60c6a37f89
|
||
|
|
9a9c2ec405
|
||
|
|
103b612082
|
||
|
|
9e1da1839e
|
||
|
|
c19e12aa87
|
||
|
|
ed4c38772f
|
||
|
|
d31fd77aee
|
||
|
|
eb0199131d
|
||
|
|
36935bdf1d
|
||
|
|
7d9a9f1cb8
|
||
|
|
3ce2483062
|
||
|
|
fc8a07f935
|
||
|
|
d1279c25fa
|
||
|
|
048c6d6707
|
||
|
|
3a29862423
|
||
|
|
8c69864456
|
||
|
|
8a7b328db4
|
||
|
|
8517bf5f50
|
||
|
|
b928101e3e
|
||
|
|
7fb671e8c6
|
||
|
|
20ff47edce
|
||
|
|
8f9b7c725f
|
||
|
|
499f8ba078
|
||
|
|
66f2d398b7
|
||
|
|
935bca6fbb
|
||
|
|
4c7ef12361
|
||
|
|
65e7864221
|
||
|
|
25430c4dcf
|
||
|
|
f0234d21e4
|
||
|
|
bfe23707f0
|
||
|
|
e74af227d8
|
||
|
|
2b5901379f
|
||
|
|
deb94b3f29
|
||
|
|
74a65b7a8b
|
||
|
|
a4cc0f3220
|
||
|
|
86f889cbd2
|
||
|
|
c2f48230f3
|
||
|
|
4153956b37
|
||
|
|
3763db1cfc
|
||
|
|
9bcab1ae28
|
||
|
|
6e13a4d1c2
|
||
|
|
8dc87d63be
|
||
|
|
0afb7afc21
|
||
|
|
2769a29808
|
||
|
|
1f21b4c49c
|
||
|
|
cafc6d6e48
|
||
|
|
49a2ce29b2
|
||
|
|
d728c8d056
|
||
|
|
b6eac20941
|
||
|
|
d8589007b3
|
||
|
|
85596f76f7
|
||
|
|
018999ff5e
|
||
|
|
c5da497bb3
|
||
|
|
f46cb08f85
|
||
|
|
b0a5293b89
|
||
|
|
67a1b4fa31
|
||
|
|
2d0fb2c47a
|
||
|
|
45d5164afa
|
||
|
|
ba20fc8187
|
||
|
|
669b24c2b3
|
||
|
|
91a3e3f762
|
||
|
|
722ae62326
|
||
|
|
fee1f293c7
|
||
|
|
b6764fe637
|
||
|
|
01e368207d
|
||
|
|
29ea2ea45c
|
||
|
|
1d60d8b245
|
||
|
|
8f2aafdffd
|
||
|
|
f26816343f
|
||
|
|
0cab8972e0
|
||
|
|
f2aa668cf6
|
||
|
|
ed27979f64
|
||
|
|
7b958ea171
|
||
|
|
332dab3889
|
||
|
|
75d457a7ab
|
||
|
|
50e1801878
|
||
|
|
793d010bdb
|
||
|
|
b564b0b185
|
||
|
|
6d83fe93d8
|
||
|
|
db9c3747ea
|
||
|
|
7d887afe5a
|
||
|
|
ac34830367
|
||
|
|
8ed188d0e2
|
||
|
|
9c55c08caf
|
||
|
|
42868023f3
|
||
|
|
e146b36fa0
|
||
|
|
5fac495848
|
||
|
|
4fd519249f
|
||
|
|
1b26df959f
|
||
|
|
3cd67212a1
|
||
|
|
46692dfe95
|
||
|
|
e8d9cef129
|
||
|
|
18036cd74e
|
||
|
|
c8f857d2b4
|
||
|
|
ac7f797566
|
||
|
|
8beae1a277
|
||
|
|
6eb4d7c9af
|
||
|
|
a843f460de
|
||
|
|
27f04c7560
|
||
|
|
43c0ce88b3
|
||
|
|
00f0d991c1
|
||
|
|
784d294ca6
|
||
|
|
260d427bcf
|
||
|
|
b62f4a3a7d
|
||
|
|
79a408cafd
|
||
|
|
807df7df8a
|
||
|
|
0c5e3066c1
|
||
|
|
fbaff95503
|
||
|
|
8dec38a911
|
||
|
|
902d729c19
|
||
|
|
79f8ff8839
|
||
|
|
9a630ecb5a
|
||
|
|
d9e6132a1f
|
||
|
|
e685e7aa40
|
||
|
|
bf49fe9984
|
||
|
|
c05a1479f9
|
||
|
|
80ddb663b0
|
||
|
|
2f1bbc3828
|
||
|
|
e911f6e83f
|
||
|
|
6162ce5c19
|
||
|
|
59dcb82b49
|
||
|
|
d37726cdf6
|
||
|
|
0c09cf4a51
|
||
|
|
0d4809924d
|
||
|
|
1e97e7d8fe
|
||
|
|
06cfefe1b4
|
||
|
|
37b1371f57
|
||
|
|
9db756c974
|
||
|
|
43f3161ebb
|
||
|
|
4b3b74edae
|
||
|
|
5129ece749
|
||
|
|
24ef4135cf
|
||
|
|
044fdbf1eb
|
||
|
|
9e1ad6c133
|
||
|
|
6d8def9f08
|
||
|
|
7a9f1ff6e8
|
||
|
|
82db144b86
|
||
|
|
d3fb73ed94
|
||
|
|
7dd777fbc6
|
||
|
|
aa17df08d8
|
||
|
|
e5c4485f16
|
||
|
|
9b901f91b6
|
||
|
|
2b24a407e6
|
||
|
|
150b4818d4
|
||
|
|
34b7d60ca6
|
||
|
|
7dc6083fd7
|
||
|
|
245fb9c323
|
||
|
|
42c3bc4f4b
|
||
|
|
d273f99593
|
||
|
|
e1763e0c81
|
||
|
|
7221ce3aca
|
||
|
|
5f3ad96ea2
|
||
|
|
4e0bf831c5
|
||
|
|
0fedfd5804
|
||
|
|
f11225e2a1
|
||
|
|
92e8c43160
|
||
|
|
5fb9eae7a0
|
||
|
|
f109232cae
|
||
|
|
1596a048cd
|
||
|
|
0b0c795d7a
|
||
|
|
2be3c3d28b
|
||
|
|
3f9e4ebca4
|
||
|
|
03042b17e7
|
||
|
|
5e6d74dfee
|
||
|
|
40d68416c2
|
||
|
|
de6472c34b
|
||
|
|
55c8bffb70
|
||
|
|
8ca66bceb8
|
||
|
|
865f5117ea
|
||
|
|
b30f7a818b
|
||
|
|
95786a1f0a
|
||
|
|
cc07e2a83d
|
||
|
|
08e5e432b7
|
||
|
|
1e9b039cef
|
||
|
|
bad39fe0db
|
||
|
|
a5567a804d
|
||
|
|
a9cb4a9cda
|
||
|
|
9e9b5277af
|
||
|
|
1d8705c7ee
|
||
|
|
14683c7909
|
||
|
|
42b123ebc3
|
||
|
|
b0114abdb7
|
||
|
|
c21de5b3eb
|
||
|
|
bd891d9a1e
|
||
|
|
d2bef10085
|
||
|
|
3eafcdc70e
|
||
|
|
6f26fc95fa
|
||
|
|
88ce786d05
|
||
|
|
d69ae5f06e
|
||
|
|
d42d8a6764
|
||
|
|
8f9ace2dc8
|
||
|
|
c416e955a4
|
||
|
|
7362e70ab8
|
||
|
|
c9741836a5
|
||
|
|
afd57d758d
|
||
|
|
c56432dbd6
|
||
|
|
9493aef779
|
||
|
|
5d55f2c083
|
||
|
|
09918c2858
|
||
|
|
a687bba0ff
|
||
|
|
bb591b6fef
|
||
|
|
27d7294290
|
||
|
|
8d1cf91499
|
||
|
|
b2a1900616
|
||
|
|
f786250866
|
||
|
|
20dfba6e7e
|
||
|
|
5e40f45910
|
||
|
|
ea4f096bc4
|
||
|
|
d7812f39dc
|
||
|
|
77fdf60ec9
|
||
|
|
bcb9925953
|
||
|
|
ec7d8a1da4
|
||
|
|
098d6e498b
|
||
|
|
ccf37dd1d3
|
||
|
|
2ce3068d54
|
||
|
|
c2a1990501
|
||
|
|
4ac25584b9
|
||
|
|
5e40f30124
|
||
|
|
9d541e06b9
|
||
|
|
bca7b5707e
|
||
|
|
a17289a2da
|
||
|
|
71e6b71056
|
||
|
|
13a0602adb
|
||
|
|
6a0c993755
|
||
|
|
484a26ec45
|
||
|
|
a121a598b6
|
||
|
|
6dd70413a9
|
||
|
|
ac482b6041
|
||
|
|
c2761c0796
|
||
|
|
3bbd411d86
|
||
|
|
324faabb96
|
||
|
|
32b706cb8b
|
||
|
|
aa97c52b38
|
||
|
|
a2f0231739
|
||
|
|
2905192d3a
|
||
|
|
ee6f6bd9c1
|
||
|
|
8853f5e403
|
||
|
|
867de7aa73
|
||
|
|
e384d7e490
|
||
|
|
87e060d71d
|
||
|
|
9c6167d224
|
||
|
|
a8a91103e1
|
||
|
|
4a2f4b2dbb
|
||
|
|
33fc45639b
|
||
|
|
7af803e46e
|
||
|
|
48e8287704
|
||
|
|
7eff4591f0
|
||
|
|
5b1bb4ad6e
|
||
|
|
7f3e6b0019
|
||
|
|
7519a11851
|
||
|
|
4193c40f41
|
||
|
|
cd68bf86b0
|
||
|
|
9948204265
|
||
|
|
25670bde90
|
||
|
|
ae230c0e10
|
||
|
|
7ee8f1ccf0
|
||
|
|
da88898a67
|
||
|
|
3c63ba0729
|
||
|
|
e7382ac289
|
||
|
|
ee7e4f43bc
|
||
|
|
7dc6e9fb40
|
||
|
|
803534d804
|
||
|
|
a25803fa30
|
||
|
|
e42401670f
|
||
|
|
a139326c39
|
||
|
|
496c237f50
|
||
|
|
dfbcbded98
|
||
|
|
2ebbe3ced0
|
||
|
|
9671cba5a1
|
||
|
|
947532f064
|
||
|
|
6e3594eb01
|
||
|
|
abc7b2cde2
|
||
|
|
68d862ded0
|
||
|
|
d3060fd202
|
||
|
|
1d92d80a86
|
||
|
|
86ad19105f
|
||
|
|
2cd5ab273a
|
||
|
|
d75aeee3c2
|
||
|
|
981fb2ceeb
|
||
|
|
01a0dcb9ae
|
||
|
|
460b5e6252
|
||
|
|
fb02580836
|
||
|
|
58a5f59b19
|
||
|
|
95598b1a88
|
||
|
|
7f436ebe17
|
||
|
|
d620f7ea3b
|
||
|
|
ad377a0923
|
||
|
|
f374038000
|
||
|
|
ddba8d63c2
|
||
|
|
ab2e195139
|
||
|
|
85c585db89
|
||
|
|
93eb681b0e
|
||
|
|
30ca75f65e
|
||
|
|
a07916de6b
|
||
|
|
467a4b0dd8
|
||
|
|
03aad4cc6e
|
||
|
|
b638c7b9c2
|
||
|
|
ede56971cd
|
||
|
|
94c11dffcb
|
||
|
|
28c1f70fa1
|
||
|
|
2ecde28980
|
||
|
|
1c2c3915e9
|
||
|
|
9f2cab9961
|
||
|
|
e1778c7c73
|
||
|
|
98426f4ca8
|
||
|
|
7358e2b0a1
|
||
|
|
1af7b8fc8b
|
||
|
|
26d7b0c470
|
||
|
|
96400605ba
|
||
|
|
695cb2f04d
|
||
|
|
6b39a4cceb
|
||
|
|
4b4252855b
|
||
|
|
0d6c3285e1
|
||
|
|
3bcf206a95
|
||
|
|
c65bb5b08f
|
||
|
|
e5b9b98a27
|
||
|
|
7906d4c735
|
||
|
|
d879f3c6fa
|
||
|
|
e7ae3bf290
|
||
|
|
735fd86bed
|
||
|
|
813b3d6686
|
||
|
|
ca43e3706b
|
||
|
|
ef4d7e8024
|
||
|
|
299da15bb8
|
||
|
|
ffba68aeb0
|
||
|
|
1085294aa0
|
||
|
|
cb7e4622e8
|
||
|
|
06e2afa7ed
|
||
|
|
3e60c6d77f
|
||
|
|
594517b436
|
||
|
|
1d3b924492
|
||
|
|
b6cd4bb43e
|
||
|
|
5c0745e039
|
||
|
|
c5fd507ab5
|
||
|
|
dfc39e9e19
|
||
|
|
48d7969a84
|
||
|
|
9eb5a44f2d
|
||
|
|
fc2fc6ab77
|
||
|
|
bc7fa914a4
|
||
|
|
c436f24ee0
|
||
|
|
5a192f5a6f
|
||
|
|
a032f0728f
|
||
|
|
548432f3a9
|
||
|
|
3bd1e5384e
|
||
|
|
738da05e59
|
||
|
|
d457b65f44
|
||
|
|
270cf025ff
|
||
|
|
c657892b7b
|
||
|
|
87cdd4ed90
|
||
|
|
5c1c1272db
|
||
|
|
bcac943775
|
||
|
|
3d0ff687e2
|
||
|
|
ce0da92ac8
|
||
|
|
7dbe063ac8
|
||
|
|
1acaef291c
|
||
|
|
26c96b302f
|
||
|
|
c4011d8eef
|
||
|
|
451b017f6f
|
||
|
|
d6b6e440bf
|
||
|
|
7601b77902
|
||
|
|
0799785cad
|
||
|
|
d607e4ec49
|
||
|
|
c7e5b91509
|
||
|
|
cf23d184fe
|
||
|
|
d2b518f611
|
||
|
|
c186a6b27d
|
||
|
|
5f411e89ec
|
||
|
|
16ed6336c3
|
||
|
|
6d2a5cbe24
|
||
|
|
94f7ad4f50
|
||
|
|
3ba77aab18
|
||
|
|
90fe288f66
|
||
|
|
6b2b5d879f | ||
|
|
d01d5d6df5 | ||
|
|
a093c458a2
|
||
|
|
0e65bf1883
|
||
|
|
d8f728b3f9
|
||
|
|
244e75a238
|
||
|
|
75cc4bd62e
|
||
|
|
6385dbeb6d
|
||
|
|
bc395a0181
|
||
|
|
a0dec019fe
|
||
|
|
c8350161db
|
||
|
|
679cab03b5
|
||
|
|
6783146231
|
||
|
|
df303ee154
|
||
|
|
f49bd740a0
|
||
|
|
80d1b75227
|
||
|
|
d7f981c38a
|
||
|
|
df0c63a270
|
||
|
|
7766b116dc
|
||
|
|
eb8f4e8055
|
||
|
|
04563a7242
|
||
|
|
875d954520
|
||
|
|
bd7f2ae691
|
||
|
|
36b3c880fe
|
||
|
|
230e6f010c
|
||
|
|
ef16ae64fb
|
||
|
|
0204d480e2
|
||
|
|
7e1f2c1d7c
|
||
|
|
bab81d27e5
|
||
|
|
a3efd55ce6
|
||
|
|
4f2389702a
|
||
|
|
247bb83230
|
||
|
|
1d495039f0
|
||
|
|
56d7937be1
|
||
|
|
cade7e8a8f
|
||
|
|
9e8e024db9
|
||
|
|
69881878e4
|
||
|
|
42e0b2b0f7
|
||
|
|
954b1bfc49
|
||
|
|
41defa1059
|
||
|
|
876f05d277
|
||
|
|
227af2c75c
|
||
|
|
5cbd5ae8ff
|
||
|
|
bb97610454
|
||
|
|
968180c459
|
||
|
|
d9ad3692f2
|
||
|
|
573234d727
|
||
|
|
69a5f26260
|
||
|
|
ed4601a03a
|
||
|
|
960569177c
|
||
|
|
2831ea25ee
|
||
|
|
a2caa2e910
|
||
|
|
26bc21681f
|
||
|
|
7edbe189a2
|
||
|
|
e8ae7d1189
|
||
|
|
ce7007c42e
|
||
|
|
f10f31ef2b
|
||
|
|
4a5043eb3a
|
||
|
|
640c9f5347
|
||
|
|
b339d60bd7
|
||
|
|
f94e0ea849
|
||
|
|
729ba355d9
|
||
|
|
67697930b7
|
||
|
|
f929c1a83a
|
||
|
|
6ee2784d6a
|
||
|
|
03db2d4faf
|
||
|
|
fda89f726b
|
||
|
|
d22035111a
|
||
|
|
28bc23cd49
|
||
|
|
796051015c
|
||
|
|
7184a89330
|
||
|
|
add78d673a
|
||
|
|
f8522ad816
|
||
|
|
45bee472e4
|
||
|
|
be411b596d
|
||
|
|
21741fc620
|
||
|
|
05ffdcc9d3
|
||
|
|
1f32ec59ce
|
||
|
|
6af9153f50
|
||
|
|
4528748493
|
||
|
|
3c0e13c85d
|
||
|
|
66786bfc98
|
||
|
|
10dbb022bc
|
||
|
|
b0e47b82f5
|
||
|
|
9e3381f0d0
|
||
|
|
6e29bf08b0
|
||
|
|
21615a5461
|
||
|
|
3dc06dbeb3
|
||
|
|
5c4e1de447
|
||
|
|
488a70ece1
|
||
|
|
41906f81e9
|
||
|
|
bc3bd511df | ||
|
|
6ab90f3584
|
||
|
|
81775e0441
|
||
|
|
c51b24cfba
|
||
|
|
3a9be71e95
|
||
|
|
1255324495
|
||
|
|
b95d66f335
|
||
|
|
c4e3bc0692 | ||
|
|
e3c672b5bb
|
検索条件に一致するファイルはありません
@@ -0,0 +1,228 @@
|
|||||||
|
name: リリース
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
tags:
|
||||||
|
- 'v*'
|
||||||
|
workflow_dispatch:
|
||||||
|
inputs:
|
||||||
|
tag:
|
||||||
|
description: リリースするタグ
|
||||||
|
required: true
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build-and-release:
|
||||||
|
runs-on: windows-latest
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: ソースコードのチェックアウト
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
env:
|
||||||
|
GIT_CONFIG_COUNT: "2"
|
||||||
|
GIT_CONFIG_KEY_0: url.https://git.routersys.com/routersys/.insteadOf
|
||||||
|
GIT_CONFIG_VALUE_0: https://github.com/routersys/
|
||||||
|
GIT_CONFIG_KEY_1: url.https://git.routersys.com/manju-summoner/YukkuriMovieMaker.Generator.insteadOf
|
||||||
|
GIT_CONFIG_VALUE_1: https://github.com/manju-summoner/YukkuriMovieMaker.Generator
|
||||||
|
with:
|
||||||
|
ref: ${{ inputs.tag || github.ref_name }}
|
||||||
|
submodules: recursive
|
||||||
|
|
||||||
|
- name: YMM4 最新リリースの取得と解凍
|
||||||
|
id: ymm4
|
||||||
|
shell: pwsh
|
||||||
|
run: |
|
||||||
|
$list = 'C:\runner\cache\ymm4\releases.json'
|
||||||
|
New-Item -ItemType Directory -Force -Path (Split-Path $list) | Out-Null
|
||||||
|
if (-not (Test-Path $list) -or (Get-Item $list).Length -lt 1000 -or ((Get-Date) - (Get-Item $list).LastWriteTime).TotalHours -gt 6) {
|
||||||
|
$fetched = $null
|
||||||
|
for ($attempt = 1; $attempt -le 6 -and -not $fetched; $attempt++) {
|
||||||
|
try {
|
||||||
|
$fetched = Invoke-RestMethod -Uri "https://api.github.com/repos/manju-summoner/YukkuriMovieMaker4/releases?per_page=100" `
|
||||||
|
-Headers @{ "User-Agent" = "LuaScript-CI" } -ErrorAction Stop
|
||||||
|
}
|
||||||
|
catch {
|
||||||
|
$message = $_.Exception.Message
|
||||||
|
Write-Host "リリース一覧の取得に失敗しました($attempt 回目): $($message.Substring(0, [Math]::Min(80, $message.Length)))"
|
||||||
|
Start-Sleep -Seconds (5 * $attempt)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (@($fetched).Count -gt 0) {
|
||||||
|
$fetched | Select-Object tag_name, published_at, prerelease, draft, assets |
|
||||||
|
ConvertTo-Json -Depth 6 | Set-Content -Path $list -Encoding UTF8
|
||||||
|
}
|
||||||
|
elseif (-not (Test-Path $list)) { throw 'the list of releases could not be fetched' }
|
||||||
|
else { Write-Host '保存済みのリリース一覧を使います' }
|
||||||
|
}
|
||||||
|
$when = [DateTimeOffset](git log -1 --format=%cI)
|
||||||
|
$releases = @(Get-Content -Raw -Path $list | ConvertFrom-Json | Where-Object { -not $_.draft -and -not $_.prerelease })
|
||||||
|
$release = $releases | Where-Object { [DateTimeOffset]$_.published_at -le $when } | Select-Object -First 1
|
||||||
|
if (-not $release) { $release = $releases | Select-Object -Last 1 }
|
||||||
|
Write-Host "最後のコミット $when に合わせた YMM4: $($release.tag_name)"
|
||||||
|
$asset = $release.assets | Where-Object { $_.name -like "*_Lite.zip" } | Select-Object -First 1
|
||||||
|
if (-not $asset) {
|
||||||
|
$asset = $release.assets | Where-Object { $_.name -like "*.zip" } | Select-Object -First 1
|
||||||
|
}
|
||||||
|
Write-Host "ダウンロード対象: $($asset.name)"
|
||||||
|
$cache = Join-Path 'C:\runner\cache\ymm4' $asset.name
|
||||||
|
$extracted = "$cache.extracted"
|
||||||
|
$lock = New-Object System.Threading.Mutex($false, 'Global\ci-ymm4-cache')
|
||||||
|
[void]$lock.WaitOne()
|
||||||
|
try {
|
||||||
|
if (-not (Test-Path "$extracted\.complete")) {
|
||||||
|
New-Item -ItemType Directory -Force -Path (Split-Path $cache) | Out-Null
|
||||||
|
Invoke-WebRequest -Uri $asset.browser_download_url -OutFile $cache
|
||||||
|
Remove-Item -Recurse -Force $extracted -ErrorAction SilentlyContinue
|
||||||
|
Expand-Archive -Path $cache -DestinationPath $extracted -Force
|
||||||
|
New-Item -ItemType File -Path "$extracted\.complete" | Out-Null
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
Write-Host "保存済みの YMM4 を使います: $extracted"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finally {
|
||||||
|
$lock.ReleaseMutex()
|
||||||
|
}
|
||||||
|
$ymm4Dir = (Get-ChildItem -Path $extracted -Recurse -Filter "YukkuriMovieMaker.dll" |
|
||||||
|
Select-Object -First 1).DirectoryName
|
||||||
|
Write-Host "YMM4 DLL ディレクトリ: $ymm4Dir"
|
||||||
|
echo "YMM4_DIR=$ymm4Dir\" >> $env:GITHUB_OUTPUT
|
||||||
|
|
||||||
|
- name: タグ名からバージョンを取得
|
||||||
|
id: version
|
||||||
|
shell: pwsh
|
||||||
|
run: |
|
||||||
|
$tag = "${{ inputs.tag || github.ref_name }}"
|
||||||
|
echo "TAG=$tag" >> $env:GITHUB_OUTPUT
|
||||||
|
echo "VERSION=$($tag.TrimStart('v'))" >> $env:GITHUB_OUTPUT
|
||||||
|
|
||||||
|
- name: プロジェクトのビルド
|
||||||
|
shell: pwsh
|
||||||
|
env:
|
||||||
|
CI: 'true'
|
||||||
|
run: |
|
||||||
|
dotnet build LuaScript/LuaScript.csproj `
|
||||||
|
-c Release `
|
||||||
|
-p:YMM4DirPath="${{ steps.ymm4.outputs.YMM4_DIR }}" `
|
||||||
|
-p:Platform=x64
|
||||||
|
|
||||||
|
- name: パッケージの作成
|
||||||
|
id: package
|
||||||
|
shell: pwsh
|
||||||
|
run: |
|
||||||
|
$version = "${{ steps.version.outputs.TAG }}"
|
||||||
|
$outDir = "LuaScript/bin/x64/Release/net10.0-windows10.0.19041.0"
|
||||||
|
$stageRoot = "stage/LuaScript"
|
||||||
|
$pkgName = "LuaScript_$version.ymme"
|
||||||
|
|
||||||
|
New-Item -ItemType Directory -Path "$stageRoot/docs" -Force | Out-Null
|
||||||
|
New-Item -ItemType Directory -Path "$stageRoot/native" -Force | Out-Null
|
||||||
|
New-Item -ItemType Directory -Path "$stageRoot/LICENSE" -Force | Out-Null
|
||||||
|
|
||||||
|
Copy-Item "$outDir/LuaScript.dll" "$stageRoot/"
|
||||||
|
Copy-Item "$outDir/LuaScript.Kernel.dll" "$stageRoot/"
|
||||||
|
Copy-Item "$outDir/LuaScript.Compat.dll" "$stageRoot/"
|
||||||
|
Copy-Item "$outDir/LuaScript.Media.dll" "$stageRoot/"
|
||||||
|
Copy-Item "$outDir/LuaScript.Runtime.dll" "$stageRoot/"
|
||||||
|
Copy-Item "$outDir/LuaScript.Gpu.dll" "$stageRoot/"
|
||||||
|
Copy-Item "$outDir/MoonSharp.Interpreter.dll" "$stageRoot/"
|
||||||
|
Copy-Item "$outDir/native/luajit.exe" "$stageRoot/native/"
|
||||||
|
Copy-Item "$outDir/native/lua51.dll" "$stageRoot/native/"
|
||||||
|
Copy-Item "$outDir/native/worker.lua" "$stageRoot/native/"
|
||||||
|
Copy-Item "$outDir/native/shim.lua" "$stageRoot/native/"
|
||||||
|
|
||||||
|
foreach ($lang in @("ar-sa", "en-us", "es-es", "id-id", "ko-kr", "zh-cn", "zh-tw")) {
|
||||||
|
$src = "$outDir/$lang"
|
||||||
|
if (Test-Path $src) {
|
||||||
|
New-Item -ItemType Directory -Path "$stageRoot/$lang" -Force | Out-Null
|
||||||
|
Copy-Item "$src/*.dll" "$stageRoot/$lang/"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Copy-Item "LuaScript/docs/LuaScript.*.txt" "$stageRoot/docs/"
|
||||||
|
Copy-Item ".github/LICENSE/*.txt" "$stageRoot/LICENSE/"
|
||||||
|
Copy-Item ".github/Plugin_Readme.txt" "$stageRoot/Readme.txt"
|
||||||
|
|
||||||
|
Compress-Archive -Path "stage/*" -DestinationPath $pkgName -CompressionLevel Optimal
|
||||||
|
echo "PKG_NAME=$pkgName" >> $env:GITHUB_OUTPUT
|
||||||
|
|
||||||
|
- name: Gitea リリースの作成
|
||||||
|
shell: pwsh
|
||||||
|
env:
|
||||||
|
GITEA_TOKEN: ${{ github.token }}
|
||||||
|
REPOSITORY: ${{ github.repository }}
|
||||||
|
SERVER_URL: ${{ github.server_url }}
|
||||||
|
EVENT_NAME: ${{ github.event_name }}
|
||||||
|
WORKFLOW_NAME: ${{ github.workflow }}
|
||||||
|
JOB_NAME: ${{ github.job }}
|
||||||
|
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_number }}
|
||||||
|
RELEASE_TAG: ${{ inputs.tag || github.ref_name }}
|
||||||
|
RELEASE_NAME: ${{ steps.version.outputs.TAG }}
|
||||||
|
RELEASE_BODY: ''
|
||||||
|
RELEASE_BODY_PATH: .github/CHANGELOG.md
|
||||||
|
RELEASE_DRAFT: false
|
||||||
|
RELEASE_PRERELEASE: false
|
||||||
|
RELEASE_FILES: |
|
||||||
|
${{ steps.package.outputs.PKG_NAME }}
|
||||||
|
run: |
|
||||||
|
$headers = @{ Authorization = "token $env:GITEA_TOKEN" }
|
||||||
|
$api = "$env:SERVER_URL/api/v1/repos/$env:REPOSITORY"
|
||||||
|
$tag = $env:RELEASE_TAG
|
||||||
|
|
||||||
|
$body = $env:RELEASE_BODY
|
||||||
|
if ($env:RELEASE_BODY_PATH -and (Test-Path $env:RELEASE_BODY_PATH)) {
|
||||||
|
$body = Get-Content $env:RELEASE_BODY_PATH -Raw -Encoding utf8
|
||||||
|
}
|
||||||
|
|
||||||
|
$files = @()
|
||||||
|
foreach ($pattern in ($env:RELEASE_FILES -split "[`r`n,]+" | Where-Object { $_.Trim() })) {
|
||||||
|
$found = @(Get-ChildItem -Path $pattern.Trim() -File -ErrorAction SilentlyContinue)
|
||||||
|
if ($found.Count -eq 0) { throw "リリースに付けるファイルが見つかりません: $pattern" }
|
||||||
|
$files += $found
|
||||||
|
}
|
||||||
|
|
||||||
|
$payload = @{
|
||||||
|
tag_name = $tag
|
||||||
|
name = $env:RELEASE_NAME
|
||||||
|
body = [string]$body
|
||||||
|
draft = ($env:RELEASE_DRAFT -eq 'true')
|
||||||
|
prerelease = ($env:RELEASE_PRERELEASE -eq 'true')
|
||||||
|
} | ConvertTo-Json
|
||||||
|
$bytes = [System.Text.Encoding]::UTF8.GetBytes($payload)
|
||||||
|
|
||||||
|
$existing = $null
|
||||||
|
try { $existing = Invoke-RestMethod -Uri "$api/releases/tags/$([System.Uri]::EscapeDataString($tag))" -Headers $headers } catch { }
|
||||||
|
if ($existing) {
|
||||||
|
$release = Invoke-RestMethod -Method Patch -Uri "$api/releases/$($existing.id)" -Headers $headers -ContentType "application/json; charset=utf-8" -Body $bytes
|
||||||
|
foreach ($asset in @($existing.assets)) {
|
||||||
|
Invoke-RestMethod -Method Delete -Uri "$api/releases/$($existing.id)/assets/$($asset.id)" -Headers $headers | Out-Null
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
$release = Invoke-RestMethod -Method Post -Uri "$api/releases" -Headers $headers -ContentType "application/json; charset=utf-8" -Body $bytes
|
||||||
|
}
|
||||||
|
foreach ($file in $files) {
|
||||||
|
$name = [System.Uri]::EscapeDataString($file.Name)
|
||||||
|
Invoke-RestMethod -Method Post -Uri "$api/releases/$($release.id)/assets?name=$name" -Headers $headers -Form @{ attachment = Get-Item $file.FullName } | Out-Null
|
||||||
|
Write-Host "添付しました: $($file.Name)"
|
||||||
|
}
|
||||||
|
Write-Host "リリースを作成しました: $($release.html_url)"
|
||||||
|
|
||||||
|
if ($env:EVENT_NAME -eq 'workflow_dispatch') {
|
||||||
|
try {
|
||||||
|
$sha = (git rev-parse HEAD).Trim()
|
||||||
|
$status = @{
|
||||||
|
state = 'success'
|
||||||
|
context = "$env:WORKFLOW_NAME / $env:JOB_NAME (workflow_dispatch)"
|
||||||
|
description = "Actions がタグ $tag のコミットから作成しました"
|
||||||
|
target_url = $env:RUN_URL
|
||||||
|
} | ConvertTo-Json
|
||||||
|
Invoke-RestMethod -Method Post -Uri "$api/statuses/$sha" -Headers $headers -ContentType "application/json; charset=utf-8" -Body ([System.Text.Encoding]::UTF8.GetBytes($status)) | Out-Null
|
||||||
|
Write-Host "タグのコミット $sha に成功の状態を付けました"
|
||||||
|
}
|
||||||
|
catch {
|
||||||
|
Write-Warning "タグのコミットに状態を付けられませんでした: $($_.Exception.Message)"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
+13
-485
@@ -1,500 +1,28 @@
|
|||||||
# v1.0.0 - Lua スクリプト for YMM4
|
# v1.20.3 - Lua スクリプト for YMM4
|
||||||
|
|
||||||
YukkuriMovieMaker4 向けの Lua スクリプトエフェクトプラグインの初回リリースです。
|
[fast] マーカーの注意書きを補うドキュメント更新リリースです。v1.20.2 で [fast] は obj.fill / obj.convolve / obj.resize の処理量のしきい値を無視して GPU へ委譲する仕様になりましたが、処理量が小さいときは GPU への委譲自体の往復コストが CPU 実行を上回り、かえって遅くなる場合があることを明記しました。動作に関わる実装、API、実行結果、エラーの扱いに変更はありません。
|
||||||
AviUtl アニメーション効果互換の変数・関数体系を YMM4 映像エフェクトとして提供し、
|
|
||||||
MoonSharp による Lua 実行エンジン・専用コードエディター・シンタックスハイライト・
|
|
||||||
折り畳み・オートコンプリート・ファイルインポート/エクスポート・ピクセル直接操作・
|
|
||||||
独自アニメーションユーティリティライブラリ・8 言語対応 UI を備えた映像エフェクトプラグインです。
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 新機能
|
## 変更
|
||||||
|
|
||||||
### 1. エフェクト定義(LuaScriptEffect)
|
### [fast] は小さな処理で遅くなる場合があることを明記
|
||||||
|
|
||||||
`LuaScriptEffect` は `VideoEffectBase` を継承し、`IScriptProvider` を実装します。
|
[fast] は obj.fill / obj.convolve / obj.resize のしきい値を無視しますが、GPU への委譲には往復コストがあります。処理量が小さいときは CPU 実行のほうが速い場合があるため、README、サイト、付属ドキュメントに注意書きを追加しました。
|
||||||
|
|
||||||
`[VideoEffect]` 属性は以下のパラメーターで宣言されます。
|
- 付属の 8 言語ドキュメントの [fast] の節へ、同じ注意書きを追加しました。
|
||||||
|
|
||||||
- 表示名:`Texts.LuaScript`(ローカライズキー)
|
|
||||||
- カテゴリー:`VideoEffectCategories.Filtering`
|
|
||||||
- 検索タグ:`"lua"`・`"script"`・`"スクリプト"`・`"lua script"`・`"アニメーション効果"`・`"animation"`
|
|
||||||
- `IsAviUtlSupported = false` により AviUtl 向け EXO 出力は非対応です。
|
|
||||||
- `ResourceType = typeof(Texts)` でローカライズリソースを指定します。
|
|
||||||
|
|
||||||
`Label` プロパティは `Texts.LuaScript` の固定値を返却します。
|
|
||||||
|
|
||||||
デフォルトスクリプトは以下のとおりです。
|
|
||||||
|
|
||||||
```lua
|
|
||||||
obj.alpha = math.min(time * 255, 255)
|
|
||||||
```
|
|
||||||
|
|
||||||
公開プロパティは以下のとおりです。
|
|
||||||
|
|
||||||
- `ToolBar`(`object?`、常に `null`):
|
|
||||||
`[LuaScriptToolBar]` でインポート・エクスポート・クリアのツールバーを表示します。
|
|
||||||
`Texts.ScriptGroup` グループに属します。
|
|
||||||
|
|
||||||
- `Script`(`string`、デフォルト `DefaultScript`):
|
|
||||||
`[CodeEditor]` でシンタックスハイライト付きコードエディターとして表示されます。
|
|
||||||
シンタックス定義は `pack://application:,,,/LuaScript;component/Resources/SyntaxDefinitions/Lua-{theme}.xshd`
|
|
||||||
をテーマ別に読み込みます。折り畳みに `LuaFoldingStrategy`、オートコンプリートに
|
|
||||||
`LuaAutoCompletionStrategy` を使用します。`PropertyEditorSize.FullWidth` で全幅表示されます。
|
|
||||||
`Set` による変更通知を伴うフィールドプロパティとして実装されます。
|
|
||||||
`Texts.ScriptGroup` グループに属します。
|
|
||||||
|
|
||||||
- `Track0`〜`Track3`(`Animation`、デフォルト `0`、内部範囲:`YMM4Constants.VerySmallValue`〜`YMM4Constants.VeryLargeValue`):
|
|
||||||
`[AnimationSlider("F2", "", -100, 100)]` でスライダー操作範囲 -100〜100 として表示されます。
|
|
||||||
スクリプト内では `obj.track0`〜`obj.track3` でアクセスします。
|
|
||||||
AviUtl の `track0`〜`track3` に対応するスライダー値です。
|
|
||||||
`Texts.ParametersGroup` グループに属します。
|
|
||||||
|
|
||||||
`CreateExoVideoFilters` は空の `IEnumerable<string>` を返却し、EXO 向けフィルター出力は実装されていません。
|
|
||||||
|
|
||||||
`CreateVideoEffect(IGraphicsDevicesAndContext devices)` は
|
|
||||||
`new LuaScriptEffectProcessor(devices, this)` を返却します。
|
|
||||||
|
|
||||||
`GetAnimatables` は `Track0`・`Track1`・`Track2`・`Track3` を列挙します。
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### 2. スクリプト実行コンテキスト(AviUtlScriptContext)
|
## 互換性・後方互換
|
||||||
|
|
||||||
`AviUtlScriptContext` はスクリプト実行時の状態を保持する内部クラスです。
|
- 動作に関わる実装の変更はありません。
|
||||||
|
- API、構文、エンジンの自動振り分け、GPU 検証、CPU への自動フォールバックに変更はありません。
|
||||||
#### 読み取り専用プロパティ
|
- v1.20.2 の [fast] の強制委譲仕様に変更はありません。
|
||||||
|
|
||||||
| プロパティ | 型 | 説明 |
|
|
||||||
|---|---|---|
|
|
||||||
| `ImageWidth` | `int` | 画像幅(ピクセル) |
|
|
||||||
| `ImageHeight` | `int` | 画像高さ(ピクセル) |
|
|
||||||
| `Track0`〜`Track3` | `double` | スライダー値 |
|
|
||||||
| `Time` | `double` | アイテム内の経過時間(秒) |
|
|
||||||
| `Frame` | `int` | アイテム内の経過フレーム数 |
|
|
||||||
| `TotalFrame` | `int` | アイテムの総フレーム数 |
|
|
||||||
| `TotalTime` | `double` | アイテムの総時間(秒) |
|
|
||||||
| `Framerate` | `int` | フレームレート |
|
|
||||||
| `TimelineFrame` | `int` | タイムライン上の経過フレーム数 |
|
|
||||||
| `TimelineTime` | `double` | タイムライン上の経過時間(秒) |
|
|
||||||
| `SceneWidth` | `int` | シーン幅 |
|
|
||||||
| `SceneHeight` | `int` | シーン高さ |
|
|
||||||
| `Layer` | `int` | レイヤー番号 |
|
|
||||||
| `Index` | `int` | グループ内のインデックス |
|
|
||||||
| `Num` | `int` | グループ内の総数 |
|
|
||||||
| `GroupIndex` | `int` | グループインデックス |
|
|
||||||
| `GroupCount` | `int` | グループ総数 |
|
|
||||||
| `TimelineTotalFrame` | `int` | タイムライン総フレーム数 |
|
|
||||||
| `TimelineTotalTime` | `double` | タイムライン総時間(秒) |
|
|
||||||
| `IsSaving` | `bool` | エクスポート中かどうか |
|
|
||||||
| `IsPlaying` | `bool` | 再生中かどうか |
|
|
||||||
| `IsPaused` | `bool` | 一時停止中かどうか |
|
|
||||||
| `TimeRatio` | `double` | アイテム内の時間比率(Frame / TotalFrame) |
|
|
||||||
| `SceneId` | `string` | シーン ID |
|
|
||||||
|
|
||||||
#### 書き換え可能プロパティ
|
|
||||||
|
|
||||||
| プロパティ | 型 | 説明 |
|
|
||||||
|---|---|---|
|
|
||||||
| `X`・`Y`・`Z` | `double` | 描画位置 |
|
|
||||||
| `Ox`・`Oy`・`Oz` | `double` | 回転中心のオフセット |
|
|
||||||
| `Sx`・`Sy` | `double` | X・Y 方向の拡大率 |
|
|
||||||
| `Zoom` | `double` | 拡大率((Sx + Sy) / 2) |
|
|
||||||
| `Aspect` | `double` | アスペクト比((Sx - Sy) / (Sx + Sy)) |
|
|
||||||
| `Alpha` | `double` | 不透明度(0〜255) |
|
|
||||||
| `Rx`・`Ry`・`Rz` | `double` | X・Y・Z 軸回転角(度) |
|
|
||||||
|
|
||||||
`RxRad`・`RyRad`・`RzRad` は各 `Rx`・`Ry`・`Rz` をラジアンに換算した計算プロパティです。
|
|
||||||
|
|
||||||
#### ピクセル操作
|
|
||||||
|
|
||||||
- `GetPixel(int x, int y)` は `(r, g, b, a)` のタプルを返却します。各成分は 0〜255 の `double` で、
|
|
||||||
プリマルチプライ済み BGRA からストレートアルファの RGB へ復元して返却します。
|
|
||||||
アルファが 0 以下の場合はすべて 0 を返却します。
|
|
||||||
- `SetPixel(int x, int y, double r, double g, double b, double a)` は
|
|
||||||
ストレートアルファの RGB をプリマルチプライ済み BGRA に変換してバッファーへ書き込みます。
|
|
||||||
`a` のデフォルトは 255 です。書き込み後は `IsPixelsDirty` が true になります。
|
|
||||||
- `EnsurePixelBuffer` はピクセルローダーを遅延呼び出しして入力画像をバッファーへ読み込みます。
|
|
||||||
- `GetPixelBuffer` は内部の `byte[]` バッファーを返却します。
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### 3. エフェクトプロセッサー(LuaScriptEffectProcessor)
|
## 内部実装
|
||||||
|
|
||||||
`LuaScriptEffectProcessor` は `VideoEffectProcessorBase` を継承し、
|
- 動作に関わるコード変更はありません。
|
||||||
コンストラクターで `IGraphicsDevicesAndContext devices` と `LuaScriptEffect item` を受け取ります。
|
- リリース対象のバージョン表記を v1.20.3 へ更新しました。
|
||||||
|
|
||||||
#### CreateEffect メソッド
|
|
||||||
|
|
||||||
`GraphicsDevicesAndContext` のプライベートコンテキスト `_ownCtx` を生成して `disposer` に登録し、
|
|
||||||
`null` を返却します。出力画像の生成はスクリプト実行後に動的に決定します。
|
|
||||||
|
|
||||||
#### setInput / ClearEffectChain メソッド
|
|
||||||
|
|
||||||
`setInput` は入力が前回と異なる場合に `_isFirst = true` としてキャッシュを無効化します。
|
|
||||||
`ClearEffectChain` は `effectOutput` を null に設定します。
|
|
||||||
|
|
||||||
#### Update メソッド
|
|
||||||
|
|
||||||
`Update(EffectDescription desc)` は毎フレーム呼び出されます。
|
|
||||||
|
|
||||||
`input` または `_ownCtx` が null の場合は `desc.DrawDescription` をそのまま返却します。
|
|
||||||
|
|
||||||
`RenderKey` レコードでフレーム・時間・長さ・FPS・スライダー値 4 本・スクリプト文字列・
|
|
||||||
利用用途・シーン ID・タイムライン情報・シーンサイズ・レイヤー・インデックス・グループ情報・
|
|
||||||
タイムライン総フレーム数・`DrawDescription` を一括保持し、
|
|
||||||
前回と同一の場合はキャッシュした結果をそのまま返却します。
|
|
||||||
|
|
||||||
スクリプト実行時は `BuildContext` で `AviUtlScriptContext` を生成し、
|
|
||||||
`SetPixelLoader` でピクセル遅延ローダーを登録してから `LuaScriptEngine.Execute` を呼び出します。
|
|
||||||
実行後に `ctx.IsPixelsDirty` が true の場合のみ出力ビットマップへ書き込み、
|
|
||||||
`AffineTransform2D` で入力境界の原点へ平行移動して `effectOutput` に設定します。
|
|
||||||
ピクセルが変更されていない場合は `effectOutput = null` としてパススルーします。
|
|
||||||
|
|
||||||
`BuildOutputDesc` が書き換え後の `ctx.X/Y/Z/Ox/Oy/Sx/Sy/Zoom/Aspect/Alpha/Rx/Ry/Rz` から
|
|
||||||
新しい `DrawDescription` を構築して返却します。`Alpha` は `ctx.Alpha / 255d` を
|
|
||||||
0〜1 にクランプします。
|
|
||||||
|
|
||||||
例外は `LuaScriptException` を捕捉してログに書き込み、エラー時は入力の `DrawDescription` を
|
|
||||||
そのまま返却します。タイムアウトは `LuaScriptRuntimeException` として処理されます。
|
|
||||||
|
|
||||||
#### ビットマップ管理
|
|
||||||
|
|
||||||
`EnsureBitmaps(int width, int height)` でサイズ変化時にビットマップ 3 枚と変換エフェクトを再生成します。
|
|
||||||
|
|
||||||
- `_renderTarget`:`BitmapOptions.Target`、入力を描画する作業バッファー
|
|
||||||
- `_stagingBitmap`:`B8G8R8A8_UNorm`・`Premultiplied`・`CpuRead | CannotDraw`、CPU 読み出し用
|
|
||||||
- `_outputBitmap`:`BitmapOptions.Target`、ピクセル操作後の書き出し先
|
|
||||||
|
|
||||||
`LoadInputPixels` は `_ownCtx` の独立デバイスコンテキストで入力を `_renderTarget` へ描画し、
|
|
||||||
`_stagingBitmap` へコピーして `Map(MapOptions.Read)` で `_pixelBuffer` へ読み出します。
|
|
||||||
ピッチが行ストライドと一致する場合は一括コピー、そうでない場合は行ごとにコピーします。
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### 4. Lua 実行エンジン(LuaScriptEngine)
|
|
||||||
|
|
||||||
`LuaScriptEngine` は `IDisposable` を実装します。
|
|
||||||
|
|
||||||
タイムアウトは `ExecutionTimeoutMilliseconds = 5000`(5 秒)です。
|
|
||||||
|
|
||||||
タイムアウト時は実行スレッドを非同期で破棄して新しいスレッドを生成し、
|
|
||||||
`LuaScriptRuntimeException` をスローします。
|
|
||||||
|
|
||||||
#### ExecutionThread 内部クラス
|
|
||||||
|
|
||||||
Lua スクリプトを専用ワーカースレッドで逐次実行する仕組みです。
|
|
||||||
キューのバウンド容量は 1 で、実行要求が溢れた場合は即座にエラーを返却します。
|
|
||||||
|
|
||||||
`CancellationDebugger` により、キャンセルトークンを MoonSharp デバッガーフックへ橋渡しし、
|
|
||||||
タイムアウト時に `OperationCanceledException` を発生させます。
|
|
||||||
|
|
||||||
コンパイル済みチャンクはスクリプト文字列が変化した場合のみ `LoadString` で再コンパイルします。
|
|
||||||
再コンパイル時の構文エラーは `LuaScriptCompilationException` としてラップします。
|
|
||||||
実行時エラーは `LuaScriptRuntimeException` としてラップします。
|
|
||||||
|
|
||||||
`EnsureScriptIntegrity` は `math` グローバルが消失していた場合に Lua VM を完全リセットします。
|
|
||||||
|
|
||||||
有効な Lua モジュールは以下のとおりです。
|
|
||||||
|
|
||||||
`Basic` / `Math` / `String` / `Table` / `Bit32` / `TableIterators` / `Metatables` / `ErrorHandling`
|
|
||||||
|
|
||||||
ファイルアクセスは `DisabledFileScriptLoader` により無効化されています。
|
|
||||||
|
|
||||||
フレームシードによる `math.randomseed` 呼び出しにより、同一フレームでは `math.random` が
|
|
||||||
再現性のある値を返します。
|
|
||||||
|
|
||||||
#### SetupGlobals メソッド
|
|
||||||
|
|
||||||
スクリプト実行前にグローバル変数と各テーブルを初期化します。
|
|
||||||
ユーザーがフレーム間でグローバルに書き込んだキーは次フレームの実行前に除去されます
|
|
||||||
(`_builtinGlobalSnapshot` との差分を削除)。
|
|
||||||
各テーブル(`obj`・`scene`・`anim`・`ymm4`)も同様にフレーム間でリセットします。
|
|
||||||
|
|
||||||
スクリプトから利用可能なグローバル変数は以下のとおりです。
|
|
||||||
|
|
||||||
| 変数名 | 型 | 説明 |
|
|
||||||
|---|---|---|
|
|
||||||
| `time` | `double` | アイテム内の経過時間(秒) |
|
|
||||||
| `frame` | `int` | アイテム内の経過フレーム数 |
|
|
||||||
| `totalframe` | `int` | アイテムの総フレーム数 |
|
|
||||||
| `framerate` | `int` | フレームレート |
|
|
||||||
| `timelineframe` | `int` | タイムライン上の経過フレーム数 |
|
|
||||||
| `timelinetime` | `double` | タイムライン上の経過時間(秒) |
|
|
||||||
| `layer` | `int` | レイヤー番号 |
|
|
||||||
|
|
||||||
#### ReadBackGlobals メソッド
|
|
||||||
|
|
||||||
スクリプト実行後に `obj` テーブルの変数を `AviUtlScriptContext` へ書き戻します。
|
|
||||||
書き戻し対象は `x`・`y`・`z`・`ox`・`oy`・`oz`・`alpha`・`sx`・`sy`・`zoom`・`aspect`・
|
|
||||||
`rx`・`ry`・`rz`・`rxr`・`ryr`・`rzr` です。
|
|
||||||
|
|
||||||
`zoom`・`aspect` が変化し、かつ `sx`・`sy` が変化していない場合は
|
|
||||||
`sx = zoom * (1 + aspect)`・`sy = zoom * (1 - aspect)` で `sx`・`sy` を再計算します。
|
|
||||||
|
|
||||||
`rxr`・`ryr`・`rzr` が前回値から変化していた場合は、それをラジアンから度に変換して
|
|
||||||
`rx`・`ry`・`rz` を上書きします。それ以外の場合は `rx`・`ry`・`rz` を直接読み返します。
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### 5. スクリプト API(obj テーブル)
|
|
||||||
|
|
||||||
スクリプトから参照・書き換えできる `obj` テーブルのメンバーは以下のとおりです。
|
|
||||||
|
|
||||||
#### 読み取り専用メンバー
|
|
||||||
|
|
||||||
| メンバー | 説明 |
|
|
||||||
|---|---|
|
|
||||||
| `obj.w` | 画像幅(ピクセル) |
|
|
||||||
| `obj.h` | 画像高さ(ピクセル) |
|
|
||||||
| `obj.hw` | 画像幅の半分 |
|
|
||||||
| `obj.hh` | 画像高さの半分 |
|
|
||||||
| `obj.cx` | 画像幅の半分(`hw` の別名) |
|
|
||||||
| `obj.cy` | 画像高さの半分(`hh` の別名) |
|
|
||||||
| `obj.cz` | 常に 0 |
|
|
||||||
| `obj.sz` | 常に 1 |
|
|
||||||
| `obj.diagonal` | 画像の対角線長(`sqrt(w^2 + h^2)`) |
|
|
||||||
| `obj.track0`〜`obj.track3` | スライダー値 |
|
|
||||||
| `obj.time` | アイテム内の経過時間(秒) |
|
|
||||||
| `obj.frame` | アイテム内の経過フレーム数 |
|
|
||||||
| `obj.totalframe` | アイテムの総フレーム数 |
|
|
||||||
| `obj.totaltime` | アイテムの総時間(秒) |
|
|
||||||
| `obj.t` | `frame / totalframe`(0 除算時は 0) |
|
|
||||||
| `obj.framerate` | フレームレート |
|
|
||||||
| `obj.layer` | レイヤー番号 |
|
|
||||||
| `obj.index` | グループ内のインデックス |
|
|
||||||
| `obj.num` | グループ内の総数 |
|
|
||||||
|
|
||||||
#### 読み書き可能メンバー
|
|
||||||
|
|
||||||
| メンバー | 説明 |
|
|
||||||
|---|---|
|
|
||||||
| `obj.x`・`obj.y`・`obj.z` | 描画位置(ピクセル) |
|
|
||||||
| `obj.ox`・`obj.oy`・`obj.oz` | 回転中心のオフセット(ピクセル) |
|
|
||||||
| `obj.sx`・`obj.sy` | X・Y 方向の拡大率 |
|
|
||||||
| `obj.zoom` | 拡大率(sx と sy の平均) |
|
|
||||||
| `obj.aspect` | アスペクト比 |
|
|
||||||
| `obj.alpha` | 不透明度(0〜255) |
|
|
||||||
| `obj.rx`・`obj.ry`・`obj.rz` | X・Y・Z 軸回転角(度) |
|
|
||||||
| `obj.rxr`・`obj.ryr`・`obj.rzr` | X・Y・Z 軸回転角(ラジアン)。変更すると対応する `rx`・`ry`・`rz` を上書きします。 |
|
|
||||||
|
|
||||||
#### ピクセル操作関数
|
|
||||||
|
|
||||||
| 関数 | 戻り値 | 説明 |
|
|
||||||
|---|---|---|
|
|
||||||
| `obj.getpixel(x, y)` | `r, g, b, a` | 指定座標のピクセルを取得します。各成分は 0〜255 の浮動小数点数です。 |
|
|
||||||
| `obj.setpixel(x, y, r, g, b [, a])` | なし | 指定座標へピクセルを書き込みます。`a` のデフォルトは 255 です。 |
|
|
||||||
| `obj.getpixeldata()` | `PixelDataProxy` | ピクセルデータへの直接アクセスオブジェクトを返却します。 |
|
|
||||||
| `obj.putpixeldata()` | なし | 互換性のために存在しますが、何もしません。 |
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### 6. スクリプト API(scene テーブル)
|
|
||||||
|
|
||||||
| メンバー | 説明 |
|
|
||||||
|---|---|
|
|
||||||
| `scene.width` | シーン幅(ピクセル) |
|
|
||||||
| `scene.height` | シーン高さ(ピクセル) |
|
|
||||||
| `scene.cx` | シーン幅の半分 |
|
|
||||||
| `scene.cy` | シーン高さの半分 |
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### 7. スクリプト API(anim テーブル)
|
|
||||||
|
|
||||||
`anim` テーブルはアニメーション補助関数と数学ユーティリティを提供します。
|
|
||||||
|
|
||||||
#### 定数
|
|
||||||
|
|
||||||
| 定数名 | 値 | 説明 |
|
|
||||||
|---|---|---|
|
|
||||||
| `anim.tau` | `2π` | 円周率の 2 倍 |
|
|
||||||
| `anim.e` | `e` | 自然対数の底 |
|
|
||||||
| `anim.phi` | `(1 + √5) / 2` | 黄金比 |
|
|
||||||
| `anim.sqrt2` | `√2` | 2 の平方根 |
|
|
||||||
|
|
||||||
#### 補間・マッピング関数
|
|
||||||
|
|
||||||
| 関数 | 説明 |
|
|
||||||
|---|---|
|
|
||||||
| `anim.lerp(a, b, t)` | `a` から `b` への線形補間 |
|
|
||||||
| `anim.smoothstep(edge0, edge1, x)` | Hermite 補間(0〜1 にクランプ) |
|
|
||||||
| `anim.smootherstep(edge0, edge1, x)` | 5 次 Hermite 補間(0〜1 にクランプ) |
|
|
||||||
| `anim.clamp(v, lo, hi)` | `v` を `lo`〜`hi` にクランプ |
|
|
||||||
| `anim.map(v, a1, b1, a2, b2)` | `a1`〜`b1` の範囲を `a2`〜`b2` へ線形写像 |
|
|
||||||
| `anim.norm(v, lo, hi)` | `lo`〜`hi` を 0〜1 に正規化 |
|
|
||||||
| `anim.wrap(v, lo, hi)` | `lo`〜`hi` の範囲でラップアラウンド |
|
|
||||||
| `anim.pingpong(t, length)` | `0`〜`length` を往復 |
|
|
||||||
|
|
||||||
#### ウェーブ・信号関数
|
|
||||||
|
|
||||||
| 関数 | 説明 |
|
|
||||||
|---|---|
|
|
||||||
| `anim.oscillate(t, lo, hi, freq)` | サイン波で `lo`〜`hi` を周期 `1/freq` 秒で往復 |
|
|
||||||
| `anim.triangle(t, freq)` | 三角波(0〜1) |
|
|
||||||
| `anim.square(t, freq)` | 矩形波(0 または 1) |
|
|
||||||
| `anim.sign(v)` | 符号(−1・0・+1) |
|
|
||||||
| `anim.step(edge, x)` | `x >= edge` なら 1、それ以外は 0 |
|
|
||||||
| `anim.fract(v)` | 小数部(`v - floor(v)`) |
|
|
||||||
| `anim.delay(t, d)` | `max(0, t - d)` |
|
|
||||||
| `anim.duration(t, dur)` | `clamp(t / dur, 0, 1)` |
|
|
||||||
|
|
||||||
#### イージング関数
|
|
||||||
|
|
||||||
| 関数 | 説明 |
|
|
||||||
|---|---|
|
|
||||||
| `anim.ease_in(t)` | 2 次イーズイン(`t^2`) |
|
|
||||||
| `anim.ease_out(t)` | 2 次イーズアウト(`1 - (1-t)^2`) |
|
|
||||||
| `anim.ease_in_out(t)` | 2 次イーズインアウト |
|
|
||||||
| `anim.elastic(t)` | 弾性イーズアウト(`t` は 0〜1 にクランプ) |
|
|
||||||
| `anim.back(t)` | バックイーズアウト(定数 c1 = 1.70158) |
|
|
||||||
| `anim.bounce(t)` | バウンスイーズアウト(`t` は 0〜1 にクランプ) |
|
|
||||||
| `anim.bezier(t, p0, p1, p2, p3)` | 3 次ベジェ補間(`t` は 0〜1 にクランプ) |
|
|
||||||
|
|
||||||
#### 色変換関数
|
|
||||||
|
|
||||||
| 関数 | 戻り値 | 説明 |
|
|
||||||
|---|---|---|
|
|
||||||
| `anim.hsv_to_rgb(h, s, v)` | `r, g, b` | HSV を RGB(0〜255)に変換。色相 `h` は 0〜360。 |
|
|
||||||
| `anim.rgb_to_hsv(r, g, b)` | `h, s, v` | RGB(0〜255)を HSV に変換。色相 `h` は 0〜360。 |
|
|
||||||
|
|
||||||
#### 2D ベクトル演算関数
|
|
||||||
|
|
||||||
| 関数 | 戻り値 | 説明 |
|
|
||||||
|---|---|---|
|
|
||||||
| `anim.len(x, y)` | `double` | ベクトルの長さ |
|
|
||||||
| `anim.dist(x1, y1, x2, y2)` | `double` | 2 点間の距離 |
|
|
||||||
| `anim.dot(x1, y1, x2, y2)` | `double` | 内積 |
|
|
||||||
| `anim.normalize(x, y)` | `x, y` | 正規化。長さが 0 の場合は `(0, 0)` を返却します。 |
|
|
||||||
| `anim.polar(r, a)` | `x, y` | 極座標(半径 `r`・角度 `a` 度)を直交座標へ変換 |
|
|
||||||
| `anim.rotate(x, y, a)` | `x, y` | ベクトルを `a` 度回転 |
|
|
||||||
|
|
||||||
#### ノイズ・乱数関数
|
|
||||||
|
|
||||||
| 関数 | 戻り値 | 説明 |
|
|
||||||
|---|---|---|
|
|
||||||
| `anim.noise(x [, y [, z]])` | `double` | 値域 0〜1 の 1〜3 次元スムースノイズ(格子点ハッシュによる補間) |
|
|
||||||
| `anim.rand([max, ] seed)` | `double` | シードベースの決定論的乱数。引数 1 個でシードのみ、2 個で `[0, max]`、3 個で `[min, max]` |
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### 8. スクリプト API(ymm4 テーブル)
|
|
||||||
|
|
||||||
`ymm4` テーブルは YMM4 固有の情報を提供します。
|
|
||||||
|
|
||||||
| メンバー | 型 | 説明 |
|
|
||||||
|---|---|---|
|
|
||||||
| `ymm4.group_index` | `int` | エフェクトグループ内のインデックス |
|
|
||||||
| `ymm4.group_count` | `int` | エフェクトグループの総数 |
|
|
||||||
| `ymm4.group_ratio` | `double` | `group_index / group_count`(0 除算時は 0) |
|
|
||||||
| `ymm4.timeline_totalframe` | `int` | タイムライン全体の総フレーム数 |
|
|
||||||
| `ymm4.timeline_totaltime` | `double` | タイムライン全体の総時間(秒) |
|
|
||||||
| `ymm4.is_saving` | `bool` | エクスポート中かどうか |
|
|
||||||
| `ymm4.time_ratio` | `double` | アイテム内の時間比率(Frame / TotalFrame) |
|
|
||||||
| `ymm4.is_playing` | `bool` | 再生中かどうか |
|
|
||||||
| `ymm4.is_paused` | `bool` | 一時停止中かどうか |
|
|
||||||
| `ymm4.scene_id` | `string` | シーン ID(GUID 文字列) |
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### 9. ピクセルデータプロキシ(PixelDataProxy)
|
|
||||||
|
|
||||||
`PixelDataProxy` は `[MoonSharpUserData]` 属性を持つ内部クラスで、
|
|
||||||
`obj.getpixeldata()` の戻り値として Lua から直接操作できます。
|
|
||||||
|
|
||||||
- `width`・`height`:画像の幅と高さを返却する読み取り専用メンバーです。
|
|
||||||
- `get(index)`:1 始まりのフラットインデックスでチャンネルデータを取得します。
|
|
||||||
チャンネル順は `R, G, B, A` の 4 チャンネルで 1 ピクセルを構成し、
|
|
||||||
`R`・`G`・`B` はプリマルチプライ済みからストレートアルファに復元した 0〜255 の値、
|
|
||||||
`A` は 0〜255 のアルファ値を返却します。
|
|
||||||
- `set(index, value)`:1 始まりのフラットインデックスでチャンネルデータを書き込みます。
|
|
||||||
`R`・`G`・`B` チャンネルはストレートアルファの値をプリマルチプライ済みに変換して格納します。
|
|
||||||
`A` チャンネルを変更すると、既存の RGB 成分を新旧アルファ比でスケーリングして整合させます。
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### 10. コードエディター拡張
|
|
||||||
|
|
||||||
#### LuaFoldingStrategy
|
|
||||||
|
|
||||||
AvalonEdit 向けの折り畳み戦略を実装します。
|
|
||||||
`function`・`do`・`if` / `end` ブロックと `repeat` / `until` ブロックを対象に
|
|
||||||
複数行にまたがるブロックの折り畳み領域を生成します。
|
|
||||||
複数行コメント(`--[[ ... ]]`)・文字列リテラル・単行コメントを正規表現でトークン化し、
|
|
||||||
ブロック開閉を誤認しないよう除外します。
|
|
||||||
|
|
||||||
#### LuaAutoCompletionStrategy
|
|
||||||
|
|
||||||
AvalonEdit 向けのオートコンプリート戦略を実装します。
|
|
||||||
|
|
||||||
提供する補完候補は以下のとおりです。
|
|
||||||
|
|
||||||
- Lua キーワード(`and`・`break`・`do`・`else`・`elseif`・`end`・`false`・`for`・
|
|
||||||
`function`・`goto`・`if`・`in`・`local`・`nil`・`not`・`or`・`repeat`・`return`・
|
|
||||||
`then`・`true`・`until`・`while`)
|
|
||||||
- グローバル変数(`time`・`frame`・`totalframe`・`framerate`・`timelineframe`・
|
|
||||||
`timelinetime`・`layer`・`obj`・`scene`・`anim`・`ymm4`・`math`・`string`・`table`・
|
|
||||||
`bit32`・`type`・`tostring`・`tonumber`・`select`・`error`・`assert`・`print`・
|
|
||||||
`ipairs`・`pairs`・`next`・`unpack`・`setmetatable`・`getmetatable`・`rawget`・
|
|
||||||
`rawset`・`rawequal`・`rawlen`・`pcall`・`xpcall`)
|
|
||||||
- 各名前空間のメンバー(ドット入力後に絞り込み)
|
|
||||||
- ソースコード内のユーザー定義関数(`function foo()`・`local function foo()` のパターンを抽出)
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### 11. ツールバー(LuaScriptToolBar)
|
|
||||||
|
|
||||||
コードエディター上部に表示される WPF `UserControl` です。
|
|
||||||
|
|
||||||
- インポートボタン:ファイルダイアログで `.lua` ファイルを選択し、
|
|
||||||
UTF-8 として読み込んでスクリプトに設定します。
|
|
||||||
- エクスポートボタン:現在のスクリプトを UTF-8 BOM なしで `.lua` ファイルに保存します。
|
|
||||||
複数選択時は最初のアイテムのスクリプトを保存します。
|
|
||||||
- クリアボタン:確認ダイアログ後にスクリプトを `DefaultScript` へリセットします。
|
|
||||||
|
|
||||||
ファイルアクセスエラーは `IOException`・`UnauthorizedAccessException` を捕捉して
|
|
||||||
メッセージボックスで通知します。
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### 12. 例外定義
|
|
||||||
|
|
||||||
| クラス | 基底 | 説明 |
|
|
||||||
|---|---|---|
|
|
||||||
| `LuaScriptException` | `Exception` | Lua スクリプト例外の基底クラス(内部抽象クラス) |
|
|
||||||
| `LuaScriptCompilationException` | `LuaScriptException` | 構文エラー時にスローされます。 |
|
|
||||||
| `LuaScriptRuntimeException` | `LuaScriptException` | 実行時エラーまたはタイムアウト時にスローされます。 |
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### 13. ローカライズ(Texts)
|
|
||||||
|
|
||||||
`Texts` クラスは `[AutoGenLocalizer]` 属性を持つ `partial` クラスとして宣言されます。
|
|
||||||
`YukkuriMovieMaker.Generator` のソースジェネレーターが `Texts.csv` を処理し、
|
|
||||||
各ロケールのリソースファイルを自動生成します。
|
|
||||||
|
|
||||||
対応言語:日本語 (`ja-jp`)・英語 (`en-us`)・中国語簡体字 (`zh-cn`)・中国語繁体字 (`zh-tw`)・
|
|
||||||
韓国語 (`ko-kr`)・スペイン語 (`es-es`)・アラビア語 (`ar-sa`)・インドネシア語 (`id-id`)
|
|
||||||
|
|
||||||
ローカライズキーの一覧は以下のとおりです。
|
|
||||||
|
|
||||||
| キー | ja-jp |
|
|
||||||
|---|---|
|
|
||||||
| `LuaScript` | Lua スクリプト |
|
|
||||||
| `ScriptGroup` | スクリプト |
|
|
||||||
| `ScriptCode` | スクリプトコード |
|
|
||||||
| `ScriptCodeDesc` | Lua スクリプトを記述します。obj.x/y/zoom/alpha 等でエフェクトを制御できます。 |
|
|
||||||
| `ParametersGroup` | パラメータ |
|
|
||||||
| `Track0` | トラック 0 |
|
|
||||||
| `Track1` | トラック 1 |
|
|
||||||
| `Track2` | トラック 2 |
|
|
||||||
| `Track3` | トラック 3 |
|
|
||||||
| `TrackDesc` | スライダー値(AviUtl 準拠 track0〜3 に対応) |
|
|
||||||
| `ToolBarImport` | インポート |
|
|
||||||
| `ToolBarExport` | エクスポート |
|
|
||||||
| `ToolBarClear` | クリア |
|
|
||||||
| `ToolBarClearConfirm` | スクリプトをデフォルトに戻しますか? |
|
|
||||||
| `ToolBarClearTitle` | 確認 |
|
|
||||||
| `ToolBarImportErrorTitle` | インポートエラー |
|
|
||||||
| `ToolBarExportErrorTitle` | エクスポートエラー |
|
|
||||||
| `LuaFileFilter` | Lua スクリプト (*.lua) \| *.lua \| すべてのファイル (*.*) \| *.* |
|
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
Lua License
|
||||||
|
-----------
|
||||||
|
|
||||||
|
Lua is licensed under the terms of the MIT license reproduced below. This means
|
||||||
|
that Lua is free software and can be used for both academic and commercial
|
||||||
|
purposes at absolutely no cost.
|
||||||
|
|
||||||
|
For details and rationale, see https://www.lua.org/license.html .
|
||||||
|
|
||||||
|
===============================================================================
|
||||||
|
|
||||||
|
Copyright (C) 1994-2025 Lua.org, PUC-Rio.
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in
|
||||||
|
all copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||||
|
THE SOFTWARE.
|
||||||
|
|
||||||
|
===============================================================================
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
===============================================================================
|
||||||
|
LuaJIT -- a Just-In-Time Compiler for Lua. https://luajit.org/
|
||||||
|
|
||||||
|
Copyright (C) 2005-2026 Mike Pall. All rights reserved.
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in
|
||||||
|
all copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||||
|
THE SOFTWARE.
|
||||||
|
|
||||||
|
[ MIT license: https://www.opensource.org/licenses/mit-license.php ]
|
||||||
|
|
||||||
|
===============================================================================
|
||||||
|
[ LuaJIT includes code from Lua 5.1/5.2, which has this license statement: ]
|
||||||
|
|
||||||
|
Copyright (C) 1994-2012 Lua.org, PUC-Rio.
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in
|
||||||
|
all copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||||
|
THE SOFTWARE.
|
||||||
|
|
||||||
|
===============================================================================
|
||||||
|
[ LuaJIT includes code from dlmalloc, which has this license statement: ]
|
||||||
|
|
||||||
|
This is a version (aka dlmalloc) of malloc/free/realloc written by
|
||||||
|
Doug Lea and released to the public domain, as explained at
|
||||||
|
https://creativecommons.org/licenses/publicdomain
|
||||||
|
|
||||||
|
===============================================================================
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
Copyright (c) 2014-2016, Marco Mastropaolo
|
||||||
|
All rights reserved.
|
||||||
|
|
||||||
|
Parts of the string library are based on the KopiLua project (https://github.com/NLua/KopiLua)
|
||||||
|
Copyright (c) 2012 LoDC
|
||||||
|
|
||||||
|
Visual Studio Code debugger code is based on code from Microsoft vscode-mono-debug project (https://github.com/Microsoft/vscode-mono-debug).
|
||||||
|
Copyright (c) Microsoft Corporation - released under MIT license.
|
||||||
|
|
||||||
|
Remote Debugger icons are from the Eclipse project (https://www.eclipse.org/).
|
||||||
|
Copyright of The Eclipse Foundation
|
||||||
|
|
||||||
|
The MoonSharp icon is (c) Isaac, 2014-2015
|
||||||
|
|
||||||
|
Redistribution and use in source and binary forms, with or without
|
||||||
|
modification, are permitted provided that the following conditions are met:
|
||||||
|
|
||||||
|
* Redistributions of source code must retain the above copyright notice, this
|
||||||
|
list of conditions and the following disclaimer.
|
||||||
|
|
||||||
|
* Redistributions in binary form must reproduce the above copyright notice,
|
||||||
|
this list of conditions and the following disclaimer in the documentation
|
||||||
|
and/or other materials provided with the distribution.
|
||||||
|
|
||||||
|
* Neither the name of the {organization} nor the names of its
|
||||||
|
contributors may be used to endorse or promote products derived from
|
||||||
|
this software without specific prior written permission.
|
||||||
|
|
||||||
|
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||||
|
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||||
|
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||||
|
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||||
|
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||||
|
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||||
|
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||||
|
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||||
|
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||||
|
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||||
@@ -1,11 +1,11 @@
|
|||||||
========================================
|
========================================
|
||||||
Luaスクリプト for YMM4 v1.0.0
|
Luaスクリプト for YMM4 v1.20.3
|
||||||
========================================
|
========================================
|
||||||
YukkuriMovieMaker4(YMM4)上で動作する、Luaスクリプトで映像エフェクトのパラメータや
|
YukkuriMovieMaker4(YMM4)上で動作する、Luaスクリプトで映像エフェクトのパラメータや
|
||||||
ピクセルを直接制御できるプラグインです。
|
ピクセルを直接制御できるプラグインです。
|
||||||
スクリプトの実行にはMoonSharpによるLuaインタプリタを使用しており、座標・拡大率・
|
スクリプトの実行にはMoonSharpによるLuaインタプリタを使用しており、座標・拡大率・
|
||||||
透明度・回転といった描画パラメータの変更に加えて、ピクセル単位での読み書きにも
|
透明度・回転といった描画パラメータの変更に加えて、ピクセル単位での読み書きや、
|
||||||
対応しています。
|
塗りつぶし・領域の一括読み書き・畳み込み・拡大縮小による画像加工にも対応しています。
|
||||||
obj.x/y/zoom/alpha等の値はキーフレームアニメーションと連動するTrack0~3パラメータ
|
obj.x/y/zoom/alpha等の値はキーフレームアニメーションと連動するTrack0~3パラメータ
|
||||||
からも参照でき、anim.*関数群によるイージングやノイズ等の演出も組み合わせられます。
|
からも参照でき、anim.*関数群によるイージングやノイズ等の演出も組み合わせられます。
|
||||||
--------------------------------------------------------------------------------
|
--------------------------------------------------------------------------------
|
||||||
@@ -26,7 +26,9 @@ obj.x/y/zoom/alpha等の値はキーフレームアニメーションと連動
|
|||||||
|
|
||||||
- スクリプトエラー時の挙動: コンパイルエラーまたは実行時エラーが発生した場合、
|
- スクリプトエラー時の挙動: コンパイルエラーまたは実行時エラーが発生した場合、
|
||||||
そのフレームでの座標・透明度・回転・ピクセルの変更は適用されず、入力された
|
そのフレームでの座標・透明度・回転・ピクセルの変更は適用されず、入力された
|
||||||
元の状態がそのまま出力されます。エラー内容はログへ出力されます。
|
元の状態がそのまま出力されます。エラー内容はログへ出力されるほか、スクリプト
|
||||||
|
エディタの該当箇所へ赤い波線が表示され、ポイントするとエラー内容をツールチップ
|
||||||
|
で確認できます。
|
||||||
|
|
||||||
- ファイルアクセスの制限: スクリプトからのファイル読み込みは許可されておらず、
|
- ファイルアクセスの制限: スクリプトからのファイル読み込みは許可されておらず、
|
||||||
io・os等のモジュールも有効化されていません。
|
io・os等のモジュールも有効化されていません。
|
||||||
|
|||||||
@@ -69,9 +69,20 @@ jobs:
|
|||||||
$pkgName = "LuaScript_$version.ymme"
|
$pkgName = "LuaScript_$version.ymme"
|
||||||
|
|
||||||
New-Item -ItemType Directory -Path "$stageRoot/docs" -Force | Out-Null
|
New-Item -ItemType Directory -Path "$stageRoot/docs" -Force | Out-Null
|
||||||
|
New-Item -ItemType Directory -Path "$stageRoot/native" -Force | Out-Null
|
||||||
|
New-Item -ItemType Directory -Path "$stageRoot/LICENSE" -Force | Out-Null
|
||||||
|
|
||||||
Copy-Item "$outDir/LuaScript.dll" "$stageRoot/"
|
Copy-Item "$outDir/LuaScript.dll" "$stageRoot/"
|
||||||
|
Copy-Item "$outDir/LuaScript.Kernel.dll" "$stageRoot/"
|
||||||
|
Copy-Item "$outDir/LuaScript.Compat.dll" "$stageRoot/"
|
||||||
|
Copy-Item "$outDir/LuaScript.Media.dll" "$stageRoot/"
|
||||||
|
Copy-Item "$outDir/LuaScript.Runtime.dll" "$stageRoot/"
|
||||||
|
Copy-Item "$outDir/LuaScript.Gpu.dll" "$stageRoot/"
|
||||||
Copy-Item "$outDir/MoonSharp.Interpreter.dll" "$stageRoot/"
|
Copy-Item "$outDir/MoonSharp.Interpreter.dll" "$stageRoot/"
|
||||||
|
Copy-Item "$outDir/native/luajit.exe" "$stageRoot/native/"
|
||||||
|
Copy-Item "$outDir/native/lua51.dll" "$stageRoot/native/"
|
||||||
|
Copy-Item "$outDir/native/worker.lua" "$stageRoot/native/"
|
||||||
|
Copy-Item "$outDir/native/shim.lua" "$stageRoot/native/"
|
||||||
|
|
||||||
foreach ($lang in @("ar-sa", "en-us", "es-es", "id-id", "ko-kr", "zh-cn", "zh-tw")) {
|
foreach ($lang in @("ar-sa", "en-us", "es-es", "id-id", "ko-kr", "zh-cn", "zh-tw")) {
|
||||||
$src = "$outDir/$lang"
|
$src = "$outDir/$lang"
|
||||||
@@ -82,6 +93,7 @@ jobs:
|
|||||||
}
|
}
|
||||||
|
|
||||||
Copy-Item "LuaScript/docs/LuaScript.*.txt" "$stageRoot/docs/"
|
Copy-Item "LuaScript/docs/LuaScript.*.txt" "$stageRoot/docs/"
|
||||||
|
Copy-Item ".github/LICENSE/*.txt" "$stageRoot/LICENSE/"
|
||||||
Copy-Item ".github/Plugin_Readme.txt" "$stageRoot/Readme.txt"
|
Copy-Item ".github/Plugin_Readme.txt" "$stageRoot/Readme.txt"
|
||||||
|
|
||||||
Compress-Archive -Path "stage/*" -DestinationPath $pkgName -CompressionLevel Optimal
|
Compress-Archive -Path "stage/*" -DestinationPath $pkgName -CompressionLevel Optimal
|
||||||
|
|||||||
+1
-1
@@ -1,3 +1,3 @@
|
|||||||
[submodule "YukkuriMovieMaker.Generator"]
|
[submodule "YukkuriMovieMaker.Generator"]
|
||||||
path = YukkuriMovieMaker.Generator
|
path = YukkuriMovieMaker.Generator
|
||||||
url = https://github.com/manju-summoner/YukkuriMovieMaker.Generator.git
|
url = https://git.routersys.com/manju-summoner/YukkuriMovieMaker.Generator.git
|
||||||
@@ -0,0 +1,195 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace LuaScript.Compat
|
||||||
|
{
|
||||||
|
internal sealed class AviUtlAudioConverter
|
||||||
|
{
|
||||||
|
public const int MaxSamples = 1024;
|
||||||
|
public const int SpectrumWindow = 1024;
|
||||||
|
public const int FourierWindow = 2048;
|
||||||
|
public const int SpectrumBins = SpectrumWindow / 2;
|
||||||
|
|
||||||
|
private const double PcmScale = 32768d;
|
||||||
|
|
||||||
|
private readonly double[] _mono = new double[FourierWindow];
|
||||||
|
private readonly double[] _real = new double[FourierWindow];
|
||||||
|
private readonly double[] _imag = new double[FourierWindow];
|
||||||
|
|
||||||
|
private enum DataKind
|
||||||
|
{
|
||||||
|
Unknown,
|
||||||
|
Pcm,
|
||||||
|
Spectrum,
|
||||||
|
Fourier,
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int RequiredFrames(string type, int size)
|
||||||
|
{
|
||||||
|
var (kind, _) = Parse(type);
|
||||||
|
return kind switch
|
||||||
|
{
|
||||||
|
DataKind.Pcm => ResolveCount(kind, size),
|
||||||
|
DataKind.Spectrum => SpectrumWindow,
|
||||||
|
DataKind.Fourier => FourierWindow,
|
||||||
|
_ => 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public int Convert(string type, ReadOnlySpan<float> interleaved, int frames, int size, Span<double> destination)
|
||||||
|
{
|
||||||
|
var (kind, channel) = Parse(type);
|
||||||
|
if (kind == DataKind.Unknown || frames <= 0)
|
||||||
|
return 0;
|
||||||
|
|
||||||
|
int window = kind switch
|
||||||
|
{
|
||||||
|
DataKind.Pcm => Math.Min(frames, ResolveCount(kind, size)),
|
||||||
|
DataKind.Spectrum => SpectrumWindow,
|
||||||
|
_ => FourierWindow,
|
||||||
|
};
|
||||||
|
FillMono(interleaved, frames, channel, window);
|
||||||
|
|
||||||
|
switch (kind)
|
||||||
|
{
|
||||||
|
case DataKind.Pcm:
|
||||||
|
{
|
||||||
|
int count = Math.Min(ResolveCount(kind, size), frames);
|
||||||
|
for (int i = 0; i < count; i++)
|
||||||
|
destination[i] = Math.Clamp(_mono[i] * PcmScale, -32768d, 32767d);
|
||||||
|
return count;
|
||||||
|
}
|
||||||
|
case DataKind.Spectrum:
|
||||||
|
{
|
||||||
|
int bands = ResolveCount(kind, size);
|
||||||
|
Fft(SpectrumWindow);
|
||||||
|
double scale = 2d / SpectrumWindow * PcmScale;
|
||||||
|
for (int b = 0; b < bands; b++)
|
||||||
|
{
|
||||||
|
int start = b * SpectrumBins / bands;
|
||||||
|
int end = (b + 1) * SpectrumBins / bands;
|
||||||
|
if (end <= start)
|
||||||
|
end = start + 1;
|
||||||
|
double sum = 0d;
|
||||||
|
for (int bin = start; bin < end; bin++)
|
||||||
|
sum += Magnitude(bin);
|
||||||
|
destination[b] = sum / (end - start) * scale;
|
||||||
|
}
|
||||||
|
return bands;
|
||||||
|
}
|
||||||
|
case DataKind.Fourier:
|
||||||
|
{
|
||||||
|
int count = ResolveCount(kind, size);
|
||||||
|
Fft(FourierWindow);
|
||||||
|
double scale = 2d / FourierWindow;
|
||||||
|
for (int i = 0; i < count; i++)
|
||||||
|
destination[i] = Magnitude(i + 1) * scale;
|
||||||
|
return count;
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int ResolveCount(DataKind kind, int size)
|
||||||
|
{
|
||||||
|
int fallback = kind == DataKind.Spectrum ? 32 : MaxSamples;
|
||||||
|
int max = kind == DataKind.Spectrum ? SpectrumBins : MaxSamples;
|
||||||
|
return size <= 0 ? Math.Min(fallback, max) : Math.Clamp(size, 1, max);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static (DataKind Kind, int Channel) Parse(string type)
|
||||||
|
{
|
||||||
|
int channel = 0;
|
||||||
|
int length = type.Length;
|
||||||
|
if (length >= 2 && type[length - 2] == '.')
|
||||||
|
{
|
||||||
|
char suffix = type[length - 1];
|
||||||
|
if (suffix == 'l')
|
||||||
|
channel = 1;
|
||||||
|
else if (suffix == 'r')
|
||||||
|
channel = 2;
|
||||||
|
if (channel != 0)
|
||||||
|
length -= 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
var name = type.AsSpan(0, length);
|
||||||
|
DataKind kind = DataKind.Unknown;
|
||||||
|
if (name.SequenceEqual("pcm"))
|
||||||
|
kind = DataKind.Pcm;
|
||||||
|
else if (name.SequenceEqual("spectrum"))
|
||||||
|
kind = DataKind.Spectrum;
|
||||||
|
else if (name.SequenceEqual("fourier"))
|
||||||
|
kind = DataKind.Fourier;
|
||||||
|
return (kind, channel);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void FillMono(ReadOnlySpan<float> interleaved, int frames, int channel, int window)
|
||||||
|
{
|
||||||
|
int available = Math.Min(frames, window);
|
||||||
|
for (int i = 0; i < available; i++)
|
||||||
|
{
|
||||||
|
float left = interleaved[i * 2];
|
||||||
|
float right = interleaved[i * 2 + 1];
|
||||||
|
_mono[i] = channel switch
|
||||||
|
{
|
||||||
|
1 => left,
|
||||||
|
2 => right,
|
||||||
|
_ => (left + right) * 0.5d,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
for (int i = available; i < window; i++)
|
||||||
|
_mono[i] = 0d;
|
||||||
|
}
|
||||||
|
|
||||||
|
private double Magnitude(int bin) =>
|
||||||
|
Math.Sqrt(_real[bin] * _real[bin] + _imag[bin] * _imag[bin]);
|
||||||
|
|
||||||
|
private void Fft(int n)
|
||||||
|
{
|
||||||
|
for (int i = 0; i < n; i++)
|
||||||
|
{
|
||||||
|
_real[i] = _mono[i];
|
||||||
|
_imag[i] = 0d;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int i = 1, j = 0; i < n; i++)
|
||||||
|
{
|
||||||
|
int bit = n >> 1;
|
||||||
|
for (; (j & bit) != 0; bit >>= 1)
|
||||||
|
j ^= bit;
|
||||||
|
j |= bit;
|
||||||
|
if (i < j)
|
||||||
|
{
|
||||||
|
(_real[i], _real[j]) = (_real[j], _real[i]);
|
||||||
|
(_imag[i], _imag[j]) = (_imag[j], _imag[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int len = 2; len <= n; len <<= 1)
|
||||||
|
{
|
||||||
|
double angle = -2d * Math.PI / len;
|
||||||
|
double wRe = Math.Cos(angle);
|
||||||
|
double wIm = Math.Sin(angle);
|
||||||
|
for (int i = 0; i < n; i += len)
|
||||||
|
{
|
||||||
|
double curRe = 1d;
|
||||||
|
double curIm = 0d;
|
||||||
|
for (int k = 0; k < len / 2; k++)
|
||||||
|
{
|
||||||
|
int a = i + k;
|
||||||
|
int b = i + k + len / 2;
|
||||||
|
double tRe = _real[b] * curRe - _imag[b] * curIm;
|
||||||
|
double tIm = _real[b] * curIm + _imag[b] * curRe;
|
||||||
|
_real[b] = _real[a] - tRe;
|
||||||
|
_imag[b] = _imag[a] - tIm;
|
||||||
|
_real[a] += tRe;
|
||||||
|
_imag[a] += tIm;
|
||||||
|
double nextRe = curRe * wRe - curIm * wIm;
|
||||||
|
curIm = curRe * wIm + curIm * wRe;
|
||||||
|
curRe = nextRe;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<aviUtlCompat>
|
||||||
|
<effect engine="both" names="ぼかし" target="GaussianBlurEffect">
|
||||||
|
<param name="範囲" property="Blur" scale="0.5" />
|
||||||
|
<param name="サイズ固定" property="IsHardBorderMode" />
|
||||||
|
</effect>
|
||||||
|
<effect engine="both" names="境界ぼかし" target="BorderBlurEffect">
|
||||||
|
<param name="範囲" property="Blur" />
|
||||||
|
</effect>
|
||||||
|
<effect engine="both" names="方向ブラー" target="DirectionalBlurEffect">
|
||||||
|
<param name="範囲" property="StandardDeviation" scale="0.5" />
|
||||||
|
<param name="角度" property="Angle" />
|
||||||
|
<param name="サイズ固定" property="IsHardBorderMode" />
|
||||||
|
</effect>
|
||||||
|
<effect engine="both" names="放射ブラー" target="RadialBlurEffect">
|
||||||
|
<param name="範囲" property="Blur" />
|
||||||
|
<param name="X" property="X" />
|
||||||
|
<param name="Y" property="Y" />
|
||||||
|
<param name="サイズを固定" property="IsHardBorderMode" />
|
||||||
|
</effect>
|
||||||
|
<effect engine="both" names="閃光" target="RadialLightEffect">
|
||||||
|
<param name="範囲" property="Value" />
|
||||||
|
<param name="X" property="X" />
|
||||||
|
<param name="Y" property="Y" />
|
||||||
|
<param name="サイズを固定" property="IsHardBorderMode" />
|
||||||
|
</effect>
|
||||||
|
<effect engine="both" names="クロマキー" target="ChromaKeyEffect">
|
||||||
|
<param name="色相範囲" property="Tolerance" scale="0.390625" />
|
||||||
|
<param name="境界補正" property="Feather" />
|
||||||
|
</effect>
|
||||||
|
<effect engine="both" names="クリッピング" target="CropEffect">
|
||||||
|
<param name="上" property="Top" />
|
||||||
|
<param name="下" property="Bottom" />
|
||||||
|
<param name="左" property="Left" />
|
||||||
|
<param name="右" property="Right" />
|
||||||
|
<param name="中心の位置を変更" property="IsCentering" />
|
||||||
|
</effect>
|
||||||
|
<effect engine="both" names="斜めクリッピング" target="CropByAngleEffect">
|
||||||
|
<param name="中心X" property="X" />
|
||||||
|
<param name="中心Y" property="Y" />
|
||||||
|
<param name="角度" property="Angle" />
|
||||||
|
<param name="ぼかし" property="Blur" scale="0.5" />
|
||||||
|
<param name="幅" property="Width" />
|
||||||
|
</effect>
|
||||||
|
<effect engine="both" names="領域拡張" target="MarginEffect">
|
||||||
|
<param name="上" property="Top" />
|
||||||
|
<param name="下" property="Bottom" />
|
||||||
|
<param name="左" property="Left" />
|
||||||
|
<param name="右" property="Right" />
|
||||||
|
</effect>
|
||||||
|
<effect engine="both" names="座標" target="DrawPositionEffect">
|
||||||
|
<param name="X" property="X" />
|
||||||
|
<param name="Y" property="Y" />
|
||||||
|
<param name="Z" property="Z" />
|
||||||
|
</effect>
|
||||||
|
<effect engine="both" names="回転" target="RotateEffect">
|
||||||
|
<param name="X" property="X" />
|
||||||
|
<param name="Y" property="Y" />
|
||||||
|
<param name="Z" property="Z" />
|
||||||
|
</effect>
|
||||||
|
<effect engine="both" names="リサイズ" target="ZoomEffect">
|
||||||
|
<param name="拡大率" property="Zoom" />
|
||||||
|
<param name="X" property="ZoomX" />
|
||||||
|
<param name="Y" property="ZoomY" />
|
||||||
|
<param name="補間なし" property="IsNearestNeighbor" />
|
||||||
|
</effect>
|
||||||
|
<effect engine="both" names="画像ループ" target="TilingEffect">
|
||||||
|
<param name="横回数" property="X" />
|
||||||
|
<param name="縦回数" property="Y" />
|
||||||
|
</effect>
|
||||||
|
<effect engine="both" names="極座標変換" target="PolarTransformEffect">
|
||||||
|
<param name="中心幅" property="CoreWidth" />
|
||||||
|
<param name="渦巻" property="TwistAngle" scale="360" />
|
||||||
|
</effect>
|
||||||
|
<effect engine="both" names="グラデーション" target="GradientEffect">
|
||||||
|
<param name="強さ" property="Opacity" />
|
||||||
|
<param name="中心X" property="X" />
|
||||||
|
<param name="中心Y" property="Y" />
|
||||||
|
<param name="角度" property="Rotation" />
|
||||||
|
<param name="幅" property="Size" />
|
||||||
|
</effect>
|
||||||
|
<effect engine="both" names="単色化" target="MonocolorizationEffect">
|
||||||
|
<param name="強さ" property="Strength" />
|
||||||
|
<param name="輝度を保持する" property="KeepBrightness" />
|
||||||
|
</effect>
|
||||||
|
<effect engine="both" names="縁取り" target="OutlineEffect">
|
||||||
|
<param name="サイズ" property="StrokeThickness" />
|
||||||
|
<param name="ぼかし" property="Blur" />
|
||||||
|
</effect>
|
||||||
|
<effect engine="both" names="反転" target="InvertEffect" />
|
||||||
|
<effect engine="both" names="モザイク" target="MosaicEffect">
|
||||||
|
<param name="サイズ" property="Size" />
|
||||||
|
</effect>
|
||||||
|
<effect engine="both" names="ディスプレイスメントマップ" target="DisplacementMapEffect">
|
||||||
|
<param name="ぼかし" property="Blur" scale="0.5" />
|
||||||
|
</effect>
|
||||||
|
<effect engine="both" names="動画ファイル合成" target="TextureEffect">
|
||||||
|
<param name="X" property="X" />
|
||||||
|
<param name="Y" property="Y" />
|
||||||
|
<param name="拡大率" property="Zoom" />
|
||||||
|
</effect>
|
||||||
|
<effect engine="both" names="色調補正" target="ColorCorrectionEffect">
|
||||||
|
<param name="明るさ" property="Lightness" />
|
||||||
|
<param name="コントラスト" property="Contrast" />
|
||||||
|
<param name="色相" property="HueRotation" />
|
||||||
|
<param name="輝度" property="Brightness" />
|
||||||
|
<param name="彩度" property="Saturation" />
|
||||||
|
</effect>
|
||||||
|
<effect engine="both" names="色ずれ" target="ColorShiftEffect">
|
||||||
|
<param name="ずれ幅" property="Shift" />
|
||||||
|
<param name="角度" property="Angle" />
|
||||||
|
<param name="強さ" property="Strength" />
|
||||||
|
</effect>
|
||||||
|
</aviUtlCompat>
|
||||||
@@ -0,0 +1,137 @@
|
|||||||
|
namespace LuaScript.Compat
|
||||||
|
{
|
||||||
|
internal static class AviUtlGlobalFunctions
|
||||||
|
{
|
||||||
|
public static int BitOr(double a, double b) => ToBitOperand(a) | ToBitOperand(b);
|
||||||
|
|
||||||
|
public static int BitAnd(double a, double b) => ToBitOperand(a) & ToBitOperand(b);
|
||||||
|
|
||||||
|
public static int BitXor(double a, double b) => ToBitOperand(a) ^ ToBitOperand(b);
|
||||||
|
|
||||||
|
public static int BitShift(double value, double shift)
|
||||||
|
{
|
||||||
|
int v = ToBitOperand(value);
|
||||||
|
int n = ToBitOperand(shift);
|
||||||
|
return n >= 0 ? v << n : v >> -n;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int ToBitOperand(double value)
|
||||||
|
{
|
||||||
|
if (double.IsNaN(value))
|
||||||
|
return 0;
|
||||||
|
if (value <= int.MinValue)
|
||||||
|
return int.MinValue;
|
||||||
|
if (value >= int.MaxValue)
|
||||||
|
return int.MaxValue;
|
||||||
|
return (int)Math.Ceiling(value - 0.5);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int RgbCompose(double r, double g, double b) =>
|
||||||
|
(ToColorChannel(r) << 16) | (ToColorChannel(g) << 8) | ToColorChannel(b);
|
||||||
|
|
||||||
|
public static void RgbComponents(double color, out int r, out int g, out int b)
|
||||||
|
{
|
||||||
|
int c = ToColor(color);
|
||||||
|
r = (c >> 16) & 0xFF;
|
||||||
|
g = (c >> 8) & 0xFF;
|
||||||
|
b = c & 0xFF;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int RgbInterpolate(double r1, double g1, double b1, double r2, double g2, double b2, double t) =>
|
||||||
|
RgbCompose(r1 + (r2 - r1) * t, g1 + (g2 - g1) * t, b1 + (b2 - b1) * t);
|
||||||
|
|
||||||
|
public static int HsvCompose(double h, double s, double v)
|
||||||
|
{
|
||||||
|
h = WrapHue(h);
|
||||||
|
s = ClampRatio(s);
|
||||||
|
v = ClampRatio(v);
|
||||||
|
|
||||||
|
double c = v * s;
|
||||||
|
double x = c * (1d - Math.Abs(h / 60d % 2d - 1d));
|
||||||
|
double m = v - c;
|
||||||
|
int sector = (int)Math.Floor(h / 60d);
|
||||||
|
|
||||||
|
double r, g, b;
|
||||||
|
if (sector == 0) { r = c; g = x; b = 0d; }
|
||||||
|
else if (sector == 1) { r = x; g = c; b = 0d; }
|
||||||
|
else if (sector == 2) { r = 0d; g = c; b = x; }
|
||||||
|
else if (sector == 3) { r = 0d; g = x; b = c; }
|
||||||
|
else if (sector == 4) { r = x; g = 0d; b = c; }
|
||||||
|
else { r = c; g = 0d; b = x; }
|
||||||
|
|
||||||
|
return (ToColorChannel(RoundHalfUp((r + m) * 255d)) << 16) |
|
||||||
|
(ToColorChannel(RoundHalfUp((g + m) * 255d)) << 8) |
|
||||||
|
ToColorChannel(RoundHalfUp((b + m) * 255d));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void HsvComponents(double color, out int h, out int s, out int v)
|
||||||
|
{
|
||||||
|
RgbComponents(color, out int r, out int g, out int b);
|
||||||
|
double rf = r / 255d;
|
||||||
|
double gf = g / 255d;
|
||||||
|
double bf = b / 255d;
|
||||||
|
|
||||||
|
double max = Math.Max(rf, Math.Max(gf, bf));
|
||||||
|
double min = Math.Min(rf, Math.Min(gf, bf));
|
||||||
|
double delta = max - min;
|
||||||
|
|
||||||
|
double hue = 0d;
|
||||||
|
if (delta > 0d)
|
||||||
|
{
|
||||||
|
if (max == rf)
|
||||||
|
hue = 60d * (((gf - bf) / delta % 6d + 6d) % 6d);
|
||||||
|
else if (max == gf)
|
||||||
|
hue = 60d * ((bf - rf) / delta + 2d);
|
||||||
|
else
|
||||||
|
hue = 60d * ((rf - gf) / delta + 4d);
|
||||||
|
}
|
||||||
|
|
||||||
|
h = (int)RoundHalfUp(hue);
|
||||||
|
s = (int)RoundHalfUp(max > 0d ? delta / max * 100d : 0d);
|
||||||
|
v = (int)RoundHalfUp(max * 100d);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int HsvInterpolate(double h1, double s1, double v1, double h2, double s2, double v2, double t) =>
|
||||||
|
HsvCompose(h1 + (h2 - h1) * t, s1 + (s2 - s1) * t, v1 + (v2 - v1) * t);
|
||||||
|
|
||||||
|
private static int ToColorChannel(double value)
|
||||||
|
{
|
||||||
|
if (double.IsNaN(value) || value <= 0d)
|
||||||
|
return 0;
|
||||||
|
if (value >= 255d)
|
||||||
|
return 255;
|
||||||
|
return (int)Math.Floor(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int ToColor(double value)
|
||||||
|
{
|
||||||
|
if (double.IsNaN(value))
|
||||||
|
return 0;
|
||||||
|
if (value <= int.MinValue)
|
||||||
|
value = int.MinValue;
|
||||||
|
else if (value >= int.MaxValue)
|
||||||
|
value = int.MaxValue;
|
||||||
|
long floored = (long)Math.Floor(value);
|
||||||
|
return (int)(floored & 0xFFFFFF);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static double WrapHue(double h)
|
||||||
|
{
|
||||||
|
if (double.IsNaN(h) || double.IsInfinity(h))
|
||||||
|
return 0d;
|
||||||
|
double wrapped = h - Math.Floor(h / 360d) * 360d;
|
||||||
|
return wrapped >= 360d ? 0d : wrapped;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static double ClampRatio(double value)
|
||||||
|
{
|
||||||
|
if (double.IsNaN(value) || value <= 0d)
|
||||||
|
return 0d;
|
||||||
|
if (value >= 100d)
|
||||||
|
return 1d;
|
||||||
|
return value / 100d;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static double RoundHalfUp(double value) => Math.Floor(value + 0.5);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace LuaScript.Compat
|
||||||
|
{
|
||||||
|
internal static class AviUtlRandom
|
||||||
|
{
|
||||||
|
public static double Next(double a, double b, double seed, double frame)
|
||||||
|
{
|
||||||
|
long seedBits = BitConverter.DoubleToInt64Bits(seed);
|
||||||
|
long frameBits = BitConverter.DoubleToInt64Bits(frame);
|
||||||
|
uint s = (uint)(seedBits ^ (seedBits >> 32));
|
||||||
|
uint f = (uint)(frameBits ^ (frameBits >> 32));
|
||||||
|
|
||||||
|
uint h = s * 374761393u + f * 668265263u;
|
||||||
|
h = (h ^ (h >> 13)) * 1274126177u;
|
||||||
|
h ^= h >> 16;
|
||||||
|
|
||||||
|
double r = h / 4294967295.0;
|
||||||
|
|
||||||
|
long lo = (long)Math.Floor(Math.Min(a, b));
|
||||||
|
long hi = (long)Math.Floor(Math.Max(a, b));
|
||||||
|
long span = hi - lo + 1L;
|
||||||
|
if (span <= 1L)
|
||||||
|
return lo;
|
||||||
|
|
||||||
|
long value = lo + (long)(r * span);
|
||||||
|
return value > hi ? hi : value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,109 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace LuaScript.Compat
|
||||||
|
{
|
||||||
|
internal static class Bit32
|
||||||
|
{
|
||||||
|
public static uint ToUInt32(double value) => unchecked((uint)(long)value);
|
||||||
|
|
||||||
|
public static uint Band(params double[] values)
|
||||||
|
{
|
||||||
|
uint accum = 0xFFFFFFFFu;
|
||||||
|
foreach (var value in values)
|
||||||
|
accum &= ToUInt32(value);
|
||||||
|
return accum;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static uint Bor(params double[] values)
|
||||||
|
{
|
||||||
|
uint accum = 0u;
|
||||||
|
foreach (var value in values)
|
||||||
|
accum |= ToUInt32(value);
|
||||||
|
return accum;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static uint Bxor(params double[] values)
|
||||||
|
{
|
||||||
|
uint accum = 0u;
|
||||||
|
foreach (var value in values)
|
||||||
|
accum ^= ToUInt32(value);
|
||||||
|
return accum;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static bool Btest(params double[] values) => Band(values) != 0u;
|
||||||
|
|
||||||
|
public static uint Bnot(double value) => ~ToUInt32(value);
|
||||||
|
|
||||||
|
public static uint Lshift(double value, double shift)
|
||||||
|
{
|
||||||
|
uint v = ToUInt32(value);
|
||||||
|
int a = (int)shift;
|
||||||
|
if (a <= -32 || a >= 32)
|
||||||
|
return 0u;
|
||||||
|
return a >= 0 ? v << a : v >> -a;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static uint Rshift(double value, double shift) => Lshift(value, -shift);
|
||||||
|
|
||||||
|
public static uint Arshift(double value, double shift)
|
||||||
|
{
|
||||||
|
uint v = ToUInt32(value);
|
||||||
|
int a = (int)shift;
|
||||||
|
if (a < 0)
|
||||||
|
return Lshift(value, -shift);
|
||||||
|
bool negative = (v & 0x80000000u) != 0u;
|
||||||
|
if (a >= 32)
|
||||||
|
return negative ? 0xFFFFFFFFu : 0u;
|
||||||
|
if (a == 0)
|
||||||
|
return v;
|
||||||
|
uint result = v >> a;
|
||||||
|
if (negative)
|
||||||
|
result |= ~0u << (32 - a);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static uint Lrotate(double value, double shift)
|
||||||
|
{
|
||||||
|
uint v = ToUInt32(value);
|
||||||
|
int a = ((int)shift % 32 + 32) % 32;
|
||||||
|
return a == 0 ? v : (v << a) | (v >> (32 - a));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static uint Rrotate(double value, double shift) => Lrotate(value, -shift);
|
||||||
|
|
||||||
|
public static uint Extract(double value, double pos, double? width)
|
||||||
|
{
|
||||||
|
uint v = ToUInt32(value);
|
||||||
|
int p = (int)pos;
|
||||||
|
int w = width is null ? 1 : (int)width.Value;
|
||||||
|
ValidatePosWidth(p, w);
|
||||||
|
return (v >> p) & NBitMask(w);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static uint Replace(double value, double replacement, double pos, double? width)
|
||||||
|
{
|
||||||
|
uint v = ToUInt32(value);
|
||||||
|
uint u = ToUInt32(replacement);
|
||||||
|
int p = (int)pos;
|
||||||
|
int w = width is null ? 1 : (int)width.Value;
|
||||||
|
ValidatePosWidth(p, w);
|
||||||
|
uint mask = NBitMask(w) << p;
|
||||||
|
return (v & ~mask) | ((u & NBitMask(w)) << p);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void ValidatePosWidth(int pos, int width)
|
||||||
|
{
|
||||||
|
if (pos < 0 || width < 1 || pos + width > 32)
|
||||||
|
throw new ArgumentException("trying to access non-existent bits");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static uint NBitMask(int bits)
|
||||||
|
{
|
||||||
|
if (bits <= 0)
|
||||||
|
return 0u;
|
||||||
|
if (bits >= 32)
|
||||||
|
return 0xFFFFFFFFu;
|
||||||
|
return (1u << bits) - 1u;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace LuaScript.Compat
|
||||||
|
{
|
||||||
|
internal static class MoonSharpBit32
|
||||||
|
{
|
||||||
|
private const double Modulo = 4294967296.0;
|
||||||
|
|
||||||
|
public static uint ToUInt32(double value) => unchecked((uint)Math.IEEERemainder(value, Modulo));
|
||||||
|
|
||||||
|
public static int ToInt32(double value) => unchecked((int)Math.IEEERemainder(value, Modulo));
|
||||||
|
|
||||||
|
public static uint Band(params double[] values)
|
||||||
|
{
|
||||||
|
uint accum = ToUInt32(values[0]);
|
||||||
|
for (int i = 1; i < values.Length; i++)
|
||||||
|
accum &= ToUInt32(values[i]);
|
||||||
|
return accum;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static uint Bor(params double[] values)
|
||||||
|
{
|
||||||
|
uint accum = ToUInt32(values[0]);
|
||||||
|
for (int i = 1; i < values.Length; i++)
|
||||||
|
accum |= ToUInt32(values[i]);
|
||||||
|
return accum;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static uint Bxor(params double[] values)
|
||||||
|
{
|
||||||
|
uint accum = ToUInt32(values[0]);
|
||||||
|
for (int i = 1; i < values.Length; i++)
|
||||||
|
accum ^= ToUInt32(values[i]);
|
||||||
|
return accum;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static bool Btest(params double[] values) => Band(values) != 0u;
|
||||||
|
|
||||||
|
public static uint Bnot(double value) => ~ToUInt32(value);
|
||||||
|
|
||||||
|
public static uint Lshift(double value, double shift)
|
||||||
|
{
|
||||||
|
uint v = ToUInt32(value);
|
||||||
|
int a = (int)shift;
|
||||||
|
return a < 0 ? v >> -a : v << a;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static uint Rshift(double value, double shift)
|
||||||
|
{
|
||||||
|
uint v = ToUInt32(value);
|
||||||
|
int a = (int)shift;
|
||||||
|
return a < 0 ? v << -a : v >> a;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int Arshift(double value, double shift)
|
||||||
|
{
|
||||||
|
int v = ToInt32(value);
|
||||||
|
int a = (int)shift;
|
||||||
|
return a < 0 ? v << -a : v >> a;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static uint Lrotate(double value, double shift)
|
||||||
|
{
|
||||||
|
uint v = ToUInt32(value);
|
||||||
|
int a = ((int)shift) % 32;
|
||||||
|
return a < 0 ? (v >> -a) | (v << (32 + a)) : (v << a) | (v >> (32 - a));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static uint Rrotate(double value, double shift)
|
||||||
|
{
|
||||||
|
uint v = ToUInt32(value);
|
||||||
|
int a = ((int)shift) % 32;
|
||||||
|
return a < 0 ? (v << -a) | (v >> (32 + a)) : (v >> a) | (v << (32 - a));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static uint Extract(double value, double pos, double? width)
|
||||||
|
{
|
||||||
|
uint v = ToUInt32(value);
|
||||||
|
int p = (int)pos;
|
||||||
|
int w = width is null ? 1 : (int)width.Value;
|
||||||
|
ValidatePosWidth(p, w);
|
||||||
|
return (v >> p) & NBitMask(w);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static uint Replace(double value, double replacement, double pos, double? width)
|
||||||
|
{
|
||||||
|
uint v = ToUInt32(value);
|
||||||
|
uint u = ToUInt32(replacement);
|
||||||
|
int p = (int)pos;
|
||||||
|
int w = width is null ? 1 : (int)width.Value;
|
||||||
|
ValidatePosWidth(p, w);
|
||||||
|
uint mask = NBitMask(w) << p;
|
||||||
|
return (v & ~mask) | (u & mask);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void ValidatePosWidth(int pos, int width)
|
||||||
|
{
|
||||||
|
if (pos > 31 || pos + width > 31)
|
||||||
|
throw new ArgumentException("trying to access non-existent bits");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static uint NBitMask(int bits)
|
||||||
|
{
|
||||||
|
if (bits <= 0)
|
||||||
|
return 0u;
|
||||||
|
if (bits >= 32)
|
||||||
|
return 0xFFFFFFFFu;
|
||||||
|
return (1u << bits) - 1u;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<Version>1.20.3</Version>
|
||||||
|
<Platforms>AnyCPU;x64</Platforms>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<InternalsVisibleTo Include="LuaScript" />
|
||||||
|
<InternalsVisibleTo Include="LuaScript.Runtime" />
|
||||||
|
<InternalsVisibleTo Include="LuaScript.Tests" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\LuaScript.Kernel\LuaScript.Kernel.csproj" />
|
||||||
|
<ProjectReference Include="..\LuaScript.Generator\LuaScript.Generator.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<EmbeddedResource Include="AviUtlCompatMap.xml" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Globalization;
|
||||||
|
using System.IO;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Reflection;
|
||||||
|
using System.Xml.Linq;
|
||||||
|
|
||||||
|
namespace LuaScript.Compat
|
||||||
|
{
|
||||||
|
internal sealed class AviUtlCompatMap
|
||||||
|
{
|
||||||
|
private const string ResourceSuffix = "AviUtlCompatMap.xml";
|
||||||
|
|
||||||
|
private readonly Dictionary<string, List<AviUtlEffectMapping>> _effects;
|
||||||
|
|
||||||
|
public static AviUtlCompatMap Default { get; } = Load();
|
||||||
|
|
||||||
|
private AviUtlCompatMap(Dictionary<string, List<AviUtlEffectMapping>> effects)
|
||||||
|
{
|
||||||
|
_effects = effects;
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool TryResolve(string name, AviUtlEngine target, out AviUtlEffectMapping mapping)
|
||||||
|
{
|
||||||
|
mapping = null!;
|
||||||
|
if (string.IsNullOrEmpty(name) || !_effects.TryGetValue(Normalize(name), out var candidates))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
foreach (var candidate in candidates)
|
||||||
|
{
|
||||||
|
if (candidate.Engine.Includes(target))
|
||||||
|
{
|
||||||
|
mapping = candidate;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static AviUtlEngine ResolveTarget(string? script)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(script))
|
||||||
|
return AviUtlEngine.AviUtl;
|
||||||
|
|
||||||
|
foreach (var raw in ScriptParserHelper.SplitLines(script))
|
||||||
|
{
|
||||||
|
var line = raw.Trim();
|
||||||
|
if (!line.StartsWith("--!", System.StringComparison.Ordinal))
|
||||||
|
continue;
|
||||||
|
var token = line[3..].Trim().ToLowerInvariant();
|
||||||
|
if (token == "aviutl2")
|
||||||
|
return AviUtlEngine.AviUtl2;
|
||||||
|
if (token == "aviutl")
|
||||||
|
return AviUtlEngine.AviUtl;
|
||||||
|
}
|
||||||
|
return AviUtlEngine.AviUtl;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static AviUtlCompatMap Load()
|
||||||
|
{
|
||||||
|
var effects = new Dictionary<string, List<AviUtlEffectMapping>>(StringComparer.OrdinalIgnoreCase);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var stream = OpenResource();
|
||||||
|
if (stream is not null)
|
||||||
|
Populate(effects, stream);
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
}
|
||||||
|
return new AviUtlCompatMap(effects);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void Populate(Dictionary<string, List<AviUtlEffectMapping>> effects, Stream stream)
|
||||||
|
{
|
||||||
|
var root = XDocument.Load(stream).Root;
|
||||||
|
if (root is null)
|
||||||
|
return;
|
||||||
|
|
||||||
|
foreach (var element in root.Elements("effect"))
|
||||||
|
{
|
||||||
|
var target = (string?)element.Attribute("target");
|
||||||
|
if (string.IsNullOrWhiteSpace(target))
|
||||||
|
continue;
|
||||||
|
|
||||||
|
if (!AviUtlEngineExtensions.TryParse(((string?)element.Attribute("engine"))?.Trim().ToLowerInvariant(), out var engine))
|
||||||
|
engine = AviUtlEngine.Both;
|
||||||
|
|
||||||
|
var parameters = element.Elements("param").Select(ParseParameter).ToArray();
|
||||||
|
var mapping = new AviUtlEffectMapping(engine, target.Trim(), parameters);
|
||||||
|
|
||||||
|
foreach (var name in SplitNames((string?)element.Attribute("names")))
|
||||||
|
{
|
||||||
|
if (!effects.TryGetValue(name, out var list))
|
||||||
|
{
|
||||||
|
list = [];
|
||||||
|
effects[name] = list;
|
||||||
|
}
|
||||||
|
list.Add(mapping);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static AviUtlParameterMapping ParseParameter(XElement element)
|
||||||
|
{
|
||||||
|
var source = ((string?)element.Attribute("name") ?? string.Empty).Trim();
|
||||||
|
var property = ((string?)element.Attribute("property") ?? string.Empty).Trim();
|
||||||
|
double scale = ParseDouble((string?)element.Attribute("scale"), 1d);
|
||||||
|
double offset = ParseDouble((string?)element.Attribute("offset"), 0d);
|
||||||
|
return new AviUtlParameterMapping(source, property, scale, offset);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static IEnumerable<string> SplitNames(string? names)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(names))
|
||||||
|
yield break;
|
||||||
|
foreach (var part in names.Split(','))
|
||||||
|
{
|
||||||
|
var trimmed = part.Trim();
|
||||||
|
if (trimmed.Length != 0)
|
||||||
|
yield return Normalize(trimmed);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static double ParseDouble(string? value, double fallback) =>
|
||||||
|
double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out double result) ? result : fallback;
|
||||||
|
|
||||||
|
private static string Normalize(string value) => value.Trim().ToLowerInvariant();
|
||||||
|
|
||||||
|
private static Stream? OpenResource()
|
||||||
|
{
|
||||||
|
var assembly = typeof(AviUtlCompatMap).Assembly;
|
||||||
|
var name = assembly.GetManifestResourceNames()
|
||||||
|
.FirstOrDefault(n => n.EndsWith(ResourceSuffix, System.StringComparison.Ordinal));
|
||||||
|
return name is null ? null : assembly.GetManifestResourceStream(name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
using System.Collections.Generic;
|
||||||
|
|
||||||
|
namespace LuaScript.Compat
|
||||||
|
{
|
||||||
|
internal sealed class AviUtlEffectMapping
|
||||||
|
{
|
||||||
|
private readonly Dictionary<string, AviUtlParameterMapping> _parameters;
|
||||||
|
|
||||||
|
public AviUtlEngine Engine { get; }
|
||||||
|
|
||||||
|
public string TargetType { get; }
|
||||||
|
|
||||||
|
public AviUtlEffectMapping(AviUtlEngine engine, string targetType, IEnumerable<AviUtlParameterMapping> parameters)
|
||||||
|
{
|
||||||
|
Engine = engine;
|
||||||
|
TargetType = targetType;
|
||||||
|
_parameters = new Dictionary<string, AviUtlParameterMapping>(StringComparer.OrdinalIgnoreCase);
|
||||||
|
foreach (var parameter in parameters)
|
||||||
|
_parameters[parameter.Source] = parameter;
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool TryGetParameter(string source, out AviUtlParameterMapping mapping) =>
|
||||||
|
_parameters.TryGetValue(source, out mapping);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
namespace LuaScript.Compat
|
||||||
|
{
|
||||||
|
internal enum AviUtlEngine
|
||||||
|
{
|
||||||
|
AviUtl,
|
||||||
|
AviUtl2,
|
||||||
|
Both,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
namespace LuaScript.Compat
|
||||||
|
{
|
||||||
|
internal static class AviUtlEngineExtensions
|
||||||
|
{
|
||||||
|
public static bool Includes(this AviUtlEngine scope, AviUtlEngine target) =>
|
||||||
|
scope == AviUtlEngine.Both || scope == target;
|
||||||
|
|
||||||
|
public static bool TryParse(string? value, out AviUtlEngine engine)
|
||||||
|
{
|
||||||
|
switch (value)
|
||||||
|
{
|
||||||
|
case "aviutl":
|
||||||
|
engine = AviUtlEngine.AviUtl;
|
||||||
|
return true;
|
||||||
|
case "aviutl2":
|
||||||
|
engine = AviUtlEngine.AviUtl2;
|
||||||
|
return true;
|
||||||
|
case "both":
|
||||||
|
engine = AviUtlEngine.Both;
|
||||||
|
return true;
|
||||||
|
default:
|
||||||
|
engine = AviUtlEngine.AviUtl;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
namespace LuaScript.Compat
|
||||||
|
{
|
||||||
|
internal readonly record struct AviUtlParameterMapping(string Source, string Property, double Scale, double Offset)
|
||||||
|
{
|
||||||
|
public double Transform(double value) => value * Scale + Offset;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,193 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace LuaScript.Compat
|
||||||
|
{
|
||||||
|
internal static class FigureRenderer
|
||||||
|
{
|
||||||
|
private enum Shape
|
||||||
|
{
|
||||||
|
Ellipse,
|
||||||
|
Rectangle,
|
||||||
|
Triangle,
|
||||||
|
Pentagon,
|
||||||
|
Hexagon,
|
||||||
|
Star,
|
||||||
|
}
|
||||||
|
|
||||||
|
public static byte[] Render(string name, int width, int height, int colorRgb, double lineWidth)
|
||||||
|
{
|
||||||
|
width = Math.Max(1, width);
|
||||||
|
height = Math.Max(1, height);
|
||||||
|
var buffer = new byte[width * height * 4];
|
||||||
|
|
||||||
|
Shape shape = Resolve(name);
|
||||||
|
double hx = width / 2d;
|
||||||
|
double hy = height / 2d;
|
||||||
|
|
||||||
|
double r = (colorRgb >> 16) & 0xFF;
|
||||||
|
double g = (colorRgb >> 8) & 0xFF;
|
||||||
|
double b = colorRgb & 0xFF;
|
||||||
|
|
||||||
|
(double X, double Y)[]? polygon = shape switch
|
||||||
|
{
|
||||||
|
Shape.Triangle => RegularPolygon(3, hx, hy),
|
||||||
|
Shape.Pentagon => RegularPolygon(5, hx, hy),
|
||||||
|
Shape.Hexagon => RegularPolygon(6, hx, hy),
|
||||||
|
Shape.Star => StarPolygon(hx, hy),
|
||||||
|
_ => null,
|
||||||
|
};
|
||||||
|
|
||||||
|
bool filled = lineWidth <= 0d;
|
||||||
|
|
||||||
|
for (int y = 0; y < height; y++)
|
||||||
|
{
|
||||||
|
double py = y + 0.5 - hy;
|
||||||
|
int row = y * width * 4;
|
||||||
|
for (int x = 0; x < width; x++)
|
||||||
|
{
|
||||||
|
double px = x + 0.5 - hx;
|
||||||
|
double d = shape switch
|
||||||
|
{
|
||||||
|
Shape.Ellipse => EllipseSdf(px, py, hx, hy),
|
||||||
|
Shape.Rectangle => BoxSdf(px, py, hx, hy),
|
||||||
|
_ => PolygonSdf(px, py, polygon!),
|
||||||
|
};
|
||||||
|
if (!filled)
|
||||||
|
d = Math.Max(d, -d - lineWidth);
|
||||||
|
|
||||||
|
double coverage = 0.5 - d;
|
||||||
|
if (coverage <= 0d)
|
||||||
|
continue;
|
||||||
|
if (coverage > 1d)
|
||||||
|
coverage = 1d;
|
||||||
|
|
||||||
|
int i = row + x * 4;
|
||||||
|
buffer[i] = ToByte(b * coverage);
|
||||||
|
buffer[i + 1] = ToByte(g * coverage);
|
||||||
|
buffer[i + 2] = ToByte(r * coverage);
|
||||||
|
buffer[i + 3] = ToByte(255d * coverage);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return buffer;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Shape Resolve(string name)
|
||||||
|
{
|
||||||
|
switch (name.Trim())
|
||||||
|
{
|
||||||
|
case "円":
|
||||||
|
case "楕円":
|
||||||
|
case "circle":
|
||||||
|
case "ellipse":
|
||||||
|
return Shape.Ellipse;
|
||||||
|
case "三角形":
|
||||||
|
case "triangle":
|
||||||
|
return Shape.Triangle;
|
||||||
|
case "五角形":
|
||||||
|
case "pentagon":
|
||||||
|
return Shape.Pentagon;
|
||||||
|
case "六角形":
|
||||||
|
case "hexagon":
|
||||||
|
return Shape.Hexagon;
|
||||||
|
case "星形":
|
||||||
|
case "star":
|
||||||
|
return Shape.Star;
|
||||||
|
default:
|
||||||
|
return Shape.Rectangle;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static (double X, double Y)[] RegularPolygon(int sides, double hx, double hy)
|
||||||
|
{
|
||||||
|
var vertices = new (double X, double Y)[sides];
|
||||||
|
for (int k = 0; k < sides; k++)
|
||||||
|
{
|
||||||
|
double angle = -Math.PI / 2d + 2d * Math.PI * k / sides;
|
||||||
|
vertices[k] = (Math.Cos(angle) * hx, Math.Sin(angle) * hy);
|
||||||
|
}
|
||||||
|
return vertices;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static (double X, double Y)[] StarPolygon(double hx, double hy)
|
||||||
|
{
|
||||||
|
const double innerRatio = 0.38196601125010515d;
|
||||||
|
var vertices = new (double X, double Y)[10];
|
||||||
|
for (int k = 0; k < 10; k++)
|
||||||
|
{
|
||||||
|
double angle = -Math.PI / 2d + Math.PI * k / 5d;
|
||||||
|
double radius = (k & 1) == 0 ? 1d : innerRatio;
|
||||||
|
vertices[k] = (Math.Cos(angle) * hx * radius, Math.Sin(angle) * hy * radius);
|
||||||
|
}
|
||||||
|
return vertices;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static double EllipseSdf(double px, double py, double ax, double ay)
|
||||||
|
{
|
||||||
|
if (ax <= 0d || ay <= 0d)
|
||||||
|
return double.MaxValue;
|
||||||
|
double kx = px / ax;
|
||||||
|
double ky = py / ay;
|
||||||
|
double k1 = Math.Sqrt(kx * kx + ky * ky);
|
||||||
|
if (k1 == 0d)
|
||||||
|
return -Math.Min(ax, ay);
|
||||||
|
double nx = kx / ax;
|
||||||
|
double ny = ky / ay;
|
||||||
|
double k2 = Math.Sqrt(nx * nx + ny * ny);
|
||||||
|
return k1 * (k1 - 1d) / k2;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static double BoxSdf(double px, double py, double hx, double hy)
|
||||||
|
{
|
||||||
|
double qx = Math.Abs(px) - hx;
|
||||||
|
double qy = Math.Abs(py) - hy;
|
||||||
|
double ox = Math.Max(qx, 0d);
|
||||||
|
double oy = Math.Max(qy, 0d);
|
||||||
|
return Math.Sqrt(ox * ox + oy * oy) + Math.Min(Math.Max(qx, qy), 0d);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static double PolygonSdf(double px, double py, (double X, double Y)[] v)
|
||||||
|
{
|
||||||
|
int n = v.Length;
|
||||||
|
double dx = px - v[0].X;
|
||||||
|
double dy = py - v[0].Y;
|
||||||
|
double d = dx * dx + dy * dy;
|
||||||
|
double s = 1d;
|
||||||
|
|
||||||
|
for (int i = 0, j = n - 1; i < n; j = i, i++)
|
||||||
|
{
|
||||||
|
double ex = v[j].X - v[i].X;
|
||||||
|
double ey = v[j].Y - v[i].Y;
|
||||||
|
double wx = px - v[i].X;
|
||||||
|
double wy = py - v[i].Y;
|
||||||
|
double t = Clamp((wx * ex + wy * ey) / (ex * ex + ey * ey), 0d, 1d);
|
||||||
|
double bx = wx - ex * t;
|
||||||
|
double by = wy - ey * t;
|
||||||
|
d = Math.Min(d, bx * bx + by * by);
|
||||||
|
|
||||||
|
bool c1 = py >= v[i].Y;
|
||||||
|
bool c2 = py < v[j].Y;
|
||||||
|
bool c3 = ex * wy > ey * wx;
|
||||||
|
if ((c1 && c2 && c3) || (!c1 && !c2 && !c3))
|
||||||
|
s = -s;
|
||||||
|
}
|
||||||
|
|
||||||
|
return s * Math.Sqrt(d);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static double Clamp(double v, double lo, double hi)
|
||||||
|
{
|
||||||
|
if (v < lo) return lo;
|
||||||
|
if (v > hi) return hi;
|
||||||
|
return v;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte ToByte(double v)
|
||||||
|
{
|
||||||
|
int i = (int)(v + 0.5d);
|
||||||
|
if (i < 0) return 0;
|
||||||
|
if (i > 255) return 255;
|
||||||
|
return (byte)i;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,153 @@
|
|||||||
|
using System;
|
||||||
|
using System.Globalization;
|
||||||
|
|
||||||
|
namespace LuaScript.Compat
|
||||||
|
{
|
||||||
|
internal sealed class AviUtlParameterLayout
|
||||||
|
{
|
||||||
|
public const int MaxTracks = 4;
|
||||||
|
public const int MaxChecks = 4;
|
||||||
|
|
||||||
|
public readonly record struct TrackParam(int Index, string Name, double Min, double Max, double Default, double Step);
|
||||||
|
public readonly record struct CheckParam(int Index, string Name, bool Default);
|
||||||
|
public readonly record struct ColorParam(int Default);
|
||||||
|
|
||||||
|
private readonly TrackParam?[] _tracks = new TrackParam?[MaxTracks];
|
||||||
|
private readonly CheckParam?[] _checks = new CheckParam?[MaxChecks];
|
||||||
|
|
||||||
|
public static readonly AviUtlParameterLayout Empty = new();
|
||||||
|
|
||||||
|
public TrackParam? GetTrack(int index) => (uint)index < MaxTracks ? _tracks[index] : null;
|
||||||
|
public CheckParam? GetCheck(int index) => (uint)index < MaxChecks ? _checks[index] : null;
|
||||||
|
public ColorParam? Color { get; private set; }
|
||||||
|
|
||||||
|
public bool HasTrack(int index) => GetTrack(index).HasValue;
|
||||||
|
public bool HasCheck(int index) => GetCheck(index).HasValue;
|
||||||
|
public bool HasColor => Color.HasValue;
|
||||||
|
|
||||||
|
public bool HasAny
|
||||||
|
{
|
||||||
|
get
|
||||||
|
{
|
||||||
|
for (int i = 0; i < MaxTracks; i++)
|
||||||
|
if (_tracks[i].HasValue) return true;
|
||||||
|
for (int i = 0; i < MaxChecks; i++)
|
||||||
|
if (_checks[i].HasValue) return true;
|
||||||
|
return HasColor;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static AviUtlParameterLayout Parse(string? source)
|
||||||
|
{
|
||||||
|
var layout = new AviUtlParameterLayout();
|
||||||
|
if (string.IsNullOrEmpty(source))
|
||||||
|
return layout;
|
||||||
|
|
||||||
|
var lines = ScriptParserHelper.SplitLines(source);
|
||||||
|
ScriptParserHelper.TryFindSection(lines, out int sectionStart, out int sectionEnd);
|
||||||
|
|
||||||
|
for (int i = sectionStart; i < sectionEnd; i++)
|
||||||
|
layout.ParseLine(lines[i]);
|
||||||
|
|
||||||
|
return layout;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ParseLine(string line)
|
||||||
|
{
|
||||||
|
if (!ScriptParserHelper.TryParseDirective(line, out string name, out string content))
|
||||||
|
return;
|
||||||
|
|
||||||
|
if (name.StartsWith("track", StringComparison.OrdinalIgnoreCase) &&
|
||||||
|
TryGetIndex(name, 5, MaxTracks, out int trackIndex))
|
||||||
|
{
|
||||||
|
ParseTrack(trackIndex, content);
|
||||||
|
}
|
||||||
|
else if (name.StartsWith("check", StringComparison.OrdinalIgnoreCase) &&
|
||||||
|
TryGetIndex(name, 5, MaxChecks, out int checkIndex))
|
||||||
|
{
|
||||||
|
ParseCheck(checkIndex, content);
|
||||||
|
}
|
||||||
|
else if (name.Equals("color", StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
ParseColor(content);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ParseTrack(int index, string content)
|
||||||
|
{
|
||||||
|
var parts = content.Split(',');
|
||||||
|
string trackName = parts.Length > 0 ? parts[0].Trim() : string.Empty;
|
||||||
|
double min = ParseNumber(parts, 1, 0d);
|
||||||
|
double max = ParseNumber(parts, 2, 100d);
|
||||||
|
double def = ParseNumber(parts, 3, min);
|
||||||
|
double step = ParseNumber(parts, 4, 0d);
|
||||||
|
if (max < min)
|
||||||
|
(min, max) = (max, min);
|
||||||
|
def = Math.Clamp(def, min, max);
|
||||||
|
_tracks[index] = new TrackParam(index, trackName, min, max, def, step);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ParseCheck(int index, string content)
|
||||||
|
{
|
||||||
|
var parts = content.Split(',');
|
||||||
|
string checkName = parts.Length > 0 ? parts[0].Trim() : string.Empty;
|
||||||
|
double def = ParseNumber(parts, 1, 0d);
|
||||||
|
_checks[index] = new CheckParam(index, checkName, def != 0d);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ParseColor(string content)
|
||||||
|
{
|
||||||
|
string token = FirstToken(content);
|
||||||
|
if (TryParseColorLiteral(token, out int rgb))
|
||||||
|
Color = new ColorParam(rgb);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool TryGetIndex(string name, int start, int max, out int index)
|
||||||
|
{
|
||||||
|
index = -1;
|
||||||
|
if (name.Length != start + 1)
|
||||||
|
return false;
|
||||||
|
char c = name[start];
|
||||||
|
if (c < '0' || c > '9')
|
||||||
|
return false;
|
||||||
|
int value = c - '0';
|
||||||
|
if (value >= max)
|
||||||
|
return false;
|
||||||
|
index = value;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static double ParseNumber(string[] parts, int idx, double fallback)
|
||||||
|
{
|
||||||
|
if (idx >= parts.Length)
|
||||||
|
return fallback;
|
||||||
|
string token = parts[idx].Trim();
|
||||||
|
return double.TryParse(token, NumberStyles.Float, CultureInfo.InvariantCulture, out double value)
|
||||||
|
? value
|
||||||
|
: fallback;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool TryParseColorLiteral(string token, out int rgb)
|
||||||
|
{
|
||||||
|
rgb = 0;
|
||||||
|
if (token.Length == 0)
|
||||||
|
return false;
|
||||||
|
if (token.StartsWith("0x", StringComparison.OrdinalIgnoreCase) || token.StartsWith("0X", StringComparison.Ordinal))
|
||||||
|
{
|
||||||
|
if (token.Length <= 2)
|
||||||
|
return false;
|
||||||
|
return int.TryParse(token.AsSpan(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out rgb);
|
||||||
|
}
|
||||||
|
return int.TryParse(token, NumberStyles.Integer, CultureInfo.InvariantCulture, out rgb);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string FirstToken(string content)
|
||||||
|
{
|
||||||
|
int start = ScriptParserHelper.SkipSpaces(content, 0);
|
||||||
|
int i = start;
|
||||||
|
while (i < content.Length && content[i] != ',' && content[i] != ' ' && content[i] != '\t')
|
||||||
|
i++;
|
||||||
|
return content.Substring(start, i - start);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
|
||||||
|
namespace LuaScript.Compat
|
||||||
|
{
|
||||||
|
internal sealed class AviUtlPixelShaderLibrary
|
||||||
|
{
|
||||||
|
private const string SectionMarker = "--[[pixelshader@";
|
||||||
|
|
||||||
|
public static AviUtlPixelShaderLibrary Empty { get; } = new(null);
|
||||||
|
|
||||||
|
private readonly Dictionary<string, string>? _shaders;
|
||||||
|
|
||||||
|
private AviUtlPixelShaderLibrary(Dictionary<string, string>? shaders) => _shaders = shaders;
|
||||||
|
|
||||||
|
public int Count => _shaders?.Count ?? 0;
|
||||||
|
|
||||||
|
public static AviUtlPixelShaderLibrary Parse(string? source)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(source))
|
||||||
|
return Empty;
|
||||||
|
|
||||||
|
Dictionary<string, string>? shaders = null;
|
||||||
|
int index = 0;
|
||||||
|
while (index < source.Length)
|
||||||
|
{
|
||||||
|
int lineStart = index;
|
||||||
|
int lineBreak = source.IndexOf('\n', index);
|
||||||
|
index = lineBreak < 0 ? source.Length : lineBreak + 1;
|
||||||
|
|
||||||
|
int i = ScriptParserHelper.SkipSpaces(source, lineStart);
|
||||||
|
if (!MatchesMarker(source, i))
|
||||||
|
continue;
|
||||||
|
i += SectionMarker.Length;
|
||||||
|
|
||||||
|
int nameStart = i;
|
||||||
|
while (i < source.Length && IsEntryPointChar(source[i]))
|
||||||
|
i++;
|
||||||
|
if (i == nameStart || i >= source.Length || source[i] != ':')
|
||||||
|
continue;
|
||||||
|
|
||||||
|
string name = source[nameStart..i];
|
||||||
|
int bodyStart = i + 1;
|
||||||
|
int bodyEnd = source.IndexOf("]]", bodyStart, StringComparison.Ordinal);
|
||||||
|
if (bodyEnd < 0)
|
||||||
|
continue;
|
||||||
|
|
||||||
|
shaders ??= new Dictionary<string, string>(StringComparer.Ordinal);
|
||||||
|
shaders.TryAdd(name, source[bodyStart..bodyEnd]);
|
||||||
|
index = bodyEnd + 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
return shaders is null ? Empty : new AviUtlPixelShaderLibrary(shaders);
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool TryGet(string name, out string hlsl)
|
||||||
|
{
|
||||||
|
hlsl = string.Empty;
|
||||||
|
if (_shaders is null || string.IsNullOrEmpty(name))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
int at = name.IndexOf('@');
|
||||||
|
string local = at < 0 ? name : name[..at];
|
||||||
|
if (_shaders.TryGetValue(local, out var found))
|
||||||
|
{
|
||||||
|
hlsl = found;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static string EntryPointOf(string name)
|
||||||
|
{
|
||||||
|
int at = name.IndexOf('@');
|
||||||
|
return at < 0 ? name : name[..at];
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool MatchesMarker(string text, int index) =>
|
||||||
|
index + SectionMarker.Length <= text.Length &&
|
||||||
|
string.CompareOrdinal(text, index, SectionMarker, 0, SectionMarker.Length) == 0;
|
||||||
|
|
||||||
|
private static bool IsEntryPointChar(char c) =>
|
||||||
|
ScriptParserHelper.IsNameChar(c) || c == '_';
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Text;
|
||||||
|
using LuaScript.Compat.Syntax;
|
||||||
|
|
||||||
|
namespace LuaScript.Compat
|
||||||
|
{
|
||||||
|
internal static class AviUtlScript
|
||||||
|
{
|
||||||
|
private enum DirectiveKind
|
||||||
|
{
|
||||||
|
None,
|
||||||
|
Dialog,
|
||||||
|
Param,
|
||||||
|
}
|
||||||
|
|
||||||
|
public static string Transform(string source) => TransformWithMap(source).Code;
|
||||||
|
|
||||||
|
public static (string Code, int[] LineMap, int[] ChangedLines, LuaRewriteDiagnostic[] Diagnostics) TransformWithMap(string source)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(source))
|
||||||
|
return (source, [], [], []);
|
||||||
|
|
||||||
|
var lines = ScriptParserHelper.SplitLines(source);
|
||||||
|
bool hasSection = ScriptParserHelper.TryFindSection(lines, out int sectionStart, out int sectionEnd);
|
||||||
|
|
||||||
|
var prelude = new List<string>();
|
||||||
|
for (int i = sectionStart; i < sectionEnd; i++)
|
||||||
|
AppendDeclarations(lines[i], prelude);
|
||||||
|
|
||||||
|
if (!hasSection && prelude.Count == 0)
|
||||||
|
{
|
||||||
|
var (code, changed, preludeless) = LuaSyntaxExtensions.RewriteWithMap(source);
|
||||||
|
return (code, [], changed, preludeless);
|
||||||
|
}
|
||||||
|
|
||||||
|
var builder = new StringBuilder(source.Length + 64);
|
||||||
|
var lineMap = new int[prelude.Count + (sectionEnd - sectionStart)];
|
||||||
|
int row = 0;
|
||||||
|
|
||||||
|
foreach (var declaration in prelude)
|
||||||
|
{
|
||||||
|
builder.Append(declaration).Append('\n');
|
||||||
|
lineMap[row++] = -1;
|
||||||
|
}
|
||||||
|
for (int i = sectionStart; i < sectionEnd; i++)
|
||||||
|
{
|
||||||
|
builder.Append(lines[i]).Append('\n');
|
||||||
|
lineMap[row++] = i;
|
||||||
|
}
|
||||||
|
|
||||||
|
var (rewritten, changedLines, diagnostics) = LuaSyntaxExtensions.RewriteWithMap(builder.ToString());
|
||||||
|
return (rewritten, lineMap, changedLines, diagnostics);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void AppendDeclarations(string line, List<string> prelude)
|
||||||
|
{
|
||||||
|
if (!ScriptParserHelper.TryParseDirective(line, out string name, out string content))
|
||||||
|
return;
|
||||||
|
|
||||||
|
switch (Classify(name))
|
||||||
|
{
|
||||||
|
case DirectiveKind.Dialog:
|
||||||
|
AppendDialog(content, prelude);
|
||||||
|
break;
|
||||||
|
case DirectiveKind.Param:
|
||||||
|
AppendParam(content, prelude);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static DirectiveKind Classify(string name)
|
||||||
|
{
|
||||||
|
if (name.Equals("dialog", StringComparison.OrdinalIgnoreCase))
|
||||||
|
return DirectiveKind.Dialog;
|
||||||
|
if (name.Equals("param", StringComparison.OrdinalIgnoreCase))
|
||||||
|
return DirectiveKind.Param;
|
||||||
|
return DirectiveKind.None;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void AppendDialog(string content, List<string> prelude)
|
||||||
|
{
|
||||||
|
foreach (var segment in content.Split(';'))
|
||||||
|
{
|
||||||
|
string trimmed = segment.Trim();
|
||||||
|
if (trimmed.Length == 0)
|
||||||
|
continue;
|
||||||
|
int comma = trimmed.IndexOf(',');
|
||||||
|
if (comma < 0)
|
||||||
|
continue;
|
||||||
|
string declaration = trimmed.Substring(comma + 1).Trim();
|
||||||
|
if (declaration.Length != 0)
|
||||||
|
prelude.Add(declaration);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void AppendParam(string content, List<string> prelude)
|
||||||
|
{
|
||||||
|
string trimmed = content.Trim();
|
||||||
|
if (trimmed.Length != 0)
|
||||||
|
prelude.Add(trimmed);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
using LuaScript.Compat.Syntax;
|
||||||
|
|
||||||
|
namespace LuaScript.Compat
|
||||||
|
{
|
||||||
|
internal static class LuaSyntaxExtensions
|
||||||
|
{
|
||||||
|
public static string Rewrite(string source) => RewriteWithMap(source).Code;
|
||||||
|
|
||||||
|
public static (string Code, int[] ChangedLines, LuaRewriteDiagnostic[] Diagnostics) RewriteWithMap(string source)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(source))
|
||||||
|
return (source, [], []);
|
||||||
|
|
||||||
|
var tokens = LuaSyntaxLexer.Tokenize(source);
|
||||||
|
var context = new LuaRewriteContext(tokens);
|
||||||
|
var rules = LuaSyntaxRuleRegistry.Rules;
|
||||||
|
|
||||||
|
while (!context.AtEnd)
|
||||||
|
{
|
||||||
|
var current = context.Current;
|
||||||
|
if (current.IsTrivia || current.Kind == LuaSyntaxTokenKind.String)
|
||||||
|
{
|
||||||
|
context.Emit(current);
|
||||||
|
context.Advance();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool matched = false;
|
||||||
|
foreach (var rule in rules)
|
||||||
|
{
|
||||||
|
if (rule.TryApply(context))
|
||||||
|
{
|
||||||
|
matched = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!matched)
|
||||||
|
{
|
||||||
|
context.Emit(current);
|
||||||
|
context.Advance();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var diagnostics = context.Diagnostics;
|
||||||
|
return context.Changed ? (context.Serialize(), context.ChangedLines, diagnostics) : (source, [], diagnostics);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using LuaScript.Compat.Syntax;
|
||||||
|
|
||||||
|
namespace LuaScript.Compat
|
||||||
|
{
|
||||||
|
internal readonly struct ScriptParameterUsage
|
||||||
|
{
|
||||||
|
private readonly HashSet<string>? _members;
|
||||||
|
private readonly bool _color;
|
||||||
|
|
||||||
|
private ScriptParameterUsage(HashSet<string>? members, bool color)
|
||||||
|
{
|
||||||
|
_members = members;
|
||||||
|
_color = color;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static readonly ScriptParameterUsage None = default;
|
||||||
|
|
||||||
|
public bool Color => _color;
|
||||||
|
|
||||||
|
public bool Uses(string member) => _members is not null && _members.Contains(member);
|
||||||
|
|
||||||
|
public bool Check0 => Uses("check0");
|
||||||
|
public bool Check1 => Uses("check1");
|
||||||
|
public bool Check2 => Uses("check2");
|
||||||
|
public bool Check3 => Uses("check3");
|
||||||
|
|
||||||
|
public bool Check(int index) => (uint)index < 4 && Uses("check" + (char)('0' + index));
|
||||||
|
|
||||||
|
public bool Slider(int index) => (uint)index < 4 && Uses("slider" + (char)('0' + index));
|
||||||
|
|
||||||
|
public static ScriptParameterUsage Detect(string? script)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(script))
|
||||||
|
return None;
|
||||||
|
|
||||||
|
var tokens = LuaSyntaxLexer.Tokenize(script);
|
||||||
|
|
||||||
|
HashSet<string>? members = null;
|
||||||
|
bool color = false;
|
||||||
|
|
||||||
|
for (int i = 0; i < tokens.Count; i++)
|
||||||
|
{
|
||||||
|
var token = tokens[i];
|
||||||
|
if (token.Kind != LuaSyntaxTokenKind.Name)
|
||||||
|
continue;
|
||||||
|
|
||||||
|
if (token.Text == "color")
|
||||||
|
{
|
||||||
|
int previous = PreviousSignificant(tokens, i);
|
||||||
|
if (previous < 0 || !tokens[previous].IsOperator("."))
|
||||||
|
color = true;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (token.Text == "obj")
|
||||||
|
{
|
||||||
|
int dot = NextSignificant(tokens, i + 1);
|
||||||
|
if (dot < 0 || !tokens[dot].IsOperator("."))
|
||||||
|
continue;
|
||||||
|
|
||||||
|
int member = NextSignificant(tokens, dot + 1);
|
||||||
|
if (member < 0 || tokens[member].Kind != LuaSyntaxTokenKind.Name)
|
||||||
|
continue;
|
||||||
|
|
||||||
|
(members ??= new HashSet<string>(StringComparer.Ordinal)).Add(tokens[member].Text);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return new ScriptParameterUsage(members, color);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int PreviousSignificant(List<LuaSyntaxToken> tokens, int from)
|
||||||
|
{
|
||||||
|
for (int i = from - 1; i >= 0; i--)
|
||||||
|
{
|
||||||
|
if (!tokens[i].IsTrivia)
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int NextSignificant(List<LuaSyntaxToken> tokens, int from)
|
||||||
|
{
|
||||||
|
for (int i = from; i < tokens.Count; i++)
|
||||||
|
{
|
||||||
|
if (!tokens[i].IsTrivia)
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
namespace LuaScript.Compat
|
||||||
|
{
|
||||||
|
internal static class ScriptParserHelper
|
||||||
|
{
|
||||||
|
public static bool IsSectionHeader(string line)
|
||||||
|
{
|
||||||
|
int i = SkipSpaces(line, 0);
|
||||||
|
return i < line.Length && line[i] == '@';
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int SkipSpaces(string text, int index)
|
||||||
|
{
|
||||||
|
while (index < text.Length && (text[index] == ' ' || text[index] == '\t'))
|
||||||
|
index++;
|
||||||
|
return index;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static bool IsNameChar(char c) =>
|
||||||
|
(c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9');
|
||||||
|
|
||||||
|
public static string[] SplitLines(string source) =>
|
||||||
|
source.Replace("\r\n", "\n").Replace("\r", "\n").Split('\n');
|
||||||
|
|
||||||
|
public static bool TryFindSection(string[] lines, out int start, out int end)
|
||||||
|
{
|
||||||
|
start = 0;
|
||||||
|
end = lines.Length;
|
||||||
|
for (int i = 0; i < lines.Length; i++)
|
||||||
|
{
|
||||||
|
if (!IsSectionHeader(lines[i]))
|
||||||
|
continue;
|
||||||
|
start = i + 1;
|
||||||
|
end = lines.Length;
|
||||||
|
for (int j = start; j < lines.Length; j++)
|
||||||
|
{
|
||||||
|
if (IsSectionHeader(lines[j]))
|
||||||
|
{
|
||||||
|
end = j;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static bool TryParseDirective(string line, out string name, out string content)
|
||||||
|
{
|
||||||
|
name = string.Empty;
|
||||||
|
content = string.Empty;
|
||||||
|
int i = SkipSpaces(line, 0);
|
||||||
|
if (i + 1 >= line.Length || line[i] != '-' || line[i + 1] != '-')
|
||||||
|
return false;
|
||||||
|
i += 2;
|
||||||
|
if (i < line.Length && line[i] == '!')
|
||||||
|
return false;
|
||||||
|
|
||||||
|
int nameStart = i;
|
||||||
|
while (i < line.Length && IsNameChar(line[i]))
|
||||||
|
i++;
|
||||||
|
if (i >= line.Length || line[i] != ':')
|
||||||
|
return false;
|
||||||
|
|
||||||
|
name = line.Substring(nameStart, i - nameStart);
|
||||||
|
content = line.Substring(i + 1);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
namespace LuaScript.Compat.Syntax
|
||||||
|
{
|
||||||
|
internal interface ILuaSyntaxRule
|
||||||
|
{
|
||||||
|
bool TryApply(LuaRewriteContext context);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
using System.Collections.Generic;
|
||||||
|
|
||||||
|
namespace LuaScript.Compat.Syntax
|
||||||
|
{
|
||||||
|
internal static class LuaKeywords
|
||||||
|
{
|
||||||
|
private static readonly HashSet<string> Reserved = new()
|
||||||
|
{
|
||||||
|
"and", "break", "do", "else", "elseif", "end", "false", "for", "function",
|
||||||
|
"goto", "if", "in", "local", "nil", "not", "or", "repeat", "return",
|
||||||
|
"then", "true", "until", "while",
|
||||||
|
};
|
||||||
|
|
||||||
|
private static readonly HashSet<string> ExpressionSafe = new()
|
||||||
|
{
|
||||||
|
"and", "or", "not", "nil", "true", "false",
|
||||||
|
};
|
||||||
|
|
||||||
|
public static bool IsReserved(string name) => Reserved.Contains(name);
|
||||||
|
|
||||||
|
public static bool IsExpressionBoundary(string name) => Reserved.Contains(name) && !ExpressionSafe.Contains(name);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,130 @@
|
|||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace LuaScript.Compat.Syntax
|
||||||
|
{
|
||||||
|
internal readonly struct LuaRangeParts
|
||||||
|
{
|
||||||
|
public LuaRangeParts(string start, string stop, string? step, bool exclusive)
|
||||||
|
{
|
||||||
|
Start = start;
|
||||||
|
Stop = stop;
|
||||||
|
Step = step;
|
||||||
|
Exclusive = exclusive;
|
||||||
|
}
|
||||||
|
|
||||||
|
public string Start { get; }
|
||||||
|
|
||||||
|
public string Stop { get; }
|
||||||
|
|
||||||
|
public string? Step { get; }
|
||||||
|
|
||||||
|
public bool Exclusive { get; }
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static class LuaRangeSyntax
|
||||||
|
{
|
||||||
|
public static bool TryParse(IReadOnlyList<LuaSyntaxToken> input, int open, out LuaRangeParts parts, out int end)
|
||||||
|
{
|
||||||
|
parts = default;
|
||||||
|
end = open;
|
||||||
|
|
||||||
|
if (open < 0 || open >= input.Count || !input[open].IsOperator("<"))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
int position = open + 1;
|
||||||
|
if (!TryReadSegment(input, ref position, "..", ">", out string start, out string startTerminator) || startTerminator != "..")
|
||||||
|
return false;
|
||||||
|
|
||||||
|
bool exclusive = false;
|
||||||
|
int caret = NextSignificant(input, position);
|
||||||
|
if (caret >= 0 && input[caret].IsOperator("<"))
|
||||||
|
{
|
||||||
|
exclusive = true;
|
||||||
|
position = caret + 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!TryReadSegment(input, ref position, ",", ">", out string stop, out string stopTerminator))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
string? step = null;
|
||||||
|
if (stopTerminator == ",")
|
||||||
|
{
|
||||||
|
if (!TryReadSegment(input, ref position, ">", ">", out string stepText, out string stepTerminator) || stepTerminator != ">")
|
||||||
|
return false;
|
||||||
|
step = stepText;
|
||||||
|
}
|
||||||
|
else if (stopTerminator != ">")
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (start.Length == 0 || stop.Length == 0 || (step is not null && step.Length == 0))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
parts = new LuaRangeParts(start, stop, step, exclusive);
|
||||||
|
end = position;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool TryReadSegment(IReadOnlyList<LuaSyntaxToken> input, ref int position, string primaryStop, string secondaryStop, out string text, out string terminator)
|
||||||
|
{
|
||||||
|
text = string.Empty;
|
||||||
|
terminator = string.Empty;
|
||||||
|
int start = position;
|
||||||
|
int depth = 0;
|
||||||
|
int count = input.Count;
|
||||||
|
|
||||||
|
while (position < count)
|
||||||
|
{
|
||||||
|
var token = input[position];
|
||||||
|
if (token.Kind == LuaSyntaxTokenKind.Newline && depth == 0)
|
||||||
|
return false;
|
||||||
|
if (token.Kind == LuaSyntaxTokenKind.Operator)
|
||||||
|
{
|
||||||
|
if (token.Text is "(" or "[" or "{")
|
||||||
|
{
|
||||||
|
depth++;
|
||||||
|
}
|
||||||
|
else if (token.Text is ")" or "]" or "}")
|
||||||
|
{
|
||||||
|
if (depth == 0)
|
||||||
|
return false;
|
||||||
|
depth--;
|
||||||
|
}
|
||||||
|
else if (depth == 0 && (token.Text == primaryStop || token.Text == secondaryStop))
|
||||||
|
{
|
||||||
|
terminator = token.Text;
|
||||||
|
text = Trim(input, start, position);
|
||||||
|
position++;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
position++;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int NextSignificant(IReadOnlyList<LuaSyntaxToken> input, int from)
|
||||||
|
{
|
||||||
|
for (int i = from; i < input.Count; i++)
|
||||||
|
{
|
||||||
|
if (!input[i].IsTrivia)
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Trim(IReadOnlyList<LuaSyntaxToken> input, int begin, int end)
|
||||||
|
{
|
||||||
|
while (begin < end && input[begin].IsTrivia)
|
||||||
|
begin++;
|
||||||
|
while (end > begin && input[end - 1].IsTrivia)
|
||||||
|
end--;
|
||||||
|
var builder = new StringBuilder();
|
||||||
|
for (int i = begin; i < end; i++)
|
||||||
|
builder.Append(input[i].Text);
|
||||||
|
return builder.ToString();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,327 @@
|
|||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace LuaScript.Compat.Syntax
|
||||||
|
{
|
||||||
|
internal sealed class LuaRewriteContext
|
||||||
|
{
|
||||||
|
private readonly List<LuaSyntaxToken> _input;
|
||||||
|
private readonly List<LuaSyntaxToken> _output;
|
||||||
|
private List<int>? _changedLines;
|
||||||
|
private List<LuaRewriteDiagnostic>? _diagnostics;
|
||||||
|
private int _line = 1;
|
||||||
|
private int _lastChangedLine;
|
||||||
|
private int _temporaries;
|
||||||
|
|
||||||
|
public LuaRewriteContext(List<LuaSyntaxToken> input)
|
||||||
|
{
|
||||||
|
_input = input;
|
||||||
|
_output = new List<LuaSyntaxToken>(input.Count);
|
||||||
|
}
|
||||||
|
|
||||||
|
public IReadOnlyList<LuaSyntaxToken> Input => _input;
|
||||||
|
|
||||||
|
public List<LuaSyntaxToken> Output => _output;
|
||||||
|
|
||||||
|
public int Index { get; set; }
|
||||||
|
|
||||||
|
public bool Changed { get; private set; }
|
||||||
|
|
||||||
|
public int[] ChangedLines => _changedLines is null ? [] : _changedLines.ToArray();
|
||||||
|
|
||||||
|
public LuaRewriteDiagnostic[] Diagnostics => _diagnostics is null ? [] : _diagnostics.ToArray();
|
||||||
|
|
||||||
|
public void AddDiagnostic(string message)
|
||||||
|
{
|
||||||
|
(_diagnostics ??= new List<LuaRewriteDiagnostic>()).Add(new LuaRewriteDiagnostic(_line, message));
|
||||||
|
MarkChanged();
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool AtEnd => Index >= _input.Count;
|
||||||
|
|
||||||
|
public LuaSyntaxToken Current => _input[Index];
|
||||||
|
|
||||||
|
public void Advance() => Index++;
|
||||||
|
|
||||||
|
public void Emit(LuaSyntaxToken token)
|
||||||
|
{
|
||||||
|
_output.Add(token);
|
||||||
|
if (token.Kind == LuaSyntaxTokenKind.Newline)
|
||||||
|
_line++;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void EmitRaw(string text)
|
||||||
|
{
|
||||||
|
_output.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Name, text));
|
||||||
|
MarkChanged();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void EmitOperator(string text)
|
||||||
|
{
|
||||||
|
_output.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Operator, text));
|
||||||
|
MarkChanged();
|
||||||
|
}
|
||||||
|
|
||||||
|
public string NextTemporary() => "__lc" + _temporaries++;
|
||||||
|
|
||||||
|
public int NextSignificant(int from)
|
||||||
|
{
|
||||||
|
for (int i = from; i < _input.Count; i++)
|
||||||
|
{
|
||||||
|
if (!_input[i].IsTrivia)
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool TryPreviousOutputSignificantSameLine(out LuaSyntaxToken token)
|
||||||
|
{
|
||||||
|
for (int i = _output.Count - 1; i >= 0; i--)
|
||||||
|
{
|
||||||
|
if (_output[i].Kind == LuaSyntaxTokenKind.Newline)
|
||||||
|
break;
|
||||||
|
if (_output[i].IsTrivia)
|
||||||
|
continue;
|
||||||
|
token = _output[i];
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
token = default;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int NextSignificantSameLine(int from)
|
||||||
|
{
|
||||||
|
for (int i = from; i < _input.Count; i++)
|
||||||
|
{
|
||||||
|
if (_input[i].Kind == LuaSyntaxTokenKind.Newline)
|
||||||
|
return -1;
|
||||||
|
if (_input[i].IsTrivia)
|
||||||
|
continue;
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void EmitWord(string word)
|
||||||
|
{
|
||||||
|
if (_output.Count > 0 && !_output[_output.Count - 1].IsTrivia)
|
||||||
|
_output.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Whitespace, " "));
|
||||||
|
_output.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Name, word));
|
||||||
|
if (Index < _input.Count && !_input[Index].IsTrivia)
|
||||||
|
_output.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Whitespace, " "));
|
||||||
|
MarkChanged();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void MarkChanged()
|
||||||
|
{
|
||||||
|
Changed = true;
|
||||||
|
if (_line == _lastChangedLine)
|
||||||
|
return;
|
||||||
|
(_changedLines ??= new List<int>()).Add(_line);
|
||||||
|
_lastChangedLine = _line;
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool TryReadTrailingLvalue(out int start, out string text)
|
||||||
|
{
|
||||||
|
start = _output.Count;
|
||||||
|
text = string.Empty;
|
||||||
|
int end = _output.Count;
|
||||||
|
while (end > 0 && _output[end - 1].IsTrivia)
|
||||||
|
end--;
|
||||||
|
if (end == 0)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
int depth = 0;
|
||||||
|
int begin = end;
|
||||||
|
for (int i = end - 1; i >= 0; i--)
|
||||||
|
{
|
||||||
|
var token = _output[i];
|
||||||
|
if (token.Kind == LuaSyntaxTokenKind.Operator)
|
||||||
|
{
|
||||||
|
if (token.Text is ")" or "]" or "}")
|
||||||
|
{
|
||||||
|
depth++;
|
||||||
|
begin = i;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (token.Text is "(" or "[" or "{")
|
||||||
|
{
|
||||||
|
if (depth == 0)
|
||||||
|
break;
|
||||||
|
depth--;
|
||||||
|
begin = i;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (depth > 0 || token.Text == ".")
|
||||||
|
{
|
||||||
|
begin = i;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (token.Kind == LuaSyntaxTokenKind.Name)
|
||||||
|
{
|
||||||
|
if (depth == 0 && LuaKeywords.IsReserved(token.Text))
|
||||||
|
break;
|
||||||
|
begin = i;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (depth > 0)
|
||||||
|
{
|
||||||
|
begin = i;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
while (begin < end && _output[begin].IsTrivia)
|
||||||
|
begin++;
|
||||||
|
if (begin >= end)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
start = begin;
|
||||||
|
text = Concat(begin, end);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool TryPopOrOperand(out string text)
|
||||||
|
{
|
||||||
|
text = string.Empty;
|
||||||
|
int end = _output.Count;
|
||||||
|
while (end > 0 && _output[end - 1].IsTrivia)
|
||||||
|
end--;
|
||||||
|
if (end == 0)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
int depth = 0;
|
||||||
|
int begin = end;
|
||||||
|
for (int i = end - 1; i >= 0; i--)
|
||||||
|
{
|
||||||
|
var token = _output[i];
|
||||||
|
if (token.Kind == LuaSyntaxTokenKind.Operator)
|
||||||
|
{
|
||||||
|
if (token.Text is ")" or "]" or "}")
|
||||||
|
{
|
||||||
|
depth++;
|
||||||
|
begin = i;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (token.Text is "(" or "[" or "{")
|
||||||
|
{
|
||||||
|
if (depth == 0)
|
||||||
|
break;
|
||||||
|
depth--;
|
||||||
|
begin = i;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (depth == 0 && token.Text is "=" or "," or ";")
|
||||||
|
break;
|
||||||
|
begin = i;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (token.Kind == LuaSyntaxTokenKind.Newline && depth == 0)
|
||||||
|
break;
|
||||||
|
if (token.Kind == LuaSyntaxTokenKind.Name && depth == 0 && LuaKeywords.IsExpressionBoundary(token.Text))
|
||||||
|
break;
|
||||||
|
begin = i;
|
||||||
|
}
|
||||||
|
|
||||||
|
while (begin < end && _output[begin].IsTrivia)
|
||||||
|
begin++;
|
||||||
|
if (begin >= end)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
text = Concat(begin, end);
|
||||||
|
_output.RemoveRange(begin, _output.Count - begin);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void RemoveOutputFrom(int start) => _output.RemoveRange(start, _output.Count - start);
|
||||||
|
|
||||||
|
public bool LastOutputIsTrivia() => _output.Count == 0 || _output[_output.Count - 1].IsTrivia;
|
||||||
|
|
||||||
|
public string ReadLineExpression()
|
||||||
|
{
|
||||||
|
int start = Index;
|
||||||
|
int depth = 0;
|
||||||
|
while (Index < _input.Count)
|
||||||
|
{
|
||||||
|
var token = _input[Index];
|
||||||
|
if (token.Kind == LuaSyntaxTokenKind.Newline && depth == 0)
|
||||||
|
break;
|
||||||
|
if (token.Kind == LuaSyntaxTokenKind.Operator)
|
||||||
|
{
|
||||||
|
if (token.Text is "(" or "[" or "{")
|
||||||
|
depth++;
|
||||||
|
else if (token.Text is ")" or "]" or "}")
|
||||||
|
{
|
||||||
|
if (depth == 0)
|
||||||
|
break;
|
||||||
|
depth--;
|
||||||
|
}
|
||||||
|
else if (depth == 0 && token.Text == ";")
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
Index++;
|
||||||
|
}
|
||||||
|
return TrimmedRange(start, Index);
|
||||||
|
}
|
||||||
|
|
||||||
|
public string ReadForwardOrOperand()
|
||||||
|
{
|
||||||
|
int start = Index;
|
||||||
|
int depth = 0;
|
||||||
|
while (Index < _input.Count)
|
||||||
|
{
|
||||||
|
var token = _input[Index];
|
||||||
|
if (token.Kind == LuaSyntaxTokenKind.Newline && depth == 0)
|
||||||
|
break;
|
||||||
|
if (token.Kind == LuaSyntaxTokenKind.Operator)
|
||||||
|
{
|
||||||
|
if (token.Text is "(" or "[" or "{")
|
||||||
|
depth++;
|
||||||
|
else if (token.Text is ")" or "]" or "}")
|
||||||
|
{
|
||||||
|
if (depth == 0)
|
||||||
|
break;
|
||||||
|
depth--;
|
||||||
|
}
|
||||||
|
else if (depth == 0 && token.Text is "," or ";")
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
else if (token.Kind == LuaSyntaxTokenKind.Name && depth == 0 && LuaKeywords.IsExpressionBoundary(token.Text))
|
||||||
|
break;
|
||||||
|
Index++;
|
||||||
|
}
|
||||||
|
return TrimmedRange(start, Index);
|
||||||
|
}
|
||||||
|
|
||||||
|
public string Serialize()
|
||||||
|
{
|
||||||
|
var builder = new StringBuilder();
|
||||||
|
foreach (var token in _output)
|
||||||
|
builder.Append(token.Text);
|
||||||
|
return builder.ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private string Concat(int begin, int end)
|
||||||
|
{
|
||||||
|
var builder = new StringBuilder();
|
||||||
|
for (int i = begin; i < end; i++)
|
||||||
|
builder.Append(_output[i].Text);
|
||||||
|
return builder.ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private string TrimmedRange(int begin, int end)
|
||||||
|
{
|
||||||
|
while (begin < end && _input[begin].IsTrivia)
|
||||||
|
begin++;
|
||||||
|
while (end > begin && _input[end - 1].IsTrivia)
|
||||||
|
end--;
|
||||||
|
var builder = new StringBuilder();
|
||||||
|
for (int i = begin; i < end; i++)
|
||||||
|
builder.Append(_input[i].Text);
|
||||||
|
return builder.ToString();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
namespace LuaScript.Compat.Syntax
|
||||||
|
{
|
||||||
|
internal readonly record struct LuaRewriteDiagnostic(int Line, string Message);
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
namespace LuaScript.Compat.Syntax
|
||||||
|
{
|
||||||
|
internal static class LuaSyntaxFacts
|
||||||
|
{
|
||||||
|
public static bool IsValueEnd(LuaSyntaxToken token) => token.Kind switch
|
||||||
|
{
|
||||||
|
LuaSyntaxTokenKind.Number or LuaSyntaxTokenKind.String => true,
|
||||||
|
LuaSyntaxTokenKind.Name => !LuaKeywords.IsReserved(token.Text) || token.Text is "nil" or "true" or "false",
|
||||||
|
LuaSyntaxTokenKind.Operator => token.Text is ")" or "]" or "}",
|
||||||
|
_ => false,
|
||||||
|
};
|
||||||
|
|
||||||
|
public static bool IsValueStart(LuaSyntaxToken token) => token.Kind switch
|
||||||
|
{
|
||||||
|
LuaSyntaxTokenKind.Number or LuaSyntaxTokenKind.String => true,
|
||||||
|
LuaSyntaxTokenKind.Name => !LuaKeywords.IsReserved(token.Text) || token.Text is "nil" or "true" or "false" or "not" or "function",
|
||||||
|
LuaSyntaxTokenKind.Operator => token.Text is "(" or "{" or "-" or "#" or "~",
|
||||||
|
_ => false,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,246 @@
|
|||||||
|
using System.Collections.Generic;
|
||||||
|
|
||||||
|
namespace LuaScript.Compat.Syntax
|
||||||
|
{
|
||||||
|
internal static class LuaSyntaxLexer
|
||||||
|
{
|
||||||
|
private static readonly string[] Operators =
|
||||||
|
{
|
||||||
|
"...", "..=", "??=", "||=", "&&=",
|
||||||
|
"==", "~=", "<=", ">=", "..", "::", "??", "||", "&&", "!=", "++",
|
||||||
|
"=>", "|>",
|
||||||
|
"+=", "-=", "*=", "/=", "%=", "^=",
|
||||||
|
"+", "-", "*", "/", "%", "^", "#", "<", ">", "=",
|
||||||
|
"(", ")", "{", "}", "[", "]", ";", ":", ",", ".",
|
||||||
|
"!", "&", "|", "?", "~",
|
||||||
|
};
|
||||||
|
|
||||||
|
public static List<LuaSyntaxToken> Tokenize(string source)
|
||||||
|
{
|
||||||
|
var tokens = new List<LuaSyntaxToken>();
|
||||||
|
int i = 0;
|
||||||
|
int length = source.Length;
|
||||||
|
|
||||||
|
while (i < length)
|
||||||
|
{
|
||||||
|
char c = source[i];
|
||||||
|
|
||||||
|
if (c == '\r' || c == '\n')
|
||||||
|
{
|
||||||
|
int start = i;
|
||||||
|
if (c == '\r' && i + 1 < length && source[i + 1] == '\n')
|
||||||
|
i += 2;
|
||||||
|
else
|
||||||
|
i++;
|
||||||
|
tokens.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Newline, source.Substring(start, i - start)));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (c == ' ' || c == '\t' || c == '\f' || c == '\v')
|
||||||
|
{
|
||||||
|
int start = i;
|
||||||
|
while (i < length && (source[i] == ' ' || source[i] == '\t' || source[i] == '\f' || source[i] == '\v'))
|
||||||
|
i++;
|
||||||
|
tokens.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Whitespace, source.Substring(start, i - start)));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (c == '-' && i + 1 < length && source[i + 1] == '-')
|
||||||
|
{
|
||||||
|
int start = i;
|
||||||
|
i = SkipComment(source, i + 2);
|
||||||
|
tokens.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Comment, source.Substring(start, i - start)));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (c == '[')
|
||||||
|
{
|
||||||
|
int level = LongBracketLevel(source, i);
|
||||||
|
if (level >= 0)
|
||||||
|
{
|
||||||
|
int start = i;
|
||||||
|
i = SkipLongBracket(source, i, level);
|
||||||
|
tokens.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.String, source.Substring(start, i - start)));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (c == '"' || c == '\'')
|
||||||
|
{
|
||||||
|
int start = i;
|
||||||
|
i = SkipShortString(source, i);
|
||||||
|
tokens.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.String, source.Substring(start, i - start)));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (c == '`')
|
||||||
|
{
|
||||||
|
int start = i;
|
||||||
|
i = SkipShortString(source, i);
|
||||||
|
tokens.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.InterpolatedString, source.Substring(start, i - start)));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (IsDigit(c) || (c == '.' && i + 1 < length && IsDigit(source[i + 1])))
|
||||||
|
{
|
||||||
|
int start = i;
|
||||||
|
i = SkipNumber(source, i);
|
||||||
|
tokens.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Number, source.Substring(start, i - start)));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (IsNameStart(c))
|
||||||
|
{
|
||||||
|
int start = i;
|
||||||
|
while (i < length && IsNamePart(source[i]))
|
||||||
|
i++;
|
||||||
|
tokens.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Name, source.Substring(start, i - start)));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
string? op = MatchOperator(source, i);
|
||||||
|
if (op is not null)
|
||||||
|
{
|
||||||
|
tokens.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Operator, op));
|
||||||
|
i += op.Length;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
tokens.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Operator, source.Substring(i, 1)));
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
|
||||||
|
return tokens;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string? MatchOperator(string source, int index)
|
||||||
|
{
|
||||||
|
int remaining = source.Length - index;
|
||||||
|
foreach (var op in Operators)
|
||||||
|
{
|
||||||
|
if (op.Length > remaining)
|
||||||
|
continue;
|
||||||
|
if (string.CompareOrdinal(source, index, op, 0, op.Length) == 0)
|
||||||
|
return op;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int SkipNumber(string source, int i)
|
||||||
|
{
|
||||||
|
int length = source.Length;
|
||||||
|
if (source[i] == '0' && i + 1 < length && (source[i + 1] == 'x' || source[i + 1] == 'X'))
|
||||||
|
{
|
||||||
|
i += 2;
|
||||||
|
while (i < length && (IsHexDigit(source[i]) || source[i] == '.'))
|
||||||
|
i++;
|
||||||
|
if (i < length && (source[i] == 'p' || source[i] == 'P'))
|
||||||
|
{
|
||||||
|
i++;
|
||||||
|
if (i < length && (source[i] == '+' || source[i] == '-'))
|
||||||
|
i++;
|
||||||
|
while (i < length && IsDigit(source[i]))
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
|
||||||
|
while (i < length && IsDigit(source[i]))
|
||||||
|
i++;
|
||||||
|
if (i < length && source[i] == '.' && !(i + 1 < length && source[i + 1] == '.'))
|
||||||
|
{
|
||||||
|
i++;
|
||||||
|
while (i < length && IsDigit(source[i]))
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
if (i < length && (source[i] == 'e' || source[i] == 'E'))
|
||||||
|
{
|
||||||
|
i++;
|
||||||
|
if (i < length && (source[i] == '+' || source[i] == '-'))
|
||||||
|
i++;
|
||||||
|
while (i < length && IsDigit(source[i]))
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int SkipComment(string source, int i)
|
||||||
|
{
|
||||||
|
int level = LongBracketLevel(source, i);
|
||||||
|
if (level >= 0)
|
||||||
|
return SkipLongBracket(source, i, level);
|
||||||
|
|
||||||
|
int length = source.Length;
|
||||||
|
while (i < length && source[i] != '\n' && source[i] != '\r')
|
||||||
|
i++;
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int LongBracketLevel(string source, int i)
|
||||||
|
{
|
||||||
|
if (i >= source.Length || source[i] != '[')
|
||||||
|
return -1;
|
||||||
|
int j = i + 1;
|
||||||
|
int level = 0;
|
||||||
|
while (j < source.Length && source[j] == '=')
|
||||||
|
{
|
||||||
|
level++;
|
||||||
|
j++;
|
||||||
|
}
|
||||||
|
return j < source.Length && source[j] == '[' ? level : -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int SkipLongBracket(string source, int i, int level)
|
||||||
|
{
|
||||||
|
int length = source.Length;
|
||||||
|
i += level + 2;
|
||||||
|
while (i < length)
|
||||||
|
{
|
||||||
|
if (source[i] == ']')
|
||||||
|
{
|
||||||
|
int j = i + 1;
|
||||||
|
int count = 0;
|
||||||
|
while (j < length && source[j] == '=')
|
||||||
|
{
|
||||||
|
count++;
|
||||||
|
j++;
|
||||||
|
}
|
||||||
|
if (count == level && j < length && source[j] == ']')
|
||||||
|
return j + 1;
|
||||||
|
}
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
return length;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int SkipShortString(string source, int start)
|
||||||
|
{
|
||||||
|
char quote = source[start];
|
||||||
|
int i = start + 1;
|
||||||
|
int length = source.Length;
|
||||||
|
while (i < length)
|
||||||
|
{
|
||||||
|
char c = source[i];
|
||||||
|
if (c == '\\')
|
||||||
|
{
|
||||||
|
i += 2;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (c == quote)
|
||||||
|
return i + 1;
|
||||||
|
if (c == '\n' || c == '\r')
|
||||||
|
return i;
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
return length;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool IsNameStart(char c) => c == '_' || char.IsLetter(c);
|
||||||
|
|
||||||
|
private static bool IsNamePart(char c) => c == '_' || char.IsLetterOrDigit(c);
|
||||||
|
|
||||||
|
private static bool IsDigit(char c) => c >= '0' && c <= '9';
|
||||||
|
|
||||||
|
private static bool IsHexDigit(char c) => IsDigit(c) || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace LuaScript.Compat.Syntax
|
||||||
|
{
|
||||||
|
[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
|
||||||
|
internal sealed class LuaSyntaxRuleAttribute(int order) : Attribute
|
||||||
|
{
|
||||||
|
public int Order { get; } = order;
|
||||||
|
|
||||||
|
public bool IsCatalog { get; set; }
|
||||||
|
|
||||||
|
public string Keyword { get; set; } = "";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
namespace LuaScript.Compat.Syntax
|
||||||
|
{
|
||||||
|
internal readonly struct LuaSyntaxToken
|
||||||
|
{
|
||||||
|
public LuaSyntaxToken(LuaSyntaxTokenKind kind, string text)
|
||||||
|
{
|
||||||
|
Kind = kind;
|
||||||
|
Text = text;
|
||||||
|
}
|
||||||
|
|
||||||
|
public LuaSyntaxTokenKind Kind { get; }
|
||||||
|
|
||||||
|
public string Text { get; }
|
||||||
|
|
||||||
|
public bool IsTrivia => Kind is LuaSyntaxTokenKind.Whitespace or LuaSyntaxTokenKind.Newline or LuaSyntaxTokenKind.Comment;
|
||||||
|
|
||||||
|
public bool IsName(string value) => Kind == LuaSyntaxTokenKind.Name && Text == value;
|
||||||
|
|
||||||
|
public bool IsOperator(string value) => Kind == LuaSyntaxTokenKind.Operator && Text == value;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
namespace LuaScript.Compat.Syntax
|
||||||
|
{
|
||||||
|
internal enum LuaSyntaxTokenKind
|
||||||
|
{
|
||||||
|
Whitespace,
|
||||||
|
Newline,
|
||||||
|
Comment,
|
||||||
|
String,
|
||||||
|
InterpolatedString,
|
||||||
|
Number,
|
||||||
|
Name,
|
||||||
|
Operator,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
namespace LuaScript.Compat.Syntax.Rules
|
||||||
|
{
|
||||||
|
[LuaSyntaxRule(70)]
|
||||||
|
internal sealed class AugmentedAssignmentRule : ILuaSyntaxRule
|
||||||
|
{
|
||||||
|
public bool TryApply(LuaRewriteContext context)
|
||||||
|
{
|
||||||
|
if (context.Current.Kind != LuaSyntaxTokenKind.Operator)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
string? connective = Connective(context.Current.Text);
|
||||||
|
if (connective is null)
|
||||||
|
return false;
|
||||||
|
if (!context.TryReadTrailingLvalue(out _, out string target))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
context.Advance();
|
||||||
|
string value = context.ReadLineExpression();
|
||||||
|
string separator = context.LastOutputIsTrivia() ? string.Empty : " ";
|
||||||
|
context.EmitRaw($"{separator}= {target} {connective} ({value})");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string? Connective(string op) => op switch
|
||||||
|
{
|
||||||
|
"+=" => "+",
|
||||||
|
"-=" => "-",
|
||||||
|
"*=" => "*",
|
||||||
|
"/=" => "/",
|
||||||
|
"%=" => "%",
|
||||||
|
"^=" => "^",
|
||||||
|
"..=" => "..",
|
||||||
|
"||=" => "or",
|
||||||
|
"&&=" => "and",
|
||||||
|
_ => null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
[LuaSyntaxRule(80)]
|
||||||
|
internal sealed class NilCoalesceAssignRule : ILuaSyntaxRule
|
||||||
|
{
|
||||||
|
public bool TryApply(LuaRewriteContext context)
|
||||||
|
{
|
||||||
|
if (!context.Current.IsOperator("??="))
|
||||||
|
return false;
|
||||||
|
if (!context.TryReadTrailingLvalue(out int start, out string target))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
context.RemoveOutputFrom(start);
|
||||||
|
context.Advance();
|
||||||
|
string value = context.ReadLineExpression();
|
||||||
|
context.EmitRaw($"if {target} == nil then {target} = ({value}) end");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[LuaSyntaxRule(90)]
|
||||||
|
internal sealed class IncrementRule : ILuaSyntaxRule
|
||||||
|
{
|
||||||
|
public bool TryApply(LuaRewriteContext context)
|
||||||
|
{
|
||||||
|
if (!context.Current.IsOperator("++"))
|
||||||
|
return false;
|
||||||
|
if (!context.TryReadTrailingLvalue(out _, out string target))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
context.Advance();
|
||||||
|
string separator = context.LastOutputIsTrivia() ? string.Empty : " ";
|
||||||
|
context.EmitRaw($"{separator}= {target} + 1");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
namespace LuaScript.Compat.Syntax.Rules
|
||||||
|
{
|
||||||
|
[LuaSyntaxRule(10)]
|
||||||
|
internal sealed class IsNotRule : ILuaSyntaxRule
|
||||||
|
{
|
||||||
|
public bool TryApply(LuaRewriteContext context)
|
||||||
|
{
|
||||||
|
if (!context.Current.IsName("is"))
|
||||||
|
return false;
|
||||||
|
if (!context.TryPreviousOutputSignificantSameLine(out var previous) || !LuaSyntaxFacts.IsValueEnd(previous))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
int notIndex = context.NextSignificantSameLine(context.Index + 1);
|
||||||
|
if (notIndex < 0 || !context.Input[notIndex].IsName("not"))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
int after = context.NextSignificant(notIndex + 1);
|
||||||
|
if (after < 0 || !LuaSyntaxFacts.IsValueStart(context.Input[after]))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
context.EmitOperator("~=");
|
||||||
|
context.Index = notIndex + 1;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[LuaSyntaxRule(20)]
|
||||||
|
internal sealed class IsRule : ILuaSyntaxRule
|
||||||
|
{
|
||||||
|
public bool TryApply(LuaRewriteContext context)
|
||||||
|
{
|
||||||
|
if (!context.Current.IsName("is"))
|
||||||
|
return false;
|
||||||
|
if (!context.TryPreviousOutputSignificantSameLine(out var previous) || !LuaSyntaxFacts.IsValueEnd(previous))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
int next = context.NextSignificantSameLine(context.Index + 1);
|
||||||
|
if (next < 0 || !LuaSyntaxFacts.IsValueStart(context.Input[next]))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
context.EmitOperator("==");
|
||||||
|
context.Advance();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[LuaSyntaxRule(30)]
|
||||||
|
internal sealed class NotEqualRule : ILuaSyntaxRule
|
||||||
|
{
|
||||||
|
public bool TryApply(LuaRewriteContext context)
|
||||||
|
{
|
||||||
|
if (!context.Current.IsOperator("!="))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
context.EmitOperator("~=");
|
||||||
|
context.Advance();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
namespace LuaScript.Compat.Syntax.Rules
|
||||||
|
{
|
||||||
|
[LuaSyntaxRule(2, IsCatalog = true, Keyword = MarkerKeyword)]
|
||||||
|
internal sealed class LuaFastRule : ILuaSyntaxRule
|
||||||
|
{
|
||||||
|
private const string MarkerKeyword = "fast";
|
||||||
|
private const string Message = "[fast]: only obj.fill, obj.convolve and obj.resize can be accelerated.";
|
||||||
|
|
||||||
|
public bool TryApply(LuaRewriteContext context)
|
||||||
|
{
|
||||||
|
if (!context.Current.IsOperator("["))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
if (context.TryPreviousOutputSignificantSameLine(out var previous) && LuaSyntaxFacts.IsValueEnd(previous))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
int nameIndex = context.NextSignificant(context.Index + 1);
|
||||||
|
if (nameIndex < 0 || !context.Input[nameIndex].IsName(MarkerKeyword))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
int closeIndex = context.NextSignificant(nameIndex + 1);
|
||||||
|
if (closeIndex < 0 || !context.Input[closeIndex].IsOperator("]"))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
int targetIndex = context.NextSignificant(closeIndex + 1);
|
||||||
|
if (targetIndex < 0 || context.Input[targetIndex].Kind != LuaSyntaxTokenKind.Name)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
if (TryResolveTarget(context, targetIndex, out int funcIndex, out string function))
|
||||||
|
{
|
||||||
|
EmitBetween(context, closeIndex + 1, targetIndex);
|
||||||
|
context.Index = funcIndex + 1;
|
||||||
|
context.EmitRaw("__fast_" + function);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
context.AddDiagnostic(Message);
|
||||||
|
EmitBetween(context, closeIndex + 1, targetIndex);
|
||||||
|
context.Index = targetIndex;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool TryResolveTarget(LuaRewriteContext context, int objIndex, out int funcIndex, out string function)
|
||||||
|
{
|
||||||
|
funcIndex = -1;
|
||||||
|
function = string.Empty;
|
||||||
|
if (!context.Input[objIndex].IsName("obj"))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
int dot = context.NextSignificant(objIndex + 1);
|
||||||
|
if (dot < 0 || !context.Input[dot].IsOperator("."))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
int name = context.NextSignificant(dot + 1);
|
||||||
|
if (name < 0)
|
||||||
|
return false;
|
||||||
|
string text = context.Input[name].Text;
|
||||||
|
if (text is not ("fill" or "convolve" or "resize"))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
int paren = context.NextSignificant(name + 1);
|
||||||
|
if (paren < 0 || !context.Input[paren].IsOperator("("))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
funcIndex = name;
|
||||||
|
function = text;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void EmitBetween(LuaRewriteContext context, int from, int to)
|
||||||
|
{
|
||||||
|
for (int i = from; i < to; i++)
|
||||||
|
context.Emit(context.Input[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace LuaScript.Compat.Syntax.Rules
|
||||||
|
{
|
||||||
|
[LuaSyntaxRule(5)]
|
||||||
|
internal sealed class LuaInterpolatedStringRule : ILuaSyntaxRule
|
||||||
|
{
|
||||||
|
public bool TryApply(LuaRewriteContext context)
|
||||||
|
{
|
||||||
|
if (context.Current.Kind != LuaSyntaxTokenKind.InterpolatedString)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
string text = context.Current.Text;
|
||||||
|
int end = text.Length;
|
||||||
|
if (end >= 2 && text[end - 1] == '`')
|
||||||
|
end--;
|
||||||
|
string content = text.Substring(1, end - 1);
|
||||||
|
|
||||||
|
var pieces = new List<string>();
|
||||||
|
var literal = new StringBuilder();
|
||||||
|
int i = 0;
|
||||||
|
while (i < content.Length)
|
||||||
|
{
|
||||||
|
char c = content[i];
|
||||||
|
if (c == '\\' && i + 1 < content.Length)
|
||||||
|
{
|
||||||
|
literal.Append(content[i]);
|
||||||
|
literal.Append(content[i + 1]);
|
||||||
|
i += 2;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (c == '{')
|
||||||
|
{
|
||||||
|
int close = FindClosingBrace(content, i + 1);
|
||||||
|
if (close < 0)
|
||||||
|
{
|
||||||
|
literal.Append(c);
|
||||||
|
i++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
string expression = content.Substring(i + 1, close - i - 1).Trim();
|
||||||
|
if (expression.Length > 0)
|
||||||
|
{
|
||||||
|
FlushLiteral(pieces, literal);
|
||||||
|
pieces.Add($"tostring({LuaSyntaxExtensions.Rewrite(expression)})");
|
||||||
|
}
|
||||||
|
i = close + 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
literal.Append(c);
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
FlushLiteral(pieces, literal);
|
||||||
|
|
||||||
|
context.Advance();
|
||||||
|
if (pieces.Count == 0)
|
||||||
|
{
|
||||||
|
context.EmitRaw("\"\"");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (pieces.Count == 1)
|
||||||
|
{
|
||||||
|
context.EmitRaw(pieces[0]);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
context.EmitRaw($"({string.Join(" .. ", pieces)})");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void FlushLiteral(List<string> pieces, StringBuilder literal)
|
||||||
|
{
|
||||||
|
if (literal.Length == 0)
|
||||||
|
return;
|
||||||
|
pieces.Add($"\"{literal.ToString().Replace("\"", "\\\"")}\"");
|
||||||
|
literal.Clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int FindClosingBrace(string content, int from)
|
||||||
|
{
|
||||||
|
int depth = 0;
|
||||||
|
char quote = '\0';
|
||||||
|
for (int i = from; i < content.Length; i++)
|
||||||
|
{
|
||||||
|
char c = content[i];
|
||||||
|
if (quote != '\0')
|
||||||
|
{
|
||||||
|
if (c == '\\')
|
||||||
|
{
|
||||||
|
i++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (c == quote)
|
||||||
|
quote = '\0';
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (c == '"' || c == '\'')
|
||||||
|
{
|
||||||
|
quote = c;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (c == '{')
|
||||||
|
{
|
||||||
|
depth++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (c == '}')
|
||||||
|
{
|
||||||
|
if (depth == 0)
|
||||||
|
return i;
|
||||||
|
depth--;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
namespace LuaScript.Compat.Syntax.Rules
|
||||||
|
{
|
||||||
|
[LuaSyntaxRule(35)]
|
||||||
|
internal sealed class LuaLambdaRule : ILuaSyntaxRule
|
||||||
|
{
|
||||||
|
public bool TryApply(LuaRewriteContext context)
|
||||||
|
{
|
||||||
|
if (!context.Current.IsOperator("=>"))
|
||||||
|
return false;
|
||||||
|
if (!context.TryReadTrailingLvalue(out int start, out string target))
|
||||||
|
return false;
|
||||||
|
if (!TryNormalizeParameters(target, out string parameters))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
int body = context.NextSignificant(context.Index + 1);
|
||||||
|
if (body < 0 || !LuaSyntaxFacts.IsValueStart(context.Input[body]))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
context.RemoveOutputFrom(start);
|
||||||
|
context.Advance();
|
||||||
|
string expression = context.ReadForwardOrOperand();
|
||||||
|
if (expression.Length == 0)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
context.EmitRaw($"(function({parameters}) return {LuaSyntaxExtensions.Rewrite(expression)} end)");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool TryNormalizeParameters(string text, out string parameters)
|
||||||
|
{
|
||||||
|
parameters = string.Empty;
|
||||||
|
text = text.Trim();
|
||||||
|
bool wrapped = text.StartsWith("(") && text.EndsWith(")");
|
||||||
|
if (wrapped)
|
||||||
|
text = text.Substring(1, text.Length - 2).Trim();
|
||||||
|
|
||||||
|
if (text.Length == 0)
|
||||||
|
return wrapped;
|
||||||
|
|
||||||
|
var names = text.Split(',');
|
||||||
|
for (int i = 0; i < names.Length; i++)
|
||||||
|
{
|
||||||
|
string name = names[i].Trim();
|
||||||
|
if (name == "...")
|
||||||
|
{
|
||||||
|
if (i != names.Length - 1)
|
||||||
|
return false;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (!IsName(name) || LuaKeywords.IsReserved(name))
|
||||||
|
return false;
|
||||||
|
if (!wrapped && names.Length > 1)
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
parameters = string.Join(", ", System.Array.ConvertAll(names, static n => n.Trim()));
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool IsName(string text)
|
||||||
|
{
|
||||||
|
if (text.Length == 0)
|
||||||
|
return false;
|
||||||
|
if (text[0] != '_' && !char.IsLetter(text[0]))
|
||||||
|
return false;
|
||||||
|
for (int i = 1; i < text.Length; i++)
|
||||||
|
{
|
||||||
|
if (text[i] != '_' && !char.IsLetterOrDigit(text[i]))
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
namespace LuaScript.Compat.Syntax.Rules
|
||||||
|
{
|
||||||
|
[LuaSyntaxRule(40)]
|
||||||
|
internal sealed class LogicalNotRule : ILuaSyntaxRule
|
||||||
|
{
|
||||||
|
public bool TryApply(LuaRewriteContext context)
|
||||||
|
{
|
||||||
|
if (!context.Current.IsOperator("!"))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
context.Advance();
|
||||||
|
context.EmitWord("not");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[LuaSyntaxRule(50)]
|
||||||
|
internal sealed class AndAliasRule : ILuaSyntaxRule
|
||||||
|
{
|
||||||
|
public bool TryApply(LuaRewriteContext context)
|
||||||
|
{
|
||||||
|
if (!context.Current.IsOperator("&&"))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
context.Advance();
|
||||||
|
context.EmitWord("and");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[LuaSyntaxRule(60)]
|
||||||
|
internal sealed class OrAliasRule : ILuaSyntaxRule
|
||||||
|
{
|
||||||
|
public bool TryApply(LuaRewriteContext context)
|
||||||
|
{
|
||||||
|
if (!context.Current.IsOperator("||"))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
context.Advance();
|
||||||
|
context.EmitWord("or");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
namespace LuaScript.Compat.Syntax.Rules
|
||||||
|
{
|
||||||
|
[LuaSyntaxRule(100)]
|
||||||
|
internal sealed class NilCoalesceRule : ILuaSyntaxRule
|
||||||
|
{
|
||||||
|
public bool TryApply(LuaRewriteContext context)
|
||||||
|
{
|
||||||
|
if (!context.Current.IsOperator("??"))
|
||||||
|
return false;
|
||||||
|
if (!context.TryPopOrOperand(out string left))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
context.Advance();
|
||||||
|
string right = context.ReadForwardOrOperand();
|
||||||
|
string temporary = context.NextTemporary();
|
||||||
|
context.EmitRaw($"(function() local {temporary} = ({left}) if {temporary} ~= nil then return {temporary} else return ({right}) end end)()");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
namespace LuaScript.Compat.Syntax.Rules
|
||||||
|
{
|
||||||
|
[LuaSyntaxRule(110)]
|
||||||
|
internal sealed class LuaNumericRangeRule : ILuaSyntaxRule
|
||||||
|
{
|
||||||
|
public bool TryApply(LuaRewriteContext context)
|
||||||
|
{
|
||||||
|
if (!context.Current.IsName("in"))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
int open = context.NextSignificant(context.Index + 1);
|
||||||
|
if (open < 0 || !context.Input[open].IsOperator("<"))
|
||||||
|
return false;
|
||||||
|
if (!LuaRangeSyntax.TryParse(context.Input, open, out var parts, out int end))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
string stopExpression = parts.Exclusive ? $"({parts.Stop}) - 1" : parts.Stop;
|
||||||
|
string replacement = parts.Step is null
|
||||||
|
? $"= {parts.Start}, {stopExpression}"
|
||||||
|
: $"= {parts.Start}, {stopExpression}, {parts.Step}";
|
||||||
|
context.EmitRaw(replacement);
|
||||||
|
context.Index = end;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace LuaScript.Compat.Syntax.Rules
|
||||||
|
{
|
||||||
|
[LuaSyntaxRule(98)]
|
||||||
|
internal sealed class LuaPipeRule : ILuaSyntaxRule
|
||||||
|
{
|
||||||
|
public bool TryApply(LuaRewriteContext context)
|
||||||
|
{
|
||||||
|
if (!context.Current.IsOperator("|>"))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
int targetStart = context.NextSignificant(context.Index + 1);
|
||||||
|
if (targetStart < 0 || !LuaSyntaxFacts.IsValueStart(context.Input[targetStart]))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
if (!context.TryPopOrOperand(out string left))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
context.Advance();
|
||||||
|
var segment = ReadSegment(context);
|
||||||
|
string call = BuildCall(segment, left);
|
||||||
|
context.EmitRaw(call);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<LuaSyntaxToken> ReadSegment(LuaRewriteContext context)
|
||||||
|
{
|
||||||
|
var tokens = new List<LuaSyntaxToken>();
|
||||||
|
int depth = 0;
|
||||||
|
while (!context.AtEnd)
|
||||||
|
{
|
||||||
|
var token = context.Current;
|
||||||
|
if (token.Kind == LuaSyntaxTokenKind.Newline && depth == 0)
|
||||||
|
break;
|
||||||
|
if (token.Kind == LuaSyntaxTokenKind.Name && depth == 0 && LuaKeywords.IsExpressionBoundary(token.Text))
|
||||||
|
break;
|
||||||
|
if (token.Kind == LuaSyntaxTokenKind.Operator)
|
||||||
|
{
|
||||||
|
if (token.Text is "(" or "[" or "{")
|
||||||
|
{
|
||||||
|
depth++;
|
||||||
|
}
|
||||||
|
else if (token.Text is ")" or "]" or "}")
|
||||||
|
{
|
||||||
|
if (depth == 0)
|
||||||
|
break;
|
||||||
|
depth--;
|
||||||
|
}
|
||||||
|
else if (depth == 0 && token.Text is "," or ";" or "|>")
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
tokens.Add(token);
|
||||||
|
context.Advance();
|
||||||
|
}
|
||||||
|
while (tokens.Count > 0 && tokens[0].IsTrivia)
|
||||||
|
tokens.RemoveAt(0);
|
||||||
|
while (tokens.Count > 0 && tokens[tokens.Count - 1].IsTrivia)
|
||||||
|
tokens.RemoveAt(tokens.Count - 1);
|
||||||
|
return tokens;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string BuildCall(List<LuaSyntaxToken> segment, string left)
|
||||||
|
{
|
||||||
|
string argument = $"({left})";
|
||||||
|
if (segment.Count == 0)
|
||||||
|
return argument;
|
||||||
|
|
||||||
|
if (segment[segment.Count - 1].IsOperator(")"))
|
||||||
|
{
|
||||||
|
int open = FindOpeningParen(segment);
|
||||||
|
if (open > 0)
|
||||||
|
{
|
||||||
|
string callee = Concat(segment, 0, open);
|
||||||
|
string arguments = Concat(segment, open + 1, segment.Count - 1);
|
||||||
|
return arguments.Length == 0
|
||||||
|
? $"{callee}({argument})"
|
||||||
|
: $"{callee}({argument}, {arguments})";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $"{Concat(segment, 0, segment.Count)}({argument})";
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int FindOpeningParen(List<LuaSyntaxToken> segment)
|
||||||
|
{
|
||||||
|
int depth = 0;
|
||||||
|
for (int i = segment.Count - 1; i >= 0; i--)
|
||||||
|
{
|
||||||
|
var token = segment[i];
|
||||||
|
if (token.Kind != LuaSyntaxTokenKind.Operator)
|
||||||
|
continue;
|
||||||
|
if (token.Text is ")" or "]" or "}")
|
||||||
|
{
|
||||||
|
depth++;
|
||||||
|
}
|
||||||
|
else if (token.Text is "(" or "[" or "{")
|
||||||
|
{
|
||||||
|
depth--;
|
||||||
|
if (depth == 0)
|
||||||
|
return token.Text == "(" ? i : -1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Concat(List<LuaSyntaxToken> segment, int begin, int end)
|
||||||
|
{
|
||||||
|
while (begin < end && segment[begin].IsTrivia)
|
||||||
|
begin++;
|
||||||
|
while (end > begin && segment[end - 1].IsTrivia)
|
||||||
|
end--;
|
||||||
|
var builder = new StringBuilder();
|
||||||
|
for (int i = begin; i < end; i++)
|
||||||
|
builder.Append(segment[i].Text);
|
||||||
|
return builder.ToString();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
namespace LuaScript.Compat.Syntax.Rules
|
||||||
|
{
|
||||||
|
[LuaSyntaxRule(108)]
|
||||||
|
internal sealed class LuaRangeMembershipRule : ILuaSyntaxRule
|
||||||
|
{
|
||||||
|
public bool TryApply(LuaRewriteContext context)
|
||||||
|
{
|
||||||
|
if (!context.Current.IsName("in"))
|
||||||
|
return false;
|
||||||
|
if (IsForHeader(context))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
int open = context.NextSignificant(context.Index + 1);
|
||||||
|
if (open < 0 || !context.Input[open].IsOperator("<"))
|
||||||
|
return false;
|
||||||
|
if (!LuaRangeSyntax.TryParse(context.Input, open, out var parts, out int end))
|
||||||
|
return false;
|
||||||
|
if (parts.Step is not null)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
if (!context.TryPopOrOperand(out string left))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
string temporary = context.NextTemporary();
|
||||||
|
string upper = parts.Exclusive ? "<" : "<=";
|
||||||
|
context.EmitRaw($"(function() local {temporary} = ({left}) return {temporary} >= ({LuaSyntaxExtensions.Rewrite(parts.Start)}) and {temporary} {upper} ({LuaSyntaxExtensions.Rewrite(parts.Stop)}) end)()");
|
||||||
|
context.Index = end;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool IsForHeader(LuaRewriteContext context)
|
||||||
|
{
|
||||||
|
var output = context.Output;
|
||||||
|
for (int i = output.Count - 1; i >= 0; i--)
|
||||||
|
{
|
||||||
|
var token = output[i];
|
||||||
|
if (token.Kind == LuaSyntaxTokenKind.Newline)
|
||||||
|
return false;
|
||||||
|
if (token.Kind != LuaSyntaxTokenKind.Name)
|
||||||
|
continue;
|
||||||
|
if (token.Text is "do" or "then")
|
||||||
|
return false;
|
||||||
|
if (token.Text == "for")
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace LuaScript.Compat.Syntax.Rules
|
||||||
|
{
|
||||||
|
[LuaSyntaxRule(92)]
|
||||||
|
internal sealed class LuaSafeNavigationRule : ILuaSyntaxRule
|
||||||
|
{
|
||||||
|
public bool TryApply(LuaRewriteContext context)
|
||||||
|
{
|
||||||
|
if (!context.Current.IsOperator("?"))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
int accessor = context.NextSignificantSameLine(context.Index + 1);
|
||||||
|
if (accessor < 0)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
if (context.Input[accessor].IsOperator("."))
|
||||||
|
return TryApplyMember(context, accessor);
|
||||||
|
if (context.Input[accessor].IsOperator("["))
|
||||||
|
return TryApplyIndex(context, accessor);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool TryApplyMember(LuaRewriteContext context, int accessor)
|
||||||
|
{
|
||||||
|
int name = context.NextSignificantSameLine(accessor + 1);
|
||||||
|
if (name < 0)
|
||||||
|
return false;
|
||||||
|
var token = context.Input[name];
|
||||||
|
if (token.Kind != LuaSyntaxTokenKind.Name || LuaKeywords.IsReserved(token.Text))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
if (!context.TryReadTrailingLvalue(out int start, out string target))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
context.RemoveOutputFrom(start);
|
||||||
|
context.Index = name + 1;
|
||||||
|
string temporary = context.NextTemporary();
|
||||||
|
context.EmitRaw($"(function() local {temporary} = ({target}) if {temporary} == nil then return nil end return {temporary}.{token.Text} end)()");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool TryApplyIndex(LuaRewriteContext context, int accessor)
|
||||||
|
{
|
||||||
|
int close = FindClosingBracket(context, accessor + 1);
|
||||||
|
if (close < 0)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
string key = Concat(context, accessor + 1, close);
|
||||||
|
if (key.Length == 0)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
if (!context.TryReadTrailingLvalue(out int start, out string target))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
context.RemoveOutputFrom(start);
|
||||||
|
context.Index = close + 1;
|
||||||
|
string temporary = context.NextTemporary();
|
||||||
|
context.EmitRaw($"(function() local {temporary} = ({target}) if {temporary} == nil then return nil end return {temporary}[{LuaSyntaxExtensions.Rewrite(key)}] end)()");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int FindClosingBracket(LuaRewriteContext context, int from)
|
||||||
|
{
|
||||||
|
int depth = 0;
|
||||||
|
for (int i = from; i < context.Input.Count; i++)
|
||||||
|
{
|
||||||
|
var token = context.Input[i];
|
||||||
|
if (token.Kind != LuaSyntaxTokenKind.Operator)
|
||||||
|
continue;
|
||||||
|
if (token.Text is "(" or "[" or "{")
|
||||||
|
{
|
||||||
|
depth++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (token.Text is ")" or "}")
|
||||||
|
{
|
||||||
|
if (depth == 0)
|
||||||
|
return -1;
|
||||||
|
depth--;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (token.Text == "]")
|
||||||
|
{
|
||||||
|
if (depth == 0)
|
||||||
|
return i;
|
||||||
|
depth--;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Concat(LuaRewriteContext context, int begin, int end)
|
||||||
|
{
|
||||||
|
while (begin < end && context.Input[begin].IsTrivia)
|
||||||
|
begin++;
|
||||||
|
while (end > begin && context.Input[end - 1].IsTrivia)
|
||||||
|
end--;
|
||||||
|
var builder = new StringBuilder();
|
||||||
|
for (int i = begin; i < end; i++)
|
||||||
|
builder.Append(context.Input[i].Text);
|
||||||
|
return builder.ToString();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
namespace LuaScript.Compat.Syntax.Rules
|
||||||
|
{
|
||||||
|
[LuaSyntaxRule(96)]
|
||||||
|
internal sealed class LuaTernaryRule : ILuaSyntaxRule
|
||||||
|
{
|
||||||
|
public bool TryApply(LuaRewriteContext context)
|
||||||
|
{
|
||||||
|
if (!context.Current.IsOperator("?"))
|
||||||
|
return false;
|
||||||
|
if (!context.TryPreviousOutputSignificantSameLine(out var previous) || !LuaSyntaxFacts.IsValueEnd(previous))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
int thenStart = context.NextSignificantSameLine(context.Index + 1);
|
||||||
|
if (thenStart < 0 || !LuaSyntaxFacts.IsValueStart(context.Input[thenStart]))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
int colon = FindColon(context, context.Index + 1);
|
||||||
|
if (colon < 0)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
int elseStart = context.NextSignificantSameLine(colon + 1);
|
||||||
|
if (elseStart < 0 || !LuaSyntaxFacts.IsValueStart(context.Input[elseStart]))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
if (!context.TryPopOrOperand(out string condition))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
context.Index++;
|
||||||
|
string thenExpression = ReadUntil(context, colon);
|
||||||
|
context.Index = colon + 1;
|
||||||
|
string elseExpression = context.ReadForwardOrOperand();
|
||||||
|
|
||||||
|
context.EmitRaw($"(function() if {condition} then return ({LuaSyntaxExtensions.Rewrite(thenExpression)}) else return ({LuaSyntaxExtensions.Rewrite(elseExpression)}) end end)()");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int FindColon(LuaRewriteContext context, int from)
|
||||||
|
{
|
||||||
|
int depth = 0;
|
||||||
|
for (int i = from; i < context.Input.Count; i++)
|
||||||
|
{
|
||||||
|
var token = context.Input[i];
|
||||||
|
if (token.Kind == LuaSyntaxTokenKind.Newline)
|
||||||
|
return -1;
|
||||||
|
if (token.Kind == LuaSyntaxTokenKind.Name && depth == 0 && LuaKeywords.IsExpressionBoundary(token.Text))
|
||||||
|
return -1;
|
||||||
|
if (token.Kind != LuaSyntaxTokenKind.Operator)
|
||||||
|
continue;
|
||||||
|
if (token.Text is "(" or "[" or "{")
|
||||||
|
{
|
||||||
|
depth++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (token.Text is ")" or "]" or "}")
|
||||||
|
{
|
||||||
|
if (depth == 0)
|
||||||
|
return -1;
|
||||||
|
depth--;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (depth > 0)
|
||||||
|
continue;
|
||||||
|
if (token.Text is "," or ";" or "?")
|
||||||
|
return -1;
|
||||||
|
if (token.Text == ":")
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string ReadUntil(LuaRewriteContext context, int stop)
|
||||||
|
{
|
||||||
|
var builder = new System.Text.StringBuilder();
|
||||||
|
int begin = context.Index;
|
||||||
|
int end = stop;
|
||||||
|
while (begin < end && context.Input[begin].IsTrivia)
|
||||||
|
begin++;
|
||||||
|
while (end > begin && context.Input[end - 1].IsTrivia)
|
||||||
|
end--;
|
||||||
|
for (int i = begin; i < end; i++)
|
||||||
|
builder.Append(context.Input[i].Text);
|
||||||
|
return builder.ToString();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
using System.Collections;
|
||||||
|
|
||||||
|
namespace LuaScript.Generator
|
||||||
|
{
|
||||||
|
internal readonly struct EquatableArray<T>(T[] items) : IEquatable<EquatableArray<T>>, IReadOnlyList<T>
|
||||||
|
where T : IEquatable<T>
|
||||||
|
{
|
||||||
|
private readonly T[] _items = items;
|
||||||
|
|
||||||
|
public static readonly EquatableArray<T> Empty = new([]);
|
||||||
|
|
||||||
|
public int Count => _items?.Length ?? 0;
|
||||||
|
|
||||||
|
public T this[int index] => _items[index];
|
||||||
|
|
||||||
|
public bool Equals(EquatableArray<T> other)
|
||||||
|
{
|
||||||
|
var a = _items ?? [];
|
||||||
|
var b = other._items ?? [];
|
||||||
|
if (a.Length != b.Length)
|
||||||
|
return false;
|
||||||
|
for (int i = 0; i < a.Length; i++)
|
||||||
|
{
|
||||||
|
if (!a[i].Equals(b[i]))
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override bool Equals(object? obj) => obj is EquatableArray<T> other && Equals(other);
|
||||||
|
|
||||||
|
public override int GetHashCode()
|
||||||
|
{
|
||||||
|
var items = _items ?? [];
|
||||||
|
int hash = 17;
|
||||||
|
foreach (var item in items)
|
||||||
|
hash = hash * 31 + (item?.GetHashCode() ?? 0);
|
||||||
|
return hash;
|
||||||
|
}
|
||||||
|
|
||||||
|
public IEnumerator<T> GetEnumerator() => ((IEnumerable<T>)(_items ?? [])).GetEnumerator();
|
||||||
|
|
||||||
|
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
namespace LuaScript.Generator
|
||||||
|
{
|
||||||
|
internal sealed record GpuShaderClass(
|
||||||
|
string Namespace,
|
||||||
|
EquatableArray<GpuShaderTypePart> TypeChain,
|
||||||
|
EquatableArray<GpuShaderMethod> Methods,
|
||||||
|
EquatableArray<string> Errors);
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
namespace LuaScript.Generator
|
||||||
|
{
|
||||||
|
internal sealed record GpuShaderFile(string Path, string Source);
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
namespace LuaScript.Generator
|
||||||
|
{
|
||||||
|
internal sealed record GpuShaderInvocation(string Resources, string Constants, string Target, string Width, string Height);
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
namespace LuaScript.Generator
|
||||||
|
{
|
||||||
|
internal sealed record GpuShaderMethod(
|
||||||
|
string Accessibility,
|
||||||
|
bool IsStatic,
|
||||||
|
string ReturnType,
|
||||||
|
string MethodName,
|
||||||
|
EquatableArray<GpuShaderParameter> Parameters,
|
||||||
|
string FileName,
|
||||||
|
string EntryPoint,
|
||||||
|
GpuShaderInvocation Invocation);
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
namespace LuaScript.Generator
|
||||||
|
{
|
||||||
|
internal sealed record GpuShaderMethodSource(GpuShaderMethod Method, string Bytecode);
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
namespace LuaScript.Generator
|
||||||
|
{
|
||||||
|
internal sealed record GpuShaderParameter(string Prefix, string Type, string Name);
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
using System.Collections.Immutable;
|
||||||
|
|
||||||
|
namespace LuaScript.Generator
|
||||||
|
{
|
||||||
|
internal sealed record GpuShaderResolution(ImmutableArray<GpuShaderMethodSource> Methods, ImmutableArray<string> Errors);
|
||||||
|
}
|
||||||
@@ -0,0 +1,436 @@
|
|||||||
|
using System.Collections.Immutable;
|
||||||
|
using System.Globalization;
|
||||||
|
using System.IO;
|
||||||
|
using System.Text;
|
||||||
|
using Microsoft.CodeAnalysis;
|
||||||
|
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||||
|
using Microsoft.CodeAnalysis.Text;
|
||||||
|
|
||||||
|
namespace LuaScript.Generator
|
||||||
|
{
|
||||||
|
[Generator]
|
||||||
|
public sealed class GpuShaderSourceGenerator : IIncrementalGenerator
|
||||||
|
{
|
||||||
|
private const string AttributeName = "LuaScript.Engine.Processing.GpuPixelOperationShaderAttribute";
|
||||||
|
|
||||||
|
public void Initialize(IncrementalGeneratorInitializationContext context)
|
||||||
|
{
|
||||||
|
var classes = context.SyntaxProvider
|
||||||
|
.CreateSyntaxProvider(
|
||||||
|
static (node, _) => node is ClassDeclarationSyntax { AttributeLists.Count: > 0 },
|
||||||
|
static (ctx, _) => CreateClass(ctx))
|
||||||
|
.Where(static model => model is not null)
|
||||||
|
.Select(static (model, _) => model!);
|
||||||
|
|
||||||
|
var files = context.AdditionalTextsProvider
|
||||||
|
.Where(static file => file.Path.EndsWith(".hlsl", StringComparison.OrdinalIgnoreCase))
|
||||||
|
.Select(static (file, token) => new GpuShaderFile(Normalize(file.Path), file.GetText(token)?.ToString() ?? string.Empty))
|
||||||
|
.Collect()
|
||||||
|
.Select(static (items, _) => new EquatableArray<GpuShaderFile>([.. items]));
|
||||||
|
|
||||||
|
context.RegisterSourceOutput(classes.Combine(files), static (context, source) =>
|
||||||
|
{
|
||||||
|
var (model, files) = source;
|
||||||
|
var resolved = Resolve(model, files);
|
||||||
|
if (resolved.Errors.Length > 0)
|
||||||
|
{
|
||||||
|
context.AddSource(ErrorHintName(model), SourceText.From(EmitErrors(resolved.Errors), Encoding.UTF8));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
context.AddSource(HintName(model), SourceText.From(Emit(model, resolved.Methods), Encoding.UTF8));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private static GpuShaderClass? CreateClass(GeneratorSyntaxContext context)
|
||||||
|
{
|
||||||
|
if (context.Node is not ClassDeclarationSyntax declaration)
|
||||||
|
return null;
|
||||||
|
if (context.SemanticModel.GetDeclaredSymbol(declaration) is not INamedTypeSymbol type)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
var attributes = type.GetAttributes()
|
||||||
|
.Where(static attribute => attribute.AttributeClass?.ToDisplayString() == AttributeName)
|
||||||
|
.ToArray();
|
||||||
|
if (attributes.Length == 0)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
var chain = new List<GpuShaderTypePart>();
|
||||||
|
for (var current = type; current is not null; current = current.ContainingType)
|
||||||
|
chain.Insert(0, new GpuShaderTypePart(current.Name, current.IsStatic));
|
||||||
|
|
||||||
|
var methods = ImmutableArray.CreateBuilder<GpuShaderMethod>();
|
||||||
|
var errors = ImmutableArray.CreateBuilder<string>();
|
||||||
|
|
||||||
|
foreach (var attribute in attributes)
|
||||||
|
{
|
||||||
|
if (attribute.ConstructorArguments.Length < 3 ||
|
||||||
|
attribute.ConstructorArguments[0].Value is not string methodName ||
|
||||||
|
attribute.ConstructorArguments[1].Value is not string fileName ||
|
||||||
|
attribute.ConstructorArguments[2].Value is not string entryPoint)
|
||||||
|
{
|
||||||
|
errors.Add("GPU shader attribute arguments are invalid");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
var candidates = type.GetMembers(methodName).OfType<IMethodSymbol>().ToArray();
|
||||||
|
if (candidates.Length == 0)
|
||||||
|
{
|
||||||
|
errors.Add($"GPU shader method '{methodName}' was not found");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (candidates.Length > 1)
|
||||||
|
{
|
||||||
|
errors.Add($"GPU shader method '{methodName}' is ambiguous");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
var method = candidates[0];
|
||||||
|
string? error = Validate(method, fileName, entryPoint, out var invocation);
|
||||||
|
if (error is not null)
|
||||||
|
{
|
||||||
|
errors.Add($"GPU shader method '{methodName}': {error}");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
var parameters = ImmutableArray.CreateBuilder<GpuShaderParameter>();
|
||||||
|
foreach (var parameter in method.Parameters)
|
||||||
|
parameters.Add(new GpuShaderParameter(ParameterPrefix(parameter), parameter.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat), parameter.Name));
|
||||||
|
|
||||||
|
methods.Add(new GpuShaderMethod(
|
||||||
|
AccessibilityName(method.DeclaredAccessibility),
|
||||||
|
method.IsStatic,
|
||||||
|
method.ReturnType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat),
|
||||||
|
method.Name,
|
||||||
|
new EquatableArray<GpuShaderParameter>([.. parameters]),
|
||||||
|
Normalize(fileName),
|
||||||
|
entryPoint,
|
||||||
|
invocation));
|
||||||
|
}
|
||||||
|
|
||||||
|
return new GpuShaderClass(
|
||||||
|
type.ContainingNamespace.IsGlobalNamespace ? string.Empty : type.ContainingNamespace.ToDisplayString(),
|
||||||
|
new EquatableArray<GpuShaderTypePart>([.. chain]),
|
||||||
|
new EquatableArray<GpuShaderMethod>([.. methods]),
|
||||||
|
new EquatableArray<string>([.. errors]));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string? Validate(IMethodSymbol method, string fileName, string entryPoint, out GpuShaderInvocation invocation)
|
||||||
|
{
|
||||||
|
invocation = new GpuShaderInvocation(string.Empty, string.Empty, string.Empty, string.Empty, string.Empty);
|
||||||
|
if (string.IsNullOrWhiteSpace(fileName))
|
||||||
|
return "file name is empty";
|
||||||
|
if (string.IsNullOrWhiteSpace(entryPoint))
|
||||||
|
return "entry point is empty";
|
||||||
|
if (method.ReturnType.SpecialType != SpecialType.System_Boolean)
|
||||||
|
return "return type must be bool";
|
||||||
|
|
||||||
|
var parameters = method.Parameters;
|
||||||
|
if (parameters.Length == 4 &&
|
||||||
|
IsReadOnlySpanSingle(parameters[0].Type) &&
|
||||||
|
IsByteArray(parameters[1].Type) &&
|
||||||
|
IsInt32(parameters[2].Type) &&
|
||||||
|
IsInt32(parameters[3].Type))
|
||||||
|
{
|
||||||
|
invocation = new GpuShaderInvocation("[]", parameters[0].Name, parameters[1].Name, parameters[2].Name, parameters[3].Name);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (parameters.Length == 5 &&
|
||||||
|
IsReadOnlySpanPixelShaderInput(parameters[0].Type) &&
|
||||||
|
IsReadOnlySpanSingle(parameters[1].Type) &&
|
||||||
|
IsByteArray(parameters[2].Type) &&
|
||||||
|
IsInt32(parameters[3].Type) &&
|
||||||
|
IsInt32(parameters[4].Type))
|
||||||
|
{
|
||||||
|
invocation = new GpuShaderInvocation(parameters[0].Name, parameters[1].Name, parameters[2].Name, parameters[3].Name, parameters[4].Name);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return "signature is invalid";
|
||||||
|
}
|
||||||
|
|
||||||
|
private static GpuShaderResolution Resolve(GpuShaderClass model, EquatableArray<GpuShaderFile> files)
|
||||||
|
{
|
||||||
|
var methods = ImmutableArray.CreateBuilder<GpuShaderMethodSource>();
|
||||||
|
var errors = ImmutableArray.CreateBuilder<string>();
|
||||||
|
errors.AddRange(model.Errors);
|
||||||
|
|
||||||
|
foreach (var method in model.Methods)
|
||||||
|
{
|
||||||
|
var matched = files.Where(file => Matches(file.Path, method.FileName)).ToArray();
|
||||||
|
if (matched.Length == 0)
|
||||||
|
{
|
||||||
|
errors.Add($"GPU shader file '{method.FileName}' for method '{method.MethodName}' was not found");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (matched.Length > 1)
|
||||||
|
{
|
||||||
|
errors.Add($"GPU shader file '{method.FileName}' for method '{method.MethodName}' matched multiple additional files");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
string? failure = ShaderCompiler.Compile(matched[0].Source, method.EntryPoint, out string bytecode);
|
||||||
|
if (failure is not null)
|
||||||
|
{
|
||||||
|
errors.Add($"GPU shader method '{method.MethodName}' failed to compile: {failure}");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
methods.Add(new GpuShaderMethodSource(method, bytecode));
|
||||||
|
}
|
||||||
|
|
||||||
|
return new GpuShaderResolution([.. methods], [.. errors]);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool Matches(string filePath, string registrationPath)
|
||||||
|
{
|
||||||
|
if (string.Equals(filePath, registrationPath, StringComparison.OrdinalIgnoreCase))
|
||||||
|
return true;
|
||||||
|
return filePath.EndsWith("/" + registrationPath, StringComparison.OrdinalIgnoreCase);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool IsReadOnlySpanSingle(ITypeSymbol type)
|
||||||
|
{
|
||||||
|
return type is INamedTypeSymbol named &&
|
||||||
|
named.OriginalDefinition.ToDisplayString() == "System.ReadOnlySpan<T>" &&
|
||||||
|
named.TypeArguments.Length == 1 &&
|
||||||
|
named.TypeArguments[0].SpecialType == SpecialType.System_Single;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool IsReadOnlySpanPixelShaderInput(ITypeSymbol type)
|
||||||
|
{
|
||||||
|
string display = type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat);
|
||||||
|
return display.Contains("ReadOnlySpan", StringComparison.Ordinal) &&
|
||||||
|
display.Contains("PixelShaderInput", StringComparison.Ordinal);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool IsByteArray(ITypeSymbol type)
|
||||||
|
{
|
||||||
|
return type is IArrayTypeSymbol array &&
|
||||||
|
array.Rank == 1 &&
|
||||||
|
array.ElementType.SpecialType == SpecialType.System_Byte;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool IsInt32(ITypeSymbol type) => type.SpecialType == SpecialType.System_Int32;
|
||||||
|
|
||||||
|
private static string Normalize(string path) => path.Replace(Path.DirectorySeparatorChar, '/').Replace(Path.AltDirectorySeparatorChar, '/');
|
||||||
|
|
||||||
|
private static string AccessibilityName(Accessibility accessibility)
|
||||||
|
{
|
||||||
|
return accessibility switch
|
||||||
|
{
|
||||||
|
Accessibility.Public => "public",
|
||||||
|
Accessibility.Internal => "internal",
|
||||||
|
Accessibility.Protected => "protected",
|
||||||
|
Accessibility.ProtectedAndInternal => "private protected",
|
||||||
|
Accessibility.ProtectedOrInternal => "protected internal",
|
||||||
|
_ => "private",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string ParameterPrefix(IParameterSymbol parameter)
|
||||||
|
{
|
||||||
|
return parameter.RefKind switch
|
||||||
|
{
|
||||||
|
RefKind.In => "in ",
|
||||||
|
RefKind.Ref => "ref ",
|
||||||
|
RefKind.Out => "out ",
|
||||||
|
_ => string.Empty,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Emit(GpuShaderClass model, ImmutableArray<GpuShaderMethodSource> sources)
|
||||||
|
{
|
||||||
|
var builder = new StringBuilder();
|
||||||
|
builder.AppendLine("#nullable enable");
|
||||||
|
if (model.Namespace.Length > 0)
|
||||||
|
{
|
||||||
|
builder.AppendLine("namespace " + model.Namespace);
|
||||||
|
builder.AppendLine("{");
|
||||||
|
}
|
||||||
|
|
||||||
|
int indent = model.Namespace.Length > 0 ? 1 : 0;
|
||||||
|
foreach (var type in model.TypeChain)
|
||||||
|
{
|
||||||
|
AppendIndent(builder, indent);
|
||||||
|
builder.Append(type.IsStatic ? "static partial class " : "partial class ");
|
||||||
|
builder.AppendLine(type.Name);
|
||||||
|
AppendIndent(builder, indent);
|
||||||
|
builder.AppendLine("{");
|
||||||
|
indent++;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int i = 0; i < sources.Length; i++)
|
||||||
|
{
|
||||||
|
if (i > 0)
|
||||||
|
builder.AppendLine();
|
||||||
|
EmitMethod(builder, indent, sources[i]);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int i = model.TypeChain.Count - 1; i >= 0; i--)
|
||||||
|
{
|
||||||
|
indent--;
|
||||||
|
AppendIndent(builder, indent);
|
||||||
|
builder.AppendLine("}");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (model.Namespace.Length > 0)
|
||||||
|
builder.AppendLine("}");
|
||||||
|
return builder.ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void EmitMethod(StringBuilder builder, int indent, GpuShaderMethodSource source)
|
||||||
|
{
|
||||||
|
var method = source.Method;
|
||||||
|
string field = "s_shader_" + method.MethodName;
|
||||||
|
|
||||||
|
AppendIndent(builder, indent);
|
||||||
|
builder.Append("private static readonly byte[] ");
|
||||||
|
builder.Append(field);
|
||||||
|
builder.Append(" = global::System.Convert.FromBase64String(");
|
||||||
|
builder.Append(Literal(source.Bytecode));
|
||||||
|
builder.AppendLine(");");
|
||||||
|
builder.AppendLine();
|
||||||
|
|
||||||
|
AppendIndent(builder, indent);
|
||||||
|
builder.Append(method.Accessibility);
|
||||||
|
builder.Append(' ');
|
||||||
|
if (method.IsStatic)
|
||||||
|
builder.Append("static ");
|
||||||
|
builder.Append("partial ");
|
||||||
|
builder.Append(method.ReturnType);
|
||||||
|
builder.Append(' ');
|
||||||
|
builder.Append(method.MethodName);
|
||||||
|
builder.Append('(');
|
||||||
|
for (int i = 0; i < method.Parameters.Count; i++)
|
||||||
|
{
|
||||||
|
if (i > 0)
|
||||||
|
builder.Append(", ");
|
||||||
|
var parameter = method.Parameters[i];
|
||||||
|
builder.Append(parameter.Prefix);
|
||||||
|
builder.Append(parameter.Type);
|
||||||
|
builder.Append(' ');
|
||||||
|
builder.Append(parameter.Name);
|
||||||
|
}
|
||||||
|
builder.AppendLine(")");
|
||||||
|
AppendIndent(builder, indent);
|
||||||
|
builder.AppendLine("{");
|
||||||
|
AppendIndent(builder, indent + 1);
|
||||||
|
builder.Append("return Run(");
|
||||||
|
builder.Append(field);
|
||||||
|
builder.Append(", ");
|
||||||
|
builder.Append(method.Invocation.Resources);
|
||||||
|
builder.Append(", ");
|
||||||
|
builder.Append(method.Invocation.Constants);
|
||||||
|
builder.Append(", ");
|
||||||
|
builder.Append(method.Invocation.Target);
|
||||||
|
builder.Append(", ");
|
||||||
|
builder.Append(method.Invocation.Width);
|
||||||
|
builder.Append(", ");
|
||||||
|
builder.Append(method.Invocation.Height);
|
||||||
|
builder.AppendLine(");");
|
||||||
|
AppendIndent(builder, indent);
|
||||||
|
builder.AppendLine("}");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void AppendIndent(StringBuilder builder, int indent)
|
||||||
|
{
|
||||||
|
for (int i = 0; i < indent; i++)
|
||||||
|
builder.Append(" ");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string EmitErrors(ImmutableArray<string> errors)
|
||||||
|
{
|
||||||
|
var builder = new StringBuilder();
|
||||||
|
foreach (var error in errors)
|
||||||
|
builder.AppendLine("#error " + error);
|
||||||
|
return builder.ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string HintName(GpuShaderClass model)
|
||||||
|
{
|
||||||
|
var builder = new StringBuilder("GpuPixelOperationShader");
|
||||||
|
if (model.Namespace.Length > 0)
|
||||||
|
{
|
||||||
|
builder.Append('.');
|
||||||
|
builder.Append(HintPart(model.Namespace));
|
||||||
|
}
|
||||||
|
foreach (var type in model.TypeChain)
|
||||||
|
{
|
||||||
|
builder.Append('.');
|
||||||
|
builder.Append(HintPart(type.Name));
|
||||||
|
}
|
||||||
|
builder.Append(".g.cs");
|
||||||
|
return builder.ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string ErrorHintName(GpuShaderClass model)
|
||||||
|
{
|
||||||
|
return Path.ChangeExtension(HintName(model), ".Errors.g.cs");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string HintPart(string value)
|
||||||
|
{
|
||||||
|
var builder = new StringBuilder(value.Length);
|
||||||
|
foreach (char c in value)
|
||||||
|
builder.Append(char.IsLetterOrDigit(c) ? c : '_');
|
||||||
|
return builder.ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Literal(string value)
|
||||||
|
{
|
||||||
|
var builder = new StringBuilder(value.Length + 2);
|
||||||
|
builder.Append('"');
|
||||||
|
foreach (char c in value)
|
||||||
|
{
|
||||||
|
switch (c)
|
||||||
|
{
|
||||||
|
case '\\':
|
||||||
|
builder.Append(@"\\");
|
||||||
|
break;
|
||||||
|
case '"':
|
||||||
|
builder.Append("\\\"");
|
||||||
|
break;
|
||||||
|
case '\0':
|
||||||
|
builder.Append(@"\0");
|
||||||
|
break;
|
||||||
|
case '\a':
|
||||||
|
builder.Append(@"\a");
|
||||||
|
break;
|
||||||
|
case '\b':
|
||||||
|
builder.Append(@"\b");
|
||||||
|
break;
|
||||||
|
case '\f':
|
||||||
|
builder.Append(@"\f");
|
||||||
|
break;
|
||||||
|
case '\n':
|
||||||
|
builder.Append(@"\n");
|
||||||
|
break;
|
||||||
|
case '\r':
|
||||||
|
builder.Append(@"\r");
|
||||||
|
break;
|
||||||
|
case '\t':
|
||||||
|
builder.Append(@"\t");
|
||||||
|
break;
|
||||||
|
case '\v':
|
||||||
|
builder.Append(@"\v");
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
if (char.IsControl(c))
|
||||||
|
{
|
||||||
|
builder.Append(@"\u");
|
||||||
|
builder.Append(((int)c).ToString("x4", CultureInfo.InvariantCulture));
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
builder.Append(c);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
builder.Append('"');
|
||||||
|
return builder.ToString();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
namespace LuaScript.Generator
|
||||||
|
{
|
||||||
|
internal sealed record GpuShaderTypePart(string Name, bool IsStatic);
|
||||||
|
}
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using System.Runtime.InteropServices;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace LuaScript.Generator
|
||||||
|
{
|
||||||
|
internal static class ShaderCompiler
|
||||||
|
{
|
||||||
|
private const string Profile = "ps_5_0";
|
||||||
|
|
||||||
|
public static string? Compile(string source, string entryPoint, out string bytecode)
|
||||||
|
{
|
||||||
|
bytecode = string.Empty;
|
||||||
|
byte[] data = Encoding.UTF8.GetBytes(source);
|
||||||
|
IntPtr code = IntPtr.Zero;
|
||||||
|
IntPtr errors = IntPtr.Zero;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
int hr = D3DCompile(data, (IntPtr)data.Length, null, IntPtr.Zero, IntPtr.Zero, entryPoint, Profile, 0u, 0u, out code, out errors);
|
||||||
|
if (hr < 0 || code == IntPtr.Zero)
|
||||||
|
return ReadError(errors, hr);
|
||||||
|
bytecode = Convert.ToBase64String(ReadBlob(code));
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
catch (DllNotFoundException)
|
||||||
|
{
|
||||||
|
return "the Direct3D shader compiler is unavailable on this build host";
|
||||||
|
}
|
||||||
|
catch (EntryPointNotFoundException)
|
||||||
|
{
|
||||||
|
return "the Direct3D shader compiler is unavailable on this build host";
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Release(errors);
|
||||||
|
Release(code);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte[] ReadBlob(IntPtr blob)
|
||||||
|
{
|
||||||
|
IntPtr pointer = Invoke<GetBufferPointerDelegate>(blob, 3)(blob);
|
||||||
|
int size = checked((int)(long)Invoke<GetBufferSizeDelegate>(blob, 4)(blob));
|
||||||
|
var buffer = new byte[size];
|
||||||
|
Marshal.Copy(pointer, buffer, 0, size);
|
||||||
|
return buffer;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string ReadError(IntPtr blob, int hr)
|
||||||
|
{
|
||||||
|
string fallback = "HRESULT 0x" + hr.ToString("X8", CultureInfo.InvariantCulture);
|
||||||
|
if (blob == IntPtr.Zero)
|
||||||
|
return fallback;
|
||||||
|
IntPtr pointer = Invoke<GetBufferPointerDelegate>(blob, 3)(blob);
|
||||||
|
int size = checked((int)(long)Invoke<GetBufferSizeDelegate>(blob, 4)(blob));
|
||||||
|
string message = (Marshal.PtrToStringAnsi(pointer, size) ?? string.Empty).Trim();
|
||||||
|
return message.Length > 0 ? message : fallback;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void Release(IntPtr unknown)
|
||||||
|
{
|
||||||
|
if (unknown != IntPtr.Zero)
|
||||||
|
Invoke<ReleaseDelegate>(unknown, 2)(unknown);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static T Invoke<T>(IntPtr instance, int slot) where T : Delegate
|
||||||
|
{
|
||||||
|
IntPtr table = Marshal.ReadIntPtr(instance);
|
||||||
|
IntPtr function = Marshal.ReadIntPtr(table, slot * IntPtr.Size);
|
||||||
|
return (T)Marshal.GetDelegateForFunctionPointer(function, typeof(T));
|
||||||
|
}
|
||||||
|
|
||||||
|
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||||
|
private delegate IntPtr GetBufferPointerDelegate(IntPtr self);
|
||||||
|
|
||||||
|
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||||
|
private delegate IntPtr GetBufferSizeDelegate(IntPtr self);
|
||||||
|
|
||||||
|
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||||
|
private delegate uint ReleaseDelegate(IntPtr self);
|
||||||
|
|
||||||
|
[DllImport("d3dcompiler_47.dll", CallingConvention = CallingConvention.StdCall)]
|
||||||
|
private static extern int D3DCompile(
|
||||||
|
byte[] srcData,
|
||||||
|
IntPtr srcDataSize,
|
||||||
|
[MarshalAs(UnmanagedType.LPStr)] string? sourceName,
|
||||||
|
IntPtr defines,
|
||||||
|
IntPtr include,
|
||||||
|
[MarshalAs(UnmanagedType.LPStr)] string entryPoint,
|
||||||
|
[MarshalAs(UnmanagedType.LPStr)] string target,
|
||||||
|
uint flags1,
|
||||||
|
uint flags2,
|
||||||
|
out IntPtr code,
|
||||||
|
out IntPtr errorMsgs);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
namespace System.Runtime.CompilerServices
|
||||||
|
{
|
||||||
|
internal static class IsExternalInit;
|
||||||
|
}
|
||||||
@@ -0,0 +1,463 @@
|
|||||||
|
using System.Text;
|
||||||
|
using Microsoft.CodeAnalysis;
|
||||||
|
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||||
|
using Microsoft.CodeAnalysis.Text;
|
||||||
|
|
||||||
|
namespace LuaScript.Generator
|
||||||
|
{
|
||||||
|
[Generator]
|
||||||
|
public sealed class LuaApiGenerator : IIncrementalGenerator
|
||||||
|
{
|
||||||
|
private const string TableAttributeName = "LuaScript.Api.LuaTableAttribute";
|
||||||
|
private const string FunctionAttributeName = "LuaScript.Api.LuaFunctionAttribute";
|
||||||
|
private const string ConstantAttributeName = "LuaScript.Api.LuaConstantAttribute";
|
||||||
|
private const string VariableAttributeName = "LuaScript.Api.LuaVariableAttribute";
|
||||||
|
private const string BuiltinAttributeName = "LuaScript.Api.LuaBuiltinAttribute";
|
||||||
|
|
||||||
|
public void Initialize(IncrementalGeneratorInitializationContext context)
|
||||||
|
{
|
||||||
|
var tables = context.SyntaxProvider
|
||||||
|
.ForAttributeWithMetadataName(
|
||||||
|
TableAttributeName,
|
||||||
|
static (node, _) => node is ClassDeclarationSyntax,
|
||||||
|
static (ctx, _) => CreateModel(ctx))
|
||||||
|
.Where(static model => model is not null)
|
||||||
|
.Select(static (model, _) => model!);
|
||||||
|
|
||||||
|
var assemblyEntries = context.CompilationProvider
|
||||||
|
.Select(static (compilation, _) => CollectAssemblyEntries(compilation));
|
||||||
|
|
||||||
|
context.RegisterSourceOutput(tables, static (ctx, model) =>
|
||||||
|
{
|
||||||
|
if (model.Functions.Count == 0 && model.Constants.Count == 0 && model.Updates.Count == 0)
|
||||||
|
return;
|
||||||
|
ctx.AddSource(RegistrationHintName(model), SourceText.From(EmitRegistration(model), Encoding.UTF8));
|
||||||
|
});
|
||||||
|
|
||||||
|
var catalog = tables.Collect().Combine(assemblyEntries);
|
||||||
|
context.RegisterSourceOutput(catalog, static (ctx, source) =>
|
||||||
|
{
|
||||||
|
var (models, extra) = source;
|
||||||
|
var entries = models
|
||||||
|
.OrderBy(static m => m.Namespace, StringComparer.Ordinal)
|
||||||
|
.ThenBy(static m => string.Join("+", m.TypeChain.Select(static p => p.Name)), StringComparer.Ordinal)
|
||||||
|
.SelectMany(static m => m.Entries)
|
||||||
|
.Concat(extra)
|
||||||
|
.ToArray();
|
||||||
|
if (entries.Length == 0)
|
||||||
|
return;
|
||||||
|
ctx.AddSource("LuaApiCatalog.g.cs", SourceText.From(EmitCatalog(entries), Encoding.UTF8));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private static LuaTableModel? CreateModel(GeneratorAttributeSyntaxContext context)
|
||||||
|
{
|
||||||
|
if (context.TargetSymbol is not INamedTypeSymbol symbol)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
var tableArguments = context.Attributes[0].ConstructorArguments;
|
||||||
|
string tableName = tableArguments.Length > 0 && tableArguments[0].Value is string name ? name : string.Empty;
|
||||||
|
|
||||||
|
var chain = new List<LuaTypePart>();
|
||||||
|
for (var type = symbol; type is not null; type = type.ContainingType)
|
||||||
|
chain.Insert(0, new LuaTypePart(type.Name, type.IsStatic));
|
||||||
|
|
||||||
|
var entries = new List<(int Position, LuaCatalogEntry Entry)>();
|
||||||
|
foreach (var attribute in symbol.GetAttributes())
|
||||||
|
{
|
||||||
|
string? attributeName = attribute.AttributeClass?.ToDisplayString();
|
||||||
|
if (attributeName is not (VariableAttributeName or BuiltinAttributeName or FunctionAttributeName))
|
||||||
|
continue;
|
||||||
|
var entry = CreateAttributeEntry(attribute, tableName);
|
||||||
|
if (entry is null)
|
||||||
|
continue;
|
||||||
|
int position = attribute.ApplicationSyntaxReference?.Span.Start ?? 0;
|
||||||
|
entries.Add((position, entry));
|
||||||
|
}
|
||||||
|
var classEntries = entries.OrderBy(static e => e.Position).Select(static e => e.Entry).ToList();
|
||||||
|
|
||||||
|
var functions = new List<(int Position, LuaFunctionModel Function, LuaCatalogEntry Entry)>();
|
||||||
|
var constants = new List<(int Position, LuaConstantModel Constant, LuaCatalogEntry Entry)>();
|
||||||
|
var updates = new List<(int Position, LuaUpdateModel Update, LuaCatalogEntry? Entry)>();
|
||||||
|
string contextType = string.Empty;
|
||||||
|
foreach (var member in symbol.GetMembers())
|
||||||
|
{
|
||||||
|
int position = member.DeclaringSyntaxReferences.Length > 0
|
||||||
|
? member.DeclaringSyntaxReferences[0].Span.Start
|
||||||
|
: 0;
|
||||||
|
|
||||||
|
if (member is IMethodSymbol method)
|
||||||
|
{
|
||||||
|
var functionAttribute = FindAttribute(method, FunctionAttributeName);
|
||||||
|
if (functionAttribute is not null)
|
||||||
|
{
|
||||||
|
var function = CreateFunctionModel(method, functionAttribute, out var catalogParameters);
|
||||||
|
if (function is null)
|
||||||
|
continue;
|
||||||
|
functions.Add((position, function, new LuaCatalogEntry(tableName, function.LuaName, true, catalogParameters)));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
var variableAttribute = FindAttribute(method, VariableAttributeName);
|
||||||
|
if (variableAttribute is not null)
|
||||||
|
{
|
||||||
|
var update = CreateUpdateModel(method, variableAttribute, tableName, ref contextType, out var entry);
|
||||||
|
if (update is not null)
|
||||||
|
updates.Add((position, update, entry));
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (member is IFieldSymbol or IPropertySymbol)
|
||||||
|
{
|
||||||
|
var attribute = FindAttribute(member, ConstantAttributeName);
|
||||||
|
if (attribute is null)
|
||||||
|
continue;
|
||||||
|
if (attribute.ConstructorArguments.Length == 0 || attribute.ConstructorArguments[0].Value is not string constantName)
|
||||||
|
continue;
|
||||||
|
constants.Add((
|
||||||
|
position,
|
||||||
|
new LuaConstantModel(constantName, member.Name),
|
||||||
|
new LuaCatalogEntry(tableName, constantName, false, EquatableArray<string>.Empty)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var orderedMembers = functions
|
||||||
|
.Select(static f => (Position: f.Position, Entry: f.Entry))
|
||||||
|
.Concat(constants.Select(static c => (Position: c.Position, Entry: c.Entry)))
|
||||||
|
.Concat(updates.Where(static u => u.Entry is not null).Select(static u => (Position: u.Position, Entry: u.Entry!)))
|
||||||
|
.OrderBy(static e => e.Position)
|
||||||
|
.Select(static e => e.Entry);
|
||||||
|
|
||||||
|
return new LuaTableModel(
|
||||||
|
symbol.ContainingNamespace.ToDisplayString(),
|
||||||
|
new EquatableArray<LuaTypePart>([.. chain]),
|
||||||
|
tableName,
|
||||||
|
contextType,
|
||||||
|
new EquatableArray<LuaFunctionModel>([.. functions.OrderBy(static f => f.Position).Select(static f => f.Function)]),
|
||||||
|
new EquatableArray<LuaConstantModel>([.. constants.OrderBy(static c => c.Position).Select(static c => c.Constant)]),
|
||||||
|
new EquatableArray<LuaUpdateModel>([.. updates.OrderBy(static u => u.Position).Select(static u => u.Update)]),
|
||||||
|
new EquatableArray<LuaCatalogEntry>([.. classEntries, .. orderedMembers]));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static AttributeData? FindAttribute(ISymbol symbol, string attributeName)
|
||||||
|
{
|
||||||
|
foreach (var attribute in symbol.GetAttributes())
|
||||||
|
{
|
||||||
|
if (attribute.AttributeClass?.ToDisplayString() == attributeName)
|
||||||
|
return attribute;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static LuaCatalogEntry? CreateAttributeEntry(AttributeData attribute, string defaultTable)
|
||||||
|
{
|
||||||
|
if (attribute.ConstructorArguments.Length == 0 || attribute.ConstructorArguments[0].Value is not string name)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
string table = defaultTable;
|
||||||
|
foreach (var argument in attribute.NamedArguments)
|
||||||
|
{
|
||||||
|
if (argument.Key == "Table" && argument.Value.Value is string overridden)
|
||||||
|
table = overridden;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool isFunction = attribute.AttributeClass?.ToDisplayString() is (BuiltinAttributeName or FunctionAttributeName);
|
||||||
|
var parameters = isFunction && attribute.ConstructorArguments.Length > 1
|
||||||
|
? ExtractStringArray(attribute.ConstructorArguments[1])
|
||||||
|
: EquatableArray<string>.Empty;
|
||||||
|
|
||||||
|
return new LuaCatalogEntry(table, name, isFunction, parameters);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static EquatableArray<string> ExtractStringArray(TypedConstant constant)
|
||||||
|
{
|
||||||
|
if (constant.Kind != TypedConstantKind.Array)
|
||||||
|
return EquatableArray<string>.Empty;
|
||||||
|
return new EquatableArray<string>([.. constant.Values.Select(static v => v.Value as string ?? string.Empty)]);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static LuaFunctionModel? CreateFunctionModel(IMethodSymbol method, AttributeData attribute, out EquatableArray<string> catalogParameters)
|
||||||
|
{
|
||||||
|
catalogParameters = EquatableArray<string>.Empty;
|
||||||
|
if (attribute.ConstructorArguments.Length == 0 || attribute.ConstructorArguments[0].Value is not string luaName)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
LuaReturnKind returnKind;
|
||||||
|
if (method.ReturnsVoid)
|
||||||
|
returnKind = LuaReturnKind.Void;
|
||||||
|
else if (method.ReturnType.ToDisplayString() == "MoonSharp.Interpreter.DynValue")
|
||||||
|
returnKind = LuaReturnKind.DynValue;
|
||||||
|
else if (method.ReturnType.SpecialType == SpecialType.System_Double)
|
||||||
|
returnKind = LuaReturnKind.Double;
|
||||||
|
else
|
||||||
|
return null;
|
||||||
|
|
||||||
|
var parameters = new List<LuaParameterModel>();
|
||||||
|
foreach (var parameter in method.Parameters)
|
||||||
|
{
|
||||||
|
LuaParameterKind kind;
|
||||||
|
string defaultLiteral = string.Empty;
|
||||||
|
switch (parameter.Type.ToDisplayString())
|
||||||
|
{
|
||||||
|
case "MoonSharp.Interpreter.ScriptExecutionContext":
|
||||||
|
kind = LuaParameterKind.ExecutionContext;
|
||||||
|
break;
|
||||||
|
case "MoonSharp.Interpreter.CallbackArguments":
|
||||||
|
kind = LuaParameterKind.Arguments;
|
||||||
|
break;
|
||||||
|
case "MoonSharp.Interpreter.DynValue":
|
||||||
|
kind = LuaParameterKind.DynValue;
|
||||||
|
break;
|
||||||
|
case "double":
|
||||||
|
kind = LuaParameterKind.Double;
|
||||||
|
defaultLiteral = FormatDouble(parameter.HasExplicitDefaultValue ? (double)parameter.ExplicitDefaultValue! : 0d);
|
||||||
|
break;
|
||||||
|
case "int":
|
||||||
|
kind = LuaParameterKind.Int;
|
||||||
|
defaultLiteral = FormatDouble(parameter.HasExplicitDefaultValue ? (int)parameter.ExplicitDefaultValue! : 0);
|
||||||
|
break;
|
||||||
|
case "bool":
|
||||||
|
kind = LuaParameterKind.Bool;
|
||||||
|
defaultLiteral = parameter.HasExplicitDefaultValue && (bool)parameter.ExplicitDefaultValue! ? "true" : "false";
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
parameters.Add(new LuaParameterModel(parameter.Name, kind, defaultLiteral));
|
||||||
|
}
|
||||||
|
|
||||||
|
var explicitParameters = attribute.ConstructorArguments.Length > 1
|
||||||
|
? ExtractStringArray(attribute.ConstructorArguments[1])
|
||||||
|
: EquatableArray<string>.Empty;
|
||||||
|
catalogParameters = explicitParameters.Count > 0
|
||||||
|
? explicitParameters
|
||||||
|
: new EquatableArray<string>([.. parameters
|
||||||
|
.Where(static p => p.Kind is not (LuaParameterKind.ExecutionContext or LuaParameterKind.Arguments))
|
||||||
|
.Select(static p => p.Name)]);
|
||||||
|
|
||||||
|
return new LuaFunctionModel(luaName, method.Name, returnKind, new EquatableArray<LuaParameterModel>([.. parameters]));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static LuaUpdateModel? CreateUpdateModel(IMethodSymbol method, AttributeData attribute, string tableName, ref string contextType, out LuaCatalogEntry? entry)
|
||||||
|
{
|
||||||
|
entry = null;
|
||||||
|
if (attribute.ConstructorArguments.Length == 0 || attribute.ConstructorArguments[0].Value is not string luaName)
|
||||||
|
return null;
|
||||||
|
if (method.Parameters.Length != 1)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
string parameterType = method.Parameters[0].Type.ToDisplayString();
|
||||||
|
if (contextType.Length == 0)
|
||||||
|
contextType = parameterType;
|
||||||
|
else if (contextType != parameterType)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
var returnType = method.ReturnType;
|
||||||
|
LuaUpdateKind kind;
|
||||||
|
ITypeSymbol valueType;
|
||||||
|
if (returnType.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T)
|
||||||
|
{
|
||||||
|
kind = LuaUpdateKind.OptionalValue;
|
||||||
|
valueType = ((INamedTypeSymbol)returnType).TypeArguments[0];
|
||||||
|
}
|
||||||
|
else if (returnType.IsReferenceType)
|
||||||
|
{
|
||||||
|
kind = LuaUpdateKind.OptionalReference;
|
||||||
|
valueType = returnType;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
kind = LuaUpdateKind.Direct;
|
||||||
|
valueType = returnType;
|
||||||
|
}
|
||||||
|
|
||||||
|
var valueKind = valueType.SpecialType switch
|
||||||
|
{
|
||||||
|
SpecialType.System_Double or SpecialType.System_Int32 => LuaValueKind.Number,
|
||||||
|
SpecialType.System_Boolean => LuaValueKind.Boolean,
|
||||||
|
SpecialType.System_String => LuaValueKind.String,
|
||||||
|
_ => LuaValueKind.Other,
|
||||||
|
};
|
||||||
|
|
||||||
|
bool inCatalog = true;
|
||||||
|
foreach (var argument in attribute.NamedArguments)
|
||||||
|
{
|
||||||
|
if (argument.Key == "InCatalog" && argument.Value.Value is bool value)
|
||||||
|
inCatalog = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (inCatalog)
|
||||||
|
entry = new LuaCatalogEntry(tableName, luaName, false, EquatableArray<string>.Empty);
|
||||||
|
return new LuaUpdateModel(luaName, method.Name, kind, valueKind);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string FormatDouble(double value) =>
|
||||||
|
value.ToString("R", System.Globalization.CultureInfo.InvariantCulture) + "d";
|
||||||
|
|
||||||
|
private static string RegistrationHintName(LuaTableModel model)
|
||||||
|
{
|
||||||
|
var chain = string.Join(".", model.TypeChain.Select(static p => p.Name));
|
||||||
|
return $"{model.Namespace}.{chain}.LuaRegistration.g.cs";
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string EmitRegistration(LuaTableModel model)
|
||||||
|
{
|
||||||
|
var builder = new StringBuilder();
|
||||||
|
builder.AppendLine("#nullable enable");
|
||||||
|
builder.AppendLine($"namespace {model.Namespace}");
|
||||||
|
builder.AppendLine("{");
|
||||||
|
|
||||||
|
string indent = " ";
|
||||||
|
foreach (var part in model.TypeChain)
|
||||||
|
{
|
||||||
|
builder.AppendLine($"{indent}{(part.IsStatic ? "static partial class " : "partial class ")}{part.Name}");
|
||||||
|
builder.AppendLine($"{indent}{{");
|
||||||
|
indent += " ";
|
||||||
|
}
|
||||||
|
|
||||||
|
bool isStatic = model.TypeChain[model.TypeChain.Count - 1].IsStatic;
|
||||||
|
string body = indent + " ";
|
||||||
|
|
||||||
|
if (model.Constants.Count > 0 || model.Functions.Count > 0)
|
||||||
|
{
|
||||||
|
builder.AppendLine($"{indent}internal {(isStatic ? "static " : "")}void RegisterLuaMembers(global::MoonSharp.Interpreter.Table table)");
|
||||||
|
builder.AppendLine($"{indent}{{");
|
||||||
|
|
||||||
|
foreach (var constant in model.Constants)
|
||||||
|
builder.AppendLine($"{body}table[\"{constant.LuaName}\"] = {constant.MemberName};");
|
||||||
|
|
||||||
|
foreach (var function in model.Functions)
|
||||||
|
{
|
||||||
|
string call = $"{function.MethodName}({EmitArguments(function.Parameters)})";
|
||||||
|
string lambda = function.ReturnKind switch
|
||||||
|
{
|
||||||
|
LuaReturnKind.DynValue => $"(execCtx, args) => {call}",
|
||||||
|
LuaReturnKind.Double => $"(execCtx, args) => global::MoonSharp.Interpreter.DynValue.NewNumber({call})",
|
||||||
|
_ => $"(execCtx, args) => {{ {call}; return global::MoonSharp.Interpreter.DynValue.Void; }}",
|
||||||
|
};
|
||||||
|
builder.AppendLine($"{body}table[\"{function.LuaName}\"] = global::MoonSharp.Interpreter.DynValue.NewCallback({lambda});");
|
||||||
|
}
|
||||||
|
|
||||||
|
builder.AppendLine($"{indent}}}");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (model.Updates.Count > 0)
|
||||||
|
{
|
||||||
|
builder.AppendLine($"{indent}internal {(isStatic ? "static " : "")}void UpdateLuaMembers(global::MoonSharp.Interpreter.Table table, global::{model.ContextType} context)");
|
||||||
|
builder.AppendLine($"{indent}{{");
|
||||||
|
foreach (var update in model.Updates)
|
||||||
|
{
|
||||||
|
switch (update.Kind)
|
||||||
|
{
|
||||||
|
case LuaUpdateKind.OptionalValue:
|
||||||
|
builder.AppendLine(update.ValueKind == LuaValueKind.Other
|
||||||
|
? $"{body}{{ var value = {update.MethodName}(context); if (value.HasValue) table[\"{update.LuaName}\"] = value.Value; }}"
|
||||||
|
: $"{body}{{ var value = {update.MethodName}(context); if (value.HasValue) table.Set(\"{update.LuaName}\", {WrapValue(update.ValueKind, "value.Value")}); }}");
|
||||||
|
break;
|
||||||
|
case LuaUpdateKind.OptionalReference:
|
||||||
|
builder.AppendLine(update.ValueKind == LuaValueKind.Other
|
||||||
|
? $"{body}{{ var value = {update.MethodName}(context); if (value is not null) table[\"{update.LuaName}\"] = value; }}"
|
||||||
|
: $"{body}{{ var value = {update.MethodName}(context); if (value is not null) table.Set(\"{update.LuaName}\", {WrapValue(update.ValueKind, "value")}); }}");
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
builder.AppendLine(update.ValueKind == LuaValueKind.Other
|
||||||
|
? $"{body}table[\"{update.LuaName}\"] = {update.MethodName}(context);"
|
||||||
|
: $"{body}table.Set(\"{update.LuaName}\", {WrapValue(update.ValueKind, $"{update.MethodName}(context)")});");
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
builder.AppendLine($"{indent}}}");
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int i = model.TypeChain.Count - 1; i >= 0; i--)
|
||||||
|
{
|
||||||
|
indent = new string(' ', 4 * (i + 1));
|
||||||
|
builder.AppendLine($"{indent}}}");
|
||||||
|
}
|
||||||
|
builder.AppendLine("}");
|
||||||
|
return builder.ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string WrapValue(LuaValueKind kind, string expression) => kind switch
|
||||||
|
{
|
||||||
|
LuaValueKind.Number => $"global::MoonSharp.Interpreter.DynValue.NewNumber({expression})",
|
||||||
|
LuaValueKind.Boolean => $"global::MoonSharp.Interpreter.DynValue.NewBoolean({expression})",
|
||||||
|
_ => $"global::MoonSharp.Interpreter.DynValue.NewString({expression})",
|
||||||
|
};
|
||||||
|
|
||||||
|
private static string EmitArguments(EquatableArray<LuaParameterModel> parameters)
|
||||||
|
{
|
||||||
|
var rendered = new List<string>();
|
||||||
|
int position = 0;
|
||||||
|
foreach (var parameter in parameters)
|
||||||
|
{
|
||||||
|
if (parameter.Kind == LuaParameterKind.ExecutionContext)
|
||||||
|
{
|
||||||
|
rendered.Add("execCtx");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (parameter.Kind == LuaParameterKind.Arguments)
|
||||||
|
{
|
||||||
|
rendered.Add("args");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
rendered.Add(parameter.Kind switch
|
||||||
|
{
|
||||||
|
LuaParameterKind.DynValue => $"args.Count > {position} ? args[{position}] : global::MoonSharp.Interpreter.DynValue.Nil",
|
||||||
|
LuaParameterKind.Double => $"args.Count > {position} ? args[{position}].CastToNumber() ?? {parameter.DefaultLiteral} : {parameter.DefaultLiteral}",
|
||||||
|
LuaParameterKind.Int => $"(int)(args.Count > {position} ? args[{position}].CastToNumber() ?? {parameter.DefaultLiteral} : {parameter.DefaultLiteral})",
|
||||||
|
_ => $"args.Count > {position} ? args[{position}].CastToBool() : {parameter.DefaultLiteral}",
|
||||||
|
});
|
||||||
|
position++;
|
||||||
|
}
|
||||||
|
return string.Join(", ", rendered);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string EmitCatalog(LuaCatalogEntry[] entries)
|
||||||
|
{
|
||||||
|
var builder = new StringBuilder();
|
||||||
|
builder.AppendLine("#nullable enable");
|
||||||
|
builder.AppendLine("namespace LuaScript.Generated");
|
||||||
|
builder.AppendLine("{");
|
||||||
|
builder.AppendLine(" internal static class LuaApiModuleInitializer");
|
||||||
|
builder.AppendLine(" {");
|
||||||
|
builder.AppendLine(" [global::System.Runtime.CompilerServices.ModuleInitializer]");
|
||||||
|
builder.AppendLine(" internal static void Initialize()");
|
||||||
|
builder.AppendLine(" {");
|
||||||
|
builder.AppendLine(" global::LuaScript.Api.LuaApiCatalog.Register(new global::LuaScript.Api.LuaApiMember[]");
|
||||||
|
builder.AppendLine(" {");
|
||||||
|
foreach (var entry in entries)
|
||||||
|
{
|
||||||
|
string kind = entry.IsFunction
|
||||||
|
? "global::LuaScript.Api.LuaApiMemberKind.Function"
|
||||||
|
: "global::LuaScript.Api.LuaApiMemberKind.Variable";
|
||||||
|
string parameters = entry.Parameters.Count == 0
|
||||||
|
? "global::System.Array.Empty<string>()"
|
||||||
|
: $"new string[] {{ {string.Join(", ", entry.Parameters.Select(static p => $"\"{p}\""))} }}";
|
||||||
|
builder.AppendLine($" new(\"{entry.Table}\", \"{entry.Name}\", {kind}, {parameters}),");
|
||||||
|
}
|
||||||
|
builder.AppendLine(" });");
|
||||||
|
builder.AppendLine(" }");
|
||||||
|
builder.AppendLine(" }");
|
||||||
|
builder.AppendLine("}");
|
||||||
|
return builder.ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static IReadOnlyList<LuaCatalogEntry> CollectAssemblyEntries(Compilation compilation)
|
||||||
|
{
|
||||||
|
var entries = new List<(int Position, LuaCatalogEntry Entry)>();
|
||||||
|
foreach (var attribute in compilation.Assembly.GetAttributes())
|
||||||
|
{
|
||||||
|
string? attributeName = attribute.AttributeClass?.ToDisplayString();
|
||||||
|
if (attributeName is not (VariableAttributeName or BuiltinAttributeName or FunctionAttributeName))
|
||||||
|
continue;
|
||||||
|
var entry = CreateAttributeEntry(attribute, string.Empty);
|
||||||
|
if (entry is null)
|
||||||
|
continue;
|
||||||
|
entries.Add((attribute.ApplicationSyntaxReference?.Span.Start ?? 0, entry));
|
||||||
|
}
|
||||||
|
return [.. entries.OrderBy(static e => e.Position).Select(static e => e.Entry)];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
namespace LuaScript.Generator
|
||||||
|
{
|
||||||
|
internal sealed record LuaCatalogEntry(
|
||||||
|
string Table,
|
||||||
|
string Name,
|
||||||
|
bool IsFunction,
|
||||||
|
EquatableArray<string> Parameters);
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
namespace LuaScript.Generator
|
||||||
|
{
|
||||||
|
internal sealed record LuaConstantModel(string LuaName, string MemberName);
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
namespace LuaScript.Generator
|
||||||
|
{
|
||||||
|
internal sealed record LuaFunctionModel(
|
||||||
|
string LuaName,
|
||||||
|
string MethodName,
|
||||||
|
LuaReturnKind ReturnKind,
|
||||||
|
EquatableArray<LuaParameterModel> Parameters);
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
namespace LuaScript.Generator
|
||||||
|
{
|
||||||
|
internal enum LuaParameterKind
|
||||||
|
{
|
||||||
|
ExecutionContext,
|
||||||
|
Arguments,
|
||||||
|
DynValue,
|
||||||
|
Double,
|
||||||
|
Int,
|
||||||
|
Bool,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
namespace LuaScript.Generator
|
||||||
|
{
|
||||||
|
internal sealed record LuaParameterModel(string Name, LuaParameterKind Kind, string DefaultLiteral);
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
namespace LuaScript.Generator
|
||||||
|
{
|
||||||
|
internal enum LuaReturnKind
|
||||||
|
{
|
||||||
|
DynValue,
|
||||||
|
Double,
|
||||||
|
Void,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Immutable;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Text;
|
||||||
|
using Microsoft.CodeAnalysis;
|
||||||
|
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||||
|
using Microsoft.CodeAnalysis.Text;
|
||||||
|
|
||||||
|
namespace LuaScript.Generator
|
||||||
|
{
|
||||||
|
[Generator]
|
||||||
|
public sealed class LuaSyntaxRuleGenerator : IIncrementalGenerator
|
||||||
|
{
|
||||||
|
private const string RuleAttributeName = "LuaScript.Compat.Syntax.LuaSyntaxRuleAttribute";
|
||||||
|
private const string RuleInterfaceName = "LuaScript.Compat.Syntax.ILuaSyntaxRule";
|
||||||
|
|
||||||
|
public void Initialize(IncrementalGeneratorInitializationContext context)
|
||||||
|
{
|
||||||
|
var rules = context.SyntaxProvider
|
||||||
|
.ForAttributeWithMetadataName(
|
||||||
|
RuleAttributeName,
|
||||||
|
static (node, _) => node is ClassDeclarationSyntax,
|
||||||
|
static (ctx, _) => CreateModel(ctx))
|
||||||
|
.Where(static model => model is not null)
|
||||||
|
.Select(static (model, _) => model!);
|
||||||
|
|
||||||
|
context.RegisterSourceOutput(rules.Collect(), static (ctx, models) =>
|
||||||
|
{
|
||||||
|
if (models.Length == 0)
|
||||||
|
return;
|
||||||
|
ctx.AddSource("LuaSyntaxRuleRegistry.g.cs", SourceText.From(Emit(models), Encoding.UTF8));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private static LuaSyntaxRuleModel? CreateModel(GeneratorAttributeSyntaxContext context)
|
||||||
|
{
|
||||||
|
if (context.TargetSymbol is not INamedTypeSymbol symbol)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
if (!symbol.AllInterfaces.Any(static contract => contract.ToDisplayString() == RuleInterfaceName))
|
||||||
|
return null;
|
||||||
|
|
||||||
|
int order = 0;
|
||||||
|
var arguments = context.Attributes[0].ConstructorArguments;
|
||||||
|
if (arguments.Length > 0 && arguments[0].Value is int value)
|
||||||
|
order = value;
|
||||||
|
|
||||||
|
bool isCatalog = false;
|
||||||
|
string keyword = string.Empty;
|
||||||
|
foreach (var argument in context.Attributes[0].NamedArguments)
|
||||||
|
{
|
||||||
|
if (argument.Key == "IsCatalog" && argument.Value.Value is bool catalogValue)
|
||||||
|
isCatalog = catalogValue;
|
||||||
|
else if (argument.Key == "Keyword" && argument.Value.Value is string keywordValue)
|
||||||
|
keyword = keywordValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
return new LuaSyntaxRuleModel(symbol.ToDisplayString(), order, isCatalog ? keyword : string.Empty);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Emit(ImmutableArray<LuaSyntaxRuleModel> models)
|
||||||
|
{
|
||||||
|
var ordered = models
|
||||||
|
.OrderBy(static m => m.Order)
|
||||||
|
.ThenBy(static m => m.TypeName, StringComparer.Ordinal)
|
||||||
|
.ToArray();
|
||||||
|
|
||||||
|
var builder = new StringBuilder();
|
||||||
|
builder.AppendLine("#nullable enable");
|
||||||
|
builder.AppendLine("namespace LuaScript.Compat.Syntax");
|
||||||
|
builder.AppendLine("{");
|
||||||
|
builder.AppendLine(" internal static class LuaSyntaxRuleRegistry");
|
||||||
|
builder.AppendLine(" {");
|
||||||
|
builder.AppendLine(" internal static readonly global::LuaScript.Compat.Syntax.ILuaSyntaxRule[] Rules = new global::LuaScript.Compat.Syntax.ILuaSyntaxRule[]");
|
||||||
|
builder.AppendLine(" {");
|
||||||
|
foreach (var model in ordered)
|
||||||
|
builder.AppendLine($" new global::{model.TypeName}(),");
|
||||||
|
builder.AppendLine(" };");
|
||||||
|
|
||||||
|
var keywords = ordered
|
||||||
|
.Where(static m => m.CatalogKeyword.Length > 0)
|
||||||
|
.Select(static m => m.CatalogKeyword)
|
||||||
|
.Distinct()
|
||||||
|
.ToArray();
|
||||||
|
if (keywords.Length == 0)
|
||||||
|
{
|
||||||
|
builder.AppendLine(" internal static readonly string[] CatalogKeywords = global::System.Array.Empty<string>();");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
builder.AppendLine(" internal static readonly string[] CatalogKeywords = new string[]");
|
||||||
|
builder.AppendLine(" {");
|
||||||
|
foreach (var keyword in keywords)
|
||||||
|
builder.AppendLine($" \"{keyword}\",");
|
||||||
|
builder.AppendLine(" };");
|
||||||
|
}
|
||||||
|
builder.AppendLine(" }");
|
||||||
|
builder.AppendLine("}");
|
||||||
|
return builder.ToString();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
namespace LuaScript.Generator
|
||||||
|
{
|
||||||
|
internal sealed record LuaSyntaxRuleModel(string TypeName, int Order, string CatalogKeyword);
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
namespace LuaScript.Generator
|
||||||
|
{
|
||||||
|
internal sealed record LuaTableModel(
|
||||||
|
string Namespace,
|
||||||
|
EquatableArray<LuaTypePart> TypeChain,
|
||||||
|
string TableName,
|
||||||
|
string ContextType,
|
||||||
|
EquatableArray<LuaFunctionModel> Functions,
|
||||||
|
EquatableArray<LuaConstantModel> Constants,
|
||||||
|
EquatableArray<LuaUpdateModel> Updates,
|
||||||
|
EquatableArray<LuaCatalogEntry> Entries);
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
namespace LuaScript.Generator
|
||||||
|
{
|
||||||
|
internal sealed record LuaTypePart(string Name, bool IsStatic);
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
namespace LuaScript.Generator
|
||||||
|
{
|
||||||
|
internal enum LuaUpdateKind
|
||||||
|
{
|
||||||
|
Direct,
|
||||||
|
OptionalValue,
|
||||||
|
OptionalReference,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
namespace LuaScript.Generator
|
||||||
|
{
|
||||||
|
internal sealed record LuaUpdateModel(string LuaName, string MethodName, LuaUpdateKind Kind, LuaValueKind ValueKind);
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
namespace LuaScript.Generator
|
||||||
|
{
|
||||||
|
internal enum LuaValueKind
|
||||||
|
{
|
||||||
|
Number,
|
||||||
|
Boolean,
|
||||||
|
String,
|
||||||
|
Other,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>netstandard2.0</TargetFramework>
|
||||||
|
<LangVersion>latest</LangVersion>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<Version>1.20.3</Version>
|
||||||
|
<IsRoslynComponent>true</IsRoslynComponent>
|
||||||
|
<EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="5.3.0">
|
||||||
|
<PrivateAssets>all</PrivateAssets>
|
||||||
|
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||||
|
</PackageReference>
|
||||||
|
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="5.3.0" PrivateAssets="all" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,134 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using LuaScript.Engine.Shader;
|
||||||
|
|
||||||
|
namespace LuaScript.Engine.Processing
|
||||||
|
{
|
||||||
|
[GpuPixelOperationShader(nameof(RunConvolve), "Shaders/convolve.hlsl", "convolve")]
|
||||||
|
internal sealed partial class GpuConvolveOperation(PixelShaderRunner runner) : GpuPixelOperation(runner)
|
||||||
|
{
|
||||||
|
private const int ConvolveWorkThreshold = 262144;
|
||||||
|
private const int MaxConvolveSize = 31;
|
||||||
|
private const int MaxConvolveValidationCount = 64;
|
||||||
|
|
||||||
|
private readonly PixelShaderInput[] _resources = new PixelShaderInput[1];
|
||||||
|
private readonly float[] _constants = new float[1024];
|
||||||
|
private readonly List<ConvolveValidation> _validations = [];
|
||||||
|
|
||||||
|
public bool TryConvolve(byte[] target, int width, int height, double[] kernel, int size, double divisor, double offset, bool force = false)
|
||||||
|
{
|
||||||
|
if (!IsTextureSupported(target, width, height) || !IsSupported(kernel, size, divisor, offset))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
long work = (long)width * height * size * size;
|
||||||
|
if (!force && work < ConvolveWorkThreshold || !EnsureValidated(target, width, height, kernel, size, divisor, offset))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
SetConstants(width, height, kernel, size, divisor, offset);
|
||||||
|
_resources[0] = new PixelShaderInput(target, width, height);
|
||||||
|
return RunConvolve(_resources.AsSpan(0, 1), _constants.AsSpan(0, size * size + 8), target, width, height);
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool EnsureValidated(byte[] target, int width, int height, double[] kernel, int size, double divisor, double offset)
|
||||||
|
{
|
||||||
|
for (int i = 0; i < _validations.Count; i++)
|
||||||
|
{
|
||||||
|
if (_validations[i].Matches(kernel, size, divisor, offset))
|
||||||
|
return _validations[i].Valid;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_validations.Count >= MaxConvolveValidationCount)
|
||||||
|
_validations.Clear();
|
||||||
|
|
||||||
|
bool valid = Validate(target, width, height, kernel, size, divisor, offset);
|
||||||
|
_validations.Add(new ConvolveValidation(kernel, size, divisor, offset, valid));
|
||||||
|
return valid;
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool Validate(byte[] target, int width, int height, double[] kernel, int size, double divisor, double offset)
|
||||||
|
{
|
||||||
|
int probeWidth = Math.Min(width, 8);
|
||||||
|
int probeHeight = Math.Min(height, 7);
|
||||||
|
var probe = CopyProbe(target, width, height, probeWidth, probeHeight);
|
||||||
|
var cpu = (byte[])probe.Clone();
|
||||||
|
var gpu = (byte[])probe.Clone();
|
||||||
|
double[]? scratch = null;
|
||||||
|
PixelBufferSoftwareProcessor.Convolve(cpu, probeWidth, probeHeight, kernel, size, divisor, offset, ref scratch);
|
||||||
|
SetConstants(probeWidth, probeHeight, kernel, size, divisor, offset);
|
||||||
|
_resources[0] = new PixelShaderInput(gpu, probeWidth, probeHeight);
|
||||||
|
return RunConvolve(_resources.AsSpan(0, 1), _constants.AsSpan(0, size * size + 8), gpu, probeWidth, probeHeight) && Equal(cpu, gpu);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void SetConstants(int width, int height, double[] kernel, int size, double divisor, double offset)
|
||||||
|
{
|
||||||
|
_constants[0] = width;
|
||||||
|
_constants[1] = height;
|
||||||
|
_constants[2] = (float)divisor;
|
||||||
|
_constants[3] = (float)offset;
|
||||||
|
_constants[4] = size;
|
||||||
|
_constants[5] = size / 2;
|
||||||
|
_constants[6] = 0f;
|
||||||
|
_constants[7] = 0f;
|
||||||
|
int taps = size * size;
|
||||||
|
for (int i = 0; i < taps; i++)
|
||||||
|
_constants[i + 8] = (float)kernel[i];
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool IsSupported(double[] kernel, int size, double divisor, double offset)
|
||||||
|
{
|
||||||
|
if (size < 1 || (size & 1) == 0 || size > MaxConvolveSize || divisor == 0d || !IsFloatCompatible(divisor) || !IsFloatCompatible(offset))
|
||||||
|
return false;
|
||||||
|
int taps = size * size;
|
||||||
|
if (kernel.Length < taps || taps + 8 > 1024)
|
||||||
|
return false;
|
||||||
|
for (int i = 0; i < taps; i++)
|
||||||
|
{
|
||||||
|
if (!IsFloatCompatible(kernel[i]))
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool IsFloatCompatible(double value)
|
||||||
|
{
|
||||||
|
return double.IsFinite(value) && float.IsFinite((float)value);
|
||||||
|
}
|
||||||
|
|
||||||
|
private partial bool RunConvolve(ReadOnlySpan<PixelShaderInput> resources, ReadOnlySpan<float> constants, byte[] target, int width, int height);
|
||||||
|
|
||||||
|
private sealed class ConvolveValidation
|
||||||
|
{
|
||||||
|
private readonly double[] _kernel;
|
||||||
|
private readonly int _size;
|
||||||
|
private readonly double _divisor;
|
||||||
|
private readonly double _offset;
|
||||||
|
|
||||||
|
public ConvolveValidation(double[] kernel, int size, double divisor, double offset, bool valid)
|
||||||
|
{
|
||||||
|
int taps = size * size;
|
||||||
|
_kernel = new double[taps];
|
||||||
|
Array.Copy(kernel, _kernel, taps);
|
||||||
|
_size = size;
|
||||||
|
_divisor = divisor;
|
||||||
|
_offset = offset;
|
||||||
|
Valid = valid;
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool Valid { get; }
|
||||||
|
|
||||||
|
public bool Matches(double[] kernel, int size, double divisor, double offset)
|
||||||
|
{
|
||||||
|
if (_size != size || BitConverter.DoubleToInt64Bits(_divisor) != BitConverter.DoubleToInt64Bits(divisor) ||
|
||||||
|
BitConverter.DoubleToInt64Bits(_offset) != BitConverter.DoubleToInt64Bits(offset))
|
||||||
|
return false;
|
||||||
|
int taps = size * size;
|
||||||
|
for (int i = 0; i < taps; i++)
|
||||||
|
{
|
||||||
|
if (BitConverter.DoubleToInt64Bits(_kernel[i]) != BitConverter.DoubleToInt64Bits(kernel[i]))
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,124 @@
|
|||||||
|
using System;
|
||||||
|
using LuaScript.Engine.Shader;
|
||||||
|
|
||||||
|
namespace LuaScript.Engine.Processing
|
||||||
|
{
|
||||||
|
[GpuPixelOperationShader(nameof(RunFillFull), "Shaders/fill.hlsl", "fill_full")]
|
||||||
|
[GpuPixelOperationShader(nameof(RunFillPartial), "Shaders/fill.hlsl", "fill_partial")]
|
||||||
|
internal sealed partial class GpuFillOperation(PixelShaderRunner runner) : GpuPixelOperation(runner)
|
||||||
|
{
|
||||||
|
private const int FillFullThreshold = 1048576;
|
||||||
|
private const int FillPartialThreshold = 1048576;
|
||||||
|
|
||||||
|
private readonly PixelShaderInput[] _resources = new PixelShaderInput[1];
|
||||||
|
private readonly float[] _constants = new float[8];
|
||||||
|
|
||||||
|
private bool? _fullValidated;
|
||||||
|
private bool? _partialValidated;
|
||||||
|
|
||||||
|
public bool TryFill(byte[] target, int width, int height, double r, double g, double b, double a, int x, int y, int fillWidth, int fillHeight, bool force = false)
|
||||||
|
{
|
||||||
|
if (!IsTextureSupported(target, width, height) || !AreFinite(r, g, b, a))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
long pixels = (long)width * height;
|
||||||
|
bool full = x == 0 && y == 0 && fillWidth == width && fillHeight == height;
|
||||||
|
if (full)
|
||||||
|
{
|
||||||
|
if (!force && pixels < FillFullThreshold || !EnsureFullValidated())
|
||||||
|
return false;
|
||||||
|
SetConstants(r, g, b, a);
|
||||||
|
return RunFillFull(_constants.AsSpan(0, 4), target, width, height);
|
||||||
|
}
|
||||||
|
|
||||||
|
long area = (long)fillWidth * fillHeight;
|
||||||
|
if (!force && (pixels < FillPartialThreshold || area * 4L < pixels * 3L) || !EnsurePartialValidated())
|
||||||
|
return false;
|
||||||
|
|
||||||
|
SetConstants(r, g, b, a);
|
||||||
|
_constants[4] = x;
|
||||||
|
_constants[5] = y;
|
||||||
|
_constants[6] = x + fillWidth;
|
||||||
|
_constants[7] = y + fillHeight;
|
||||||
|
_resources[0] = new PixelShaderInput(target, width, height);
|
||||||
|
return RunFillPartial(_resources.AsSpan(0, 1), _constants.AsSpan(0, 8), target, width, height);
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool EnsureFullValidated()
|
||||||
|
{
|
||||||
|
if (_fullValidated.HasValue)
|
||||||
|
return _fullValidated.Value;
|
||||||
|
|
||||||
|
const int width = 7;
|
||||||
|
const int height = 5;
|
||||||
|
var source = CreateProbe(width, height);
|
||||||
|
var cpu = (byte[])source.Clone();
|
||||||
|
var gpu = (byte[])source.Clone();
|
||||||
|
PixelBufferSoftwareProcessor.Fill(cpu, width, height, 23d, 197d, 89d, 173d, 0, 0, width, height);
|
||||||
|
SetConstants(23d, 197d, 89d, 173d);
|
||||||
|
_fullValidated = RunFillFull(_constants.AsSpan(0, 4), gpu, width, height) && Equal(cpu, gpu);
|
||||||
|
return _fullValidated.Value;
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool EnsurePartialValidated()
|
||||||
|
{
|
||||||
|
if (_partialValidated.HasValue)
|
||||||
|
return _partialValidated.Value;
|
||||||
|
|
||||||
|
const int width = 7;
|
||||||
|
const int height = 5;
|
||||||
|
var source = CreateProbe(width, height);
|
||||||
|
var cpu = (byte[])source.Clone();
|
||||||
|
var gpu = (byte[])source.Clone();
|
||||||
|
PixelBufferSoftwareProcessor.Fill(cpu, width, height, 23d, 197d, 89d, 173d, 1, 2, 4, 2);
|
||||||
|
SetConstants(23d, 197d, 89d, 173d);
|
||||||
|
_constants[4] = 1f;
|
||||||
|
_constants[5] = 2f;
|
||||||
|
_constants[6] = 5f;
|
||||||
|
_constants[7] = 4f;
|
||||||
|
_resources[0] = new PixelShaderInput(gpu, width, height);
|
||||||
|
_partialValidated = RunFillPartial(_resources.AsSpan(0, 1), _constants.AsSpan(0, 8), gpu, width, height) && Equal(cpu, gpu);
|
||||||
|
return _partialValidated.Value;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void SetConstants(double r, double g, double b, double a)
|
||||||
|
{
|
||||||
|
double aK = Math.Clamp(a, 0d, 255d) / 255d;
|
||||||
|
byte pb = (byte)Math.Clamp(b * aK, 0d, 255d);
|
||||||
|
byte pg = (byte)Math.Clamp(g * aK, 0d, 255d);
|
||||||
|
byte pr = (byte)Math.Clamp(r * aK, 0d, 255d);
|
||||||
|
byte pa = (byte)Math.Clamp(a, 0d, 255d);
|
||||||
|
_constants[0] = pr / 255f;
|
||||||
|
_constants[1] = pg / 255f;
|
||||||
|
_constants[2] = pb / 255f;
|
||||||
|
_constants[3] = pa / 255f;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool AreFinite(double r, double g, double b, double a)
|
||||||
|
{
|
||||||
|
return double.IsFinite(r) && double.IsFinite(g) && double.IsFinite(b) && double.IsFinite(a);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte[] CreateProbe(int width, int height)
|
||||||
|
{
|
||||||
|
var data = new byte[width * height * 4];
|
||||||
|
for (int y = 0; y < height; y++)
|
||||||
|
{
|
||||||
|
for (int x = 0; x < width; x++)
|
||||||
|
{
|
||||||
|
int index = (y * width + x) * 4;
|
||||||
|
byte a = (byte)((x * 31 + y * 47) & 255);
|
||||||
|
data[index] = a == 0 ? (byte)0 : (byte)((x * 17 + y * 29) % (a + 1));
|
||||||
|
data[index + 1] = a == 0 ? (byte)0 : (byte)((x * 43 + y * 11) % (a + 1));
|
||||||
|
data[index + 2] = a == 0 ? (byte)0 : (byte)((x * 7 + y * 53) % (a + 1));
|
||||||
|
data[index + 3] = a;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
private partial bool RunFillFull(ReadOnlySpan<float> constants, byte[] target, int width, int height);
|
||||||
|
|
||||||
|
private partial bool RunFillPartial(ReadOnlySpan<PixelShaderInput> resources, ReadOnlySpan<float> constants, byte[] target, int width, int height);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
using LuaScript.Engine.Shader;
|
||||||
|
|
||||||
|
namespace LuaScript.Engine.Processing
|
||||||
|
{
|
||||||
|
internal sealed class GpuPixelBufferProcessor(PixelShaderRunner runner) : IPixelBufferProcessor
|
||||||
|
{
|
||||||
|
private readonly object _gate = new();
|
||||||
|
private readonly GpuFillOperation _fill = new(runner);
|
||||||
|
private readonly GpuConvolveOperation _convolve = new(runner);
|
||||||
|
private readonly GpuResizeOperation _resize = new(runner);
|
||||||
|
|
||||||
|
public bool TryFill(byte[] target, int width, int height, double r, double g, double b, double a, int x, int y, int fillWidth, int fillHeight, bool force = false)
|
||||||
|
{
|
||||||
|
lock (_gate)
|
||||||
|
return _fill.TryFill(target, width, height, r, g, b, a, x, y, fillWidth, fillHeight, force);
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool TryConvolve(byte[] target, int width, int height, double[] kernel, int size, double divisor, double offset, bool force = false)
|
||||||
|
{
|
||||||
|
lock (_gate)
|
||||||
|
return _convolve.TryConvolve(target, width, height, kernel, size, divisor, offset, force);
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool TryResize(byte[] source, int sourceWidth, int sourceHeight, int targetWidth, int targetHeight, bool linear, out byte[]? target, bool force = false)
|
||||||
|
{
|
||||||
|
lock (_gate)
|
||||||
|
return _resize.TryResize(source, sourceWidth, sourceHeight, targetWidth, targetHeight, linear, out target, force);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
using System;
|
||||||
|
using LuaScript.Engine.Shader;
|
||||||
|
|
||||||
|
namespace LuaScript.Engine.Processing
|
||||||
|
{
|
||||||
|
internal abstract class GpuPixelOperation(PixelShaderRunner runner)
|
||||||
|
{
|
||||||
|
protected const int MaxTextureSize = 16384;
|
||||||
|
|
||||||
|
protected bool Run(byte[] bytecode, ReadOnlySpan<PixelShaderInput> resources, ReadOnlySpan<float> constants, byte[] target, int width, int height)
|
||||||
|
{
|
||||||
|
return runner.TryRunHardware(
|
||||||
|
bytecode,
|
||||||
|
resources,
|
||||||
|
constants,
|
||||||
|
PixelShaderBlend.Copy,
|
||||||
|
PixelShaderSampler.None,
|
||||||
|
target,
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
out _) == PixelShaderRunStatus.Success;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected static bool IsTextureSupported(byte[] buffer, int width, int height)
|
||||||
|
{
|
||||||
|
return IsTextureSizeSupported(width, height) && (long)buffer.Length >= (long)width * height * 4;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected static bool IsTextureSizeSupported(int width, int height)
|
||||||
|
{
|
||||||
|
return width > 0 && height > 0 && width <= MaxTextureSize && height <= MaxTextureSize;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected static bool Equal(byte[] expected, byte[] actual)
|
||||||
|
{
|
||||||
|
return expected.AsSpan().SequenceEqual(actual);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected static byte[] CopyProbe(byte[] source, int width, int height, int probeWidth, int probeHeight)
|
||||||
|
{
|
||||||
|
var data = new byte[probeWidth * probeHeight * 4];
|
||||||
|
for (int y = 0; y < probeHeight; y++)
|
||||||
|
Buffer.BlockCopy(source, y * width * 4, data, y * probeWidth * 4, probeWidth * 4);
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace LuaScript.Engine.Processing
|
||||||
|
{
|
||||||
|
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
|
||||||
|
internal sealed class GpuPixelOperationShaderAttribute(string methodName, string fileName, string entryPoint) : Attribute
|
||||||
|
{
|
||||||
|
public string MethodName { get; } = methodName;
|
||||||
|
|
||||||
|
public string FileName { get; } = fileName;
|
||||||
|
|
||||||
|
public string EntryPoint { get; } = entryPoint;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
using System;
|
||||||
|
using LuaScript.Engine.Shader;
|
||||||
|
|
||||||
|
namespace LuaScript.Engine.Processing
|
||||||
|
{
|
||||||
|
[GpuPixelOperationShader(nameof(RunResizeNearest), "Shaders/resize.hlsl", "resize_nearest")]
|
||||||
|
[GpuPixelOperationShader(nameof(RunResizeLinear), "Shaders/resize.hlsl", "resize_linear")]
|
||||||
|
internal sealed partial class GpuResizeOperation(PixelShaderRunner runner) : GpuPixelOperation(runner)
|
||||||
|
{
|
||||||
|
private const int ResizeThreshold = 262144;
|
||||||
|
|
||||||
|
private readonly PixelShaderInput[] _resources = new PixelShaderInput[1];
|
||||||
|
private readonly float[] _constants = new float[4];
|
||||||
|
|
||||||
|
private byte[] _target = [];
|
||||||
|
private bool? _nearestValidated;
|
||||||
|
private bool? _linearValidated;
|
||||||
|
|
||||||
|
public bool TryResize(byte[] source, int sourceWidth, int sourceHeight, int targetWidth, int targetHeight, bool linear, out byte[]? target, bool force = false)
|
||||||
|
{
|
||||||
|
target = null;
|
||||||
|
if (!IsTextureSupported(source, sourceWidth, sourceHeight) || !IsTextureSizeSupported(targetWidth, targetHeight))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
long pixels = (long)targetWidth * targetHeight;
|
||||||
|
if (!force && pixels < ResizeThreshold || !(linear ? EnsureLinearValidated(source, sourceWidth, sourceHeight) : EnsureNearestValidated(source, sourceWidth, sourceHeight)))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
return RunShader(source, sourceWidth, sourceHeight, targetWidth, targetHeight, linear, out target);
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool EnsureNearestValidated(byte[] source, int sourceWidth, int sourceHeight)
|
||||||
|
{
|
||||||
|
if (_nearestValidated.HasValue)
|
||||||
|
return _nearestValidated.Value;
|
||||||
|
_nearestValidated = Validate(source, sourceWidth, sourceHeight, false);
|
||||||
|
return _nearestValidated.Value;
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool EnsureLinearValidated(byte[] source, int sourceWidth, int sourceHeight)
|
||||||
|
{
|
||||||
|
if (_linearValidated.HasValue)
|
||||||
|
return _linearValidated.Value;
|
||||||
|
_linearValidated = Validate(source, sourceWidth, sourceHeight, true);
|
||||||
|
return _linearValidated.Value;
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool Validate(byte[] source, int sourceWidth, int sourceHeight, bool linear)
|
||||||
|
{
|
||||||
|
int probeWidth = Math.Min(sourceWidth, 8);
|
||||||
|
int probeHeight = Math.Min(sourceHeight, 7);
|
||||||
|
int targetWidth = Math.Max(1, probeWidth * 2 - 3);
|
||||||
|
int targetHeight = Math.Max(1, probeHeight * 2 - 5);
|
||||||
|
var probe = CopyProbe(source, sourceWidth, sourceHeight, probeWidth, probeHeight);
|
||||||
|
byte[]? sourceScratch = null;
|
||||||
|
byte[]? targetScratch = null;
|
||||||
|
var cpu = PixelBufferSoftwareProcessor.Resize(probe, probeWidth, probeHeight, targetWidth, targetHeight, linear, ref sourceScratch, ref targetScratch);
|
||||||
|
return RunShader(probe, probeWidth, probeHeight, targetWidth, targetHeight, linear, out var gpu) && gpu is not null && Equal(cpu, gpu);
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool RunShader(byte[] source, int sourceWidth, int sourceHeight, int targetWidth, int targetHeight, bool linear, out byte[]? target)
|
||||||
|
{
|
||||||
|
int count = checked(targetWidth * targetHeight * 4);
|
||||||
|
if (_target.Length != count)
|
||||||
|
_target = new byte[count];
|
||||||
|
|
||||||
|
_constants[0] = sourceWidth;
|
||||||
|
_constants[1] = sourceHeight;
|
||||||
|
_constants[2] = targetWidth;
|
||||||
|
_constants[3] = targetHeight;
|
||||||
|
_resources[0] = new PixelShaderInput(source, sourceWidth, sourceHeight);
|
||||||
|
target = _target;
|
||||||
|
return linear
|
||||||
|
? RunResizeLinear(_resources.AsSpan(0, 1), _constants.AsSpan(0, 4), _target, targetWidth, targetHeight)
|
||||||
|
: RunResizeNearest(_resources.AsSpan(0, 1), _constants.AsSpan(0, 4), _target, targetWidth, targetHeight);
|
||||||
|
}
|
||||||
|
|
||||||
|
private partial bool RunResizeNearest(ReadOnlySpan<PixelShaderInput> resources, ReadOnlySpan<float> constants, byte[] target, int width, int height);
|
||||||
|
|
||||||
|
private partial bool RunResizeLinear(ReadOnlySpan<PixelShaderInput> resources, ReadOnlySpan<float> constants, byte[] target, int width, int height);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<Version>1.20.3</Version>
|
||||||
|
<Platforms>AnyCPU;x64</Platforms>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<InternalsVisibleTo Include="LuaScript" />
|
||||||
|
<InternalsVisibleTo Include="LuaScript.Tests" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\LuaScript.Runtime\LuaScript.Runtime.csproj" />
|
||||||
|
<ProjectReference Include="..\LuaScript.Generator\LuaScript.Generator.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
|
||||||
|
<AdditionalFiles Include="Shaders\*.hlsl" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<Reference Include="SharpGen.Runtime">
|
||||||
|
<HintPath>$(YMM4DirPath)SharpGen.Runtime.dll</HintPath>
|
||||||
|
<Private>false</Private>
|
||||||
|
</Reference>
|
||||||
|
<Reference Include="Vortice.Direct3D11">
|
||||||
|
<HintPath>$(YMM4DirPath)Vortice.Direct3D11.dll</HintPath>
|
||||||
|
<Private>false</Private>
|
||||||
|
</Reference>
|
||||||
|
<Reference Include="Vortice.DirectX">
|
||||||
|
<HintPath>$(YMM4DirPath)Vortice.DirectX.dll</HintPath>
|
||||||
|
<Private>false</Private>
|
||||||
|
</Reference>
|
||||||
|
<Reference Include="Vortice.D3DCompiler.dll">
|
||||||
|
<HintPath>$(YMM4DirPath)Vortice.D3DCompiler.dll</HintPath>
|
||||||
|
<Private>false</Private>
|
||||||
|
</Reference>
|
||||||
|
<Reference Include="Vortice.DXGI.dll">
|
||||||
|
<HintPath>$(YMM4DirPath)Vortice.DXGI.dll</HintPath>
|
||||||
|
<Private>false</Private>
|
||||||
|
</Reference>
|
||||||
|
<Reference Include="Vortice.Mathematics">
|
||||||
|
<HintPath>$(YMM4DirPath)Vortice.Mathematics.dll</HintPath>
|
||||||
|
<Private>false</Private>
|
||||||
|
</Reference>
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,674 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading;
|
||||||
|
using Vortice.D3DCompiler;
|
||||||
|
using Vortice.Direct3D;
|
||||||
|
using Vortice.Direct3D11;
|
||||||
|
using Vortice.DXGI;
|
||||||
|
using Vortice.Mathematics;
|
||||||
|
|
||||||
|
namespace LuaScript.Engine.Shader
|
||||||
|
{
|
||||||
|
internal sealed unsafe class PixelShaderRunner : IPixelShaderRunner, IDisposable
|
||||||
|
{
|
||||||
|
private const int MaxResources = 8;
|
||||||
|
private const int ConstantBufferSize = 4096;
|
||||||
|
private const int RandomSeed = 20260704;
|
||||||
|
|
||||||
|
private const string VertexShaderSource = """
|
||||||
|
struct VsOutput { float4 pos : SV_Position; float2 uv : TEXCOORD0; };
|
||||||
|
VsOutput vsmain(uint id : SV_VertexID)
|
||||||
|
{
|
||||||
|
VsOutput output;
|
||||||
|
float2 t = float2((id << 1) & 2, id & 2);
|
||||||
|
output.uv = t;
|
||||||
|
output.pos = float4(t.x * 2.0 - 1.0, 1.0 - t.y * 2.0, 0.0, 1.0);
|
||||||
|
return output;
|
||||||
|
}
|
||||||
|
""";
|
||||||
|
|
||||||
|
private static readonly FeatureLevel[] s_featureLevels = [FeatureLevel.Level_11_0];
|
||||||
|
|
||||||
|
private sealed record CompiledShader(ID3D11PixelShader? Shader, string? Error);
|
||||||
|
|
||||||
|
private struct InputSlot
|
||||||
|
{
|
||||||
|
public ID3D11Texture2D? Texture;
|
||||||
|
public ID3D11ShaderResourceView? View;
|
||||||
|
public int Width;
|
||||||
|
public int Height;
|
||||||
|
}
|
||||||
|
|
||||||
|
private readonly Lock _locker = new();
|
||||||
|
private readonly Dictionary<(string Hlsl, string Entry), CompiledShader> _shaders = [];
|
||||||
|
private readonly Dictionary<byte[], ID3D11PixelShader> _precompiled = new(ReferenceEqualityComparer.Instance);
|
||||||
|
private readonly InputSlot[] _inputs = new InputSlot[MaxResources];
|
||||||
|
private readonly ID3D11ShaderResourceView[] _boundViews = new ID3D11ShaderResourceView[MaxResources];
|
||||||
|
private readonly ID3D11ShaderResourceView[] _nullViews = new ID3D11ShaderResourceView[MaxResources];
|
||||||
|
|
||||||
|
private byte[] _compositeBuffer = [];
|
||||||
|
|
||||||
|
public IBufferCompositor Compositor { get; set; } = SoftwareCompositor.Instance;
|
||||||
|
|
||||||
|
public Action<string, Exception?>? Logger { get; set; }
|
||||||
|
|
||||||
|
private ID3D11Device? _device;
|
||||||
|
private ID3D11DeviceContext? _context;
|
||||||
|
private DriverType _driverType;
|
||||||
|
private ID3D11VertexShader? _vertexShader;
|
||||||
|
private ID3D11Buffer? _constantBuffer;
|
||||||
|
private ID3D11RasterizerState? _rasterizer;
|
||||||
|
private readonly ID3D11BlendState?[] _blendStates = new ID3D11BlendState?[4];
|
||||||
|
private readonly ID3D11SamplerState?[] _samplerStates = new ID3D11SamplerState?[6];
|
||||||
|
private ID3D11Texture2D? _randomTexture;
|
||||||
|
private ID3D11ShaderResourceView? _randomView;
|
||||||
|
private ID3D11Texture2D? _targetTexture;
|
||||||
|
private ID3D11RenderTargetView? _targetView;
|
||||||
|
private int _targetWidth;
|
||||||
|
private int _targetHeight;
|
||||||
|
private ID3D11Texture2D? _stagingTexture;
|
||||||
|
private int _stagingWidth;
|
||||||
|
private int _stagingHeight;
|
||||||
|
|
||||||
|
private bool _disposed;
|
||||||
|
private bool _unavailable;
|
||||||
|
private bool _hardwareUnavailable;
|
||||||
|
private bool _failureLogged;
|
||||||
|
private int _recreateBudget = 3;
|
||||||
|
|
||||||
|
public PixelShaderRunStatus TryRun(
|
||||||
|
string hlsl,
|
||||||
|
string entryPoint,
|
||||||
|
ReadOnlySpan<PixelShaderInput> resources,
|
||||||
|
ReadOnlySpan<float> constants,
|
||||||
|
PixelShaderBlend blend,
|
||||||
|
PixelShaderSampler sampler,
|
||||||
|
byte[] target,
|
||||||
|
int targetWidth,
|
||||||
|
int targetHeight,
|
||||||
|
out string? error)
|
||||||
|
{
|
||||||
|
error = null;
|
||||||
|
lock (_locker)
|
||||||
|
{
|
||||||
|
if (!CanRun(target, targetWidth, targetHeight))
|
||||||
|
return PixelShaderRunStatus.Unavailable;
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (!EnsureDevice())
|
||||||
|
return PixelShaderRunStatus.Unavailable;
|
||||||
|
|
||||||
|
var compiled = GetOrCompile(hlsl, entryPoint);
|
||||||
|
if (compiled.Shader is null)
|
||||||
|
{
|
||||||
|
error = compiled.Error;
|
||||||
|
return PixelShaderRunStatus.CompileError;
|
||||||
|
}
|
||||||
|
|
||||||
|
Execute(compiled.Shader, resources, constants, blend, sampler, target, targetWidth, targetHeight);
|
||||||
|
return PixelShaderRunStatus.Success;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
HandleFailure(ex);
|
||||||
|
return PixelShaderRunStatus.Unavailable;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public PixelShaderRunStatus TryRunHardware(
|
||||||
|
byte[] bytecode,
|
||||||
|
ReadOnlySpan<PixelShaderInput> resources,
|
||||||
|
ReadOnlySpan<float> constants,
|
||||||
|
PixelShaderBlend blend,
|
||||||
|
PixelShaderSampler sampler,
|
||||||
|
byte[] target,
|
||||||
|
int targetWidth,
|
||||||
|
int targetHeight,
|
||||||
|
out string? error)
|
||||||
|
{
|
||||||
|
error = null;
|
||||||
|
lock (_locker)
|
||||||
|
{
|
||||||
|
if (!CanRun(target, targetWidth, targetHeight))
|
||||||
|
return PixelShaderRunStatus.Unavailable;
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (!EnsureHardwareDevice())
|
||||||
|
return PixelShaderRunStatus.Unavailable;
|
||||||
|
|
||||||
|
Execute(GetOrCreate(bytecode), resources, constants, blend, sampler, target, targetWidth, targetHeight);
|
||||||
|
return PixelShaderRunStatus.Success;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
HandleFailure(ex);
|
||||||
|
return PixelShaderRunStatus.Unavailable;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool CanRun(byte[] target, int targetWidth, int targetHeight)
|
||||||
|
{
|
||||||
|
return !_disposed && !_unavailable &&
|
||||||
|
targetWidth > 0 && targetHeight > 0 &&
|
||||||
|
(long)target.Length >= (long)targetWidth * targetHeight * 4;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Invalidate()
|
||||||
|
{
|
||||||
|
lock (_locker)
|
||||||
|
{
|
||||||
|
ReleaseShaders();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
lock (_locker)
|
||||||
|
{
|
||||||
|
if (_disposed)
|
||||||
|
return;
|
||||||
|
_disposed = true;
|
||||||
|
ReleaseDeviceObjects();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool EnsureDevice()
|
||||||
|
{
|
||||||
|
if (_device is not null)
|
||||||
|
return true;
|
||||||
|
if (_recreateBudget <= 0)
|
||||||
|
{
|
||||||
|
MarkUnavailable(null);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
_recreateBudget--;
|
||||||
|
|
||||||
|
DriverType driverType;
|
||||||
|
if (TryCreateDevice(DriverType.Hardware, out var device, out var context))
|
||||||
|
{
|
||||||
|
driverType = DriverType.Hardware;
|
||||||
|
}
|
||||||
|
else if (TryCreateDevice(DriverType.Warp, out device, out context))
|
||||||
|
{
|
||||||
|
driverType = DriverType.Warp;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
MarkUnavailable(null);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return InitializeDevice(device, context, driverType, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool EnsureHardwareDevice()
|
||||||
|
{
|
||||||
|
if (_device is not null)
|
||||||
|
return _driverType == DriverType.Hardware;
|
||||||
|
if (_hardwareUnavailable)
|
||||||
|
return false;
|
||||||
|
if (_recreateBudget <= 0)
|
||||||
|
{
|
||||||
|
_hardwareUnavailable = true;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
_recreateBudget--;
|
||||||
|
if (!TryCreateDevice(DriverType.Hardware, out var device, out var context))
|
||||||
|
{
|
||||||
|
_hardwareUnavailable = true;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return InitializeDevice(device, context, DriverType.Hardware, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool InitializeDevice(ID3D11Device? device, ID3D11DeviceContext? context, DriverType driverType, bool markUnavailable)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var vsBytecode = CompileOrThrow(VertexShaderSource, "vsmain", "vs_4_0");
|
||||||
|
var vertexShader = device!.CreateVertexShader(vsBytecode);
|
||||||
|
_device = device;
|
||||||
|
_context = context;
|
||||||
|
_driverType = driverType;
|
||||||
|
_hardwareUnavailable = driverType != DriverType.Hardware && _hardwareUnavailable;
|
||||||
|
_vertexShader = vertexShader;
|
||||||
|
_constantBuffer = device.CreateBuffer(new BufferDescription(
|
||||||
|
ConstantBufferSize, BindFlags.ConstantBuffer, ResourceUsage.Dynamic, CpuAccessFlags.Write));
|
||||||
|
_rasterizer = device.CreateRasterizerState(RasterizerDescription.CullNone);
|
||||||
|
CreateBlendStates(device);
|
||||||
|
CreateSamplerStates(device);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
if (ReferenceEquals(_device, device))
|
||||||
|
{
|
||||||
|
ReleaseDeviceObjects();
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
context?.Dispose();
|
||||||
|
device?.Dispose();
|
||||||
|
}
|
||||||
|
if (markUnavailable)
|
||||||
|
MarkUnavailable(ex);
|
||||||
|
else
|
||||||
|
_hardwareUnavailable = true;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool TryCreateDevice(DriverType driverType, out ID3D11Device? device, out ID3D11DeviceContext? context)
|
||||||
|
{
|
||||||
|
device = null;
|
||||||
|
context = null;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var result = D3D11.D3D11CreateDevice(
|
||||||
|
null, driverType, DeviceCreationFlags.BgraSupport, s_featureLevels,
|
||||||
|
out device, out context);
|
||||||
|
if (result.Success && device is not null && context is not null)
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
}
|
||||||
|
context?.Dispose();
|
||||||
|
device?.Dispose();
|
||||||
|
device = null;
|
||||||
|
context = null;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void CreateBlendStates(ID3D11Device device)
|
||||||
|
{
|
||||||
|
_blendStates[(int)PixelShaderBlendMode.Copy] = null;
|
||||||
|
_blendStates[(int)PixelShaderBlendMode.Mask] = device.CreateBlendState(new BlendDescription(
|
||||||
|
Blend.Zero, Blend.One, Blend.Zero, Blend.SourceAlpha));
|
||||||
|
_blendStates[(int)PixelShaderBlendMode.Draw] = device.CreateBlendState(new BlendDescription(
|
||||||
|
Blend.One, Blend.InverseSourceAlpha, Blend.One, Blend.InverseSourceAlpha));
|
||||||
|
_blendStates[(int)PixelShaderBlendMode.Add] = device.CreateBlendState(new BlendDescription(
|
||||||
|
Blend.One, Blend.One, Blend.One, Blend.One));
|
||||||
|
}
|
||||||
|
|
||||||
|
private void CreateSamplerStates(ID3D11Device device)
|
||||||
|
{
|
||||||
|
_samplerStates[(int)PixelShaderSampler.None] = null;
|
||||||
|
_samplerStates[(int)PixelShaderSampler.Clip] = CreateSampler(device, Filter.MinMagMipLinear, TextureAddressMode.Border);
|
||||||
|
_samplerStates[(int)PixelShaderSampler.Clamp] = CreateSampler(device, Filter.MinMagMipLinear, TextureAddressMode.Clamp);
|
||||||
|
_samplerStates[(int)PixelShaderSampler.Loop] = CreateSampler(device, Filter.MinMagMipLinear, TextureAddressMode.Wrap);
|
||||||
|
_samplerStates[(int)PixelShaderSampler.Mirror] = CreateSampler(device, Filter.MinMagMipLinear, TextureAddressMode.Mirror);
|
||||||
|
_samplerStates[(int)PixelShaderSampler.Dot] = CreateSampler(device, Filter.MinMagMipPoint, TextureAddressMode.Border);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static ID3D11SamplerState CreateSampler(ID3D11Device device, Filter filter, TextureAddressMode address)
|
||||||
|
{
|
||||||
|
var description = new SamplerDescription(filter, address, address, address)
|
||||||
|
{
|
||||||
|
BorderColor = new Color4(0f, 0f, 0f, 0f),
|
||||||
|
};
|
||||||
|
return device.CreateSamplerState(description);
|
||||||
|
}
|
||||||
|
|
||||||
|
private CompiledShader GetOrCompile(string hlsl, string entryPoint)
|
||||||
|
{
|
||||||
|
var key = (hlsl, entryPoint);
|
||||||
|
if (_shaders.TryGetValue(key, out var cached))
|
||||||
|
return cached;
|
||||||
|
|
||||||
|
CompiledShader compiled;
|
||||||
|
byte[] source = Encoding.UTF8.GetBytes(hlsl);
|
||||||
|
var result = Compiler.Compile(source, entryPoint, string.Empty, "ps_5_0", out var bytecode, out var errors);
|
||||||
|
if (result.Failure || bytecode is null)
|
||||||
|
{
|
||||||
|
compiled = new CompiledShader(null, errors?.AsString()?.Trim() ?? result.ToString());
|
||||||
|
errors?.Dispose();
|
||||||
|
bytecode?.Dispose();
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
compiled = new CompiledShader(_device!.CreatePixelShader(bytecode.AsSpan()), null);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
errors?.Dispose();
|
||||||
|
bytecode.Dispose();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_shaders[key] = compiled;
|
||||||
|
return compiled;
|
||||||
|
}
|
||||||
|
|
||||||
|
private ID3D11PixelShader GetOrCreate(byte[] bytecode)
|
||||||
|
{
|
||||||
|
if (_precompiled.TryGetValue(bytecode, out var cached))
|
||||||
|
return cached;
|
||||||
|
|
||||||
|
var shader = _device!.CreatePixelShader(bytecode);
|
||||||
|
_precompiled[bytecode] = shader;
|
||||||
|
return shader;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte[] CompileOrThrow(string source, string entryPoint, string profile)
|
||||||
|
{
|
||||||
|
var result = Compiler.Compile(Encoding.UTF8.GetBytes(source), entryPoint, string.Empty, profile, out var bytecode, out var errors);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (result.Failure || bytecode is null)
|
||||||
|
throw new InvalidOperationException(errors?.AsString() ?? result.ToString());
|
||||||
|
return bytecode.AsBytes();
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
errors?.Dispose();
|
||||||
|
bytecode?.Dispose();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void Execute(
|
||||||
|
ID3D11PixelShader shader,
|
||||||
|
ReadOnlySpan<PixelShaderInput> resources,
|
||||||
|
ReadOnlySpan<float> constants,
|
||||||
|
PixelShaderBlend blend,
|
||||||
|
PixelShaderSampler sampler,
|
||||||
|
byte[] target,
|
||||||
|
int width,
|
||||||
|
int height)
|
||||||
|
{
|
||||||
|
var context = _context!;
|
||||||
|
|
||||||
|
bool composite = blend.Mode == PixelShaderBlendMode.Composite;
|
||||||
|
EnsureTarget(width, height);
|
||||||
|
if (!composite && blend.Mode != PixelShaderBlendMode.Copy)
|
||||||
|
UploadPixels(_targetTexture!, target, width, height);
|
||||||
|
|
||||||
|
UploadConstants(constants);
|
||||||
|
BindResources(resources);
|
||||||
|
|
||||||
|
context.OMSetRenderTargets(_targetView!);
|
||||||
|
context.OMSetBlendState(composite ? null : _blendStates[(int)blend.Mode]);
|
||||||
|
context.RSSetViewport(0f, 0f, width, height);
|
||||||
|
context.RSSetState(_rasterizer);
|
||||||
|
context.IASetInputLayout(null);
|
||||||
|
context.IASetPrimitiveTopology(PrimitiveTopology.TriangleList);
|
||||||
|
context.VSSetShader(_vertexShader);
|
||||||
|
context.PSSetShader(shader);
|
||||||
|
context.PSSetConstantBuffer(0, _constantBuffer);
|
||||||
|
context.PSSetSampler(0, _samplerStates[(int)sampler]);
|
||||||
|
context.PSSetShaderResources(0, _boundViews);
|
||||||
|
context.Draw(3, 0);
|
||||||
|
context.PSSetShaderResources(0, _nullViews);
|
||||||
|
context.UnsetRenderTargets();
|
||||||
|
|
||||||
|
if (composite)
|
||||||
|
{
|
||||||
|
int length = width * height * 4;
|
||||||
|
if (_compositeBuffer.Length < length)
|
||||||
|
_compositeBuffer = new byte[length];
|
||||||
|
ReadBack(_compositeBuffer, width, height);
|
||||||
|
Compositor.TryCompose(target, width, height, _compositeBuffer, width, height,
|
||||||
|
new DrawCommand(width * 0.5, height * 0.5, 0d, 1d, 1d, 0d, null, 0d, blend.CompositeBlend));
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
ReadBack(target, width, height);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void EnsureTarget(int width, int height)
|
||||||
|
{
|
||||||
|
if (_targetTexture is null || _targetWidth != width || _targetHeight != height)
|
||||||
|
{
|
||||||
|
_targetView?.Dispose();
|
||||||
|
_targetTexture?.Dispose();
|
||||||
|
_targetTexture = _device!.CreateTexture2D(new Texture2DDescription
|
||||||
|
{
|
||||||
|
Width = width,
|
||||||
|
Height = height,
|
||||||
|
MipLevels = 1,
|
||||||
|
ArraySize = 1,
|
||||||
|
Format = Format.B8G8R8A8_UNorm,
|
||||||
|
SampleDescription = new SampleDescription(1, 0),
|
||||||
|
Usage = ResourceUsage.Default,
|
||||||
|
BindFlags = BindFlags.RenderTarget,
|
||||||
|
});
|
||||||
|
_targetView = _device.CreateRenderTargetView(_targetTexture);
|
||||||
|
_targetWidth = width;
|
||||||
|
_targetHeight = height;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_stagingTexture is null || _stagingWidth != width || _stagingHeight != height)
|
||||||
|
{
|
||||||
|
_stagingTexture?.Dispose();
|
||||||
|
_stagingTexture = _device!.CreateTexture2D(new Texture2DDescription
|
||||||
|
{
|
||||||
|
Width = width,
|
||||||
|
Height = height,
|
||||||
|
MipLevels = 1,
|
||||||
|
ArraySize = 1,
|
||||||
|
Format = Format.B8G8R8A8_UNorm,
|
||||||
|
SampleDescription = new SampleDescription(1, 0),
|
||||||
|
Usage = ResourceUsage.Staging,
|
||||||
|
CPUAccessFlags = CpuAccessFlags.Read,
|
||||||
|
});
|
||||||
|
_stagingWidth = width;
|
||||||
|
_stagingHeight = height;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void UploadPixels(ID3D11Texture2D texture, byte[] pixels, int width, int height)
|
||||||
|
{
|
||||||
|
fixed (byte* source = pixels)
|
||||||
|
_context!.UpdateSubresource(texture, 0, null, (nint)source, width * 4, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void UploadConstants(ReadOnlySpan<float> constants)
|
||||||
|
{
|
||||||
|
var mapped = _context!.Map(_constantBuffer!, MapMode.WriteDiscard);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var destination = new Span<float>((void*)mapped.DataPointer, ConstantBufferSize / sizeof(float));
|
||||||
|
constants.CopyTo(destination);
|
||||||
|
destination[constants.Length..].Clear();
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_context.Unmap(_constantBuffer!);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void BindResources(ReadOnlySpan<PixelShaderInput> resources)
|
||||||
|
{
|
||||||
|
for (int i = 0; i < MaxResources; i++)
|
||||||
|
{
|
||||||
|
if (i >= resources.Length)
|
||||||
|
{
|
||||||
|
_boundViews[i] = null!;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
var resource = resources[i];
|
||||||
|
if (resource.IsRandom)
|
||||||
|
{
|
||||||
|
_boundViews[i] = EnsureRandomView();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
ref var slot = ref _inputs[i];
|
||||||
|
if (slot.Texture is null || slot.Width != resource.Width || slot.Height != resource.Height)
|
||||||
|
{
|
||||||
|
slot.View?.Dispose();
|
||||||
|
slot.Texture?.Dispose();
|
||||||
|
slot.Texture = _device!.CreateTexture2D(new Texture2DDescription
|
||||||
|
{
|
||||||
|
Width = resource.Width,
|
||||||
|
Height = resource.Height,
|
||||||
|
MipLevels = 1,
|
||||||
|
ArraySize = 1,
|
||||||
|
Format = Format.B8G8R8A8_UNorm,
|
||||||
|
SampleDescription = new SampleDescription(1, 0),
|
||||||
|
Usage = ResourceUsage.Default,
|
||||||
|
BindFlags = BindFlags.ShaderResource,
|
||||||
|
});
|
||||||
|
slot.View = _device.CreateShaderResourceView(slot.Texture);
|
||||||
|
slot.Width = resource.Width;
|
||||||
|
slot.Height = resource.Height;
|
||||||
|
}
|
||||||
|
|
||||||
|
UploadPixels(slot.Texture, resource.Data!, resource.Width, resource.Height);
|
||||||
|
_boundViews[i] = slot.View!;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private ID3D11ShaderResourceView EnsureRandomView()
|
||||||
|
{
|
||||||
|
if (_randomView is not null)
|
||||||
|
return _randomView;
|
||||||
|
|
||||||
|
int size = PixelShaderInput.RandomSize;
|
||||||
|
var values = new float[size * size];
|
||||||
|
var random = new Random(RandomSeed);
|
||||||
|
for (int i = 0; i < values.Length; i++)
|
||||||
|
values[i] = (float)random.NextDouble();
|
||||||
|
|
||||||
|
fixed (float* source = values)
|
||||||
|
{
|
||||||
|
_randomTexture = _device!.CreateTexture2D(new Texture2DDescription
|
||||||
|
{
|
||||||
|
Width = size,
|
||||||
|
Height = size,
|
||||||
|
MipLevels = 1,
|
||||||
|
ArraySize = 1,
|
||||||
|
Format = Format.R32_Float,
|
||||||
|
SampleDescription = new SampleDescription(1, 0),
|
||||||
|
Usage = ResourceUsage.Immutable,
|
||||||
|
BindFlags = BindFlags.ShaderResource,
|
||||||
|
}, [new SubresourceData((nint)source, size * sizeof(float))]);
|
||||||
|
}
|
||||||
|
_randomView = _device!.CreateShaderResourceView(_randomTexture);
|
||||||
|
return _randomView;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ReadBack(byte[] target, int width, int height)
|
||||||
|
{
|
||||||
|
var context = _context!;
|
||||||
|
context.CopyResource(_stagingTexture!, _targetTexture!);
|
||||||
|
var mapped = context.Map(_stagingTexture!, 0, MapMode.Read);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
int rowBytes = width * 4;
|
||||||
|
byte* source = (byte*)mapped.DataPointer;
|
||||||
|
fixed (byte* destination = target)
|
||||||
|
{
|
||||||
|
if (mapped.RowPitch == rowBytes)
|
||||||
|
{
|
||||||
|
Buffer.MemoryCopy(source, destination, target.Length, (long)rowBytes * height);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
for (int row = 0; row < height; row++)
|
||||||
|
Buffer.MemoryCopy(
|
||||||
|
source + (long)mapped.RowPitch * row,
|
||||||
|
destination + (long)rowBytes * row,
|
||||||
|
rowBytes, rowBytes);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
context.Unmap(_stagingTexture!, 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void HandleFailure(Exception ex)
|
||||||
|
{
|
||||||
|
if (!_failureLogged)
|
||||||
|
{
|
||||||
|
_failureLogged = true;
|
||||||
|
WriteLog("LuaScript: obj.pixelshader execution failed; the call is skipped.", ex);
|
||||||
|
}
|
||||||
|
ReleaseDeviceObjects();
|
||||||
|
if (_recreateBudget <= 0)
|
||||||
|
_unavailable = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void MarkUnavailable(Exception? ex)
|
||||||
|
{
|
||||||
|
_unavailable = true;
|
||||||
|
if (_failureLogged)
|
||||||
|
return;
|
||||||
|
_failureLogged = true;
|
||||||
|
if (ex is null)
|
||||||
|
WriteLog("LuaScript: Direct3D 11 is unavailable; obj.pixelshader is disabled.", null);
|
||||||
|
else
|
||||||
|
WriteLog("LuaScript: Direct3D 11 initialization failed; obj.pixelshader is disabled.", ex);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void WriteLog(string message, Exception? exception) => Logger?.Invoke(message, exception);
|
||||||
|
|
||||||
|
private void ReleaseShaders()
|
||||||
|
{
|
||||||
|
foreach (var compiled in _shaders.Values)
|
||||||
|
compiled.Shader?.Dispose();
|
||||||
|
_shaders.Clear();
|
||||||
|
foreach (var shader in _precompiled.Values)
|
||||||
|
shader.Dispose();
|
||||||
|
_precompiled.Clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ReleaseDeviceObjects()
|
||||||
|
{
|
||||||
|
ReleaseShaders();
|
||||||
|
for (int i = 0; i < _inputs.Length; i++)
|
||||||
|
{
|
||||||
|
_inputs[i].View?.Dispose();
|
||||||
|
_inputs[i].Texture?.Dispose();
|
||||||
|
_inputs[i] = default;
|
||||||
|
_boundViews[i] = null!;
|
||||||
|
}
|
||||||
|
for (int i = 0; i < _blendStates.Length; i++)
|
||||||
|
{
|
||||||
|
_blendStates[i]?.Dispose();
|
||||||
|
_blendStates[i] = null;
|
||||||
|
}
|
||||||
|
for (int i = 0; i < _samplerStates.Length; i++)
|
||||||
|
{
|
||||||
|
_samplerStates[i]?.Dispose();
|
||||||
|
_samplerStates[i] = null;
|
||||||
|
}
|
||||||
|
_randomView?.Dispose();
|
||||||
|
_randomView = null;
|
||||||
|
_randomTexture?.Dispose();
|
||||||
|
_randomTexture = null;
|
||||||
|
_targetView?.Dispose();
|
||||||
|
_targetView = null;
|
||||||
|
_targetTexture?.Dispose();
|
||||||
|
_targetTexture = null;
|
||||||
|
_targetWidth = 0;
|
||||||
|
_targetHeight = 0;
|
||||||
|
_stagingTexture?.Dispose();
|
||||||
|
_stagingTexture = null;
|
||||||
|
_stagingWidth = 0;
|
||||||
|
_stagingHeight = 0;
|
||||||
|
_constantBuffer?.Dispose();
|
||||||
|
_constantBuffer = null;
|
||||||
|
_rasterizer?.Dispose();
|
||||||
|
_rasterizer = null;
|
||||||
|
_vertexShader?.Dispose();
|
||||||
|
_vertexShader = null;
|
||||||
|
_context?.Dispose();
|
||||||
|
_context = null;
|
||||||
|
_device?.Dispose();
|
||||||
|
_device = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
Texture2D source : register(t0);
|
||||||
|
|
||||||
|
cbuffer Parameters : register(b0)
|
||||||
|
{
|
||||||
|
float4 values[256];
|
||||||
|
};
|
||||||
|
|
||||||
|
float get_value(uint index)
|
||||||
|
{
|
||||||
|
uint row = index >> 2;
|
||||||
|
uint column = index & 3u;
|
||||||
|
float4 value = values[row];
|
||||||
|
if (column == 0u)
|
||||||
|
return value.x;
|
||||||
|
if (column == 1u)
|
||||||
|
return value.y;
|
||||||
|
if (column == 2u)
|
||||||
|
return value.z;
|
||||||
|
return value.w;
|
||||||
|
}
|
||||||
|
|
||||||
|
float convolve_channel(float value)
|
||||||
|
{
|
||||||
|
return floor(saturate(value) * 255.0) / 255.0;
|
||||||
|
}
|
||||||
|
|
||||||
|
float4 convolve(float4 pos : SV_Position) : SV_Target
|
||||||
|
{
|
||||||
|
uint2 p = (uint2)floor(pos.xy);
|
||||||
|
int width = (int)get_value(0u);
|
||||||
|
int height = (int)get_value(1u);
|
||||||
|
float divisor = get_value(2u);
|
||||||
|
float offset = get_value(3u) / 255.0;
|
||||||
|
int kernelSize = (int)get_value(4u);
|
||||||
|
int radius = (int)get_value(5u);
|
||||||
|
float4 sum = 0.0;
|
||||||
|
|
||||||
|
for (int ky = 0; ky < kernelSize; ky++)
|
||||||
|
{
|
||||||
|
int sy = clamp((int)p.y + ky - radius, 0, height - 1);
|
||||||
|
for (int kx = 0; kx < kernelSize; kx++)
|
||||||
|
{
|
||||||
|
int sx = clamp((int)p.x + kx - radius, 0, width - 1);
|
||||||
|
float kv = get_value((uint)(8 + ky * kernelSize + kx));
|
||||||
|
float4 sourceValue = source[uint2((uint)sx, (uint)sy)];
|
||||||
|
float3 rgb = sourceValue.a <= 0.0 ? 0.0 : saturate(sourceValue.rgb / sourceValue.a);
|
||||||
|
sum += float4(rgb, sourceValue.a) * kv;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
float3 rgbOut = saturate(sum.rgb / divisor + offset);
|
||||||
|
float alpha = saturate(sum.a / divisor + offset);
|
||||||
|
return float4(
|
||||||
|
convolve_channel(rgbOut.r * alpha),
|
||||||
|
convolve_channel(rgbOut.g * alpha),
|
||||||
|
convolve_channel(rgbOut.b * alpha),
|
||||||
|
convolve_channel(alpha));
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
Texture2D source : register(t0);
|
||||||
|
|
||||||
|
cbuffer Parameters : register(b0)
|
||||||
|
{
|
||||||
|
float4 color;
|
||||||
|
float4 rect;
|
||||||
|
};
|
||||||
|
|
||||||
|
float4 fill_full(float4 pos : SV_Position) : SV_Target
|
||||||
|
{
|
||||||
|
return color;
|
||||||
|
}
|
||||||
|
|
||||||
|
float4 fill_partial(float4 pos : SV_Position) : SV_Target
|
||||||
|
{
|
||||||
|
uint2 p = (uint2)floor(pos.xy);
|
||||||
|
uint4 r = (uint4)rect;
|
||||||
|
if (p.x >= r.x && p.y >= r.y && p.x < r.z && p.y < r.w)
|
||||||
|
return color;
|
||||||
|
return source[p];
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
Texture2D source : register(t0);
|
||||||
|
|
||||||
|
cbuffer Parameters : register(b0)
|
||||||
|
{
|
||||||
|
float4 size;
|
||||||
|
};
|
||||||
|
|
||||||
|
float channel(float value)
|
||||||
|
{
|
||||||
|
return floor(saturate(value) * 255.0) / 255.0;
|
||||||
|
}
|
||||||
|
|
||||||
|
float4 resize_pack(float4 value)
|
||||||
|
{
|
||||||
|
return float4(channel(value.r), channel(value.g), channel(value.b), channel(value.a));
|
||||||
|
}
|
||||||
|
|
||||||
|
float4 resize_nearest(float4 pos : SV_Position) : SV_Target
|
||||||
|
{
|
||||||
|
uint2 p = (uint2)floor(pos.xy);
|
||||||
|
uint sourceWidth = (uint)size.x;
|
||||||
|
uint sourceHeight = (uint)size.y;
|
||||||
|
uint targetWidth = (uint)size.z;
|
||||||
|
uint targetHeight = (uint)size.w;
|
||||||
|
uint sx = min(((p.x * 2u + 1u) * sourceWidth) / (targetWidth * 2u), sourceWidth - 1u);
|
||||||
|
uint sy = min(((p.y * 2u + 1u) * sourceHeight) / (targetHeight * 2u), sourceHeight - 1u);
|
||||||
|
return source[uint2(sx, sy)];
|
||||||
|
}
|
||||||
|
|
||||||
|
float4 resize_linear(float4 pos : SV_Position) : SV_Target
|
||||||
|
{
|
||||||
|
uint2 p = (uint2)floor(pos.xy);
|
||||||
|
float sourceWidth = size.x;
|
||||||
|
float sourceHeight = size.y;
|
||||||
|
float targetWidth = size.z;
|
||||||
|
float targetHeight = size.w;
|
||||||
|
float u = (p.x + 0.5) * sourceWidth / targetWidth - 0.5;
|
||||||
|
float v = (p.y + 0.5) * sourceHeight / targetHeight - 0.5;
|
||||||
|
int x0 = (int)floor(u);
|
||||||
|
int y0 = (int)floor(v);
|
||||||
|
float tx = u - x0;
|
||||||
|
float ty = v - y0;
|
||||||
|
int maxX = (int)sourceWidth - 1;
|
||||||
|
int maxY = (int)sourceHeight - 1;
|
||||||
|
uint xA = (uint)clamp(x0, 0, maxX);
|
||||||
|
uint yA = (uint)clamp(y0, 0, maxY);
|
||||||
|
uint xB = (uint)clamp(x0 + 1, 0, maxX);
|
||||||
|
uint yB = (uint)clamp(y0 + 1, 0, maxY);
|
||||||
|
float4 c00 = source[uint2(xA, yA)];
|
||||||
|
float4 c10 = source[uint2(xB, yA)];
|
||||||
|
float4 c01 = source[uint2(xA, yB)];
|
||||||
|
float4 c11 = source[uint2(xB, yB)];
|
||||||
|
float4 top = c00 * (1.0 - tx) + c10 * tx;
|
||||||
|
float4 bottom = c01 * (1.0 - tx) + c11 * tx;
|
||||||
|
return resize_pack(top * (1.0 - ty) + bottom * ty);
|
||||||
|
}
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
using System.Diagnostics;
|
||||||
|
using System.Runtime.Intrinsics;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal sealed class CpuKernel(CpuKernel.RowDelegate row, CpuKernel.RowDelegate? block)
|
||||||
|
{
|
||||||
|
public delegate void RowDelegate(byte[] buffer, int rowBase, int xStart, int xEnd, double y, double[] uniforms);
|
||||||
|
|
||||||
|
private const int ParallelThreshold = 64;
|
||||||
|
private const int WarmupRunsPerPath = 1;
|
||||||
|
private const int TimedRunsPerPath = 3;
|
||||||
|
|
||||||
|
private readonly RowDelegate _row = row;
|
||||||
|
private readonly RowDelegate? _block = block;
|
||||||
|
private long _rowTicks;
|
||||||
|
private long _blockTicks;
|
||||||
|
private int _rowRuns;
|
||||||
|
private int _blockRuns;
|
||||||
|
private bool _nextIsBlock = true;
|
||||||
|
private bool _decided;
|
||||||
|
private bool _useBlock;
|
||||||
|
|
||||||
|
public bool? BlockAdopted => _decided ? _useBlock : null;
|
||||||
|
|
||||||
|
public void Execute(byte[] buffer, int width, int height, double[] uniforms)
|
||||||
|
{
|
||||||
|
if (_block is null || !Vector256.IsHardwareAccelerated)
|
||||||
|
{
|
||||||
|
Run(buffer, width, height, uniforms, false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_decided)
|
||||||
|
{
|
||||||
|
Run(buffer, width, height, uniforms, _useBlock);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool useBlock = _nextIsBlock;
|
||||||
|
_nextIsBlock = !_nextIsBlock;
|
||||||
|
|
||||||
|
long start = Stopwatch.GetTimestamp();
|
||||||
|
Run(buffer, width, height, uniforms, useBlock);
|
||||||
|
long elapsed = Stopwatch.GetTimestamp() - start;
|
||||||
|
|
||||||
|
if (useBlock)
|
||||||
|
{
|
||||||
|
if (_blockRuns >= WarmupRunsPerPath)
|
||||||
|
_blockTicks += elapsed;
|
||||||
|
_blockRuns++;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
if (_rowRuns >= WarmupRunsPerPath)
|
||||||
|
_rowTicks += elapsed;
|
||||||
|
_rowRuns++;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_rowRuns >= WarmupRunsPerPath + TimedRunsPerPath &&
|
||||||
|
_blockRuns >= WarmupRunsPerPath + TimedRunsPerPath)
|
||||||
|
{
|
||||||
|
_useBlock = _blockTicks < _rowTicks;
|
||||||
|
_decided = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void Run(byte[] buffer, int width, int height, double[] uniforms, bool useBlock)
|
||||||
|
{
|
||||||
|
var row = _row;
|
||||||
|
var block = useBlock ? _block : null;
|
||||||
|
int stride = width * 4;
|
||||||
|
int blockWidth = block is null ? 0 : width & ~3;
|
||||||
|
|
||||||
|
void RunRow(int y)
|
||||||
|
{
|
||||||
|
int rowBase = y * stride;
|
||||||
|
if (blockWidth > 0)
|
||||||
|
block!(buffer, rowBase, 0, blockWidth, y, uniforms);
|
||||||
|
if (blockWidth < width)
|
||||||
|
row(buffer, rowBase, blockWidth, width, y, uniforms);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (height < ParallelThreshold)
|
||||||
|
{
|
||||||
|
for (int y = 0; y < height; y++)
|
||||||
|
RunRow(y);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
Parallel.For(0, height, RunRow);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,222 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq.Expressions;
|
||||||
|
using System.Reflection;
|
||||||
|
|
||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal static class CpuKernelCompiler
|
||||||
|
{
|
||||||
|
private static readonly MethodInfo Clamp = typeof(Math).GetMethod(nameof(Math.Clamp), [typeof(double), typeof(double), typeof(double)])!;
|
||||||
|
private static readonly MethodInfo Floor = Unary(nameof(Math.Floor));
|
||||||
|
private static readonly MethodInfo Pow = Binary(nameof(Math.Pow));
|
||||||
|
|
||||||
|
private static readonly Dictionary<KFunc, MethodInfo> Functions = new()
|
||||||
|
{
|
||||||
|
[KFunc.Abs] = Unary(nameof(Math.Abs)),
|
||||||
|
[KFunc.Floor] = Floor,
|
||||||
|
[KFunc.Ceil] = Unary(nameof(Math.Ceiling)),
|
||||||
|
[KFunc.Sqrt] = Unary(nameof(Math.Sqrt)),
|
||||||
|
[KFunc.Sin] = Unary(nameof(Math.Sin)),
|
||||||
|
[KFunc.Cos] = Unary(nameof(Math.Cos)),
|
||||||
|
[KFunc.Tan] = Unary(nameof(Math.Tan)),
|
||||||
|
[KFunc.Asin] = Unary(nameof(Math.Asin)),
|
||||||
|
[KFunc.Acos] = Unary(nameof(Math.Acos)),
|
||||||
|
[KFunc.Atan] = Unary(nameof(Math.Atan)),
|
||||||
|
[KFunc.Atan2] = Binary(nameof(Math.Atan2)),
|
||||||
|
[KFunc.Exp] = Unary(nameof(Math.Exp)),
|
||||||
|
[KFunc.Log] = Unary(nameof(Math.Log)),
|
||||||
|
[KFunc.Pow] = Pow,
|
||||||
|
[KFunc.Min] = Binary(nameof(Math.Min)),
|
||||||
|
[KFunc.Max] = Binary(nameof(Math.Max)),
|
||||||
|
};
|
||||||
|
|
||||||
|
public static CpuKernel Compile(KernelProgram program) =>
|
||||||
|
new(CompileRow(program), SimdKernelCompiler.TryCompile(program));
|
||||||
|
|
||||||
|
public static CpuKernel.RowDelegate CompileRow(KernelProgram program)
|
||||||
|
{
|
||||||
|
var buffer = Expression.Parameter(typeof(byte[]), "buffer");
|
||||||
|
var rowBase = Expression.Parameter(typeof(int), "rowBase");
|
||||||
|
var xStart = Expression.Parameter(typeof(int), "xStart");
|
||||||
|
var xEnd = Expression.Parameter(typeof(int), "xEnd");
|
||||||
|
var y = Expression.Parameter(typeof(double), "y");
|
||||||
|
var uniforms = Expression.Parameter(typeof(double[]), "uniforms");
|
||||||
|
|
||||||
|
var x = Expression.Variable(typeof(int), "x");
|
||||||
|
var index = Expression.Variable(typeof(int), "index");
|
||||||
|
var alphaRaw = Expression.Variable(typeof(double), "alphaRaw");
|
||||||
|
var transparent = Expression.Variable(typeof(bool), "transparent");
|
||||||
|
var scale = Expression.Variable(typeof(double), "scale");
|
||||||
|
var inputs = new[]
|
||||||
|
{
|
||||||
|
Expression.Variable(typeof(double), "inR"),
|
||||||
|
Expression.Variable(typeof(double), "inG"),
|
||||||
|
Expression.Variable(typeof(double), "inB"),
|
||||||
|
Expression.Variable(typeof(double), "inA"),
|
||||||
|
};
|
||||||
|
var slots = new ParameterExpression[program.Bindings.Count];
|
||||||
|
for (int i = 0; i < slots.Length; i++)
|
||||||
|
slots[i] = Expression.Variable(typeof(double), "slot" + i);
|
||||||
|
|
||||||
|
var context = new Context(x, y, uniforms, inputs, slots);
|
||||||
|
|
||||||
|
var statements = new List<Expression>
|
||||||
|
{
|
||||||
|
Expression.Assign(index, Expression.Add(rowBase, Expression.Multiply(x, Constant(4)))),
|
||||||
|
Expression.Assign(alphaRaw, ToDouble(ReadByte(buffer, index, 3))),
|
||||||
|
Expression.Assign(transparent, Expression.LessThanOrEqual(alphaRaw, Constant(0d))),
|
||||||
|
Expression.Assign(scale, Select(transparent, Constant(0d), Expression.Divide(Constant(255d), alphaRaw))),
|
||||||
|
Expression.Assign(inputs[3], Select(transparent, Constant(0d), alphaRaw)),
|
||||||
|
Expression.Assign(inputs[0], Select(transparent, Constant(0d), ClampByte(Expression.Multiply(ToDouble(ReadByte(buffer, index, 2)), scale)))),
|
||||||
|
Expression.Assign(inputs[1], Select(transparent, Constant(0d), ClampByte(Expression.Multiply(ToDouble(ReadByte(buffer, index, 1)), scale)))),
|
||||||
|
Expression.Assign(inputs[2], Select(transparent, Constant(0d), ClampByte(Expression.Multiply(ToDouble(ReadByte(buffer, index, 0)), scale)))),
|
||||||
|
};
|
||||||
|
|
||||||
|
for (int i = 0; i < slots.Length; i++)
|
||||||
|
statements.Add(Expression.Assign(slots[i], Build(program.Bindings[i], context)));
|
||||||
|
|
||||||
|
var outA = Expression.Variable(typeof(double), "outA");
|
||||||
|
var alphaScale = Expression.Variable(typeof(double), "alphaScale");
|
||||||
|
statements.Add(Expression.Assign(outA, Build(program.OutputA, context)));
|
||||||
|
statements.Add(Expression.Assign(alphaScale, Expression.Divide(ClampByte(outA), Constant(255d))));
|
||||||
|
statements.Add(WriteByte(buffer, index, 0, ClampByte(Expression.Multiply(Build(program.OutputB, context), alphaScale))));
|
||||||
|
statements.Add(WriteByte(buffer, index, 1, ClampByte(Expression.Multiply(Build(program.OutputG, context), alphaScale))));
|
||||||
|
statements.Add(WriteByte(buffer, index, 2, ClampByte(Expression.Multiply(Build(program.OutputR, context), alphaScale))));
|
||||||
|
statements.Add(WriteByte(buffer, index, 3, ClampByte(outA)));
|
||||||
|
statements.Add(Expression.PostIncrementAssign(x));
|
||||||
|
|
||||||
|
var breakLabel = Expression.Label("break");
|
||||||
|
var loop = Expression.Loop(
|
||||||
|
Expression.IfThenElse(
|
||||||
|
Expression.LessThan(x, xEnd),
|
||||||
|
Expression.Block(statements),
|
||||||
|
Expression.Break(breakLabel)),
|
||||||
|
breakLabel);
|
||||||
|
|
||||||
|
var locals = new List<ParameterExpression> { x, index, alphaRaw, transparent, scale, outA, alphaScale };
|
||||||
|
locals.AddRange(inputs);
|
||||||
|
locals.AddRange(slots);
|
||||||
|
|
||||||
|
var body = Expression.Block(locals, Expression.Assign(x, xStart), loop);
|
||||||
|
|
||||||
|
var lambda = Expression.Lambda<CpuKernel.RowDelegate>(body, buffer, rowBase, xStart, xEnd, y, uniforms);
|
||||||
|
return lambda.Compile();
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed record Context(
|
||||||
|
ParameterExpression X,
|
||||||
|
ParameterExpression Y,
|
||||||
|
ParameterExpression Uniforms,
|
||||||
|
ParameterExpression[] Inputs,
|
||||||
|
ParameterExpression[] Slots);
|
||||||
|
|
||||||
|
private static Expression Build(KExpr expression, Context context)
|
||||||
|
{
|
||||||
|
switch (expression)
|
||||||
|
{
|
||||||
|
case KConst value:
|
||||||
|
return Constant(value.Value);
|
||||||
|
case KInput input:
|
||||||
|
return context.Inputs[(int)input.Channel];
|
||||||
|
case KCoord coord:
|
||||||
|
return coord.Axis == KAxis.X ? ToDouble(context.X) : context.Y;
|
||||||
|
case KUniformRef uniform:
|
||||||
|
return Expression.ArrayIndex(context.Uniforms, Constant((int)uniform.Uniform));
|
||||||
|
case KLocalRef local:
|
||||||
|
return context.Slots[local.Slot];
|
||||||
|
case KNegate negate:
|
||||||
|
return Expression.Negate(Build(negate.Operand, context));
|
||||||
|
case KArith arithmetic:
|
||||||
|
return BuildArithmetic(arithmetic, context);
|
||||||
|
case KCall call:
|
||||||
|
return BuildCall(call, context);
|
||||||
|
case KSelect select:
|
||||||
|
return Select(BuildBool(select.Condition, context), Build(select.WhenTrue, context), Build(select.WhenFalse, context));
|
||||||
|
}
|
||||||
|
throw new KernelUnsupportedException("Unsupported CPU expression.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Expression BuildArithmetic(KArith arithmetic, Context context)
|
||||||
|
{
|
||||||
|
var left = Build(arithmetic.Left, context);
|
||||||
|
var right = Build(arithmetic.Right, context);
|
||||||
|
return arithmetic.Op switch
|
||||||
|
{
|
||||||
|
KArithOp.Add => Expression.Add(left, right),
|
||||||
|
KArithOp.Subtract => Expression.Subtract(left, right),
|
||||||
|
KArithOp.Multiply => Expression.Multiply(left, right),
|
||||||
|
KArithOp.Divide => Expression.Divide(left, right),
|
||||||
|
KArithOp.Modulo => FlooredModulo(left, right),
|
||||||
|
KArithOp.Power => Expression.Call(Pow, left, right),
|
||||||
|
_ => throw new KernelUnsupportedException("Unsupported arithmetic operator."),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Expression BuildCall(KCall call, Context context)
|
||||||
|
{
|
||||||
|
if (call.Func == KFunc.Fmod)
|
||||||
|
return Expression.Modulo(Build(call.Arguments[0], context), Build(call.Arguments[1], context));
|
||||||
|
var method = Functions[call.Func];
|
||||||
|
if (call.Arguments.Count == 1)
|
||||||
|
return Expression.Call(method, Build(call.Arguments[0], context));
|
||||||
|
return Expression.Call(method, Build(call.Arguments[0], context), Build(call.Arguments[1], context));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Expression BuildBool(KBool condition, Context context)
|
||||||
|
{
|
||||||
|
switch (condition)
|
||||||
|
{
|
||||||
|
case KBoolConst value:
|
||||||
|
return Expression.Constant(value.Value);
|
||||||
|
case KNot not:
|
||||||
|
return Expression.Not(BuildBool(not.Operand, context));
|
||||||
|
case KLogical logical:
|
||||||
|
return logical.IsAnd
|
||||||
|
? Expression.AndAlso(BuildBool(logical.Left, context), BuildBool(logical.Right, context))
|
||||||
|
: Expression.OrElse(BuildBool(logical.Left, context), BuildBool(logical.Right, context));
|
||||||
|
case KCompare compare:
|
||||||
|
var left = Build(compare.Left, context);
|
||||||
|
var right = Build(compare.Right, context);
|
||||||
|
return compare.Op switch
|
||||||
|
{
|
||||||
|
KCompareOp.Less => Expression.LessThan(left, right),
|
||||||
|
KCompareOp.Greater => Expression.GreaterThan(left, right),
|
||||||
|
KCompareOp.LessEqual => Expression.LessThanOrEqual(left, right),
|
||||||
|
KCompareOp.GreaterEqual => Expression.GreaterThanOrEqual(left, right),
|
||||||
|
KCompareOp.Equal => Expression.Equal(left, right),
|
||||||
|
KCompareOp.NotEqual => Expression.NotEqual(left, right),
|
||||||
|
_ => throw new KernelUnsupportedException("Unsupported comparison."),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
throw new KernelUnsupportedException("Unsupported CPU condition.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Expression FlooredModulo(Expression left, Expression right) =>
|
||||||
|
Expression.Subtract(left, Expression.Multiply(Expression.Call(Floor, Expression.Divide(left, right)), right));
|
||||||
|
|
||||||
|
private static Expression Select(Expression condition, Expression whenTrue, Expression whenFalse) =>
|
||||||
|
Expression.Condition(condition, whenTrue, whenFalse);
|
||||||
|
|
||||||
|
private static Expression ClampByte(Expression value) =>
|
||||||
|
Expression.Call(Clamp, value, Constant(0d), Constant(255d));
|
||||||
|
|
||||||
|
private static Expression ReadByte(ParameterExpression buffer, ParameterExpression index, int offset) =>
|
||||||
|
Expression.ArrayIndex(buffer, offset == 0 ? index : Expression.Add(index, Constant(offset)));
|
||||||
|
|
||||||
|
private static Expression WriteByte(ParameterExpression buffer, ParameterExpression index, int offset, Expression value) =>
|
||||||
|
Expression.Assign(
|
||||||
|
Expression.ArrayAccess(buffer, offset == 0 ? index : Expression.Add(index, Constant(offset))),
|
||||||
|
Expression.Convert(value, typeof(byte)));
|
||||||
|
|
||||||
|
private static Expression ToDouble(Expression value) => Expression.Convert(value, typeof(double));
|
||||||
|
|
||||||
|
private static ConstantExpression Constant(double value) => Expression.Constant(value, typeof(double));
|
||||||
|
|
||||||
|
private static ConstantExpression Constant(int value) => Expression.Constant(value, typeof(int));
|
||||||
|
|
||||||
|
private static MethodInfo Unary(string name) => typeof(Math).GetMethod(name, [typeof(double)])!;
|
||||||
|
|
||||||
|
private static MethodInfo Binary(string name) => typeof(Math).GetMethod(name, [typeof(double), typeof(double)])!;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,219 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal static class HlslKernelEmitter
|
||||||
|
{
|
||||||
|
public const int ConstantVectorCount = 16;
|
||||||
|
|
||||||
|
public const int ConstantFloatCount = ConstantVectorCount * 4;
|
||||||
|
|
||||||
|
public static string Emit(KernelProgram program)
|
||||||
|
{
|
||||||
|
var builder = new StringBuilder(1024);
|
||||||
|
|
||||||
|
builder.Append("Texture2D InputTexture : register(t0);\n");
|
||||||
|
builder.Append("SamplerState InputSampler : register(s0);\n");
|
||||||
|
builder.Append("cbuffer constants : register(b0)\n{\n");
|
||||||
|
builder.Append(" float4 uniforms[").Append(ConstantVectorCount).Append("];\n");
|
||||||
|
builder.Append("};\n\n");
|
||||||
|
builder.Append("float4 main(float4 pos : SV_POSITION, float4 posScene : SCENE_POSITION, float4 uv : TEXCOORD0) : SV_Target\n{\n");
|
||||||
|
builder.Append(" float4 src = InputTexture.Sample(InputSampler, uv.xy);\n");
|
||||||
|
builder.Append(" float srcA = src.a;\n");
|
||||||
|
builder.Append(" float invA = srcA <= 0.0 ? 0.0 : 1.0 / srcA;\n");
|
||||||
|
builder.Append(" float inR = clamp(src.r * invA * 255.0, 0.0, 255.0);\n");
|
||||||
|
builder.Append(" float inG = clamp(src.g * invA * 255.0, 0.0, 255.0);\n");
|
||||||
|
builder.Append(" float inB = clamp(src.b * invA * 255.0, 0.0, 255.0);\n");
|
||||||
|
builder.Append(" float inA = srcA * 255.0;\n");
|
||||||
|
builder.Append(" float px = uv.x * ").Append(Uniform(KernelUniform.Width)).Append(" - 0.5;\n");
|
||||||
|
builder.Append(" float py = uv.y * ").Append(Uniform(KernelUniform.Height)).Append(" - 0.5;\n");
|
||||||
|
|
||||||
|
for (int i = 0; i < program.Bindings.Count; i++)
|
||||||
|
{
|
||||||
|
builder.Append(" float slot").Append(i).Append(" = ");
|
||||||
|
EmitExpression(builder, program.Bindings[i]);
|
||||||
|
builder.Append(";\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
builder.Append(" float outA = clamp(");
|
||||||
|
EmitExpression(builder, program.OutputA);
|
||||||
|
builder.Append(", 0.0, 255.0);\n");
|
||||||
|
builder.Append(" float alphaK = outA / 255.0;\n");
|
||||||
|
|
||||||
|
builder.Append(" float oR = floor(clamp((");
|
||||||
|
EmitExpression(builder, program.OutputR);
|
||||||
|
builder.Append(") * alphaK, 0.0, 255.0)) / 255.0;\n");
|
||||||
|
builder.Append(" float oG = floor(clamp((");
|
||||||
|
EmitExpression(builder, program.OutputG);
|
||||||
|
builder.Append(") * alphaK, 0.0, 255.0)) / 255.0;\n");
|
||||||
|
builder.Append(" float oB = floor(clamp((");
|
||||||
|
EmitExpression(builder, program.OutputB);
|
||||||
|
builder.Append(") * alphaK, 0.0, 255.0)) / 255.0;\n");
|
||||||
|
builder.Append(" float oA = floor(outA) / 255.0;\n");
|
||||||
|
builder.Append(" return float4(oR, oG, oB, oA);\n}\n");
|
||||||
|
|
||||||
|
return builder.ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void EmitExpression(StringBuilder builder, KExpr expression)
|
||||||
|
{
|
||||||
|
switch (expression)
|
||||||
|
{
|
||||||
|
case KConst value:
|
||||||
|
builder.Append(Number(value.Value));
|
||||||
|
return;
|
||||||
|
case KInput input:
|
||||||
|
builder.Append(input.Channel switch
|
||||||
|
{
|
||||||
|
KChannel.R => "inR",
|
||||||
|
KChannel.G => "inG",
|
||||||
|
KChannel.B => "inB",
|
||||||
|
_ => "inA",
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
case KCoord coord:
|
||||||
|
builder.Append(coord.Axis == KAxis.X ? "px" : "py");
|
||||||
|
return;
|
||||||
|
case KUniformRef uniform:
|
||||||
|
builder.Append(Uniform(uniform.Uniform));
|
||||||
|
return;
|
||||||
|
case KLocalRef local:
|
||||||
|
builder.Append("slot").Append(local.Slot);
|
||||||
|
return;
|
||||||
|
case KNegate negate:
|
||||||
|
builder.Append("(-(");
|
||||||
|
EmitExpression(builder, negate.Operand);
|
||||||
|
builder.Append("))");
|
||||||
|
return;
|
||||||
|
case KArith arithmetic:
|
||||||
|
EmitArithmetic(builder, arithmetic);
|
||||||
|
return;
|
||||||
|
case KCall call:
|
||||||
|
EmitCall(builder, call);
|
||||||
|
return;
|
||||||
|
case KSelect select:
|
||||||
|
builder.Append('(');
|
||||||
|
EmitCondition(builder, select.Condition);
|
||||||
|
builder.Append(" ? (");
|
||||||
|
EmitExpression(builder, select.WhenTrue);
|
||||||
|
builder.Append(") : (");
|
||||||
|
EmitExpression(builder, select.WhenFalse);
|
||||||
|
builder.Append("))");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
throw new KernelUnsupportedException("Unsupported HLSL expression.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void EmitArithmetic(StringBuilder builder, KArith arithmetic)
|
||||||
|
{
|
||||||
|
if (arithmetic.Op == KArithOp.Power)
|
||||||
|
{
|
||||||
|
builder.Append("pow(");
|
||||||
|
EmitExpression(builder, arithmetic.Left);
|
||||||
|
builder.Append(", ");
|
||||||
|
EmitExpression(builder, arithmetic.Right);
|
||||||
|
builder.Append(')');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (arithmetic.Op == KArithOp.Modulo)
|
||||||
|
{
|
||||||
|
builder.Append('(');
|
||||||
|
EmitExpression(builder, arithmetic.Left);
|
||||||
|
builder.Append(" - floor((");
|
||||||
|
EmitExpression(builder, arithmetic.Left);
|
||||||
|
builder.Append(") / (");
|
||||||
|
EmitExpression(builder, arithmetic.Right);
|
||||||
|
builder.Append(")) * (");
|
||||||
|
EmitExpression(builder, arithmetic.Right);
|
||||||
|
builder.Append("))");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
builder.Append('(');
|
||||||
|
EmitExpression(builder, arithmetic.Left);
|
||||||
|
builder.Append(arithmetic.Op switch
|
||||||
|
{
|
||||||
|
KArithOp.Add => " + ",
|
||||||
|
KArithOp.Subtract => " - ",
|
||||||
|
KArithOp.Multiply => " * ",
|
||||||
|
KArithOp.Divide => " / ",
|
||||||
|
_ => throw new KernelUnsupportedException("Unsupported arithmetic operator."),
|
||||||
|
});
|
||||||
|
EmitExpression(builder, arithmetic.Right);
|
||||||
|
builder.Append(')');
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void EmitCall(StringBuilder builder, KCall call)
|
||||||
|
{
|
||||||
|
builder.Append(KFunctions.Intrinsic(call.Func)).Append('(');
|
||||||
|
for (int i = 0; i < call.Arguments.Count; i++)
|
||||||
|
{
|
||||||
|
if (i > 0)
|
||||||
|
builder.Append(", ");
|
||||||
|
EmitExpression(builder, call.Arguments[i]);
|
||||||
|
}
|
||||||
|
builder.Append(')');
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void EmitCondition(StringBuilder builder, KBool condition)
|
||||||
|
{
|
||||||
|
switch (condition)
|
||||||
|
{
|
||||||
|
case KBoolConst value:
|
||||||
|
builder.Append(value.Value ? "true" : "false");
|
||||||
|
return;
|
||||||
|
case KNot not:
|
||||||
|
builder.Append("(!(");
|
||||||
|
EmitCondition(builder, not.Operand);
|
||||||
|
builder.Append("))");
|
||||||
|
return;
|
||||||
|
case KLogical logical:
|
||||||
|
builder.Append('(');
|
||||||
|
EmitCondition(builder, logical.Left);
|
||||||
|
builder.Append(logical.IsAnd ? " && " : " || ");
|
||||||
|
EmitCondition(builder, logical.Right);
|
||||||
|
builder.Append(')');
|
||||||
|
return;
|
||||||
|
case KCompare compare:
|
||||||
|
builder.Append('(');
|
||||||
|
EmitExpression(builder, compare.Left);
|
||||||
|
builder.Append(compare.Op switch
|
||||||
|
{
|
||||||
|
KCompareOp.Less => " < ",
|
||||||
|
KCompareOp.Greater => " > ",
|
||||||
|
KCompareOp.LessEqual => " <= ",
|
||||||
|
KCompareOp.GreaterEqual => " >= ",
|
||||||
|
KCompareOp.Equal => " == ",
|
||||||
|
_ => " != ",
|
||||||
|
});
|
||||||
|
EmitExpression(builder, compare.Right);
|
||||||
|
builder.Append(')');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
throw new KernelUnsupportedException("Unsupported HLSL condition.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Uniform(KernelUniform uniform)
|
||||||
|
{
|
||||||
|
int index = (int)uniform;
|
||||||
|
return $"uniforms[{index / 4}].{"xyzw"[index % 4]}";
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Number(double value)
|
||||||
|
{
|
||||||
|
if (double.IsPositiveInfinity(value))
|
||||||
|
return "3.4028235e38";
|
||||||
|
if (double.IsNegativeInfinity(value))
|
||||||
|
return "-3.4028235e38";
|
||||||
|
if (double.IsNaN(value))
|
||||||
|
return "(0.0 / 0.0)";
|
||||||
|
|
||||||
|
string text = value.ToString("R", CultureInfo.InvariantCulture);
|
||||||
|
if (!text.Contains('.') && !text.Contains('e') && !text.Contains('E'))
|
||||||
|
text += ".0";
|
||||||
|
return text;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,615 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
|
||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal sealed class KernelExtractor
|
||||||
|
{
|
||||||
|
private readonly List<KExpr> _bindings = [];
|
||||||
|
private Dictionary<string, int> _scope = new(StringComparer.Ordinal);
|
||||||
|
private readonly SortedSet<KernelUniform> _uniforms = [];
|
||||||
|
|
||||||
|
private string _widthVariable = string.Empty;
|
||||||
|
private string _heightVariable = string.Empty;
|
||||||
|
private bool _coordsEnabled;
|
||||||
|
private string? _pixelDataVariable;
|
||||||
|
private string _baseIndexVariable = string.Empty;
|
||||||
|
private readonly bool[] _writtenChannels = new bool[4];
|
||||||
|
|
||||||
|
public static KernelProgram? TryExtract(string runnableScript)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return new KernelExtractor().Extract(runnableScript);
|
||||||
|
}
|
||||||
|
catch (KernelUnsupportedException)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private KernelProgram? Extract(string runnableScript)
|
||||||
|
{
|
||||||
|
var block = LuaParser.Parse(runnableScript);
|
||||||
|
|
||||||
|
int index = 0;
|
||||||
|
while (index < block.Count && block[index] is LocalStmt prelude)
|
||||||
|
{
|
||||||
|
if (TryBindPixelData(prelude))
|
||||||
|
{
|
||||||
|
index++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
BindLocal(prelude);
|
||||||
|
index++;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (index >= block.Count || block[index] is not NumericForStmt outer)
|
||||||
|
return null;
|
||||||
|
int tail = index + 1;
|
||||||
|
if (tail < block.Count && IsPutPixelData(block[tail]))
|
||||||
|
tail++;
|
||||||
|
if (tail != block.Count)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
if (!TryAxis(outer, out string outerVar, out KAxis outerAxis))
|
||||||
|
return null;
|
||||||
|
_scope.Remove(outerVar);
|
||||||
|
if (outer.Body.Count != 1 || outer.Body[0] is not NumericForStmt inner)
|
||||||
|
return null;
|
||||||
|
if (!TryAxis(inner, out string innerVar, out KAxis innerAxis))
|
||||||
|
return null;
|
||||||
|
_scope.Remove(innerVar);
|
||||||
|
if (outerAxis == innerAxis)
|
||||||
|
return null;
|
||||||
|
if (_pixelDataVariable is not null &&
|
||||||
|
(string.Equals(outerVar, _pixelDataVariable, StringComparison.Ordinal) ||
|
||||||
|
string.Equals(innerVar, _pixelDataVariable, StringComparison.Ordinal)))
|
||||||
|
return null;
|
||||||
|
|
||||||
|
_widthVariable = outerAxis == KAxis.X ? outerVar : innerVar;
|
||||||
|
_heightVariable = outerAxis == KAxis.Y ? outerVar : innerVar;
|
||||||
|
|
||||||
|
return _pixelDataVariable is null ? BuildKernel(inner.Body) : BuildPixelDataKernel(inner.Body);
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool IsPutPixelData(LuaStmt statement) =>
|
||||||
|
_pixelDataVariable is not null &&
|
||||||
|
statement is CallStmt { Call: CallExpr { Arguments.Count: 1 } call } &&
|
||||||
|
IsObjectMethod(call, "putpixeldata") &&
|
||||||
|
call.Arguments[0] is NameExpr { } handle &&
|
||||||
|
string.Equals(handle.Name, _pixelDataVariable, StringComparison.Ordinal);
|
||||||
|
|
||||||
|
private bool TryBindPixelData(LocalStmt local)
|
||||||
|
{
|
||||||
|
if (local.Names.Count != 1 || local.Values.Count != 1 ||
|
||||||
|
local.Values[0] is not CallExpr { Target: MemberExpr { Target: NameExpr { Name: "obj" }, Name: "getpixeldata" }, Arguments.Count: 0 })
|
||||||
|
return false;
|
||||||
|
if (_pixelDataVariable is not null)
|
||||||
|
throw new KernelUnsupportedException("Multiple pixel-data handles are not supported.");
|
||||||
|
_pixelDataVariable = local.Names[0];
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private KernelProgram? BuildPixelDataKernel(IReadOnlyList<LuaStmt> body)
|
||||||
|
{
|
||||||
|
if (body.Count < 5)
|
||||||
|
return null;
|
||||||
|
if (body[0] is not LocalStmt { Names.Count: 1, Values.Count: 1 } baseStmt || !IsBaseIndex(baseStmt.Values[0]))
|
||||||
|
return null;
|
||||||
|
|
||||||
|
EnsureNotCoordinateName(baseStmt.Names[0]);
|
||||||
|
_baseIndexVariable = baseStmt.Names[0];
|
||||||
|
_coordsEnabled = true;
|
||||||
|
|
||||||
|
KExpr? outR = null, outG = null, outB = null;
|
||||||
|
for (int i = 1; i < body.Count; i++)
|
||||||
|
{
|
||||||
|
switch (body[i])
|
||||||
|
{
|
||||||
|
case LocalStmt local:
|
||||||
|
BindLocal(local);
|
||||||
|
break;
|
||||||
|
case AssignStmt assign:
|
||||||
|
BindAssign(assign);
|
||||||
|
break;
|
||||||
|
case IfStmt conditional:
|
||||||
|
LowerConditional(conditional);
|
||||||
|
break;
|
||||||
|
case CallStmt { Call: MethodCallExpr set } when IsPixelDataSet(set, out int writeChannel):
|
||||||
|
var value = ClampChannel(Lower(set.Arguments[1]));
|
||||||
|
if (writeChannel == 0) outR = value;
|
||||||
|
else if (writeChannel == 1) outG = value;
|
||||||
|
else outB = value;
|
||||||
|
_writtenChannels[writeChannel] = true;
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (outR is null || outG is null || outB is null)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
return new KernelProgram(_bindings, outR, outG, outB, new KInput(KChannel.A), [.. _uniforms]);
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool IsBaseIndex(LuaExpr expression)
|
||||||
|
{
|
||||||
|
if (expression is not BinaryExpr { Operator: "*", Right: NumberExpr { Value: 4d } } scaled ||
|
||||||
|
scaled.Left is not BinaryExpr { Operator: "+" } sum)
|
||||||
|
return false;
|
||||||
|
if (!IsCoordinate(sum.Right, KAxis.X))
|
||||||
|
return false;
|
||||||
|
if (sum.Left is not BinaryExpr { Operator: "*" } stride)
|
||||||
|
return false;
|
||||||
|
return IsCoordinate(stride.Left, KAxis.Y) && IsWidth(stride.Right);
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool IsWidth(LuaExpr expression)
|
||||||
|
{
|
||||||
|
if (expression is MemberExpr { Target: NameExpr { Name: "obj" }, Name: var field } &&
|
||||||
|
KernelUniforms.TryResolveMember("obj", field, out var uniform))
|
||||||
|
return uniform == KernelUniform.Width;
|
||||||
|
if (expression is NameExpr { } alias &&
|
||||||
|
TryUniformAlias(alias.Name, out var aliased))
|
||||||
|
return aliased == KernelUniform.Width;
|
||||||
|
return _pixelDataVariable is not null &&
|
||||||
|
expression is MemberExpr { Target: NameExpr { } target, Name: "width" } &&
|
||||||
|
string.Equals(target.Name, _pixelDataVariable, StringComparison.Ordinal);
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool TryUniformAlias(string name, out KernelUniform uniform)
|
||||||
|
{
|
||||||
|
if (_scope.TryGetValue(name, out int slot) && _bindings[slot] is KUniformRef reference)
|
||||||
|
{
|
||||||
|
uniform = reference.Uniform;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
uniform = default;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool TryPixelDataChannel(LuaExpr expression, out int channel)
|
||||||
|
{
|
||||||
|
channel = 0;
|
||||||
|
if (expression is not MethodCallExpr { Method: "get", Arguments.Count: 1 } call ||
|
||||||
|
call.Target is not NameExpr { } handle ||
|
||||||
|
!string.Equals(handle.Name, _pixelDataVariable, StringComparison.Ordinal))
|
||||||
|
return false;
|
||||||
|
if (!TryChannelOffset(call.Arguments[0], 1, 4, out channel))
|
||||||
|
return false;
|
||||||
|
channel--;
|
||||||
|
return !_writtenChannels[channel];
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool IsPixelDataSet(MethodCallExpr call, out int channel)
|
||||||
|
{
|
||||||
|
channel = 0;
|
||||||
|
if (call.Method != "set" || call.Arguments.Count != 2 ||
|
||||||
|
call.Target is not NameExpr { } handle ||
|
||||||
|
!string.Equals(handle.Name, _pixelDataVariable, StringComparison.Ordinal))
|
||||||
|
return false;
|
||||||
|
if (!TryChannelOffset(call.Arguments[0], 1, 3, out channel))
|
||||||
|
return false;
|
||||||
|
channel--;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private KExpr ClampChannel(KExpr value)
|
||||||
|
{
|
||||||
|
var bound = new KLocalRef(AddBinding(value));
|
||||||
|
return new KSelect(
|
||||||
|
new KCompare(KCompareOp.Less, bound, new KConst(0d)),
|
||||||
|
new KConst(0d),
|
||||||
|
new KSelect(
|
||||||
|
new KCompare(KCompareOp.Greater, bound, new KConst(255d)),
|
||||||
|
new KConst(255d),
|
||||||
|
bound));
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool TryChannelOffset(LuaExpr expression, int min, int max, out int offset)
|
||||||
|
{
|
||||||
|
offset = 0;
|
||||||
|
if (expression is not BinaryExpr { Operator: "+", Left: NameExpr baseName, Right: NumberExpr number } ||
|
||||||
|
!string.Equals(baseName.Name, _baseIndexVariable, StringComparison.Ordinal))
|
||||||
|
return false;
|
||||||
|
offset = (int)number.Value;
|
||||||
|
return offset == number.Value && offset >= min && offset <= max;
|
||||||
|
}
|
||||||
|
|
||||||
|
private KernelProgram? BuildKernel(IReadOnlyList<LuaStmt> body)
|
||||||
|
{
|
||||||
|
if (body.Count < 2)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
if (body[0] is not LocalStmt sample || sample.Values.Count != 1 ||
|
||||||
|
!IsGetPixel(sample.Values[0]))
|
||||||
|
return null;
|
||||||
|
if (sample.Names.Count is < 1 or > 4)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
_coordsEnabled = true;
|
||||||
|
for (int i = 0; i < sample.Names.Count; i++)
|
||||||
|
{
|
||||||
|
EnsureNotCoordinateName(sample.Names[i]);
|
||||||
|
_scope[sample.Names[i]] = AddBinding(new KInput((KChannel)i));
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int i = 1; i < body.Count - 1; i++)
|
||||||
|
{
|
||||||
|
switch (body[i])
|
||||||
|
{
|
||||||
|
case LocalStmt local:
|
||||||
|
BindLocal(local);
|
||||||
|
break;
|
||||||
|
case AssignStmt assign:
|
||||||
|
BindAssign(assign);
|
||||||
|
break;
|
||||||
|
case IfStmt conditional:
|
||||||
|
LowerConditional(conditional);
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (body[^1] is not CallStmt { Call: CallExpr call } || !IsObjectMethod(call, "setpixel"))
|
||||||
|
return null;
|
||||||
|
if (call.Arguments.Count is < 5 or > 6)
|
||||||
|
return null;
|
||||||
|
if (!IsCoordinate(call.Arguments[0], KAxis.X) || !IsCoordinate(call.Arguments[1], KAxis.Y))
|
||||||
|
return null;
|
||||||
|
|
||||||
|
var outR = Lower(call.Arguments[2]);
|
||||||
|
var outG = Lower(call.Arguments[3]);
|
||||||
|
var outB = Lower(call.Arguments[4]);
|
||||||
|
var outA = call.Arguments.Count == 6 ? Lower(call.Arguments[5]) : new KConst(255d);
|
||||||
|
|
||||||
|
return new KernelProgram(_bindings, outR, outG, outB, outA, [.. _uniforms]);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void BindLocal(LocalStmt local)
|
||||||
|
{
|
||||||
|
if (local.Values.Count == 1 && IsGetPixel(local.Values[0]))
|
||||||
|
throw new KernelUnsupportedException("Unexpected pixel sample.");
|
||||||
|
if (local.Names.Count != local.Values.Count)
|
||||||
|
throw new KernelUnsupportedException("Multiple-value assignment is not supported.");
|
||||||
|
|
||||||
|
var lowered = new KExpr[local.Values.Count];
|
||||||
|
for (int i = 0; i < local.Values.Count; i++)
|
||||||
|
lowered[i] = Lower(local.Values[i]);
|
||||||
|
for (int i = 0; i < local.Names.Count; i++)
|
||||||
|
{
|
||||||
|
EnsureNotCoordinateName(local.Names[i]);
|
||||||
|
_scope[local.Names[i]] = AddBinding(lowered[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void BindAssign(AssignStmt assign)
|
||||||
|
{
|
||||||
|
if (assign.Targets.Count != assign.Values.Count)
|
||||||
|
throw new KernelUnsupportedException("Unbalanced assignment is not supported.");
|
||||||
|
|
||||||
|
foreach (var target in assign.Targets)
|
||||||
|
{
|
||||||
|
if (target is not NameExpr name || !_scope.ContainsKey(name.Name))
|
||||||
|
throw new KernelUnsupportedException("Assignment target must be a local variable.");
|
||||||
|
}
|
||||||
|
|
||||||
|
var lowered = new KExpr[assign.Values.Count];
|
||||||
|
for (int i = 0; i < assign.Values.Count; i++)
|
||||||
|
lowered[i] = Lower(assign.Values[i]);
|
||||||
|
for (int i = 0; i < assign.Targets.Count; i++)
|
||||||
|
_scope[((NameExpr)assign.Targets[i]).Name] = AddBinding(lowered[i]);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void LowerConditional(IfStmt statement) =>
|
||||||
|
LowerConditional(statement.Clauses, 0, statement.ElseBody);
|
||||||
|
|
||||||
|
private void LowerConditional(IReadOnlyList<IfClause> clauses, int index, IReadOnlyList<LuaStmt>? elseBody)
|
||||||
|
{
|
||||||
|
var clause = clauses[index];
|
||||||
|
var condition = LowerBool(clause.Condition);
|
||||||
|
var baseline = _scope;
|
||||||
|
|
||||||
|
_scope = new Dictionary<string, int>(baseline, StringComparer.Ordinal);
|
||||||
|
LowerBranchBody(clause.Body);
|
||||||
|
var taken = _scope;
|
||||||
|
|
||||||
|
_scope = new Dictionary<string, int>(baseline, StringComparer.Ordinal);
|
||||||
|
if (index + 1 < clauses.Count)
|
||||||
|
LowerConditional(clauses, index + 1, elseBody);
|
||||||
|
else if (elseBody is not null)
|
||||||
|
LowerBranchBody(elseBody);
|
||||||
|
var skipped = _scope;
|
||||||
|
|
||||||
|
var merged = new Dictionary<string, int>(baseline.Count, StringComparer.Ordinal);
|
||||||
|
foreach (var name in baseline.Keys)
|
||||||
|
{
|
||||||
|
int whenTrue = taken[name];
|
||||||
|
int whenFalse = skipped[name];
|
||||||
|
merged[name] = whenTrue == whenFalse
|
||||||
|
? whenTrue
|
||||||
|
: AddBinding(new KSelect(condition, new KLocalRef(whenTrue), new KLocalRef(whenFalse)));
|
||||||
|
}
|
||||||
|
_scope = merged;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void LowerBranchBody(IReadOnlyList<LuaStmt> body)
|
||||||
|
{
|
||||||
|
Dictionary<string, int>? shadowed = null;
|
||||||
|
HashSet<string>? introduced = null;
|
||||||
|
foreach (var statement in body)
|
||||||
|
{
|
||||||
|
switch (statement)
|
||||||
|
{
|
||||||
|
case LocalStmt local:
|
||||||
|
foreach (var name in local.Names)
|
||||||
|
{
|
||||||
|
if (introduced?.Contains(name) == true || shadowed?.ContainsKey(name) == true)
|
||||||
|
continue;
|
||||||
|
if (_scope.TryGetValue(name, out int slot))
|
||||||
|
(shadowed ??= new(StringComparer.Ordinal))[name] = slot;
|
||||||
|
else
|
||||||
|
(introduced ??= new(StringComparer.Ordinal)).Add(name);
|
||||||
|
}
|
||||||
|
BindLocal(local);
|
||||||
|
break;
|
||||||
|
case AssignStmt assign:
|
||||||
|
BindAssign(assign);
|
||||||
|
break;
|
||||||
|
case IfStmt nested:
|
||||||
|
LowerConditional(nested);
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
throw new KernelUnsupportedException("Unsupported statement in a conditional branch.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (shadowed is not null)
|
||||||
|
foreach (var (name, slot) in shadowed)
|
||||||
|
_scope[name] = slot;
|
||||||
|
if (introduced is not null)
|
||||||
|
foreach (var name in introduced)
|
||||||
|
_scope.Remove(name);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void EnsureNotCoordinateName(string name)
|
||||||
|
{
|
||||||
|
if (string.Equals(name, _widthVariable, StringComparison.Ordinal) ||
|
||||||
|
string.Equals(name, _heightVariable, StringComparison.Ordinal))
|
||||||
|
throw new KernelUnsupportedException("Local variable shadows a loop coordinate.");
|
||||||
|
if (_pixelDataVariable is not null && string.Equals(name, _pixelDataVariable, StringComparison.Ordinal))
|
||||||
|
throw new KernelUnsupportedException("Local variable shadows the pixel-data handle.");
|
||||||
|
if (_baseIndexVariable.Length > 0 && string.Equals(name, _baseIndexVariable, StringComparison.Ordinal))
|
||||||
|
throw new KernelUnsupportedException("Local variable shadows the base index.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private int AddBinding(KExpr expression)
|
||||||
|
{
|
||||||
|
_bindings.Add(expression);
|
||||||
|
return _bindings.Count - 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
private KExpr Lower(LuaExpr expression)
|
||||||
|
{
|
||||||
|
switch (expression)
|
||||||
|
{
|
||||||
|
case NumberExpr number:
|
||||||
|
return new KConst(number.Value);
|
||||||
|
case NameExpr name:
|
||||||
|
return LowerName(name.Name);
|
||||||
|
case MemberExpr member:
|
||||||
|
return LowerMember(member);
|
||||||
|
case CallExpr call:
|
||||||
|
return LowerCall(call);
|
||||||
|
case MethodCallExpr method when TryPixelDataChannel(method, out int channel):
|
||||||
|
return new KInput((KChannel)channel);
|
||||||
|
case UnaryExpr { Operator: "-" } unary:
|
||||||
|
return new KNegate(Lower(unary.Operand));
|
||||||
|
case BinaryExpr binary:
|
||||||
|
return LowerBinary(binary);
|
||||||
|
}
|
||||||
|
throw new KernelUnsupportedException("Unsupported expression in pixel kernel.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private KExpr LowerName(string name)
|
||||||
|
{
|
||||||
|
if (_scope.TryGetValue(name, out int slot))
|
||||||
|
return new KLocalRef(slot);
|
||||||
|
if (_coordsEnabled && string.Equals(name, _widthVariable, StringComparison.Ordinal))
|
||||||
|
return new KCoord(KAxis.X);
|
||||||
|
if (_coordsEnabled && string.Equals(name, _heightVariable, StringComparison.Ordinal))
|
||||||
|
return new KCoord(KAxis.Y);
|
||||||
|
if (KernelUniforms.TryResolveGlobal(name, out var uniform))
|
||||||
|
return UseUniform(uniform);
|
||||||
|
throw new KernelUnsupportedException($"Unknown identifier '{name}'.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private KExpr LowerMember(MemberExpr member)
|
||||||
|
{
|
||||||
|
if (member.Target is NameExpr { Name: "math" })
|
||||||
|
{
|
||||||
|
return member.Name switch
|
||||||
|
{
|
||||||
|
"pi" => new KConst(Math.PI),
|
||||||
|
"huge" => new KConst(double.PositiveInfinity),
|
||||||
|
_ => throw new KernelUnsupportedException($"Unsupported math field '{member.Name}'."),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (member.Target is NameExpr target && KernelUniforms.TryResolveMember(target.Name, member.Name, out var uniform))
|
||||||
|
return UseUniform(uniform);
|
||||||
|
|
||||||
|
if (_pixelDataVariable is not null &&
|
||||||
|
member.Target is NameExpr { } handle &&
|
||||||
|
string.Equals(handle.Name, _pixelDataVariable, StringComparison.Ordinal))
|
||||||
|
{
|
||||||
|
if (string.Equals(member.Name, "width", StringComparison.Ordinal))
|
||||||
|
return UseUniform(KernelUniform.Width);
|
||||||
|
if (string.Equals(member.Name, "height", StringComparison.Ordinal))
|
||||||
|
return UseUniform(KernelUniform.Height);
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new KernelUnsupportedException("Unsupported member access in pixel kernel.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private KExpr LowerCall(CallExpr call)
|
||||||
|
{
|
||||||
|
if (call.Target is not MemberExpr { Target: NameExpr { Name: "math" }, Name: var function } ||
|
||||||
|
!KFunctions.TryResolve(function, out var spec))
|
||||||
|
throw new KernelUnsupportedException("Unsupported function call in pixel kernel.");
|
||||||
|
|
||||||
|
int count = call.Arguments.Count;
|
||||||
|
if (count < spec.MinArgs || count > spec.MaxArgs)
|
||||||
|
throw new KernelUnsupportedException($"Wrong argument count for 'math.{function}'.");
|
||||||
|
|
||||||
|
var arguments = new KExpr[count];
|
||||||
|
for (int i = 0; i < count; i++)
|
||||||
|
arguments[i] = Lower(call.Arguments[i]);
|
||||||
|
|
||||||
|
if (spec.Func is KFunc.Min or KFunc.Max)
|
||||||
|
{
|
||||||
|
var folded = arguments[0];
|
||||||
|
for (int i = 1; i < count; i++)
|
||||||
|
folded = new KCall(spec.Func, [folded, arguments[i]]);
|
||||||
|
return folded;
|
||||||
|
}
|
||||||
|
|
||||||
|
return new KCall(spec.Func, arguments);
|
||||||
|
}
|
||||||
|
|
||||||
|
private KExpr LowerBinary(BinaryExpr binary)
|
||||||
|
{
|
||||||
|
switch (binary.Operator)
|
||||||
|
{
|
||||||
|
case "+": return new KArith(KArithOp.Add, Lower(binary.Left), Lower(binary.Right));
|
||||||
|
case "-": return new KArith(KArithOp.Subtract, Lower(binary.Left), Lower(binary.Right));
|
||||||
|
case "*": return new KArith(KArithOp.Multiply, Lower(binary.Left), Lower(binary.Right));
|
||||||
|
case "/": return new KArith(KArithOp.Divide, Lower(binary.Left), Lower(binary.Right));
|
||||||
|
case "%": return new KArith(KArithOp.Modulo, Lower(binary.Left), Lower(binary.Right));
|
||||||
|
case "^": return new KArith(KArithOp.Power, Lower(binary.Left), Lower(binary.Right));
|
||||||
|
case "or" when binary.Left is BinaryExpr { Operator: "and" } conditional:
|
||||||
|
return new KSelect(LowerBool(conditional.Left), Lower(conditional.Right), Lower(binary.Right));
|
||||||
|
}
|
||||||
|
throw new KernelUnsupportedException($"Unsupported operator '{binary.Operator}' in value position.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private KBool LowerBool(LuaExpr expression)
|
||||||
|
{
|
||||||
|
switch (expression)
|
||||||
|
{
|
||||||
|
case BoolExpr boolean:
|
||||||
|
return new KBoolConst(boolean.Value);
|
||||||
|
case UnaryExpr { Operator: "not" } unary:
|
||||||
|
return new KNot(LowerBool(unary.Operand));
|
||||||
|
case BinaryExpr { Operator: "and" } conjunction:
|
||||||
|
return new KLogical(true, LowerBool(conjunction.Left), LowerBool(conjunction.Right));
|
||||||
|
case BinaryExpr { Operator: "or" } disjunction:
|
||||||
|
return new KLogical(false, LowerBool(disjunction.Left), LowerBool(disjunction.Right));
|
||||||
|
case BinaryExpr binary when TryCompareOp(binary.Operator, out var op):
|
||||||
|
return new KCompare(op, Lower(binary.Left), Lower(binary.Right));
|
||||||
|
case NameExpr name when IsCheck(LowerName(name.Name)):
|
||||||
|
return new KCompare(KCompareOp.NotEqual, LowerName(name.Name), new KConst(0d));
|
||||||
|
case MemberExpr member when IsCheck(LowerMember(member)):
|
||||||
|
return new KCompare(KCompareOp.NotEqual, LowerMember(member), new KConst(0d));
|
||||||
|
}
|
||||||
|
throw new KernelUnsupportedException("Unsupported condition in pixel kernel.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool IsCheck(KExpr expression) =>
|
||||||
|
expression is KUniformRef { Uniform: KernelUniform.Check0 or KernelUniform.Check1 or KernelUniform.Check2 or KernelUniform.Check3 };
|
||||||
|
|
||||||
|
private static bool TryCompareOp(string symbol, out KCompareOp op)
|
||||||
|
{
|
||||||
|
switch (symbol)
|
||||||
|
{
|
||||||
|
case "<": op = KCompareOp.Less; return true;
|
||||||
|
case ">": op = KCompareOp.Greater; return true;
|
||||||
|
case "<=": op = KCompareOp.LessEqual; return true;
|
||||||
|
case ">=": op = KCompareOp.GreaterEqual; return true;
|
||||||
|
case "==": op = KCompareOp.Equal; return true;
|
||||||
|
case "~=": op = KCompareOp.NotEqual; return true;
|
||||||
|
default: op = default; return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private KExpr UseUniform(KernelUniform uniform)
|
||||||
|
{
|
||||||
|
_uniforms.Add(uniform);
|
||||||
|
return new KUniformRef(uniform);
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool TryAxis(NumericForStmt loop, out string variable, out KAxis axis)
|
||||||
|
{
|
||||||
|
variable = loop.Variable;
|
||||||
|
axis = default;
|
||||||
|
|
||||||
|
if (loop.Start is not NumberExpr { Value: 0d })
|
||||||
|
return false;
|
||||||
|
if (loop.Step is not null && loop.Step is not NumberExpr { Value: 1d })
|
||||||
|
return false;
|
||||||
|
if (loop.Stop is not BinaryExpr { Operator: "-", Right: NumberExpr { Value: 1d } } bound)
|
||||||
|
return false;
|
||||||
|
if (bound.Left is MemberExpr { Target: NameExpr { Name: "obj" }, Name: var field } &&
|
||||||
|
KernelUniforms.TryResolveMember("obj", field, out var uniform))
|
||||||
|
{
|
||||||
|
if (uniform == KernelUniform.Width)
|
||||||
|
{
|
||||||
|
axis = KAxis.X;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (uniform == KernelUniform.Height)
|
||||||
|
{
|
||||||
|
axis = KAxis.Y;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_pixelDataVariable is not null &&
|
||||||
|
bound.Left is MemberExpr { Target: NameExpr { } handle, Name: var pixelField } &&
|
||||||
|
string.Equals(handle.Name, _pixelDataVariable, StringComparison.Ordinal))
|
||||||
|
{
|
||||||
|
if (pixelField == "width")
|
||||||
|
{
|
||||||
|
axis = KAxis.X;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (pixelField == "height")
|
||||||
|
{
|
||||||
|
axis = KAxis.Y;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (bound.Left is NameExpr { } alias && TryUniformAlias(alias.Name, out var aliased))
|
||||||
|
{
|
||||||
|
if (aliased == KernelUniform.Width)
|
||||||
|
{
|
||||||
|
axis = KAxis.X;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (aliased == KernelUniform.Height)
|
||||||
|
{
|
||||||
|
axis = KAxis.Y;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool IsGetPixel(LuaExpr expression) =>
|
||||||
|
expression is CallExpr call && IsObjectMethod(call, "getpixel") &&
|
||||||
|
call.Arguments.Count == 2 &&
|
||||||
|
IsCoordinate(call.Arguments[0], KAxis.X) && IsCoordinate(call.Arguments[1], KAxis.Y);
|
||||||
|
|
||||||
|
private bool IsCoordinate(LuaExpr expression, KAxis axis) =>
|
||||||
|
expression is NameExpr name &&
|
||||||
|
string.Equals(name.Name, axis == KAxis.X ? _widthVariable : _heightVariable, StringComparison.Ordinal);
|
||||||
|
|
||||||
|
private static bool IsObjectMethod(CallExpr call, string method) =>
|
||||||
|
call.Target is MemberExpr { Target: NameExpr { Name: "obj" }, Name: var name } &&
|
||||||
|
string.Equals(name, method, StringComparison.Ordinal);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal sealed class KernelUnsupportedException(string reason) : Exception(reason);
|
||||||
|
}
|
||||||
@@ -0,0 +1,270 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Linq.Expressions;
|
||||||
|
using System.Reflection;
|
||||||
|
using System.Runtime.Intrinsics;
|
||||||
|
|
||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal static class SimdKernelCompiler
|
||||||
|
{
|
||||||
|
private static readonly Type Vec = typeof(Vector256<double>);
|
||||||
|
|
||||||
|
private static readonly MethodInfo Broadcast = typeof(Vector256).GetMethod(nameof(Vector256.Create), [typeof(double)])!;
|
||||||
|
private static readonly MethodInfo Create4 = typeof(Vector256).GetMethod(nameof(Vector256.Create), [typeof(double), typeof(double), typeof(double), typeof(double)])!;
|
||||||
|
private static readonly MethodInfo GetElement = VecOp(nameof(Vector256.GetElement), 1, 1);
|
||||||
|
private static readonly MethodInfo Add = VecOp(nameof(Vector256.Add), 2);
|
||||||
|
private static readonly MethodInfo Subtract = VecOp(nameof(Vector256.Subtract), 2);
|
||||||
|
private static readonly MethodInfo Multiply = VecOp(nameof(Vector256.Multiply), 2);
|
||||||
|
private static readonly MethodInfo Divide = VecOp(nameof(Vector256.Divide), 2);
|
||||||
|
private static readonly MethodInfo Negate = VecOp(nameof(Vector256.Negate), 1);
|
||||||
|
private static readonly MethodInfo Abs = VecOp(nameof(Vector256.Abs), 1);
|
||||||
|
private static readonly MethodInfo Sqrt = VecOp(nameof(Vector256.Sqrt), 1);
|
||||||
|
private static readonly MethodInfo FloorFn = typeof(Vector256).GetMethod(nameof(Vector256.Floor), [Vec])!;
|
||||||
|
private static readonly MethodInfo CeilingFn = typeof(Vector256).GetMethod(nameof(Vector256.Ceiling), [Vec])!;
|
||||||
|
private static readonly MethodInfo ConditionalSelect = VecOp(nameof(Vector256.ConditionalSelect), 3);
|
||||||
|
private static readonly MethodInfo LessThan = VecOp(nameof(Vector256.LessThan), 2);
|
||||||
|
private static readonly MethodInfo GreaterThan = VecOp(nameof(Vector256.GreaterThan), 2);
|
||||||
|
private static readonly MethodInfo LessThanOrEqual = VecOp(nameof(Vector256.LessThanOrEqual), 2);
|
||||||
|
private static readonly MethodInfo GreaterThanOrEqual = VecOp(nameof(Vector256.GreaterThanOrEqual), 2);
|
||||||
|
private static readonly MethodInfo EqualsFn = VecOp(nameof(Vector256.Equals), 2);
|
||||||
|
private static readonly MethodInfo BitwiseAnd = VecOp(nameof(Vector256.BitwiseAnd), 2);
|
||||||
|
private static readonly MethodInfo BitwiseOr = VecOp(nameof(Vector256.BitwiseOr), 2);
|
||||||
|
private static readonly MethodInfo OnesComplement = VecOp(nameof(Vector256.OnesComplement), 1);
|
||||||
|
|
||||||
|
private static readonly Expression Zero = Expression.Constant(Vector256<double>.Zero, Vec);
|
||||||
|
private static readonly Expression AllBits = Expression.Constant(Vector256<double>.AllBitsSet, Vec);
|
||||||
|
private static readonly Expression V255 = Expression.Constant(Vector256.Create(255d), Vec);
|
||||||
|
|
||||||
|
public static CpuKernel.RowDelegate? TryCompile(KernelProgram program)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return Compile(program);
|
||||||
|
}
|
||||||
|
catch (KernelUnsupportedException)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static CpuKernel.RowDelegate Compile(KernelProgram program)
|
||||||
|
{
|
||||||
|
var buffer = Expression.Parameter(typeof(byte[]), "buffer");
|
||||||
|
var rowBase = Expression.Parameter(typeof(int), "rowBase");
|
||||||
|
var xStart = Expression.Parameter(typeof(int), "xStart");
|
||||||
|
var xEnd = Expression.Parameter(typeof(int), "xEnd");
|
||||||
|
var yScalar = Expression.Parameter(typeof(double), "y");
|
||||||
|
var uniforms = Expression.Parameter(typeof(double[]), "uniforms");
|
||||||
|
|
||||||
|
var x = Expression.Variable(typeof(int), "x");
|
||||||
|
var index = Expression.Variable(typeof(int), "index");
|
||||||
|
var yVec = Expression.Variable(Vec, "yVec");
|
||||||
|
var xVec = Expression.Variable(Vec, "xVec");
|
||||||
|
var alphaRaw = Expression.Variable(Vec, "alphaRaw");
|
||||||
|
var transparent = Expression.Variable(Vec, "transparent");
|
||||||
|
var scale = Expression.Variable(Vec, "scale");
|
||||||
|
var inputs = new[]
|
||||||
|
{
|
||||||
|
Expression.Variable(Vec, "inR"),
|
||||||
|
Expression.Variable(Vec, "inG"),
|
||||||
|
Expression.Variable(Vec, "inB"),
|
||||||
|
Expression.Variable(Vec, "inA"),
|
||||||
|
};
|
||||||
|
var slots = new ParameterExpression[program.Bindings.Count];
|
||||||
|
for (int i = 0; i < slots.Length; i++)
|
||||||
|
slots[i] = Expression.Variable(Vec, "slot" + i);
|
||||||
|
|
||||||
|
var context = new Context(xVec, yVec, uniforms, inputs, slots);
|
||||||
|
|
||||||
|
var statements = new List<Expression>
|
||||||
|
{
|
||||||
|
Expression.Assign(index, Expression.Add(rowBase, Expression.Multiply(x, Constant(4)))),
|
||||||
|
Expression.Assign(xVec, Expression.Call(Create4,
|
||||||
|
ToDouble(x),
|
||||||
|
ToDouble(Expression.Add(x, Constant(1))),
|
||||||
|
ToDouble(Expression.Add(x, Constant(2))),
|
||||||
|
ToDouble(Expression.Add(x, Constant(3))))),
|
||||||
|
Expression.Assign(alphaRaw, LoadChannel(buffer, index, 3)),
|
||||||
|
Expression.Assign(transparent, Call(LessThanOrEqual, alphaRaw, Zero)),
|
||||||
|
Expression.Assign(scale, Select(transparent, Zero, Call(Divide, V255, alphaRaw))),
|
||||||
|
Expression.Assign(inputs[3], Select(transparent, Zero, alphaRaw)),
|
||||||
|
Expression.Assign(inputs[0], Select(transparent, Zero, ClampByte(Call(Multiply, LoadChannel(buffer, index, 2), scale)))),
|
||||||
|
Expression.Assign(inputs[1], Select(transparent, Zero, ClampByte(Call(Multiply, LoadChannel(buffer, index, 1), scale)))),
|
||||||
|
Expression.Assign(inputs[2], Select(transparent, Zero, ClampByte(Call(Multiply, LoadChannel(buffer, index, 0), scale)))),
|
||||||
|
};
|
||||||
|
|
||||||
|
for (int i = 0; i < slots.Length; i++)
|
||||||
|
statements.Add(Expression.Assign(slots[i], Build(program.Bindings[i], context)));
|
||||||
|
|
||||||
|
var outA = Expression.Variable(Vec, "outA");
|
||||||
|
var alphaScale = Expression.Variable(Vec, "alphaScale");
|
||||||
|
statements.Add(Expression.Assign(outA, Build(program.OutputA, context)));
|
||||||
|
statements.Add(Expression.Assign(alphaScale, Call(Divide, ClampByte(outA), V255)));
|
||||||
|
statements.Add(StoreChannel(buffer, index, 0, ClampByte(Call(Multiply, Build(program.OutputB, context), alphaScale))));
|
||||||
|
statements.Add(StoreChannel(buffer, index, 1, ClampByte(Call(Multiply, Build(program.OutputG, context), alphaScale))));
|
||||||
|
statements.Add(StoreChannel(buffer, index, 2, ClampByte(Call(Multiply, Build(program.OutputR, context), alphaScale))));
|
||||||
|
statements.Add(StoreChannel(buffer, index, 3, ClampByte(outA)));
|
||||||
|
statements.Add(Expression.AddAssign(x, Constant(4)));
|
||||||
|
|
||||||
|
var breakLabel = Expression.Label("break");
|
||||||
|
var loop = Expression.Loop(
|
||||||
|
Expression.IfThenElse(
|
||||||
|
Expression.LessThan(x, xEnd),
|
||||||
|
Expression.Block(statements),
|
||||||
|
Expression.Break(breakLabel)),
|
||||||
|
breakLabel);
|
||||||
|
|
||||||
|
var locals = new List<ParameterExpression> { x, index, yVec, xVec, alphaRaw, transparent, scale, outA, alphaScale };
|
||||||
|
locals.AddRange(inputs);
|
||||||
|
locals.AddRange(slots);
|
||||||
|
|
||||||
|
var body = Expression.Block(
|
||||||
|
locals,
|
||||||
|
Expression.Assign(yVec, Expression.Call(Broadcast, yScalar)),
|
||||||
|
Expression.Assign(x, xStart),
|
||||||
|
loop);
|
||||||
|
|
||||||
|
var lambda = Expression.Lambda<CpuKernel.RowDelegate>(body, buffer, rowBase, xStart, xEnd, yScalar, uniforms);
|
||||||
|
return lambda.Compile();
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed record Context(
|
||||||
|
Expression X,
|
||||||
|
Expression Y,
|
||||||
|
ParameterExpression Uniforms,
|
||||||
|
Expression[] Inputs,
|
||||||
|
ParameterExpression[] Slots);
|
||||||
|
|
||||||
|
private static Expression Build(KExpr expression, Context context)
|
||||||
|
{
|
||||||
|
switch (expression)
|
||||||
|
{
|
||||||
|
case KConst value:
|
||||||
|
return Expression.Constant(Vector256.Create(value.Value), Vec);
|
||||||
|
case KInput input:
|
||||||
|
return context.Inputs[(int)input.Channel];
|
||||||
|
case KCoord coord:
|
||||||
|
return coord.Axis == KAxis.X ? context.X : context.Y;
|
||||||
|
case KUniformRef uniform:
|
||||||
|
return Expression.Call(Broadcast, Expression.ArrayIndex(context.Uniforms, Constant((int)uniform.Uniform)));
|
||||||
|
case KLocalRef local:
|
||||||
|
return context.Slots[local.Slot];
|
||||||
|
case KNegate negate:
|
||||||
|
return Call(Negate, Build(negate.Operand, context));
|
||||||
|
case KArith arithmetic:
|
||||||
|
return BuildArithmetic(arithmetic, context);
|
||||||
|
case KCall call:
|
||||||
|
return BuildCall(call, context);
|
||||||
|
case KSelect select:
|
||||||
|
return Select(BuildBool(select.Condition, context), Build(select.WhenTrue, context), Build(select.WhenFalse, context));
|
||||||
|
}
|
||||||
|
throw new KernelUnsupportedException("Unsupported SIMD expression.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Expression BuildArithmetic(KArith arithmetic, Context context)
|
||||||
|
{
|
||||||
|
var left = Build(arithmetic.Left, context);
|
||||||
|
var right = Build(arithmetic.Right, context);
|
||||||
|
return arithmetic.Op switch
|
||||||
|
{
|
||||||
|
KArithOp.Add => Call(Add, left, right),
|
||||||
|
KArithOp.Subtract => Call(Subtract, left, right),
|
||||||
|
KArithOp.Multiply => Call(Multiply, left, right),
|
||||||
|
KArithOp.Divide => Call(Divide, left, right),
|
||||||
|
KArithOp.Modulo => Call(Subtract, left, Call(Multiply, Call(FloorFn, Call(Divide, left, right)), right)),
|
||||||
|
_ => throw new KernelUnsupportedException("Unsupported SIMD arithmetic operator."),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Expression BuildCall(KCall call, Context context)
|
||||||
|
{
|
||||||
|
var argument = Build(call.Arguments[0], context);
|
||||||
|
return call.Func switch
|
||||||
|
{
|
||||||
|
KFunc.Abs => Call(Abs, argument),
|
||||||
|
KFunc.Floor => Call(FloorFn, argument),
|
||||||
|
KFunc.Ceil => Call(CeilingFn, argument),
|
||||||
|
KFunc.Sqrt => Call(Sqrt, argument),
|
||||||
|
_ => throw new KernelUnsupportedException("Unsupported SIMD function."),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Expression BuildBool(KBool condition, Context context)
|
||||||
|
{
|
||||||
|
switch (condition)
|
||||||
|
{
|
||||||
|
case KBoolConst value:
|
||||||
|
return value.Value ? AllBits : Zero;
|
||||||
|
case KNot not:
|
||||||
|
return Call(OnesComplement, BuildBool(not.Operand, context));
|
||||||
|
case KLogical logical:
|
||||||
|
return logical.IsAnd
|
||||||
|
? Call(BitwiseAnd, BuildBool(logical.Left, context), BuildBool(logical.Right, context))
|
||||||
|
: Call(BitwiseOr, BuildBool(logical.Left, context), BuildBool(logical.Right, context));
|
||||||
|
case KCompare compare:
|
||||||
|
var left = Build(compare.Left, context);
|
||||||
|
var right = Build(compare.Right, context);
|
||||||
|
return compare.Op switch
|
||||||
|
{
|
||||||
|
KCompareOp.Less => Call(LessThan, left, right),
|
||||||
|
KCompareOp.Greater => Call(GreaterThan, left, right),
|
||||||
|
KCompareOp.LessEqual => Call(LessThanOrEqual, left, right),
|
||||||
|
KCompareOp.GreaterEqual => Call(GreaterThanOrEqual, left, right),
|
||||||
|
KCompareOp.Equal => Call(EqualsFn, left, right),
|
||||||
|
KCompareOp.NotEqual => Call(OnesComplement, Call(EqualsFn, left, right)),
|
||||||
|
_ => throw new KernelUnsupportedException("Unsupported SIMD comparison."),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
throw new KernelUnsupportedException("Unsupported SIMD condition.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Expression ClampByte(Expression value)
|
||||||
|
{
|
||||||
|
var low = Select(Call(LessThan, value, Zero), Zero, value);
|
||||||
|
return Select(Call(GreaterThan, low, V255), V255, low);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Expression Select(Expression condition, Expression whenTrue, Expression whenFalse) =>
|
||||||
|
Expression.Call(ConditionalSelect, condition, whenTrue, whenFalse);
|
||||||
|
|
||||||
|
private static Expression LoadChannel(ParameterExpression buffer, ParameterExpression index, int offset) =>
|
||||||
|
Expression.Call(Create4,
|
||||||
|
ToDouble(ReadByte(buffer, index, offset)),
|
||||||
|
ToDouble(ReadByte(buffer, index, offset + 4)),
|
||||||
|
ToDouble(ReadByte(buffer, index, offset + 8)),
|
||||||
|
ToDouble(ReadByte(buffer, index, offset + 12)));
|
||||||
|
|
||||||
|
private static Expression StoreChannel(ParameterExpression buffer, ParameterExpression index, int offset, Expression value)
|
||||||
|
{
|
||||||
|
var writes = new Expression[4];
|
||||||
|
for (int lane = 0; lane < 4; lane++)
|
||||||
|
writes[lane] = Expression.Assign(
|
||||||
|
Expression.ArrayAccess(buffer, Expression.Add(index, Constant(lane * 4 + offset))),
|
||||||
|
Expression.Convert(Expression.Call(GetElement, value, Constant(lane)), typeof(byte)));
|
||||||
|
return Expression.Block(writes);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Expression ReadByte(ParameterExpression buffer, ParameterExpression index, int offset) =>
|
||||||
|
Expression.ArrayIndex(buffer, offset == 0 ? index : Expression.Add(index, Constant(offset)));
|
||||||
|
|
||||||
|
private static Expression Call(MethodInfo method, params Expression[] arguments) =>
|
||||||
|
Expression.Call(method, arguments);
|
||||||
|
|
||||||
|
private static Expression ToDouble(Expression value) => Expression.Convert(value, typeof(double));
|
||||||
|
|
||||||
|
private static ConstantExpression Constant(int value) => Expression.Constant(value, typeof(int));
|
||||||
|
|
||||||
|
private static MethodInfo VecOp(string name, int vectorArgs, int intArgs = 0) =>
|
||||||
|
typeof(Vector256).GetMethods()
|
||||||
|
.Single(m => m.Name == name && m.IsGenericMethodDefinition &&
|
||||||
|
m.GetParameters().Length == vectorArgs + intArgs &&
|
||||||
|
m.GetParameters().Take(vectorArgs).All(p => IsVector(p.ParameterType)) &&
|
||||||
|
m.GetParameters().Skip(vectorArgs).All(p => p.ParameterType == typeof(int)))
|
||||||
|
.MakeGenericMethod(typeof(double));
|
||||||
|
|
||||||
|
private static bool IsVector(Type type) =>
|
||||||
|
type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Vector256<>);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal sealed record KArith(KArithOp Op, KExpr Left, KExpr Right) : KExpr;
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal enum KArithOp
|
||||||
|
{
|
||||||
|
Add,
|
||||||
|
Subtract,
|
||||||
|
Multiply,
|
||||||
|
Divide,
|
||||||
|
Modulo,
|
||||||
|
Power,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal enum KAxis
|
||||||
|
{
|
||||||
|
X,
|
||||||
|
Y,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal abstract record KBool;
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal sealed record KBoolConst(bool Value) : KBool;
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal sealed record KCall(KFunc Func, IReadOnlyList<KExpr> Arguments) : KExpr;
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal enum KChannel
|
||||||
|
{
|
||||||
|
R,
|
||||||
|
G,
|
||||||
|
B,
|
||||||
|
A,
|
||||||
|
}
|
||||||
|
}
|
||||||
345ファイル中100ファイルを読み込みました。 変更されたファイルが多すぎるため、それ以降のファイルは表示していません。
さらに表示
新しいイシューから参照
ユーザーをブロックする