Compare commits
666 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
835dd01fa1 | ||
|
|
20afc762cc | ||
|
|
dfb23c8db0 | ||
|
|
78e94b299d | ||
|
|
b52f7c76cd | ||
|
|
2877e8e624 | ||
|
|
0f166aa7ec | ||
|
|
a760faa3fa | ||
|
|
c0fd23e688 | ||
|
|
e558e44af4 | ||
|
|
0dcf3c57c7 | ||
|
|
6c19e68d6b | ||
|
|
5142f32878 | ||
|
|
aeda08c109 | ||
|
|
3d556da8b8 | ||
|
|
aa11c1a278 | ||
|
|
1cd9591997 | ||
|
|
4208022d55 | ||
|
|
4a4730be9b | ||
|
|
16c4ba599e | ||
|
|
b66aa9a954 | ||
|
|
ebaf3c8d77 | ||
|
|
62a8c5ca32 | ||
|
|
f5a53647f9 | ||
|
|
8ef2c42150 | ||
|
|
10fd41b4a8 | ||
|
|
95a0cc8f9a | ||
|
|
c489cef875 | ||
|
|
8bff2f23c6 | ||
|
|
d566b0e280 | ||
|
|
26deb26f17 | ||
|
|
2ba1d60ba5 | ||
|
|
30dcd41d91 | ||
|
|
90fccc15eb | ||
|
|
ac284e61b4 | ||
|
|
7625f88a0c | ||
|
|
4e1661eded | ||
|
|
60f8c02e18 | ||
|
|
768fd4adee | ||
|
|
682b789dd5 | ||
|
|
02f40e5b0d | ||
|
|
a7a719261e | ||
|
|
eba0806d77 | ||
|
|
b03e9ef1c7 | ||
|
|
8e59d8b682 | ||
|
|
ecf6295b4a | ||
|
|
569df37442 | ||
|
|
d733e1abea | ||
|
|
c3efcb3896 | ||
|
|
1e7f554bcd | ||
|
|
0e9fe7f194 | ||
|
|
f5716ef141 | ||
|
|
652a21ba8a | ||
|
|
4d39943d0f | ||
|
|
540ea34ade | ||
|
|
183a2b5579 | ||
|
|
d2ece3c165 | ||
|
|
a31d6b0886 | ||
|
|
2e62025d7e | ||
|
|
42522a277c | ||
|
|
987ade361d | ||
|
|
385df95ef4 | ||
|
|
5b9fb5ac02 | ||
|
|
c96f246200 | ||
|
|
e55a8ab77a | ||
|
|
fe137c0941 | ||
|
|
285a73cf0e | ||
|
|
306a6f57f3 | ||
|
|
105f5ec092 | ||
|
|
275e2d8ff8 | ||
|
|
ca33bcf2ab | ||
|
|
386a249b0c | ||
|
|
dd8b1680f5 | ||
|
|
6acfa2babf | ||
|
|
7025e9dff9 | ||
|
|
67cdbb54bc | ||
|
|
2028a2c2f3 | ||
|
|
570fdbf9fd | ||
|
|
090a270246 | ||
|
|
fcb09f440f | ||
|
|
ab2ad8aec1 | ||
|
|
55334cfbc0 | ||
|
|
590273e2fd | ||
|
|
a813e261b4 | ||
|
|
043961fc3e | ||
|
|
c85cefde67 | ||
|
|
34326df680 | ||
|
|
6af09cb2ad | ||
|
|
70fc175e74 | ||
|
|
4fd4ed6ca3 | ||
|
|
9c6d5a8408 | ||
|
|
6079d4488a | ||
|
|
0163e0b099 | ||
|
|
ace8c56199 | ||
|
|
abd05a38ad | ||
|
|
e7c8346861 | ||
|
|
69dd8c61c9 | ||
|
|
4e3185af88 | ||
|
|
b69c02a824 | ||
|
|
606da069b4 | ||
|
|
607f473be2 | ||
|
|
e283b6fb25 | ||
|
|
da7e95a221 | ||
|
|
754842c6af | ||
|
|
675b6e9228 | ||
|
|
070c5ee632 | ||
|
|
b78042fc2f | ||
|
|
a55c689d7c | ||
|
|
f0a28c381b | ||
|
|
3d9a5e6866 | ||
|
|
857d5fe6a1 | ||
|
|
1e485d5dbc | ||
|
|
20bc6d6789 | ||
|
|
ed07a70327 | ||
|
|
dfc10f4a32 | ||
|
|
64cc3b90c7 | ||
|
|
02776f9768 | ||
|
|
2ab6662a13 | ||
|
|
be56413593 | ||
|
|
f0de9c100d | ||
|
|
5693327ca1 | ||
|
|
a1f82dcfb7 | ||
|
|
2b7fd07150 | ||
|
|
9c197693d7 | ||
|
|
6afd79c771 | ||
|
|
35485379bd | ||
|
|
da3deefae2 | ||
|
|
1a53086f7c | ||
|
|
0ca6bb3a1f | ||
|
|
c5d461c379 | ||
|
|
531e2b442d | ||
|
|
7ead579c67 | ||
|
|
2e91094afa | ||
|
|
b991941227 | ||
|
|
65aa894749 | ||
|
|
3f478d8597 | ||
|
|
470f6742bc | ||
|
|
3f2f38842c | ||
|
|
a6121c7f67 | ||
|
|
bb3f271a20 | ||
|
|
3de42f56c5 | ||
|
|
fcb4f258f5 | ||
|
|
8ed55b3aff | ||
|
|
d5444e1172 | ||
|
|
ea827e4c5d | ||
|
|
95e77bd7cb | ||
|
|
321b217feb | ||
|
|
3958c19f83 | ||
|
|
7709d92289 | ||
|
|
868b548dd0 | ||
|
|
837aab0e98 | ||
|
|
77ac20a66b | ||
|
|
7362ecb3b4 | ||
|
|
88ffe75b58 | ||
|
|
c1520c9e11 | ||
|
|
9a1501ae89 | ||
|
|
514e106414 | ||
|
|
4c001bd248 | ||
|
|
fb6ceb2664 | ||
|
|
50da26da91 | ||
|
|
28857841aa | ||
|
|
157d129e30 | ||
|
|
9ab447843b | ||
|
|
fe6da3a16b | ||
|
|
fac9aac821 | ||
|
|
d7f4ce6cff | ||
|
|
a9cca5e76c | ||
|
|
7a64527db5 | ||
|
|
bc23a610d3 | ||
|
|
9def45aa80 | ||
|
|
85878d894a | ||
|
|
ae4cd1ebf1 | ||
|
|
781c7a800f | ||
|
|
5133ae52df | ||
|
|
3539af7d77 | ||
|
|
c03894321a | ||
|
|
b7e886a740 | ||
|
|
8268c61b9f | ||
|
|
fee6e8e11b | ||
|
|
558d749d54 | ||
|
|
27cb54c1db | ||
|
|
4c9be808a7 | ||
|
|
71893807b3 | ||
|
|
08485f6781 | ||
|
|
87232358d3 | ||
|
|
ec9c000be9 | ||
|
|
75f3a2183f | ||
|
|
445e485fc5 | ||
|
|
508b5ccc63 | ||
|
|
833bb542fc | ||
|
|
981d67324b | ||
|
|
140b9e5a5a | ||
|
|
a4768d1638 | ||
|
|
abf353c178 | ||
|
|
670bb32b2c | ||
|
|
f836a47bc1 | ||
|
|
43df39c4f7 | ||
|
|
9da5c5e2d0 | ||
|
|
cdbbac5b6d | ||
|
|
3120558dd1 | ||
|
|
f3c91e4f96 | ||
|
|
b1fa430dad | ||
|
|
83bc362dac | ||
|
|
a86baefda7 | ||
|
|
82790b1556 | ||
|
|
728f643ea7 | ||
|
|
d5fc040d2d | ||
|
|
6c0b8229ec | ||
|
|
bc60693a5d | ||
|
|
1298374818 | ||
|
|
a078cfee3e | ||
|
|
bd4572cfd1 | ||
|
|
df8a600b22 | ||
|
|
567f85752d | ||
|
|
5009259473 | ||
|
|
b21a974342 | ||
|
|
ab783b9bb2 | ||
|
|
36d236c5e0 | ||
|
|
408faa11a1 | ||
|
|
8972e829f2 | ||
|
|
c4703a7f19 | ||
|
|
f6cfe6b873 | ||
|
|
bceef8f529 | ||
|
|
b23042839b | ||
|
|
5625be70fa | ||
|
|
5c187363b2 | ||
|
|
93f4844c9c | ||
|
|
39fd9b93c3 | ||
|
|
c38e0d05bf | ||
|
|
5a4d7fb0d6 | ||
|
|
6303334cc2 | ||
|
|
472742266b | ||
|
|
0889048cb5 | ||
|
|
57b6e74abb | ||
|
|
a8af0c0ca4 | ||
|
|
07fe8d4481 | ||
|
|
e0e1d0855d | ||
|
|
178591b6d5 | ||
|
|
dd475d8af4 | ||
|
|
121d22f137 | ||
|
|
59bf1d8cd9 | ||
|
|
780543f0a2 | ||
|
|
de78ffb551 | ||
|
|
1aba7f1fde | ||
|
|
3017b0213b | ||
|
|
d748c8c653 | ||
|
|
af8cb63292 | ||
|
|
d7f9da49eb | ||
|
|
70bddcf318 | ||
|
|
f0bb5313d3 | ||
|
|
c352fbf5c9 | ||
|
|
9c3c286aab | ||
|
|
e10adf83d5 | ||
|
|
c24a04d246 | ||
|
|
2e89529eef | ||
|
|
92d03f3832 | ||
|
|
2efd0996e6 | ||
|
|
ac4f13e78f | ||
|
|
2bdd0a6bdb | ||
|
|
c044a3c1ca | ||
|
|
72cb4e9bea | ||
|
|
fc0ac64277 | ||
|
|
df4c9e2903 | ||
|
|
73dbd2f0ab | ||
|
|
05d5dc4cec | ||
|
|
815b5cb086 | ||
|
|
0837d674eb | ||
|
|
a7bde8e523 | ||
|
|
c63c05b141 | ||
|
|
12ccbe6f12 | ||
|
|
be540043ee | ||
|
|
de8d80dee0 | ||
|
|
98fd5bd453 | ||
|
|
15b569fb71 | ||
|
|
58eccc7a2a | ||
|
|
e39e47b21f | ||
|
|
e7f6e7d7b6 | ||
|
|
af27d97003 | ||
|
|
c8e46749a4 | ||
|
|
eb432d3da0 | ||
|
|
4ab3c54f5b | ||
|
|
de1d8ec070 | ||
|
|
c8a41409d9 | ||
|
|
d2a089ffd9 | ||
|
|
3bd5169aee | ||
|
|
b7887a339d | ||
|
|
1b89d4d541 | ||
|
|
d8190e1c5f | ||
|
|
2af5191070 | ||
|
|
4027e08cc8 | ||
|
|
72eeb9fecb | ||
|
|
5a07f5a652 | ||
|
|
d767ab0890 | ||
|
|
df2fd399df | ||
|
|
f2b5c35fa2 | ||
|
|
b2057a5da7 | ||
|
|
38cacfa577 | ||
|
|
13e271c6cb | ||
|
|
7a6ca85081 | ||
|
|
ecfe9c5c2f | ||
|
|
9f263319ca | ||
|
|
00ef597639 | ||
|
|
30e280b694 | ||
|
|
b9adf244e5 | ||
|
|
8a5e49c856 | ||
|
|
284f6d3682 | ||
|
|
cc1bfc6d03 | ||
|
|
07fdf7158d | ||
|
|
fca60e2a41 | ||
|
|
e12db0c182 | ||
|
|
1d673ce075 | ||
|
|
7e4462e0ac | ||
|
|
f87994edc7 | ||
|
|
ef0c19477c | ||
|
|
9bee6d899b | ||
|
|
2d8e4df7bc | ||
|
|
4e1679d2a2 | ||
|
|
fd8e02195e | ||
|
|
b2982a6f14 | ||
|
|
a9a0f1e129 | ||
|
|
0ea1ec31fc | ||
|
|
f8bff346f4 | ||
|
|
ff88ed7c75 | ||
|
|
57a737c417 | ||
|
|
eb8785a209 | ||
|
|
d4b10db998 | ||
|
|
3a35db6e67 | ||
|
|
e79587c934 | ||
|
|
8935f2af3c | ||
|
|
517f1602aa | ||
|
|
e8a8525bcd | ||
|
|
6e3246c5fd | ||
|
|
97066bf795 | ||
|
|
5df60d85f7 | ||
|
|
008d6be900 | ||
|
|
d1a1aed23e | ||
|
|
673d2499e8 | ||
|
|
6ac053bbaa | ||
|
|
6c6e48f006 | ||
|
|
bb6782ca58 | ||
|
|
d307d01b18 | ||
|
|
08284e420d | ||
|
|
d53ef90a73 | ||
|
|
b487341c32 | ||
|
|
6a7a613741 | ||
|
|
9cee9bc279 | ||
|
|
f638482fba | ||
|
|
a7908da968 | ||
|
|
20bfaba0b7 | ||
|
|
5a27c05b6a | ||
|
|
24cc33e704 | ||
|
|
6c4a110679 | ||
|
|
b42b03bc40 | ||
|
|
5727d74d37 | ||
|
|
bc4ab8b99e | ||
|
|
24f2c38093 | ||
|
|
dfba79f8ff | ||
|
|
0d817ff4ff | ||
|
|
178943b4b7 | ||
|
|
751ede516b | ||
|
|
cda112493a | ||
|
|
fa072c1d2c | ||
|
|
a862e4290c | ||
|
|
234b01a8c2 | ||
|
|
e3b9828f24 | ||
|
|
8339594206 | ||
|
|
2386bfda7e | ||
|
|
ef0009aea7 | ||
|
|
4d24537590 | ||
|
|
4f84b01356 | ||
|
|
c8b615acc9 | ||
|
|
61a5733692 | ||
|
|
4245a7604b | ||
|
|
d5d6e36ae0 | ||
|
|
658bc9fcc8 | ||
|
|
60810c2d37 | ||
|
|
f07e1026ac | ||
|
|
32f68f35cf | ||
|
|
02a893d613 | ||
|
|
f596c36f4f | ||
|
|
8ff0e1da15 | ||
|
|
4660310db6 | ||
|
|
58bf4f04b1 | ||
|
|
d88f0866b7 | ||
|
|
bf52d1e624 | ||
|
|
fc80f65a6d | ||
|
|
badd42789a | ||
|
|
c524c52baa | ||
|
|
585ca90ae0 | ||
|
|
e734b3f0d8 | ||
|
|
91ea47fddf | ||
|
|
9b97147637 | ||
|
|
d4d4712361 | ||
|
|
879f7e9f03 | ||
|
|
aaf77025b6 | ||
|
|
cdce33dd05 | ||
|
|
b10797b3d5 | ||
|
|
e73e562a63 | ||
|
|
e40417f687 | ||
|
|
aac616fcc5 | ||
|
|
fa0745f7da | ||
|
|
00a3e6bbd7 | ||
|
|
bb7f57b095 | ||
|
|
d85c842ce9 | ||
|
|
dce166dc93 | ||
|
|
13a0e5fb4a | ||
|
|
0c3a4cc7b9 | ||
|
|
e9ab5bc223 | ||
|
|
5da18d34ba | ||
|
|
09d542dfe0 | ||
|
|
5280863300 | ||
|
|
fbec378869 | ||
|
|
9fcd7f2dc0 | ||
|
|
229389b7f6 | ||
|
|
5d8a22066c | ||
|
|
63a9853811 | ||
|
|
39b1311a1b | ||
|
|
f4eba3bfba | ||
|
|
4caf0e4cb9 | ||
|
|
762fca538c | ||
|
|
fa1d80b53b | ||
|
|
b4be483d3e | ||
|
|
57de599a29 | ||
|
|
492aab20fe | ||
|
|
6952bab519 | ||
|
|
87fa4de59c | ||
|
|
0d4b489545 | ||
|
|
0d30a3071a | ||
|
|
753f03ff6a | ||
|
|
bf2098c07f | ||
|
|
2f35b121a4 | ||
|
|
34286d77c7 | ||
|
|
e3cc26cb7c | ||
|
|
84dd812da4 | ||
|
|
4acbd59162 | ||
|
|
1e316a9704 | ||
|
|
6ca214fefc | ||
|
|
fa47af737f | ||
|
|
0f2517070e | ||
|
|
f483d10c95 | ||
|
|
8c3a6a819e | ||
|
|
933432e62d | ||
|
|
2b97fead9e | ||
|
|
9ac6d330b4 | ||
|
|
4843890c56 | ||
|
|
c81e0b7433 | ||
|
|
ce97210eb1 | ||
|
|
cb5fa56e17 | ||
|
|
6cbb9193ea | ||
|
|
3cac17d23e | ||
|
|
d4b107e2e8 | ||
|
|
c90ebad46b | ||
|
|
af69d4f7a9 | ||
|
|
6c8ae2b72a | ||
|
|
7901087466 | ||
|
|
e2ccd14c05 | ||
|
|
a14320fc44 | ||
|
|
eb52a149a0 | ||
|
|
adaa4cc2f3 | ||
|
|
f2b99332d9 | ||
|
|
4859cf44ce | ||
|
|
83f779c52d | ||
|
|
c9e10e1dd9 | ||
|
|
4259ac96ea | ||
|
|
714c9361ea | ||
|
|
93381014a0 | ||
|
|
16aaef097a | ||
|
|
1d9c9710d7 | ||
|
|
e7dbd325d2 | ||
|
|
893594d81a | ||
|
|
176e674a51 | ||
|
|
e10d8080ba | ||
|
|
9da1354f3a | ||
|
|
e1f6108789 | ||
|
|
40bf88ac74 | ||
|
|
ffec698d3e | ||
|
|
b1ee137177 | ||
|
|
fbec168e91 | ||
|
|
89f3502b56 | ||
|
|
5dbc1d4c08 | ||
|
|
c0f852e016 | ||
|
|
397682a5b0 | ||
|
|
2b99dabdac | ||
|
|
df9975f35d | ||
|
|
4158759265 | ||
|
|
8927e7caf6 | ||
|
|
a46fe79939 | ||
|
|
2ef080a51b | ||
|
|
4468813d47 | ||
|
|
6a2eb4da07 | ||
|
|
731b84d725 | ||
|
|
362e4505e8 | ||
|
|
13013d1b8b | ||
|
|
6df0de565f | ||
|
|
89eabb5803 | ||
|
|
6aa4f14a28 | ||
|
|
be7844192b | ||
|
|
9e3a11534f | ||
|
|
a29d3cf074 | ||
|
|
f6ecd931dc | ||
|
|
f0180ad488 | ||
|
|
afc48cf224 | ||
|
|
5958714309 | ||
|
|
fb461d21a5 | ||
|
|
404a063fdf | ||
|
|
8cbd629010 | ||
|
|
e9233bc169 | ||
|
|
bec080be8d | ||
|
|
371b9a7fc2 | ||
|
|
699d1bf27c | ||
|
|
225aa107f6 | ||
|
|
e416c99419 | ||
|
|
7c9706fdcf | ||
|
|
f08e4bb27d | ||
|
|
432988a4ad | ||
|
|
a8cf10b0b5 | ||
|
|
e985b7a0bf | ||
|
|
6caa06eaed | ||
|
|
02fa33252a | ||
|
|
2211f4f8f7 | ||
|
|
5ceb327e55 | ||
|
|
b0f76d82c5 | ||
|
|
2bcebc4e4e | ||
|
|
cd55a533e8 | ||
|
|
021eddac73 | ||
|
|
5756d6262e | ||
|
|
56943bef48 | ||
|
|
ee727eb65e | ||
|
|
e8008c1b21 | ||
|
|
bdc124ba41 | ||
|
|
f27f701251 | ||
|
|
b2f0a37b18 | ||
|
|
050152eb90 | ||
|
|
3987318f09 | ||
|
|
9f684eac92 | ||
|
|
abf3142b26 | ||
|
|
eeb873b23c | ||
|
|
84d4647329 | ||
|
|
7acb14f7a1 | ||
|
|
2587302987 | ||
|
|
db88d24ff8 | ||
|
|
2ea8d9ca11 | ||
|
|
0383c44f0d | ||
|
|
08ee6d8d4b | ||
|
|
e7dd9737bd | ||
|
|
ceaa7e2fb0 | ||
|
|
8093044f07 | ||
|
|
9cca12ff0b | ||
|
|
1b0d2a37bb | ||
|
|
92c55c27cf | ||
|
|
ed7d4037b2 | ||
|
|
dd094d7606 | ||
|
|
1ba26d67bd | ||
|
|
e824e9023f | ||
|
|
d20f1182f2 | ||
|
|
e83530d40b | ||
|
|
6f494a968d | ||
|
|
133f706bf3 | ||
|
|
863c9b55b4 | ||
|
|
45561b89a4 | ||
|
|
6b9250e4ef | ||
|
|
5089e8342f | ||
|
|
b12be0498e | ||
|
|
59abf1bb42 | ||
|
|
518ecd7f4e | ||
|
|
025516a005 | ||
|
|
345e93d19c | ||
|
|
d98ea7fdb6 | ||
|
|
a7eaee77ca | ||
|
|
0d41996562 | ||
|
|
7bae8ab838 | ||
|
|
4bf95703a0 | ||
|
|
2766c70ad3 | ||
|
|
2c390b5473 | ||
|
|
20692d54de | ||
|
|
dc7fb26921 | ||
|
|
171f911237 | ||
|
|
bd42cc2c77 | ||
|
|
8db4ba9e58 | ||
|
|
7c7ae79f9f | ||
|
|
8674dc831d | ||
|
|
3fbe42c3a2 | ||
|
|
6550bc252f | ||
|
|
e04f618979 | ||
|
|
c2c8d4d410 | ||
|
|
15f73258fd | ||
|
|
34ce86a8f5 | ||
|
|
05a53cd330 | ||
|
|
e17455cb22 | ||
|
|
995c192874 | ||
|
|
c9cd0d20ef | ||
|
|
3eab5e9002 | ||
|
|
a22b1700a4 | ||
|
|
8e9d7611ae | ||
|
|
de4cc5c20a | ||
|
|
0b423dd061 | ||
|
|
2c44620e5e | ||
|
|
d0753dddb1 | ||
|
|
c9ab61aa8c | ||
|
|
431444ba9f | ||
|
|
c99196d363 | ||
|
|
22a1653702 | ||
|
|
edd947b645 | ||
|
|
b8dc349099 | ||
|
|
93c2aff2cf | ||
|
|
ad5e9aa5e3 | ||
|
|
467d3a8c62 | ||
|
|
bc336480e6 | ||
|
|
32e492837c | ||
|
|
4f1dbb127a | ||
|
|
93dfa8a6d8 | ||
|
|
5054918efc | ||
|
|
335af393f0 | ||
|
|
524721ee27 | ||
|
|
5405a558fd | ||
|
|
094c433e58 | ||
|
|
961652c2e9 | ||
|
|
322c4a5b2b | ||
|
|
b6c7c5a7ab | ||
|
|
46c930cf70 | ||
|
|
e0d4a9d575 | ||
|
|
04f0d545da | ||
|
|
cad8e895f2 | ||
|
|
cb38b841af | ||
|
|
d58cc7fb7a | ||
|
|
7e143cb33d | ||
|
|
04dc4a10f0 | ||
|
|
47e557b96a | ||
|
|
3b346fd3c9 | ||
|
|
0d61598d8a | ||
|
|
61d0f613df | ||
|
|
00d9d96e48 | ||
|
|
b1aec1b5c8 | ||
|
|
5d3e830176 | ||
|
|
91ba02449b | ||
|
|
7162b536eb | ||
|
|
ca1a723890 | ||
|
|
16c22477c2 | ||
|
|
128ed87dd8 | ||
|
|
9408a1a025 | ||
|
|
777dca7043 | ||
|
|
f5b35a074f | ||
|
|
c6cf90f67b | ||
|
|
cb6e3ac6e1 | ||
|
|
2c2bc4a427 | ||
|
|
e5a6048eec | ||
|
|
3c60d359ed | ||
|
|
94a54375e2 | ||
|
|
c871b6dd4e | ||
|
|
62c6667b0b | ||
|
|
704b5d88b9 | ||
|
|
a292cc42aa | ||
|
|
da832a295e | ||
|
|
64b59184d1 | ||
|
|
bd06466d3a | ||
|
|
d4123a387c | ||
|
|
e7be135b78 | ||
|
|
d1a55e9ca4 | ||
|
|
6eb9269741 | ||
|
|
a98200bb4c | ||
|
|
55fafb7d25 | ||
|
|
321bcf5c44 | ||
|
|
689aaf50b3 | ||
|
|
2ec3325381 | ||
|
|
634e49b961 | ||
|
|
55f40a7f8d |
@@ -1,33 +0,0 @@
|
||||
BasedOnStyle: LLVM
|
||||
IndentWidth: 4
|
||||
UseTab: Always
|
||||
TabWidth: 4
|
||||
BreakBeforeBraces: Custom
|
||||
Standard: c++17
|
||||
BraceWrapping:
|
||||
AfterClass: true
|
||||
AfterControlStatement: Never
|
||||
AfterEnum: true
|
||||
AfterFunction: true
|
||||
AfterNamespace: true
|
||||
AfterStruct: true
|
||||
AfterUnion: true
|
||||
BeforeCatch: false
|
||||
BeforeElse: false
|
||||
FixNamespaceComments: false
|
||||
AllowShortIfStatementsOnASingleLine: false
|
||||
IndentCaseLabels: false
|
||||
AccessModifierOffset: -4
|
||||
ColumnLimit: 90
|
||||
AllowShortFunctionsOnASingleLine: InlineOnly
|
||||
SortIncludes: Never
|
||||
IncludeCategories:
|
||||
- Regex: '^".*'
|
||||
Priority: 2
|
||||
- Regex: '^<.*'
|
||||
Priority: 1
|
||||
AlignAfterOpenBracket: DontAlign
|
||||
ContinuationIndentWidth: 8
|
||||
ConstructorInitializerIndentWidth: 8
|
||||
BreakConstructorInitializers: AfterColon
|
||||
AlwaysBreakTemplateDeclarations: Yes
|
||||
0
.editorconfig
Executable file → Normal file
0
.editorconfig
Executable file → Normal file
3
.gitattributes
vendored
3
.gitattributes
vendored
@@ -1,2 +1,5 @@
|
||||
# Forces all files which git considers text files to use LF line endings
|
||||
* text=auto eol=lf
|
||||
|
||||
*.cpp diff=cpp
|
||||
*.h diff=cpp
|
||||
|
||||
17
.github/CONTRIBUTING.md
vendored
17
.github/CONTRIBUTING.md
vendored
@@ -36,6 +36,9 @@ Contributions are welcome! Here's how you can help:
|
||||
- Follow the [C/C++](http://dev.minetest.net/Code_style_guidelines) and
|
||||
[Lua](http://dev.minetest.net/Lua_code_style_guidelines) code style guidelines.
|
||||
- Check your code works as expected and document any changes to the Lua API.
|
||||
- To avoid conflicting changes between contributions, do not do the following manually. They will be done before each release.
|
||||
- Run `updatepo.sh` or update `minetest.po{,t}` even if your code adds new translatable strings.
|
||||
- Update `minetest.conf.example` and `settings_translation_file.cpp` even if your code adds new core settings.
|
||||
|
||||
4. Commit & [push](https://help.github.com/articles/pushing-to-a-remote/) your changes to a new branch (not `master`, one change per branch)
|
||||
- Commit messages should:
|
||||
@@ -67,20 +70,6 @@ Contributions are welcome! Here's how you can help:
|
||||
might need more work in the future.
|
||||
5. It uses protocols and formats which include the required compatibility.
|
||||
|
||||
### Important note about automated GitHub checks
|
||||
|
||||
When you submit a pull request, GitHub automatically runs checks on the Minetest
|
||||
Engine combined with your changes. One of these checks is called 'cpp lint /
|
||||
clang format', which checks code formatting. Because formatting for readability
|
||||
requires human judgement this check often fails and often makes unsuitable
|
||||
formatting requests which make code readability worse.
|
||||
|
||||
If this check fails, look at the details to check for any clear mistakes and
|
||||
correct those. However, you should not apply everything ClangFormat requests.
|
||||
Ignore requests that make code readability worse and any other clearly
|
||||
unsuitable requests. Discuss in the pull request with a core developer about how
|
||||
to progress.
|
||||
|
||||
## Issues
|
||||
|
||||
If you experience an issue, we would like to know the details - especially when
|
||||
|
||||
39
.github/ISSUE_TEMPLATE/bug_report.yaml
vendored
39
.github/ISSUE_TEMPLATE/bug_report.yaml
vendored
@@ -15,11 +15,10 @@ body:
|
||||
label: Minetest version
|
||||
description: |
|
||||
Paste the Minetest version below.
|
||||
If you are on a devel version, please add a git commit hash.
|
||||
You can use `minetest --version` to find it.
|
||||
You can also refer to the "About" tab of the menu.
|
||||
If you are on a dev version, please also indicate the git commit hash.
|
||||
Refer to the "About" tab of the menu or run `minetest --version` on the command line.
|
||||
placeholder: |
|
||||
Example:
|
||||
Example:
|
||||
Minetest 5.7.0-dev-ca13c51 (Linux)
|
||||
Using Irrlicht 1.9.0mt9
|
||||
Using LuaJIT 2.1.0-beta3
|
||||
@@ -33,59 +32,53 @@ body:
|
||||
render: "true"
|
||||
validations:
|
||||
required: true
|
||||
- type: input
|
||||
attributes:
|
||||
label: Active renderer
|
||||
description: For graphical and input-related issues. You can find these in the About tab in the mainmenu.
|
||||
placeholder: "Example: OpenGL 4.6.0"
|
||||
validations:
|
||||
required: false
|
||||
- type: input
|
||||
attributes:
|
||||
label: Irrlicht device
|
||||
description:
|
||||
description:
|
||||
placeholder: "Example: X11"
|
||||
validations:
|
||||
required: false
|
||||
- type: input
|
||||
attributes:
|
||||
label: Operating system and version
|
||||
description: It is recommended to upgrade your operating system to see if the problem still exists.
|
||||
description: It is recommended to upgrade your operating system to see if the problem persists.
|
||||
placeholder: "Example: Ubuntu 22.04"
|
||||
validations:
|
||||
required: true
|
||||
- type: input
|
||||
attributes:
|
||||
label: CPU model
|
||||
description: Usually found in system settings.
|
||||
placeholder: "Example: Intel i5-2410M (4) @ 2.900GHz"
|
||||
description: Usually found in OS/system settings.
|
||||
placeholder: "Example: Intel Core i5-2410M"
|
||||
validations:
|
||||
required: false
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: The GPU model and OpenGL version can be omitted if the bug is not a graphical issue.
|
||||
value: The GPU model and renderer can be omitted if the bug is not a graphical issue.
|
||||
- type: input
|
||||
attributes:
|
||||
label: GPU model
|
||||
description: Usually found in system settings.
|
||||
placeholder: "Example: NVIDA GeForce RTX 4090"
|
||||
description: Usually found in OS/system settings.
|
||||
placeholder: "Example: NVIDIA GeForce GTX 1660"
|
||||
validations:
|
||||
required: false
|
||||
- type: input
|
||||
attributes:
|
||||
label: OpenGL version
|
||||
placeholder: "Example: 4.6"
|
||||
label: Active renderer
|
||||
description: You can find this in the "About" tab in the main menu.
|
||||
placeholder: "Example: OpenGL 4.6.0"
|
||||
validations:
|
||||
required: false
|
||||
- type: textarea
|
||||
attributes:
|
||||
attributes:
|
||||
label: Summary
|
||||
description: Describe your problem here.
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
attributes:
|
||||
attributes:
|
||||
label: Steps to reproduce
|
||||
description: Explain how the problem has happened, providing a minimal test (i.e. a code snippet reduced to the bone) where possible.
|
||||
description: Explain how the problem has happened, providing a minimal test (e.g. a minimized code snippet) where possible.
|
||||
validations:
|
||||
required: true
|
||||
|
||||
38
.github/workflows/android.yml
vendored
38
.github/workflows/android.yml
vendored
@@ -8,6 +8,10 @@ on:
|
||||
- 'lib/**.cpp'
|
||||
- 'src/**.[ch]'
|
||||
- 'src/**.cpp'
|
||||
- 'irr/**.[ch]'
|
||||
- 'irr/**.cpp'
|
||||
- '**/CMakeLists.txt'
|
||||
- 'cmake/Modules/**'
|
||||
- 'android/**'
|
||||
- '.github/workflows/android.yml'
|
||||
pull_request:
|
||||
@@ -16,37 +20,55 @@ on:
|
||||
- 'lib/**.cpp'
|
||||
- 'src/**.[ch]'
|
||||
- 'src/**.cpp'
|
||||
- 'irr/**.[ch]'
|
||||
- 'irr/**.cpp'
|
||||
- '**/CMakeLists.txt'
|
||||
- 'cmake/Modules/**'
|
||||
- 'android/**'
|
||||
- '.github/workflows/android.yml'
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-20.04
|
||||
runs-on: ubuntu-22.04
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/checkout@v4
|
||||
- name: Install deps
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y --no-install-recommends gettext openjdk-11-jdk-headless
|
||||
- name: Build with Gradle
|
||||
sudo apt-get install -y --no-install-recommends gettext
|
||||
- name: Set up JDK 17
|
||||
uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: 'temurin'
|
||||
java-version: '17'
|
||||
- name: Build AAB with Gradle
|
||||
# We build an AAB as well for uploading to the the Play Store.
|
||||
run: cd android; ./gradlew bundlerelease
|
||||
- name: Build APKs with Gradle
|
||||
# "assemblerelease" is very fast after "bundlerelease".
|
||||
run: cd android; ./gradlew assemblerelease
|
||||
- name: Save AAB artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: Minetest-release.aab
|
||||
path: android/app/build/outputs/bundle/release/app-release.aab
|
||||
- name: Save armeabi artifact
|
||||
uses: actions/upload-artifact@v3
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: Minetest-armeabi-v7a.apk
|
||||
path: android/app/build/outputs/apk/release/app-armeabi-v7a-release-unsigned.apk
|
||||
- name: Save arm64 artifact
|
||||
uses: actions/upload-artifact@v3
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: Minetest-arm64-v8a.apk
|
||||
path: android/app/build/outputs/apk/release/app-arm64-v8a-release-unsigned.apk
|
||||
- name: Save x86 artifact
|
||||
uses: actions/upload-artifact@v3
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: Minetest-x86.apk
|
||||
path: android/app/build/outputs/apk/release/app-x86-release-unsigned.apk
|
||||
- name: Save x86_64 artifact
|
||||
uses: actions/upload-artifact@v3
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: Minetest-x86_64.apk
|
||||
path: android/app/build/outputs/apk/release/app-x86_64-release-unsigned.apk
|
||||
|
||||
274
.github/workflows/build.yml
vendored
274
.github/workflows/build.yml
vendored
@@ -1,274 +0,0 @@
|
||||
name: build
|
||||
|
||||
# build on c/cpp changes or workflow changes
|
||||
on:
|
||||
push:
|
||||
paths:
|
||||
- 'lib/**.[ch]'
|
||||
- 'lib/**.cpp'
|
||||
- 'src/**.[ch]'
|
||||
- 'src/**.cpp'
|
||||
- '**/CMakeLists.txt'
|
||||
- 'cmake/Modules/**'
|
||||
- 'util/buildbot/**'
|
||||
- 'util/ci/**'
|
||||
- '.github/workflows/**.yml'
|
||||
- 'Dockerfile'
|
||||
- '.dockerignore'
|
||||
pull_request:
|
||||
paths:
|
||||
- 'lib/**.[ch]'
|
||||
- 'lib/**.cpp'
|
||||
- 'src/**.[ch]'
|
||||
- 'src/**.cpp'
|
||||
- '**/CMakeLists.txt'
|
||||
- 'cmake/Modules/**'
|
||||
- 'util/buildbot/**'
|
||||
- 'util/ci/**'
|
||||
- '.github/workflows/**.yml'
|
||||
- 'Dockerfile'
|
||||
- '.dockerignore'
|
||||
|
||||
env:
|
||||
MINETEST_POSTGRESQL_CONNECT_STRING: 'host=localhost user=minetest password=minetest dbname=minetest'
|
||||
|
||||
jobs:
|
||||
# Older gcc version (should be close to our minimum supported version)
|
||||
gcc_7:
|
||||
runs-on: ubuntu-20.04
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: Install deps
|
||||
run: |
|
||||
source ./util/ci/common.sh
|
||||
install_linux_deps g++-7
|
||||
|
||||
- name: Build
|
||||
run: |
|
||||
./util/ci/build.sh
|
||||
env:
|
||||
CC: gcc-7
|
||||
CXX: g++-7
|
||||
|
||||
- name: Test
|
||||
run: |
|
||||
./bin/minetest --run-unittests
|
||||
|
||||
# Current gcc version
|
||||
gcc_12:
|
||||
runs-on: ubuntu-22.04
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: Install deps
|
||||
run: |
|
||||
source ./util/ci/common.sh
|
||||
install_linux_deps g++-12 libluajit-5.1-dev
|
||||
|
||||
- name: Build
|
||||
run: |
|
||||
./util/ci/build.sh
|
||||
env:
|
||||
CC: gcc-12
|
||||
CXX: g++-12
|
||||
|
||||
- name: Test
|
||||
run: |
|
||||
./bin/minetest --run-unittests
|
||||
|
||||
# Older clang version (should be close to our minimum supported version)
|
||||
clang_7:
|
||||
runs-on: ubuntu-20.04
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: Install deps
|
||||
run: |
|
||||
source ./util/ci/common.sh
|
||||
install_linux_deps clang-7 valgrind
|
||||
|
||||
- name: Build
|
||||
run: |
|
||||
./util/ci/build.sh
|
||||
env:
|
||||
CC: clang-7
|
||||
CXX: clang++-7
|
||||
|
||||
- name: Unittest
|
||||
run: |
|
||||
./bin/minetest --run-unittests
|
||||
|
||||
- name: Valgrind
|
||||
run: |
|
||||
valgrind --leak-check=full --leak-check-heuristics=all --undef-value-errors=no --error-exitcode=9 ./bin/minetest --run-unittests
|
||||
|
||||
# Current clang version
|
||||
clang_14:
|
||||
runs-on: ubuntu-22.04
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: Install deps
|
||||
run: |
|
||||
source ./util/ci/common.sh
|
||||
install_linux_deps clang-14 gdb
|
||||
|
||||
- name: Build
|
||||
run: |
|
||||
./util/ci/build.sh
|
||||
env:
|
||||
CC: clang-14
|
||||
CXX: clang++-14
|
||||
|
||||
- name: Test
|
||||
run: |
|
||||
./bin/minetest --run-unittests
|
||||
|
||||
- name: Integration test + devtest
|
||||
run: |
|
||||
./util/test_multiplayer.sh
|
||||
|
||||
# Build with prometheus-cpp (server-only)
|
||||
clang_9_prometheus:
|
||||
name: "clang_9 (PROMETHEUS=1)"
|
||||
runs-on: ubuntu-20.04
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: Install deps
|
||||
run: |
|
||||
source ./util/ci/common.sh
|
||||
install_linux_deps clang-9
|
||||
|
||||
- name: Build prometheus-cpp
|
||||
run: |
|
||||
./util/ci/build_prometheus_cpp.sh
|
||||
|
||||
- name: Build
|
||||
run: |
|
||||
./util/ci/build.sh
|
||||
env:
|
||||
CC: clang-9
|
||||
CXX: clang++-9
|
||||
CMAKE_FLAGS: "-DENABLE_PROMETHEUS=1 -DBUILD_CLIENT=0"
|
||||
|
||||
- name: Test
|
||||
run: |
|
||||
./bin/minetestserver --run-unittests
|
||||
|
||||
docker:
|
||||
name: "Docker image"
|
||||
runs-on: ubuntu-20.04
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: Build docker image
|
||||
run: |
|
||||
docker build . -t minetest:latest
|
||||
docker run --rm minetest:latest /usr/local/bin/minetestserver --version
|
||||
|
||||
win32:
|
||||
name: "MinGW cross-compiler (32-bit)"
|
||||
runs-on: ubuntu-20.04
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: Install compiler
|
||||
run: |
|
||||
sudo apt-get update && sudo apt-get install -y gettext
|
||||
wget http://minetest.kitsunemimi.pw/mingw-w64-i686_11.2.0_ubuntu20.04.tar.xz -O mingw.tar.xz
|
||||
sudo tar -xaf mingw.tar.xz -C /usr
|
||||
|
||||
- name: Build
|
||||
run: |
|
||||
EXISTING_MINETEST_DIR=$PWD ./util/buildbot/buildwin32.sh winbuild
|
||||
env:
|
||||
NO_PACKAGE: 1
|
||||
|
||||
win64:
|
||||
name: "MinGW cross-compiler (64-bit)"
|
||||
runs-on: ubuntu-20.04
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: Install compiler
|
||||
run: |
|
||||
sudo apt-get update && sudo apt-get install -y gettext
|
||||
wget http://minetest.kitsunemimi.pw/mingw-w64-x86_64_11.2.0_ubuntu20.04.tar.xz -O mingw.tar.xz
|
||||
sudo tar -xaf mingw.tar.xz -C /usr
|
||||
|
||||
- name: Build
|
||||
run: |
|
||||
EXISTING_MINETEST_DIR=$PWD ./util/buildbot/buildwin64.sh winbuild
|
||||
env:
|
||||
NO_PACKAGE: 1
|
||||
|
||||
msvc:
|
||||
name: VS 2019 ${{ matrix.config.arch }}-${{ matrix.type }}
|
||||
runs-on: windows-2019
|
||||
env:
|
||||
VCPKG_VERSION: 8eb57355a4ffb410a2e94c07b4dca2dffbee8e50
|
||||
# 2023.10.19
|
||||
vcpkg_packages: zlib zstd curl[winssl] openal-soft libvorbis libogg libjpeg-turbo sqlite3 freetype luajit gmp jsoncpp opengl-registry
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
config:
|
||||
- {
|
||||
arch: x86,
|
||||
generator: "-G'Visual Studio 16 2019' -A Win32",
|
||||
vcpkg_triplet: x86-windows
|
||||
}
|
||||
- {
|
||||
arch: x64,
|
||||
generator: "-G'Visual Studio 16 2019' -A x64",
|
||||
vcpkg_triplet: x64-windows
|
||||
}
|
||||
type: [portable]
|
||||
# type: [portable, installer]
|
||||
# The installer type is working, but disabled, to save runner jobs.
|
||||
# Enable it, when working on the installer.
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- name: Checkout IrrlichtMt
|
||||
run: |
|
||||
$ref = @(Get-Content misc\irrlichtmt_tag.txt)
|
||||
git clone https://github.com/minetest/irrlicht lib\irrlichtmt --depth 1 -b $ref[0]
|
||||
|
||||
- name: Restore from cache and run vcpkg
|
||||
uses: lukka/run-vcpkg@v7
|
||||
with:
|
||||
vcpkgArguments: ${{env.vcpkg_packages}}
|
||||
vcpkgDirectory: '${{ github.workspace }}\vcpkg'
|
||||
appendedCacheKey: ${{ matrix.config.vcpkg_triplet }}
|
||||
vcpkgGitCommitId: ${{ env.VCPKG_VERSION }}
|
||||
vcpkgTriplet: ${{ matrix.config.vcpkg_triplet }}
|
||||
|
||||
- name: Minetest CMake
|
||||
run: |
|
||||
cmake ${{matrix.config.generator}} `
|
||||
-DCMAKE_TOOLCHAIN_FILE="${{ github.workspace }}\vcpkg\scripts\buildsystems\vcpkg.cmake" `
|
||||
-DCMAKE_BUILD_TYPE=Release `
|
||||
-DENABLE_POSTGRESQL=OFF `
|
||||
-DENABLE_LUAJIT=TRUE `
|
||||
-DREQUIRE_LUAJIT=TRUE `
|
||||
-DRUN_IN_PLACE=${{ contains(matrix.type, 'portable') }} .
|
||||
|
||||
- name: Build Minetest
|
||||
run: cmake --build . --config Release
|
||||
|
||||
- name: CPack
|
||||
run: |
|
||||
If ($env:TYPE -eq "installer")
|
||||
{
|
||||
cpack -G WIX -B "$env:GITHUB_WORKSPACE\Package"
|
||||
}
|
||||
ElseIf($env:TYPE -eq "portable")
|
||||
{
|
||||
cpack -G ZIP -B "$env:GITHUB_WORKSPACE\Package"
|
||||
}
|
||||
env:
|
||||
TYPE: ${{matrix.type}}
|
||||
|
||||
- name: Package Clean
|
||||
run: rm -r $env:GITHUB_WORKSPACE\Package\_CPack_Packages
|
||||
|
||||
- uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: msvc-${{ matrix.config.arch }}-${{ matrix.type }}
|
||||
path: .\Package\
|
||||
30
.github/workflows/cpp_lint.yml
vendored
30
.github/workflows/cpp_lint.yml
vendored
@@ -8,6 +8,8 @@ on:
|
||||
- 'lib/**.cpp'
|
||||
- 'src/**.[ch]'
|
||||
- 'src/**.cpp'
|
||||
- 'irr/**.[ch]'
|
||||
- 'irr/**.cpp'
|
||||
- '**/CMakeLists.txt'
|
||||
- 'cmake/Modules/**'
|
||||
- 'util/ci/**'
|
||||
@@ -18,37 +20,25 @@ on:
|
||||
- 'lib/**.cpp'
|
||||
- 'src/**.[ch]'
|
||||
- 'src/**.cpp'
|
||||
- 'irr/**.[ch]'
|
||||
- 'irr/**.cpp'
|
||||
- '**/CMakeLists.txt'
|
||||
- 'cmake/Modules/**'
|
||||
- 'util/ci/**'
|
||||
- '.github/workflows/**.yml'
|
||||
|
||||
env:
|
||||
CLANG_TIDY: clang-tidy-15
|
||||
|
||||
jobs:
|
||||
|
||||
# clang_format:
|
||||
# runs-on: ubuntu-20.04
|
||||
# steps:
|
||||
# - uses: actions/checkout@v3
|
||||
# - name: Install clang-format
|
||||
# run: |
|
||||
# sudo apt-get update
|
||||
# sudo apt-get install -y clang-format-9
|
||||
#
|
||||
# - name: Run clang-format
|
||||
# run: |
|
||||
# source ./util/ci/clang-format.sh
|
||||
# check_format
|
||||
# env:
|
||||
# CLANG_FORMAT: clang-format-9
|
||||
|
||||
clang_tidy:
|
||||
runs-on: ubuntu-20.04
|
||||
runs-on: ubuntu-22.04
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/checkout@v4
|
||||
- name: Install deps
|
||||
run: |
|
||||
source ./util/ci/common.sh
|
||||
install_linux_deps clang-tidy-9
|
||||
install_linux_deps $CLANG_TIDY
|
||||
|
||||
- name: Run clang-tidy
|
||||
run: |
|
||||
|
||||
98
.github/workflows/docker_image.yml
vendored
Normal file
98
.github/workflows/docker_image.yml
vendored
Normal file
@@ -0,0 +1,98 @@
|
||||
---
|
||||
name: docker_image
|
||||
|
||||
# https://docs.github.com/en/actions/publishing-packages/publishing-docker-images
|
||||
# https://docs.docker.com/build/ci/github-actions/multi-platform
|
||||
# https://github.com/opencontainers/image-spec/blob/main/annotations.md
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ "master" ]
|
||||
# Publish semver tags as releases.
|
||||
tags: [ "*" ]
|
||||
pull_request:
|
||||
# Build docker image on pull requests. (but do not publish)
|
||||
paths:
|
||||
- 'lib/**.[ch]'
|
||||
- 'lib/**.cpp'
|
||||
- 'src/**.[ch]'
|
||||
- 'src/**.cpp'
|
||||
- 'irr/**.[ch]'
|
||||
- 'irr/**.cpp'
|
||||
- '**/CMakeLists.txt'
|
||||
- 'cmake/Modules/**'
|
||||
- 'util/ci/**'
|
||||
- 'misc/irrlichtmt_tag.txt'
|
||||
- 'Dockerfile'
|
||||
- '.dockerignore'
|
||||
- '.github/workflows/docker_image.yml'
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
use_cache:
|
||||
description: "Use build cache"
|
||||
required: true
|
||||
type: boolean
|
||||
default: true
|
||||
|
||||
env:
|
||||
REGISTRY: ghcr.io
|
||||
# github.repository as <account>/<repo>
|
||||
IMAGE_NAME: ${{ github.repository }}
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
|
||||
steps:
|
||||
- name: Check out repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Docker buildx
|
||||
uses: docker/setup-buildx-action@v3.0.0
|
||||
|
||||
# Login against the Docker registry except on PR
|
||||
# https://github.com/docker/login-action
|
||||
- name: Log into registry ${{ env.REGISTRY }}
|
||||
if: github.event_name != 'pull_request'
|
||||
uses: docker/login-action@v3.0.0
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
# Extract metadata (tags, labels) for Docker
|
||||
# https://github.com/docker/metadata-action
|
||||
- name: Extract Docker metadata
|
||||
id: meta
|
||||
uses: docker/metadata-action@v5.5.0
|
||||
with:
|
||||
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
|
||||
labels: |
|
||||
org.opencontainers.image.title=Minetest
|
||||
org.opencontainers.image.vendor=Minetest
|
||||
org.opencontainers.image.licenses=LGPL-2.1-only
|
||||
|
||||
# Build and push Docker image
|
||||
# https://github.com/docker/build-push-action
|
||||
# No arm support for now. Require cross-compilation support in Dockerfile to not use QEMU.
|
||||
- name: Build and push Docker image
|
||||
uses: docker/build-push-action@v5.1.0
|
||||
with:
|
||||
context: .
|
||||
platforms: linux/amd64
|
||||
push: ${{ github.event_name != 'pull_request' }}
|
||||
load: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
no-cache: ${{ (github.event_name == 'workflow_dispatch' && !inputs.use_cache) || startsWith(github.ref, 'refs/tags/') }}
|
||||
|
||||
- name: Test Docker Image
|
||||
run: |
|
||||
docker run --rm $(cut -d, -f1 <<<"$DOCKER_METADATA_OUTPUT_TAGS") minetestserver --version
|
||||
shell: bash
|
||||
154
.github/workflows/linux.yml
vendored
Normal file
154
.github/workflows/linux.yml
vendored
Normal file
@@ -0,0 +1,154 @@
|
||||
name: linux
|
||||
|
||||
# build on c/cpp changes or workflow changes
|
||||
on:
|
||||
push:
|
||||
paths:
|
||||
- 'lib/**.[ch]'
|
||||
- 'lib/**.cpp'
|
||||
- 'src/**.[ch]'
|
||||
- 'src/**.cpp'
|
||||
- 'irr/**.[ch]'
|
||||
- 'irr/**.cpp'
|
||||
- '**/CMakeLists.txt'
|
||||
- 'cmake/Modules/**'
|
||||
- 'util/ci/**'
|
||||
- 'Dockerfile'
|
||||
- '.dockerignore'
|
||||
- '.github/workflows/linux.yml'
|
||||
pull_request:
|
||||
paths:
|
||||
- 'lib/**.[ch]'
|
||||
- 'lib/**.cpp'
|
||||
- 'src/**.[ch]'
|
||||
- 'src/**.cpp'
|
||||
- 'irr/**.[ch]'
|
||||
- 'irr/**.cpp'
|
||||
- '**/CMakeLists.txt'
|
||||
- 'cmake/Modules/**'
|
||||
- 'util/ci/**'
|
||||
- 'Dockerfile'
|
||||
- '.dockerignore'
|
||||
- '.github/workflows/linux.yml'
|
||||
|
||||
env:
|
||||
MINETEST_POSTGRESQL_CONNECT_STRING: 'host=localhost user=minetest password=minetest dbname=minetest'
|
||||
|
||||
jobs:
|
||||
# Older gcc version (should be close to our minimum supported version)
|
||||
gcc_7:
|
||||
runs-on: ubuntu-20.04
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Install deps
|
||||
run: |
|
||||
source ./util/ci/common.sh
|
||||
install_linux_deps g++-7
|
||||
|
||||
- name: Build
|
||||
run: |
|
||||
./util/ci/build.sh
|
||||
env:
|
||||
CC: gcc-7
|
||||
CXX: g++-7
|
||||
|
||||
- name: Test
|
||||
run: |
|
||||
./bin/minetest --run-unittests
|
||||
|
||||
# Current gcc version
|
||||
gcc_14:
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Install deps
|
||||
run: |
|
||||
source ./util/ci/common.sh
|
||||
install_linux_deps g++-14 libluajit-5.1-dev
|
||||
|
||||
- name: Build
|
||||
run: |
|
||||
./util/ci/build.sh
|
||||
env:
|
||||
CC: gcc-14
|
||||
CXX: g++-14
|
||||
|
||||
- name: Test
|
||||
run: |
|
||||
mkdir nowrite
|
||||
chmod a-w nowrite
|
||||
cd nowrite
|
||||
../bin/minetest --run-unittests
|
||||
|
||||
# Older clang version (should be close to our minimum supported version)
|
||||
clang_7:
|
||||
runs-on: ubuntu-20.04
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Install deps
|
||||
run: |
|
||||
source ./util/ci/common.sh
|
||||
install_linux_deps clang-7 llvm
|
||||
|
||||
- name: Build
|
||||
run: |
|
||||
./util/ci/build.sh
|
||||
env:
|
||||
CC: clang-7
|
||||
CXX: clang++-7
|
||||
CMAKE_FLAGS: '-DCMAKE_C_FLAGS="-fsanitize=address" -DCMAKE_CXX_FLAGS="-fsanitize=address"'
|
||||
|
||||
- name: Unittest
|
||||
run: |
|
||||
./bin/minetest --run-unittests
|
||||
|
||||
# Current clang version
|
||||
clang_18:
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Install deps
|
||||
run: |
|
||||
source ./util/ci/common.sh
|
||||
install_linux_deps clang-18 lldb
|
||||
|
||||
- name: Build
|
||||
run: |
|
||||
./util/ci/build.sh
|
||||
env:
|
||||
CC: clang-18
|
||||
CXX: clang++-18
|
||||
|
||||
- name: Test
|
||||
run: |
|
||||
./bin/minetest --run-unittests
|
||||
|
||||
- name: Integration test + devtest
|
||||
run: |
|
||||
./util/test_multiplayer.sh
|
||||
|
||||
# Build with prometheus-cpp (server-only)
|
||||
clang_11_prometheus:
|
||||
name: "clang_11 (PROMETHEUS=1)"
|
||||
runs-on: ubuntu-22.04
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Install deps
|
||||
run: |
|
||||
source ./util/ci/common.sh
|
||||
install_linux_deps clang-11
|
||||
|
||||
- name: Build prometheus-cpp
|
||||
run: ./util/ci/build_prometheus_cpp.sh
|
||||
|
||||
- name: Build
|
||||
run: |
|
||||
./util/ci/build.sh
|
||||
env:
|
||||
CC: clang-11
|
||||
CXX: clang++-11
|
||||
CMAKE_FLAGS: "-DENABLE_PROMETHEUS=1 -DBUILD_CLIENT=0 -DENABLE_CURSES=0"
|
||||
|
||||
- name: Test
|
||||
run: |
|
||||
./bin/minetestserver --run-unittests
|
||||
28
.github/workflows/lua.yml
vendored
28
.github/workflows/lua.yml
vendored
@@ -14,24 +14,24 @@ on:
|
||||
- '.github/workflows/**.yml'
|
||||
|
||||
jobs:
|
||||
# Note that the integration tests are also run build.yml, but only when C++ code is changed.
|
||||
# Note that the integration tests are also run in build.yml, but only when C++ code is changed.
|
||||
integration_tests:
|
||||
name: "Compile and run multiplayer tests"
|
||||
runs-on: ubuntu-20.04
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/checkout@v4
|
||||
- name: Install deps
|
||||
run: |
|
||||
source ./util/ci/common.sh
|
||||
install_linux_deps clang-10 gdb libluajit-5.1-dev
|
||||
install_linux_deps clang gdb libluajit-5.1-dev
|
||||
|
||||
- name: Build
|
||||
run: |
|
||||
./util/ci/build.sh
|
||||
env:
|
||||
CC: clang-10
|
||||
CXX: clang++-10
|
||||
CMAKE_FLAGS: "-DENABLE_GETTEXT=0 -DBUILD_SERVER=0"
|
||||
CC: clang
|
||||
CXX: clang++
|
||||
CMAKE_FLAGS: "-DENABLE_GETTEXT=0 -DBUILD_SERVER=0 -DBUILD_UNITTESTS=0"
|
||||
|
||||
- name: Integration test + devtest
|
||||
run: |
|
||||
@@ -39,22 +39,18 @@ jobs:
|
||||
|
||||
luacheck:
|
||||
name: "Builtin Luacheck and Unit Tests"
|
||||
runs-on: ubuntu-20.04
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
|
||||
- uses: actions/checkout@v3
|
||||
- uses: leafo/gh-actions-lua@v9
|
||||
- uses: actions/checkout@v4
|
||||
- uses: leafo/gh-actions-lua@v10
|
||||
with:
|
||||
luaVersion: "5.1.5"
|
||||
- uses: leafo/gh-actions-luarocks@v4
|
||||
- uses: leafo/gh-actions-luarocks@v4.3.0
|
||||
|
||||
- name: Install LuaJIT
|
||||
run: |
|
||||
cd $HOME
|
||||
git clone https://github.com/LuaJIT/LuaJIT/
|
||||
cd LuaJIT
|
||||
make -j$(nproc)
|
||||
run: ./util/ci/build_luajit.sh
|
||||
|
||||
- name: Install luarocks tools
|
||||
run: |
|
||||
|
||||
14
.github/workflows/lua_api_deploy.yml
vendored
14
.github/workflows/lua_api_deploy.yml
vendored
@@ -16,13 +16,13 @@ on:
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-22.04
|
||||
|
||||
if: github.repository == 'minetest/minetest'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v4
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: 3.11
|
||||
|
||||
@@ -36,13 +36,13 @@ jobs:
|
||||
./build.sh
|
||||
|
||||
- name: Setup Pages
|
||||
uses: actions/configure-pages@v3
|
||||
uses: actions/configure-pages@v4
|
||||
|
||||
- name: Upload artifact
|
||||
uses: actions/upload-pages-artifact@v2
|
||||
uses: actions/upload-pages-artifact@v3
|
||||
with:
|
||||
path: 'public/'
|
||||
|
||||
- name: Deploy to GitHub Pages
|
||||
id: deployment
|
||||
uses: actions/deploy-pages@v2
|
||||
uses: actions/deploy-pages@v4
|
||||
|
||||
16
.github/workflows/macos.yml
vendored
16
.github/workflows/macos.yml
vendored
@@ -8,6 +8,9 @@ on:
|
||||
- 'lib/**.cpp'
|
||||
- 'src/**.[ch]'
|
||||
- 'src/**.cpp'
|
||||
- 'irr/**.[ch]'
|
||||
- 'irr/**.cpp'
|
||||
- 'irr/**.mm' # Objective-C(++)
|
||||
- '**/CMakeLists.txt'
|
||||
- 'cmake/Modules/**'
|
||||
- '.github/workflows/macos.yml'
|
||||
@@ -17,15 +20,19 @@ on:
|
||||
- 'lib/**.cpp'
|
||||
- 'src/**.[ch]'
|
||||
- 'src/**.cpp'
|
||||
- 'irr/**.[ch]'
|
||||
- 'irr/**.cpp'
|
||||
- 'irr/**.mm' # Objective-C(++)
|
||||
- '**/CMakeLists.txt'
|
||||
- 'cmake/Modules/**'
|
||||
- '.github/workflows/macos.yml'
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: macos-latest
|
||||
# use macOS 13 since it's the last one that still runs on x86
|
||||
runs-on: macos-13
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/checkout@v4
|
||||
- name: Install deps
|
||||
run: |
|
||||
source ./util/ci/common.sh
|
||||
@@ -33,7 +40,6 @@ jobs:
|
||||
|
||||
- name: Build
|
||||
run: |
|
||||
git clone https://github.com/minetest/irrlicht lib/irrlichtmt --depth 1 -b $(cat misc/irrlichtmt_tag.txt)
|
||||
mkdir build
|
||||
cd build
|
||||
cmake .. \
|
||||
@@ -54,9 +60,11 @@ jobs:
|
||||
- name: CPack
|
||||
run: |
|
||||
cd build
|
||||
rm -rf macos
|
||||
cmake .. -DINSTALL_DEVTEST=FALSE
|
||||
cpack -G ZIP -B macos
|
||||
|
||||
- uses: actions/upload-artifact@v3
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: minetest-macos
|
||||
path: ./build/macos/*.zip
|
||||
|
||||
144
.github/workflows/windows.yml
vendored
Normal file
144
.github/workflows/windows.yml
vendored
Normal file
@@ -0,0 +1,144 @@
|
||||
name: windows
|
||||
|
||||
# build on c/cpp changes or workflow changes
|
||||
on:
|
||||
push:
|
||||
paths:
|
||||
- 'lib/**.[ch]'
|
||||
- 'lib/**.cpp'
|
||||
- 'src/**.[ch]'
|
||||
- 'src/**.cpp'
|
||||
- 'irr/**.[ch]'
|
||||
- 'irr/**.cpp'
|
||||
- '**/CMakeLists.txt'
|
||||
- 'cmake/Modules/**'
|
||||
- 'util/buildbot/**'
|
||||
- 'misc/*.manifest'
|
||||
- '.github/workflows/windows.yml'
|
||||
pull_request:
|
||||
paths:
|
||||
- 'lib/**.[ch]'
|
||||
- 'lib/**.cpp'
|
||||
- 'src/**.[ch]'
|
||||
- 'src/**.cpp'
|
||||
- 'irr/**.[ch]'
|
||||
- 'irr/**.cpp'
|
||||
- '**/CMakeLists.txt'
|
||||
- 'cmake/Modules/**'
|
||||
- 'util/buildbot/**'
|
||||
- 'misc/*.manifest'
|
||||
- '.github/workflows/windows.yml'
|
||||
|
||||
jobs:
|
||||
mingw:
|
||||
name: "MinGW cross-compiler (${{ matrix.bits }}-bit)"
|
||||
runs-on: ubuntu-22.04
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
bits: [32, 64]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Install compiler
|
||||
run: |
|
||||
sudo dpkg --add-architecture i386
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y --no-install-recommends gettext wine wine${{ matrix.bits }}
|
||||
sudo ./util/buildbot/download_toolchain.sh /usr
|
||||
|
||||
- name: Build
|
||||
run: |
|
||||
EXISTING_MINETEST_DIR=$PWD \
|
||||
./util/buildbot/buildwin${{ matrix.bits }}.sh B
|
||||
|
||||
# Check that the resulting binary can run (DLLs etc.)
|
||||
- name: Runtime test
|
||||
run: |
|
||||
dest=$(mktemp -d)
|
||||
unzip -q -d "$dest" B/build/*.zip
|
||||
cd "$dest"/minetest-*-win*
|
||||
wine bin/minetest.exe --version
|
||||
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: "mingw${{ matrix.bits }}"
|
||||
path: B/build/*.zip
|
||||
if-no-files-found: error
|
||||
|
||||
msvc:
|
||||
name: VS 2019 ${{ matrix.config.arch }}-${{ matrix.type }}
|
||||
runs-on: windows-2019
|
||||
env:
|
||||
VCPKG_VERSION: 01f602195983451bc83e72f4214af2cbc495aa94
|
||||
# 2024.05.24
|
||||
vcpkg_packages: zlib zstd curl[winssl] openal-soft libvorbis libogg libjpeg-turbo sqlite3 freetype luajit gmp jsoncpp opengl-registry
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
config:
|
||||
- {
|
||||
arch: x86,
|
||||
generator: "-G'Visual Studio 16 2019' -A Win32",
|
||||
vcpkg_triplet: x86-windows
|
||||
}
|
||||
- {
|
||||
arch: x64,
|
||||
generator: "-G'Visual Studio 16 2019' -A x64",
|
||||
vcpkg_triplet: x64-windows
|
||||
}
|
||||
type: [portable]
|
||||
# type: [portable, installer]
|
||||
# The installer type is working, but disabled, to save runner jobs.
|
||||
# Enable it, when working on the installer.
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Restore from cache and run vcpkg
|
||||
uses: lukka/run-vcpkg@v7
|
||||
with:
|
||||
vcpkgArguments: ${{env.vcpkg_packages}}
|
||||
vcpkgDirectory: '${{ github.workspace }}\vcpkg'
|
||||
appendedCacheKey: ${{ matrix.config.vcpkg_triplet }}
|
||||
vcpkgGitCommitId: ${{ env.VCPKG_VERSION }}
|
||||
vcpkgTriplet: ${{ matrix.config.vcpkg_triplet }}
|
||||
|
||||
- name: Minetest CMake
|
||||
run: |
|
||||
cmake ${{matrix.config.generator}} `
|
||||
-DCMAKE_TOOLCHAIN_FILE="${{ github.workspace }}\vcpkg\scripts\buildsystems\vcpkg.cmake" `
|
||||
-DCMAKE_BUILD_TYPE=Release `
|
||||
-DENABLE_POSTGRESQL=OFF `
|
||||
-DENABLE_LUAJIT=TRUE `
|
||||
-DREQUIRE_LUAJIT=TRUE `
|
||||
-DRUN_IN_PLACE=${{ contains(matrix.type, 'portable') }} .
|
||||
|
||||
- name: Build Minetest
|
||||
run: cmake --build . --config Release
|
||||
|
||||
- name: Unittests
|
||||
# need this workaround for stdout to work
|
||||
run: |
|
||||
$proc = start .\bin\Release\minetest.exe --run-unittests -NoNewWindow -Wait -PassThru
|
||||
exit $proc.ExitCode
|
||||
continue-on-error: true # FIXME!!
|
||||
|
||||
- name: CPack
|
||||
run: |
|
||||
If ($env:TYPE -eq "installer")
|
||||
{
|
||||
cpack -G WIX -B "$env:GITHUB_WORKSPACE\Package"
|
||||
}
|
||||
ElseIf($env:TYPE -eq "portable")
|
||||
{
|
||||
cpack -G ZIP -B "$env:GITHUB_WORKSPACE\Package"
|
||||
}
|
||||
rm -r $env:GITHUB_WORKSPACE\Package\_CPack_Packages
|
||||
env:
|
||||
TYPE: ${{matrix.type}}
|
||||
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: msvc-${{ matrix.config.arch }}-${{ matrix.type }}
|
||||
path: .\Package\
|
||||
if-no-files-found: error
|
||||
15
.gitignore
vendored
15
.gitignore
vendored
@@ -1,5 +1,8 @@
|
||||
## Editors and development environments
|
||||
*~
|
||||
.cmake
|
||||
CMakeUserPresets.json
|
||||
Testing/*
|
||||
*.swp
|
||||
*.bak*
|
||||
*.orig
|
||||
@@ -26,7 +29,8 @@ gtags.files
|
||||
# Codelite
|
||||
*.project
|
||||
# Visual Studio Code & plugins
|
||||
.vscode/
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
build/.cmake/
|
||||
# Fleet
|
||||
.fleet
|
||||
@@ -64,6 +68,7 @@ AppDir
|
||||
/clientmods/*
|
||||
!/clientmods/preview/
|
||||
/client/mod_storage/
|
||||
/mod_data
|
||||
|
||||
## Configuration/log files
|
||||
minetest.conf
|
||||
@@ -92,11 +97,8 @@ cmake_install.cmake
|
||||
CMakeCache.txt
|
||||
CPackConfig.cmake
|
||||
CPackSourceConfig.cmake
|
||||
src/test_config.h
|
||||
src/cmake_config.h
|
||||
src/cmake_config_githash.h
|
||||
src/unittest/test_world/world.mt
|
||||
games/devtest/mods/testnodes/textures/testnodes_generated_*.png
|
||||
/locale/
|
||||
.directory
|
||||
*.cbp
|
||||
@@ -109,7 +111,10 @@ games/devtest/mods/testnodes/textures/testnodes_generated_*.png
|
||||
*.iml
|
||||
test_config.h
|
||||
cmake-build-debug/
|
||||
cmake-build-minsizerel/
|
||||
cmake-build-release/
|
||||
cmake-build-relwithdebinfo/
|
||||
cmake-build-default/
|
||||
cmake_config.h
|
||||
cmake_config_githash.h
|
||||
CMakeDoxy*
|
||||
@@ -121,7 +126,7 @@ compile_commands.json
|
||||
*.sln
|
||||
.vs/
|
||||
|
||||
# Optional user provided library folder
|
||||
# Old irrlichtmt. Still ignored to make bisecting easier.
|
||||
lib/irrlichtmt
|
||||
|
||||
# Generated mod storage database
|
||||
|
||||
116
.gitlab-ci.yml
116
.gitlab-ci.yml
@@ -3,128 +3,14 @@
|
||||
# https://gitlab.com/minetest/minetest
|
||||
# Pipelines URL: https://gitlab.com/minetest/minetest/pipelines
|
||||
|
||||
stages:
|
||||
- build
|
||||
- package
|
||||
- deploy
|
||||
|
||||
variables:
|
||||
CONTAINER_IMAGE: registry.gitlab.com/$CI_PROJECT_PATH
|
||||
|
||||
.build_template:
|
||||
stage: build
|
||||
before_script:
|
||||
- apt-get update
|
||||
- DEBIAN_FRONTEND=noninteractive apt-get -y install build-essential gettext git cmake libpng-dev libjpeg-dev libxi-dev libgl1-mesa-dev libsqlite3-dev libleveldb-dev libogg-dev libvorbis-dev libopenal-dev libcurl4-gnutls-dev libfreetype6-dev zlib1g-dev libgmp-dev libjsoncpp-dev libzstd-dev libluajit-5.1-dev
|
||||
script:
|
||||
- git clone https://github.com/minetest/irrlicht lib/irrlichtmt --depth 1 -b $(cat misc/irrlichtmt_tag.txt)
|
||||
- mkdir build && cd build
|
||||
- cmake -DCMAKE_INSTALL_PREFIX=../artifact/minetest/usr/ -DRUN_IN_PLACE=FALSE -DENABLE_GETTEXT=TRUE ..
|
||||
- make -j $(($(nproc) + 1))
|
||||
- make install
|
||||
artifacts:
|
||||
when: on_success
|
||||
expire_in: 1h
|
||||
paths:
|
||||
- artifact/*
|
||||
|
||||
##
|
||||
## Ubuntu (prerequisite for AppImage build)
|
||||
##
|
||||
|
||||
build:ubuntu-20.04:
|
||||
extends: .build_template
|
||||
image: ubuntu:focal
|
||||
|
||||
##
|
||||
## MinGW for Windows
|
||||
##
|
||||
|
||||
.generic_win_template:
|
||||
image: ubuntu:focal
|
||||
before_script:
|
||||
- apt-get update
|
||||
- DEBIAN_FRONTEND=noninteractive apt-get install -y wget xz-utils unzip git cmake gettext
|
||||
- wget -nv http://minetest.kitsunemimi.pw/mingw-w64-${WIN_ARCH}_11.2.0_ubuntu20.04.tar.xz -O mingw.tar.xz
|
||||
- tar -xaf mingw.tar.xz -C /usr
|
||||
|
||||
.build_win_template:
|
||||
extends: .generic_win_template
|
||||
stage: build
|
||||
artifacts:
|
||||
expire_in: 90 day
|
||||
paths:
|
||||
- minetest-*-win*/*
|
||||
|
||||
build:win32:
|
||||
extends: .build_win_template
|
||||
script:
|
||||
- EXISTING_MINETEST_DIR=$PWD ./util/buildbot/buildwin32.sh build
|
||||
- unzip -q build/build/*.zip
|
||||
variables:
|
||||
WIN_ARCH: "i686"
|
||||
|
||||
build:win64:
|
||||
extends: .build_win_template
|
||||
script:
|
||||
- EXISTING_MINETEST_DIR=$PWD ./util/buildbot/buildwin64.sh build
|
||||
- unzip -q build/build/*.zip
|
||||
variables:
|
||||
WIN_ARCH: "x86_64"
|
||||
|
||||
##
|
||||
## Docker
|
||||
##
|
||||
|
||||
package:docker:
|
||||
stage: package
|
||||
image: docker:stable
|
||||
services:
|
||||
- docker:dind
|
||||
before_script:
|
||||
- docker login -u gitlab-ci-token -p $CI_JOB_TOKEN registry.gitlab.com
|
||||
script:
|
||||
- ./util/ci/docker.sh
|
||||
|
||||
##
|
||||
## Gitlab Pages (Lua API documentation)
|
||||
##
|
||||
|
||||
pages:
|
||||
stage: deploy
|
||||
image: python:3.8
|
||||
before_script:
|
||||
- pip install -U -r doc/mkdocs/requirements.txt
|
||||
script:
|
||||
- cd doc/mkdocs && ./build.sh
|
||||
- ./misc/make_redirects.sh
|
||||
artifacts:
|
||||
paths:
|
||||
- public
|
||||
only:
|
||||
- master
|
||||
|
||||
##
|
||||
## AppImage
|
||||
##
|
||||
|
||||
package:appimage-client:
|
||||
stage: package
|
||||
image: appimagecrafters/appimage-builder
|
||||
needs:
|
||||
- build:ubuntu-20.04
|
||||
before_script:
|
||||
- apt-get update
|
||||
- apt-get install -y git
|
||||
# Collect files
|
||||
- mkdir AppDir
|
||||
- cp -a artifact/minetest/usr/ AppDir/usr/
|
||||
- cp -a clientmods AppDir/usr/share/minetest
|
||||
# Remove PrefersNonDefaultGPU property due to validation errors
|
||||
- sed -i '/PrefersNonDefaultGPU/d' AppDir/usr/share/applications/net.minetest.minetest.desktop
|
||||
script:
|
||||
- export VERSION=$CI_COMMIT_REF_NAME-$CI_COMMIT_SHORT_SHA
|
||||
- appimage-builder --skip-test --recipe misc/AppImageBuilder.yml
|
||||
artifacts:
|
||||
expire_in: 90 day
|
||||
paths:
|
||||
- ./*.AppImage
|
||||
|
||||
@@ -17,6 +17,7 @@ read_globals = {
|
||||
"VoxelArea",
|
||||
"profiler",
|
||||
"Settings",
|
||||
"PerlinNoise", "PerlinNoiseMap",
|
||||
|
||||
string = {fields = {"split", "trim"}},
|
||||
table = {fields = {"copy", "getn", "indexof", "insert_all"}},
|
||||
@@ -70,7 +71,6 @@ files["builtin/mainmenu"] = {
|
||||
|
||||
read_globals = {
|
||||
"PLATFORM",
|
||||
"TOUCHSCREEN_GUI",
|
||||
},
|
||||
}
|
||||
|
||||
@@ -81,9 +81,3 @@ files["builtin/common/tests"] = {
|
||||
"assert",
|
||||
},
|
||||
}
|
||||
|
||||
files["builtin/fstk"] = {
|
||||
read_globals = {
|
||||
"TOUCHSCREEN_GUI",
|
||||
},
|
||||
}
|
||||
|
||||
5
.vscode/extensions.json
vendored
Normal file
5
.vscode/extensions.json
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"recommendations": [
|
||||
"ms-vscode.cpptools-extension-pack"
|
||||
]
|
||||
}
|
||||
112
CMakeLists.txt
112
CMakeLists.txt
@@ -1,11 +1,4 @@
|
||||
cmake_minimum_required(VERSION 3.5)
|
||||
|
||||
# Set policies up to 3.9 since we want to enable the IPO option
|
||||
if(${CMAKE_VERSION} VERSION_LESS 3.9)
|
||||
cmake_policy(VERSION ${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION})
|
||||
else()
|
||||
cmake_policy(VERSION 3.9)
|
||||
endif()
|
||||
cmake_minimum_required(VERSION 3.12)
|
||||
|
||||
# This can be read from ${PROJECT_NAME} after project() is called
|
||||
project(minetest)
|
||||
@@ -18,7 +11,7 @@ set(CLANG_MINIMUM_VERSION "7.0.1")
|
||||
|
||||
# You should not need to edit these manually, use util/bump_version.sh
|
||||
set(VERSION_MAJOR 5)
|
||||
set(VERSION_MINOR 8)
|
||||
set(VERSION_MINOR 9)
|
||||
set(VERSION_PATCH 0)
|
||||
set(VERSION_EXTRA "" CACHE STRING "Stuff to append to version string")
|
||||
|
||||
@@ -44,6 +37,25 @@ set(BUILD_UNITTESTS TRUE CACHE BOOL "Build unittests")
|
||||
set(BUILD_BENCHMARKS FALSE CACHE BOOL "Build benchmarks")
|
||||
set(BUILD_DOCUMENTATION TRUE CACHE BOOL "Build documentation")
|
||||
|
||||
set(DEFAULT_ENABLE_LTO TRUE)
|
||||
# by default don't enable on Debug builds to get faster builds
|
||||
if(CMAKE_BUILD_TYPE STREQUAL "Debug")
|
||||
set(DEFAULT_ENABLE_LTO FALSE)
|
||||
endif()
|
||||
#### LTO testing list ####
|
||||
# - Linux: seems to work always
|
||||
# - win32/msvc: works
|
||||
# - win32/gcc: fails to link
|
||||
# - win32/clang: works
|
||||
# - macOS on x86: seems to be fine
|
||||
# - macOS on ARM: crashes, see <https://github.com/minetest/minetest/issues/14397>
|
||||
# Note: since CMake has no easy architecture detection disabling for Mac entirely
|
||||
#### ####
|
||||
if((WIN32 AND CMAKE_CXX_COMPILER_ID STREQUAL "GNU") OR APPLE)
|
||||
set(DEFAULT_ENABLE_LTO FALSE)
|
||||
endif()
|
||||
set(ENABLE_LTO ${DEFAULT_ENABLE_LTO} CACHE BOOL "Use Link Time Optimization")
|
||||
|
||||
set(DEFAULT_RUN_IN_PLACE FALSE)
|
||||
if(WIN32)
|
||||
set(DEFAULT_RUN_IN_PLACE TRUE)
|
||||
@@ -79,28 +91,10 @@ if(ANDROID)
|
||||
endif()
|
||||
|
||||
|
||||
set(IRRLICHTMT_BUILD_DIR "" CACHE PATH "Path to IrrlichtMt build directory.")
|
||||
if(ANDROID)
|
||||
# currently manually provided
|
||||
elseif(NOT "${IRRLICHTMT_BUILD_DIR}" STREQUAL "")
|
||||
find_package(IrrlichtMt QUIET
|
||||
PATHS "${IRRLICHTMT_BUILD_DIR}"
|
||||
NO_DEFAULT_PATH
|
||||
)
|
||||
|
||||
if(NOT TARGET IrrlichtMt::IrrlichtMt)
|
||||
# find_package() searches certain subdirectories. ${PATH}/cmake is not
|
||||
# the only one, but it is the one where IrrlichtMt is supposed to export
|
||||
# IrrlichtMtConfig.cmake
|
||||
message(FATAL_ERROR "Could not find IrrlichtMtConfig.cmake in ${IRRLICHTMT_BUILD_DIR}/cmake.")
|
||||
endif()
|
||||
elseif(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/lib/irrlichtmt")
|
||||
message(STATUS "Using user-provided IrrlichtMt at subdirectory 'lib/irrlichtmt'")
|
||||
if(TRUE)
|
||||
message(STATUS "Using imported IrrlichtMt at subdirectory 'irr'")
|
||||
if(BUILD_CLIENT)
|
||||
# tell IrrlichtMt to create a static library
|
||||
set(BUILD_SHARED_LIBS OFF CACHE BOOL "Build shared library" FORCE)
|
||||
add_subdirectory(lib/irrlichtmt EXCLUDE_FROM_ALL)
|
||||
unset(BUILD_SHARED_LIBS CACHE)
|
||||
add_subdirectory(irr EXCLUDE_FROM_ALL)
|
||||
|
||||
if(NOT TARGET IrrlichtMt)
|
||||
message(FATAL_ERROR "IrrlichtMt project is missing a CMake target?!")
|
||||
@@ -108,47 +102,22 @@ elseif(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/lib/irrlichtmt")
|
||||
else()
|
||||
add_library(IrrlichtMt::IrrlichtMt INTERFACE IMPORTED)
|
||||
set_target_properties(IrrlichtMt::IrrlichtMt PROPERTIES
|
||||
INTERFACE_INCLUDE_DIRECTORIES "${CMAKE_CURRENT_SOURCE_DIR}/lib/irrlichtmt/include")
|
||||
endif()
|
||||
else()
|
||||
find_package(IrrlichtMt QUIET)
|
||||
if(NOT TARGET IrrlichtMt::IrrlichtMt)
|
||||
string(CONCAT explanation_msg
|
||||
"The Minetest team has forked Irrlicht to make their own customizations. "
|
||||
"It can be found here: https://github.com/minetest/irrlicht\n"
|
||||
"For example use: git clone --depth=1 https://github.com/minetest/irrlicht lib/irrlichtmt\n")
|
||||
if(BUILD_CLIENT)
|
||||
message(FATAL_ERROR "IrrlichtMt is required to build the client, but it was not found.\n${explanation_msg}")
|
||||
endif()
|
||||
|
||||
include(MinetestFindIrrlichtHeaders)
|
||||
if(NOT IRRLICHT_INCLUDE_DIR)
|
||||
message(FATAL_ERROR "IrrlichtMt headers are required to build the server, but none found.\n${explanation_msg}")
|
||||
endif()
|
||||
message(STATUS "Found IrrlichtMt headers: ${IRRLICHT_INCLUDE_DIR}")
|
||||
add_library(IrrlichtMt::IrrlichtMt INTERFACE IMPORTED)
|
||||
# Note that we can't use target_include_directories() since that doesn't work for IMPORTED targets before CMake 3.11
|
||||
set_target_properties(IrrlichtMt::IrrlichtMt PROPERTIES
|
||||
INTERFACE_INCLUDE_DIRECTORIES "${IRRLICHT_INCLUDE_DIR}")
|
||||
INTERFACE_INCLUDE_DIRECTORIES "${CMAKE_CURRENT_SOURCE_DIR}/irr/include")
|
||||
endif()
|
||||
endif()
|
||||
|
||||
if(ANDROID)
|
||||
# skipped for now
|
||||
elseif(BUILD_CLIENT AND TARGET IrrlichtMt::IrrlichtMt)
|
||||
# retrieve version somehow
|
||||
if(NOT IrrlichtMt_VERSION)
|
||||
get_target_property(IrrlichtMt_VERSION IrrlichtMt VERSION)
|
||||
endif()
|
||||
message(STATUS "Found IrrlichtMt ${IrrlichtMt_VERSION}")
|
||||
|
||||
set(TARGET_VER_S 1.9.0mt13)
|
||||
string(REPLACE "mt" "." TARGET_VER ${TARGET_VER_S})
|
||||
if(IrrlichtMt_VERSION VERSION_LESS ${TARGET_VER})
|
||||
message(FATAL_ERROR "At least IrrlichtMt ${TARGET_VER_S} is required to build")
|
||||
elseif(NOT DEVELOPMENT_BUILD AND IrrlichtMt_VERSION VERSION_GREATER ${TARGET_VER})
|
||||
message(FATAL_ERROR "IrrlichtMt ${TARGET_VER_S} is required to build")
|
||||
if (ENABLE_LTO OR CMAKE_INTERPROCEDURAL_OPTIMIZATION)
|
||||
include(CheckIPOSupported)
|
||||
check_ipo_supported(RESULT lto_supported OUTPUT lto_output)
|
||||
if(lto_supported)
|
||||
set(CMAKE_INTERPROCEDURAL_OPTIMIZATION TRUE)
|
||||
message(STATUS "LTO/IPO is enabled")
|
||||
else()
|
||||
set(CMAKE_INTERPROCEDURAL_OPTIMIZATION FALSE)
|
||||
message(STATUS "LTO/IPO was requested but is not supported by the compiler: ${lto_output}")
|
||||
endif()
|
||||
else()
|
||||
message(STATUS "LTO/IPO is not enabled")
|
||||
endif()
|
||||
|
||||
if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
|
||||
@@ -187,7 +156,7 @@ elseif(UNIX) # Linux, BSD etc
|
||||
set(EXAMPLE_CONF_DIR ".")
|
||||
set(MANDIR "unix/man")
|
||||
set(XDG_APPS_DIR "unix/applications")
|
||||
set(APPDATADIR "unix/metainfo")
|
||||
set(METAINFODIR "unix/metainfo")
|
||||
set(ICONDIR "unix/icons")
|
||||
set(LOCALEDIR "locale")
|
||||
else()
|
||||
@@ -198,7 +167,7 @@ elseif(UNIX) # Linux, BSD etc
|
||||
set(MANDIR "${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_MANDIR}")
|
||||
set(EXAMPLE_CONF_DIR ${DOCDIR})
|
||||
set(XDG_APPS_DIR "${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_DATADIR}/applications")
|
||||
set(APPDATADIR "${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_DATADIR}/metainfo")
|
||||
set(METAINFODIR "${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_DATADIR}/metainfo")
|
||||
set(ICONDIR "${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_DATADIR}/icons")
|
||||
set(LOCALEDIR "${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_LOCALEDIR}")
|
||||
endif()
|
||||
@@ -289,7 +258,7 @@ install(FILES "minetest.conf.example" DESTINATION "${EXAMPLE_CONF_DIR}")
|
||||
if(UNIX AND NOT APPLE)
|
||||
install(FILES "doc/minetest.6" "doc/minetestserver.6" DESTINATION "${MANDIR}/man6")
|
||||
install(FILES "misc/net.minetest.minetest.desktop" DESTINATION "${XDG_APPS_DIR}")
|
||||
install(FILES "misc/net.minetest.minetest.appdata.xml" DESTINATION "${APPDATADIR}")
|
||||
install(FILES "misc/net.minetest.minetest.metainfo.xml" DESTINATION "${METAINFODIR}")
|
||||
install(FILES "misc/minetest.svg" DESTINATION "${ICONDIR}/hicolor/scalable/apps")
|
||||
install(FILES "misc/minetest-xorg-icon-128.png"
|
||||
DESTINATION "${ICONDIR}/hicolor/128x128/apps"
|
||||
@@ -308,8 +277,9 @@ find_package(Lua REQUIRED)
|
||||
if(NOT USE_LUAJIT)
|
||||
add_subdirectory(lib/bitop)
|
||||
endif()
|
||||
add_subdirectory(lib/sha256)
|
||||
|
||||
if(BUILD_BENCHMARKS)
|
||||
if(BUILD_UNITTESTS OR BUILD_BENCHMARKS)
|
||||
add_subdirectory(lib/catch2)
|
||||
endif()
|
||||
|
||||
|
||||
41
CMakePresets.json
Normal file
41
CMakePresets.json
Normal file
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"version": 3,
|
||||
"cmakeMinimumRequired": {
|
||||
"major": 3,
|
||||
"minor": 12
|
||||
},
|
||||
"configurePresets": [
|
||||
{
|
||||
"name": "Debug",
|
||||
"displayName": "Debug",
|
||||
"description": "Debug preset with debug symbols and no optimizations",
|
||||
"cacheVariables": {
|
||||
"CMAKE_BUILD_TYPE": "Debug"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "Release",
|
||||
"displayName": "Release",
|
||||
"description": "Release preset with optimizations and no debug symbols",
|
||||
"cacheVariables": {
|
||||
"CMAKE_BUILD_TYPE": "Release"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "RelWithDebInfo",
|
||||
"displayName": "RelWithDebInfo",
|
||||
"description": "Release with debug symbols",
|
||||
"cacheVariables": {
|
||||
"CMAKE_BUILD_TYPE": "RelWithDebInfo"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "MinSizeRel",
|
||||
"displayName": "MinSizeRel",
|
||||
"description": "Release with minimal code size",
|
||||
"cacheVariables": {
|
||||
"CMAKE_BUILD_TYPE": "MinSizeRel"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
18
Dockerfile
18
Dockerfile
@@ -1,8 +1,6 @@
|
||||
ARG DOCKER_IMAGE=alpine:3.16
|
||||
ARG DOCKER_IMAGE=alpine:3.19
|
||||
FROM $DOCKER_IMAGE AS dev
|
||||
|
||||
ENV IRRLICHT_VERSION master
|
||||
ENV SPATIALINDEX_VERSION 1.9.3
|
||||
ENV LUAJIT_VERSION v2.1
|
||||
|
||||
RUN apk add --no-cache git build-base cmake curl-dev zlib-dev zstd-dev \
|
||||
@@ -10,7 +8,7 @@ RUN apk add --no-cache git build-base cmake curl-dev zlib-dev zstd-dev \
|
||||
gmp-dev jsoncpp-dev ninja ca-certificates
|
||||
|
||||
WORKDIR /usr/src/
|
||||
RUN git clone --recursive https://github.com/jupp0r/prometheus-cpp/ && \
|
||||
RUN git clone --recursive https://github.com/jupp0r/prometheus-cpp && \
|
||||
cd prometheus-cpp && \
|
||||
cmake -B build \
|
||||
-DCMAKE_INSTALL_PREFIX=/usr/local \
|
||||
@@ -20,7 +18,7 @@ RUN git clone --recursive https://github.com/jupp0r/prometheus-cpp/ && \
|
||||
cmake --build build && \
|
||||
cmake --install build && \
|
||||
cd /usr/src/ && \
|
||||
git clone --recursive https://github.com/libspatialindex/libspatialindex -b ${SPATIALINDEX_VERSION} && \
|
||||
git clone --recursive https://github.com/libspatialindex/libspatialindex && \
|
||||
cd libspatialindex && \
|
||||
cmake -B build \
|
||||
-DCMAKE_INSTALL_PREFIX=/usr/local && \
|
||||
@@ -29,10 +27,8 @@ RUN git clone --recursive https://github.com/jupp0r/prometheus-cpp/ && \
|
||||
cd /usr/src/ && \
|
||||
git clone --recursive https://luajit.org/git/luajit.git -b ${LUAJIT_VERSION} && \
|
||||
cd luajit && \
|
||||
make && make install && \
|
||||
cd /usr/src/ && \
|
||||
git clone --depth=1 https://github.com/minetest/irrlicht/ -b ${IRRLICHT_VERSION} && \
|
||||
cp -r irrlicht/include /usr/include/irrlichtmt
|
||||
make amalg && make install && \
|
||||
cd /usr/src/
|
||||
|
||||
FROM dev as builder
|
||||
|
||||
@@ -48,6 +44,7 @@ COPY lib /usr/src/minetest/lib
|
||||
COPY misc /usr/src/minetest/misc
|
||||
COPY po /usr/src/minetest/po
|
||||
COPY src /usr/src/minetest/src
|
||||
COPY irr /usr/src/minetest/irr
|
||||
COPY textures /usr/src/minetest/textures
|
||||
|
||||
WORKDIR /usr/src/minetest
|
||||
@@ -56,13 +53,12 @@ RUN cmake -B build \
|
||||
-DCMAKE_BUILD_TYPE=Release \
|
||||
-DBUILD_SERVER=TRUE \
|
||||
-DENABLE_PROMETHEUS=TRUE \
|
||||
-DBUILD_UNITTESTS=FALSE \
|
||||
-DBUILD_UNITTESTS=FALSE -DBUILD_BENCHMARKS=FALSE \
|
||||
-DBUILD_CLIENT=FALSE \
|
||||
-GNinja && \
|
||||
cmake --build build && \
|
||||
cmake --install build
|
||||
|
||||
ARG DOCKER_IMAGE=alpine:3.16
|
||||
FROM $DOCKER_IMAGE AS runtime
|
||||
|
||||
RUN apk add --no-cache curl gmp libstdc++ libgcc libpq jsoncpp zstd-libs \
|
||||
|
||||
29
README.md
29
README.md
@@ -25,11 +25,11 @@ Table of Contents
|
||||
|
||||
Further documentation
|
||||
----------------------
|
||||
- Website: https://minetest.net/
|
||||
- Website: https://www.minetest.net/
|
||||
- Wiki: https://wiki.minetest.net/
|
||||
- Developer wiki: https://dev.minetest.net/
|
||||
- Forum: https://forum.minetest.net/
|
||||
- GitHub: https://github.com/minetest/minetest/
|
||||
- [Developer documentation](doc/developing/)
|
||||
- [doc/](doc/) directory of source distribution
|
||||
|
||||
Default controls
|
||||
@@ -127,30 +127,7 @@ Docker
|
||||
------
|
||||
|
||||
- [Developing minetestserver with Docker](doc/developing/docker.md)
|
||||
|
||||
We provide Minetest server Docker images using the GitLab mirror registry.
|
||||
|
||||
Images are built on each commit and available using the following tag scheme:
|
||||
|
||||
* `registry.gitlab.com/minetest/minetest/server:latest` (latest build)
|
||||
* `registry.gitlab.com/minetest/minetest/server:<branch/tag>` (current branch or current tag)
|
||||
* `registry.gitlab.com/minetest/minetest/server:<commit-id>` (current commit id)
|
||||
|
||||
If you want to test it on a Docker server you can easily run:
|
||||
|
||||
sudo docker run registry.gitlab.com/minetest/minetest/server:<docker tag>
|
||||
|
||||
If you want to use it in a production environment you should use volumes bound to the Docker host
|
||||
to persist data and modify the configuration:
|
||||
|
||||
sudo docker create -v /home/minetest/data/:/var/lib/minetest/ -v /home/minetest/conf/:/etc/minetest/ registry.gitlab.com/minetest/minetest/server:master
|
||||
|
||||
Data will be written to `/home/minetest/data` on the host, and configuration will be read from `/home/minetest/conf/minetest.conf`.
|
||||
|
||||
**Note:** If you don't understand the previous commands please read the official Docker documentation before use.
|
||||
|
||||
You can also host your Minetest server inside a Kubernetes cluster. See our example implementation in [`misc/kubernetes.yml`](misc/kubernetes.yml).
|
||||
|
||||
- [Running a server with Docker](doc/docker_server.md)
|
||||
|
||||
Version scheme
|
||||
--------------
|
||||
|
||||
18
android/SDL_Java_RMB_fix.patch
Normal file
18
android/SDL_Java_RMB_fix.patch
Normal file
@@ -0,0 +1,18 @@
|
||||
diff --git a/android/app/src/main/java/org/libsdl/app/SDLActivity.java b/android/app/src/main/java/org/libsdl/app/SDLActivity.java
|
||||
index fd5a056e3..83e3cf657 100644
|
||||
--- a/android/app/src/main/java/org/libsdl/app/SDLActivity.java
|
||||
+++ b/android/app/src/main/java/org/libsdl/app/SDLActivity.java
|
||||
@@ -1345,7 +1345,12 @@ public class SDLActivity extends Activity implements View.OnSystemUiVisibilityCh
|
||||
}
|
||||
}
|
||||
|
||||
- if ((source & InputDevice.SOURCE_MOUSE) == InputDevice.SOURCE_MOUSE) {
|
||||
+ if ((source & InputDevice.SOURCE_MOUSE) == InputDevice.SOURCE_MOUSE ||
|
||||
+ /*
|
||||
+ * CUSTOM ADDITION FOR MINETEST
|
||||
+ * should be upstreamed
|
||||
+ */
|
||||
+ (source & InputDevice.SOURCE_MOUSE_RELATIVE) == InputDevice.SOURCE_MOUSE_RELATIVE) {
|
||||
// on some devices key events are sent for mouse BUTTON_BACK/FORWARD presses
|
||||
// they are ignored here because sending them as mouse input to SDL is messy
|
||||
if ((keyCode == KeyEvent.KEYCODE_BACK) || (keyCode == KeyEvent.KEYCODE_FORWARD)) {
|
||||
@@ -1,17 +1,20 @@
|
||||
apply plugin: 'com.android.application'
|
||||
|
||||
android {
|
||||
compileSdkVersion 33
|
||||
buildToolsVersion '33.0.2'
|
||||
ndkVersion "$ndk_version"
|
||||
defaultConfig {
|
||||
applicationId 'net.minetest.minetest'
|
||||
minSdkVersion 21
|
||||
targetSdkVersion 33
|
||||
compileSdk 34
|
||||
targetSdkVersion 34
|
||||
versionName "${versionMajor}.${versionMinor}.${versionPatch}"
|
||||
versionCode project.versionCode
|
||||
}
|
||||
|
||||
buildFeatures {
|
||||
buildConfig true
|
||||
}
|
||||
|
||||
// load properties
|
||||
Properties props = new Properties()
|
||||
def propfile = file('../local.properties')
|
||||
@@ -49,6 +52,7 @@ android {
|
||||
sourceCompatibility JavaVersion.VERSION_1_8
|
||||
targetCompatibility JavaVersion.VERSION_1_8
|
||||
}
|
||||
namespace 'net.minetest.minetest'
|
||||
}
|
||||
|
||||
task prepareAssets() {
|
||||
@@ -75,7 +79,7 @@ task prepareAssets() {
|
||||
from "${projRoot}/client/shaders" into "${assetsFolder}/client/shaders"
|
||||
}
|
||||
copy {
|
||||
from "../native/deps/armeabi-v7a/Irrlicht/Shaders" into "${assetsFolder}/client/shaders/Irrlicht"
|
||||
from "${projRoot}/irr/media/Shaders" into "${assetsFolder}/client/shaders/Irrlicht"
|
||||
}
|
||||
copy {
|
||||
from "${projRoot}/fonts" include "*.ttf" into "${assetsFolder}/fonts"
|
||||
@@ -108,6 +112,10 @@ task prepareAssets() {
|
||||
preBuild.dependsOn zipAssets
|
||||
prepareAssets.dependsOn ':native:getDeps'
|
||||
|
||||
clean {
|
||||
delete new File("src/main/assets", "Minetest.zip")
|
||||
}
|
||||
|
||||
// Map for the version code that gives each ABI a value.
|
||||
import com.android.build.OutputFile
|
||||
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:tools="http://schemas.android.com/tools"
|
||||
package="net.minetest.minetest"
|
||||
android:installLocation="auto">
|
||||
android:installLocation="auto">
|
||||
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
|
||||
@@ -20,8 +20,10 @@ with this program; if not, write to the Free Software Foundation, Inc.,
|
||||
|
||||
package net.minetest.minetest;
|
||||
|
||||
import android.app.NativeActivity;
|
||||
import org.libsdl.app.SDLActivity;
|
||||
|
||||
import android.content.Intent;
|
||||
import android.content.ActivityNotFoundException;
|
||||
import android.net.Uri;
|
||||
import android.os.Bundle;
|
||||
import android.text.InputType;
|
||||
@@ -32,6 +34,8 @@ import android.view.WindowManager;
|
||||
import android.view.inputmethod.InputMethodManager;
|
||||
import android.widget.Button;
|
||||
import android.widget.LinearLayout;
|
||||
import android.widget.Toast;
|
||||
import android.content.res.Configuration;
|
||||
|
||||
import androidx.annotation.Keep;
|
||||
import androidx.appcompat.app.AlertDialog;
|
||||
@@ -45,51 +49,59 @@ import java.util.Objects;
|
||||
// This annotation prevents the minifier/Proguard from mangling them.
|
||||
@Keep
|
||||
@SuppressWarnings("unused")
|
||||
public class GameActivity extends NativeActivity {
|
||||
static {
|
||||
System.loadLibrary("c++_shared");
|
||||
System.loadLibrary("minetest");
|
||||
public class GameActivity extends SDLActivity {
|
||||
@Override
|
||||
protected String getMainSharedObject() {
|
||||
return getContext().getApplicationInfo().nativeLibraryDir + "/libminetest.so";
|
||||
}
|
||||
|
||||
private int messageReturnCode = -1;
|
||||
@Override
|
||||
protected String getMainFunction() {
|
||||
return "SDL_Main";
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String[] getLibraries() {
|
||||
return new String[] {
|
||||
"minetest"
|
||||
};
|
||||
}
|
||||
|
||||
// Prevent SDL from changing orientation settings since we already set the
|
||||
// correct orientation in our AndroidManifest.xml
|
||||
@Override
|
||||
public void setOrientationBis(int w, int h, boolean resizable, String hint) {}
|
||||
|
||||
enum DialogType { TEXT_INPUT, SELECTION_INPUT }
|
||||
enum DialogState { DIALOG_SHOWN, DIALOG_INPUTTED, DIALOG_CANCELED }
|
||||
|
||||
private DialogType lastDialogType = DialogType.TEXT_INPUT;
|
||||
private DialogState inputDialogState = DialogState.DIALOG_CANCELED;
|
||||
private String messageReturnValue = "";
|
||||
private int selectionReturnValue = 0;
|
||||
|
||||
private native void saveSettings();
|
||||
|
||||
@Override
|
||||
public void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
|
||||
protected void onStop() {
|
||||
super.onStop();
|
||||
// Avoid losing setting changes in case the app is onDestroy()ed later.
|
||||
// Saving stuff in onStop() is recommended in the Android activity
|
||||
// lifecycle documentation.
|
||||
saveSettings();
|
||||
}
|
||||
|
||||
private void makeFullScreen() {
|
||||
this.getWindow().getDecorView().setSystemUiVisibility(
|
||||
View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION |
|
||||
View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
|
||||
View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
|
||||
public void showTextInputDialog(String hint, String current, int editType) {
|
||||
runOnUiThread(() -> showTextInputDialogUI(hint, current, editType));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onWindowFocusChanged(boolean hasFocus) {
|
||||
super.onWindowFocusChanged(hasFocus);
|
||||
if (hasFocus)
|
||||
makeFullScreen();
|
||||
public void showSelectionInputDialog(String[] optionList, int selectedIdx) {
|
||||
runOnUiThread(() -> showSelectionInputDialogUI(optionList, selectedIdx));
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onResume() {
|
||||
super.onResume();
|
||||
makeFullScreen();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onBackPressed() {
|
||||
// Ignore the back press so Minetest can handle it
|
||||
}
|
||||
|
||||
public void showDialog(String acceptButton, String hint, String current, int editType) {
|
||||
runOnUiThread(() -> showDialogUI(hint, current, editType));
|
||||
}
|
||||
|
||||
private void showDialogUI(String hint, String current, int editType) {
|
||||
private void showTextInputDialogUI(String hint, String current, int editType) {
|
||||
lastDialogType = DialogType.TEXT_INPUT;
|
||||
inputDialogState = DialogState.DIALOG_SHOWN;
|
||||
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
|
||||
LinearLayout container = new LinearLayout(this);
|
||||
container.setOrientation(LinearLayout.VERTICAL);
|
||||
@@ -114,7 +126,7 @@ public class GameActivity extends NativeActivity {
|
||||
// For multi-line, do not submit the text after pressing Enter key
|
||||
if (keyCode == KeyEvent.KEYCODE_ENTER && editType != 1) {
|
||||
imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
|
||||
messageReturnCode = 0;
|
||||
inputDialogState = DialogState.DIALOG_INPUTTED;
|
||||
messageReturnValue = editText.getText().toString();
|
||||
alertDialog.dismiss();
|
||||
return true;
|
||||
@@ -128,29 +140,55 @@ public class GameActivity extends NativeActivity {
|
||||
doneButton.setText(R.string.ime_dialog_done);
|
||||
doneButton.setOnClickListener((view -> {
|
||||
imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
|
||||
messageReturnCode = 0;
|
||||
inputDialogState = DialogState.DIALOG_INPUTTED;
|
||||
messageReturnValue = editText.getText().toString();
|
||||
alertDialog.dismiss();
|
||||
}));
|
||||
}
|
||||
alertDialog.setOnCancelListener(dialog -> {
|
||||
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
|
||||
inputDialogState = DialogState.DIALOG_CANCELED;
|
||||
messageReturnValue = current;
|
||||
messageReturnCode = -1;
|
||||
});
|
||||
alertDialog.show();
|
||||
editText.requestFocusTryShow();
|
||||
}
|
||||
|
||||
public int getDialogState() {
|
||||
return messageReturnCode;
|
||||
public void showSelectionInputDialogUI(String[] optionList, int selectedIdx) {
|
||||
lastDialogType = DialogType.SELECTION_INPUT;
|
||||
inputDialogState = DialogState.DIALOG_SHOWN;
|
||||
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
|
||||
builder.setSingleChoiceItems(optionList, selectedIdx, (dialog, selection) -> {
|
||||
inputDialogState = DialogState.DIALOG_INPUTTED;
|
||||
selectionReturnValue = selection;
|
||||
dialog.dismiss();
|
||||
});
|
||||
builder.setOnCancelListener(dialog -> {
|
||||
inputDialogState = DialogState.DIALOG_CANCELED;
|
||||
selectionReturnValue = selectedIdx;
|
||||
});
|
||||
AlertDialog alertDialog = builder.create();
|
||||
alertDialog.show();
|
||||
}
|
||||
|
||||
public String getDialogValue() {
|
||||
messageReturnCode = -1;
|
||||
public int getLastDialogType() {
|
||||
return lastDialogType.ordinal();
|
||||
}
|
||||
|
||||
public int getInputDialogState() {
|
||||
return inputDialogState.ordinal();
|
||||
}
|
||||
|
||||
public String getDialogMessage() {
|
||||
inputDialogState = DialogState.DIALOG_CANCELED;
|
||||
return messageReturnValue;
|
||||
}
|
||||
|
||||
public int getDialogSelection() {
|
||||
inputDialogState = DialogState.DIALOG_CANCELED;
|
||||
return selectionReturnValue;
|
||||
}
|
||||
|
||||
public float getDensity() {
|
||||
return getResources().getDisplayMetrics().density;
|
||||
}
|
||||
@@ -165,7 +203,11 @@ public class GameActivity extends NativeActivity {
|
||||
|
||||
public void openURI(String uri) {
|
||||
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
|
||||
startActivity(browserIntent);
|
||||
try {
|
||||
startActivity(browserIntent);
|
||||
} catch (ActivityNotFoundException e) {
|
||||
runOnUiThread(() -> Toast.makeText(this, R.string.no_web_browser, Toast.LENGTH_SHORT).show());
|
||||
}
|
||||
}
|
||||
|
||||
public String getUserDataPath() {
|
||||
@@ -217,4 +259,8 @@ public class GameActivity extends NativeActivity {
|
||||
|
||||
return langCode;
|
||||
}
|
||||
|
||||
public boolean hasPhysicalKeyboard() {
|
||||
return getContext().getResources().getConfiguration().keyboard != Configuration.KEYBOARD_NOKEYS;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,23 +20,30 @@ with this program; if not, write to the Free Software Foundation, Inc.,
|
||||
|
||||
package net.minetest.minetest;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.app.NotificationChannel;
|
||||
import android.app.NotificationManager;
|
||||
import android.content.BroadcastReceiver;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.IntentFilter;
|
||||
import android.content.SharedPreferences;
|
||||
import android.os.Build;
|
||||
import android.os.Bundle;
|
||||
import android.view.View;
|
||||
import android.widget.ProgressBar;
|
||||
import android.widget.TextView;
|
||||
import android.widget.Toast;
|
||||
|
||||
import androidx.annotation.RequiresApi;
|
||||
import androidx.annotation.StringRes;
|
||||
import androidx.appcompat.app.AppCompatActivity;
|
||||
|
||||
import static net.minetest.minetest.UnzipService.*;
|
||||
|
||||
public class MainActivity extends AppCompatActivity {
|
||||
public static final String NOTIFICATION_CHANNEL_ID = "Minetest channel";
|
||||
|
||||
private final static int versionCode = BuildConfig.VERSION_CODE;
|
||||
private static final String SETTINGS = "MinetestSettings";
|
||||
private static final String TAG_VERSION_CODE = "versionCode";
|
||||
@@ -77,16 +84,27 @@ public class MainActivity extends AppCompatActivity {
|
||||
}
|
||||
};
|
||||
|
||||
@SuppressLint("UnspecifiedRegisterReceiverFlag")
|
||||
@Override
|
||||
public void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
setContentView(R.layout.activity_main);
|
||||
|
||||
IntentFilter filter = new IntentFilter(ACTION_UPDATE);
|
||||
registerReceiver(myReceiver, filter);
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||
registerReceiver(myReceiver, filter, RECEIVER_NOT_EXPORTED);
|
||||
} else {
|
||||
registerReceiver(myReceiver, filter);
|
||||
}
|
||||
|
||||
mProgressBar = findViewById(R.id.progressBar);
|
||||
mTextView = findViewById(R.id.textView);
|
||||
sharedPreferences = getSharedPreferences(SETTINGS, Context.MODE_PRIVATE);
|
||||
|
||||
checkAppVersion();
|
||||
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
|
||||
createNotificationChannel();
|
||||
}
|
||||
|
||||
private void checkAppVersion() {
|
||||
@@ -114,6 +132,28 @@ public class MainActivity extends AppCompatActivity {
|
||||
startActivity(intent);
|
||||
}
|
||||
|
||||
@RequiresApi(Build.VERSION_CODES.O)
|
||||
private void createNotificationChannel() {
|
||||
NotificationManager notifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
|
||||
if (notifyManager == null)
|
||||
return;
|
||||
|
||||
NotificationChannel notifyChannel = new NotificationChannel(
|
||||
NOTIFICATION_CHANNEL_ID,
|
||||
getString(R.string.notification_channel_name),
|
||||
NotificationManager.IMPORTANCE_LOW
|
||||
);
|
||||
notifyChannel.setDescription(getString(R.string.notification_channel_description));
|
||||
// Configure the notification channel without sound set
|
||||
notifyChannel.setSound(null, null);
|
||||
notifyChannel.enableLights(false);
|
||||
notifyChannel.enableVibration(false);
|
||||
|
||||
// It is fine to always create the notification channel because creating a channel
|
||||
// with the same ID is the same as overriding it (only its name and description).
|
||||
notifyManager.createNotificationChannel(notifyChannel);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onBackPressed() {
|
||||
// Prevent abrupt interruption when copy game files from assets
|
||||
|
||||
@@ -22,7 +22,6 @@ package net.minetest.minetest;
|
||||
|
||||
import android.app.IntentService;
|
||||
import android.app.Notification;
|
||||
import android.app.NotificationChannel;
|
||||
import android.app.NotificationManager;
|
||||
import android.app.PendingIntent;
|
||||
import android.content.Context;
|
||||
@@ -58,9 +57,11 @@ public class UnzipService extends IntentService {
|
||||
private String failureMessage;
|
||||
|
||||
private static boolean isRunning = false;
|
||||
|
||||
public static synchronized boolean getIsRunning() {
|
||||
return isRunning;
|
||||
}
|
||||
|
||||
private static synchronized void setIsRunning(boolean v) {
|
||||
isRunning = v;
|
||||
}
|
||||
@@ -99,28 +100,13 @@ public class UnzipService extends IntentService {
|
||||
}
|
||||
}
|
||||
|
||||
@NonNull
|
||||
private Notification.Builder createNotification() {
|
||||
String name = "net.minetest.minetest";
|
||||
String channelId = "Minetest channel";
|
||||
String description = "notifications from Minetest";
|
||||
Notification.Builder builder;
|
||||
if (mNotifyManager == null)
|
||||
mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
int importance = NotificationManager.IMPORTANCE_LOW;
|
||||
NotificationChannel mChannel = null;
|
||||
if (mNotifyManager != null)
|
||||
mChannel = mNotifyManager.getNotificationChannel(channelId);
|
||||
if (mChannel == null) {
|
||||
mChannel = new NotificationChannel(channelId, name, importance);
|
||||
mChannel.setDescription(description);
|
||||
// Configure the notification channel, NO SOUND
|
||||
mChannel.setSound(null, null);
|
||||
mChannel.enableLights(false);
|
||||
mChannel.enableVibration(false);
|
||||
mNotifyManager.createNotificationChannel(mChannel);
|
||||
}
|
||||
builder = new Notification.Builder(this, channelId);
|
||||
builder = new Notification.Builder(this, MainActivity.NOTIFICATION_CHANNEL_ID);
|
||||
} else {
|
||||
builder = new Notification.Builder(this);
|
||||
}
|
||||
@@ -135,9 +121,9 @@ public class UnzipService extends IntentService {
|
||||
PendingIntent intent = PendingIntent.getActivity(this, 0,
|
||||
notificationIntent, pendingIntentFlag);
|
||||
|
||||
builder.setContentTitle(getString(R.string.notification_title))
|
||||
builder.setContentTitle(getString(R.string.unzip_notification_title))
|
||||
.setSmallIcon(R.mipmap.ic_launcher)
|
||||
.setContentText(getString(R.string.notification_description))
|
||||
.setContentText(getString(R.string.unzip_notification_description))
|
||||
.setContentIntent(intent)
|
||||
.setOngoing(true)
|
||||
.setProgress(0, 0, true);
|
||||
@@ -198,8 +184,9 @@ public class UnzipService extends IntentService {
|
||||
}
|
||||
}
|
||||
|
||||
private void publishProgress(@Nullable Notification.Builder notificationBuilder, @StringRes int message, int progress) {
|
||||
private void publishProgress(@Nullable Notification.Builder notificationBuilder, @StringRes int message, int progress) {
|
||||
Intent intentUpdate = new Intent(ACTION_UPDATE);
|
||||
intentUpdate.setPackage(getPackageName());
|
||||
intentUpdate.putExtra(ACTION_PROGRESS, progress);
|
||||
intentUpdate.putExtra(ACTION_PROGRESS_MESSAGE, message);
|
||||
if (!isSuccess)
|
||||
|
||||
22
android/app/src/main/java/org/libsdl/app/HIDDevice.java
Normal file
22
android/app/src/main/java/org/libsdl/app/HIDDevice.java
Normal file
@@ -0,0 +1,22 @@
|
||||
package org.libsdl.app;
|
||||
|
||||
import android.hardware.usb.UsbDevice;
|
||||
|
||||
interface HIDDevice
|
||||
{
|
||||
public int getId();
|
||||
public int getVendorId();
|
||||
public int getProductId();
|
||||
public String getSerialNumber();
|
||||
public int getVersion();
|
||||
public String getManufacturerName();
|
||||
public String getProductName();
|
||||
public UsbDevice getDevice();
|
||||
public boolean open();
|
||||
public int sendFeatureReport(byte[] report);
|
||||
public int sendOutputReport(byte[] report);
|
||||
public boolean getFeatureReport(byte[] report);
|
||||
public void setFrozen(boolean frozen);
|
||||
public void close();
|
||||
public void shutdown();
|
||||
}
|
||||
@@ -0,0 +1,650 @@
|
||||
package org.libsdl.app;
|
||||
|
||||
import android.content.Context;
|
||||
import android.bluetooth.BluetoothDevice;
|
||||
import android.bluetooth.BluetoothGatt;
|
||||
import android.bluetooth.BluetoothGattCallback;
|
||||
import android.bluetooth.BluetoothGattCharacteristic;
|
||||
import android.bluetooth.BluetoothGattDescriptor;
|
||||
import android.bluetooth.BluetoothManager;
|
||||
import android.bluetooth.BluetoothProfile;
|
||||
import android.bluetooth.BluetoothGattService;
|
||||
import android.hardware.usb.UsbDevice;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.util.Log;
|
||||
import android.os.*;
|
||||
|
||||
//import com.android.internal.util.HexDump;
|
||||
|
||||
import java.lang.Runnable;
|
||||
import java.util.Arrays;
|
||||
import java.util.LinkedList;
|
||||
import java.util.UUID;
|
||||
|
||||
class HIDDeviceBLESteamController extends BluetoothGattCallback implements HIDDevice {
|
||||
|
||||
private static final String TAG = "hidapi";
|
||||
private HIDDeviceManager mManager;
|
||||
private BluetoothDevice mDevice;
|
||||
private int mDeviceId;
|
||||
private BluetoothGatt mGatt;
|
||||
private boolean mIsRegistered = false;
|
||||
private boolean mIsConnected = false;
|
||||
private boolean mIsChromebook = false;
|
||||
private boolean mIsReconnecting = false;
|
||||
private boolean mFrozen = false;
|
||||
private LinkedList<GattOperation> mOperations;
|
||||
GattOperation mCurrentOperation = null;
|
||||
private Handler mHandler;
|
||||
|
||||
private static final int TRANSPORT_AUTO = 0;
|
||||
private static final int TRANSPORT_BREDR = 1;
|
||||
private static final int TRANSPORT_LE = 2;
|
||||
|
||||
private static final int CHROMEBOOK_CONNECTION_CHECK_INTERVAL = 10000;
|
||||
|
||||
static public final UUID steamControllerService = UUID.fromString("100F6C32-1735-4313-B402-38567131E5F3");
|
||||
static public final UUID inputCharacteristic = UUID.fromString("100F6C33-1735-4313-B402-38567131E5F3");
|
||||
static public final UUID reportCharacteristic = UUID.fromString("100F6C34-1735-4313-B402-38567131E5F3");
|
||||
static private final byte[] enterValveMode = new byte[] { (byte)0xC0, (byte)0x87, 0x03, 0x08, 0x07, 0x00 };
|
||||
|
||||
static class GattOperation {
|
||||
private enum Operation {
|
||||
CHR_READ,
|
||||
CHR_WRITE,
|
||||
ENABLE_NOTIFICATION
|
||||
}
|
||||
|
||||
Operation mOp;
|
||||
UUID mUuid;
|
||||
byte[] mValue;
|
||||
BluetoothGatt mGatt;
|
||||
boolean mResult = true;
|
||||
|
||||
private GattOperation(BluetoothGatt gatt, GattOperation.Operation operation, UUID uuid) {
|
||||
mGatt = gatt;
|
||||
mOp = operation;
|
||||
mUuid = uuid;
|
||||
}
|
||||
|
||||
private GattOperation(BluetoothGatt gatt, GattOperation.Operation operation, UUID uuid, byte[] value) {
|
||||
mGatt = gatt;
|
||||
mOp = operation;
|
||||
mUuid = uuid;
|
||||
mValue = value;
|
||||
}
|
||||
|
||||
public void run() {
|
||||
// This is executed in main thread
|
||||
BluetoothGattCharacteristic chr;
|
||||
|
||||
switch (mOp) {
|
||||
case CHR_READ:
|
||||
chr = getCharacteristic(mUuid);
|
||||
//Log.v(TAG, "Reading characteristic " + chr.getUuid());
|
||||
if (!mGatt.readCharacteristic(chr)) {
|
||||
Log.e(TAG, "Unable to read characteristic " + mUuid.toString());
|
||||
mResult = false;
|
||||
break;
|
||||
}
|
||||
mResult = true;
|
||||
break;
|
||||
case CHR_WRITE:
|
||||
chr = getCharacteristic(mUuid);
|
||||
//Log.v(TAG, "Writing characteristic " + chr.getUuid() + " value=" + HexDump.toHexString(value));
|
||||
chr.setValue(mValue);
|
||||
if (!mGatt.writeCharacteristic(chr)) {
|
||||
Log.e(TAG, "Unable to write characteristic " + mUuid.toString());
|
||||
mResult = false;
|
||||
break;
|
||||
}
|
||||
mResult = true;
|
||||
break;
|
||||
case ENABLE_NOTIFICATION:
|
||||
chr = getCharacteristic(mUuid);
|
||||
//Log.v(TAG, "Writing descriptor of " + chr.getUuid());
|
||||
if (chr != null) {
|
||||
BluetoothGattDescriptor cccd = chr.getDescriptor(UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));
|
||||
if (cccd != null) {
|
||||
int properties = chr.getProperties();
|
||||
byte[] value;
|
||||
if ((properties & BluetoothGattCharacteristic.PROPERTY_NOTIFY) == BluetoothGattCharacteristic.PROPERTY_NOTIFY) {
|
||||
value = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE;
|
||||
} else if ((properties & BluetoothGattCharacteristic.PROPERTY_INDICATE) == BluetoothGattCharacteristic.PROPERTY_INDICATE) {
|
||||
value = BluetoothGattDescriptor.ENABLE_INDICATION_VALUE;
|
||||
} else {
|
||||
Log.e(TAG, "Unable to start notifications on input characteristic");
|
||||
mResult = false;
|
||||
return;
|
||||
}
|
||||
|
||||
mGatt.setCharacteristicNotification(chr, true);
|
||||
cccd.setValue(value);
|
||||
if (!mGatt.writeDescriptor(cccd)) {
|
||||
Log.e(TAG, "Unable to write descriptor " + mUuid.toString());
|
||||
mResult = false;
|
||||
return;
|
||||
}
|
||||
mResult = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public boolean finish() {
|
||||
return mResult;
|
||||
}
|
||||
|
||||
private BluetoothGattCharacteristic getCharacteristic(UUID uuid) {
|
||||
BluetoothGattService valveService = mGatt.getService(steamControllerService);
|
||||
if (valveService == null)
|
||||
return null;
|
||||
return valveService.getCharacteristic(uuid);
|
||||
}
|
||||
|
||||
static public GattOperation readCharacteristic(BluetoothGatt gatt, UUID uuid) {
|
||||
return new GattOperation(gatt, Operation.CHR_READ, uuid);
|
||||
}
|
||||
|
||||
static public GattOperation writeCharacteristic(BluetoothGatt gatt, UUID uuid, byte[] value) {
|
||||
return new GattOperation(gatt, Operation.CHR_WRITE, uuid, value);
|
||||
}
|
||||
|
||||
static public GattOperation enableNotification(BluetoothGatt gatt, UUID uuid) {
|
||||
return new GattOperation(gatt, Operation.ENABLE_NOTIFICATION, uuid);
|
||||
}
|
||||
}
|
||||
|
||||
public HIDDeviceBLESteamController(HIDDeviceManager manager, BluetoothDevice device) {
|
||||
mManager = manager;
|
||||
mDevice = device;
|
||||
mDeviceId = mManager.getDeviceIDForIdentifier(getIdentifier());
|
||||
mIsRegistered = false;
|
||||
mIsChromebook = mManager.getContext().getPackageManager().hasSystemFeature("org.chromium.arc.device_management");
|
||||
mOperations = new LinkedList<GattOperation>();
|
||||
mHandler = new Handler(Looper.getMainLooper());
|
||||
|
||||
mGatt = connectGatt();
|
||||
// final HIDDeviceBLESteamController finalThis = this;
|
||||
// mHandler.postDelayed(new Runnable() {
|
||||
// @Override
|
||||
// public void run() {
|
||||
// finalThis.checkConnectionForChromebookIssue();
|
||||
// }
|
||||
// }, CHROMEBOOK_CONNECTION_CHECK_INTERVAL);
|
||||
}
|
||||
|
||||
public String getIdentifier() {
|
||||
return String.format("SteamController.%s", mDevice.getAddress());
|
||||
}
|
||||
|
||||
public BluetoothGatt getGatt() {
|
||||
return mGatt;
|
||||
}
|
||||
|
||||
// Because on Chromebooks we show up as a dual-mode device, it will attempt to connect TRANSPORT_AUTO, which will use TRANSPORT_BREDR instead
|
||||
// of TRANSPORT_LE. Let's force ourselves to connect low energy.
|
||||
private BluetoothGatt connectGatt(boolean managed) {
|
||||
if (Build.VERSION.SDK_INT >= 23 /* Android 6.0 (M) */) {
|
||||
try {
|
||||
return mDevice.connectGatt(mManager.getContext(), managed, this, TRANSPORT_LE);
|
||||
} catch (Exception e) {
|
||||
return mDevice.connectGatt(mManager.getContext(), managed, this);
|
||||
}
|
||||
} else {
|
||||
return mDevice.connectGatt(mManager.getContext(), managed, this);
|
||||
}
|
||||
}
|
||||
|
||||
private BluetoothGatt connectGatt() {
|
||||
return connectGatt(false);
|
||||
}
|
||||
|
||||
protected int getConnectionState() {
|
||||
|
||||
Context context = mManager.getContext();
|
||||
if (context == null) {
|
||||
// We are lacking any context to get our Bluetooth information. We'll just assume disconnected.
|
||||
return BluetoothProfile.STATE_DISCONNECTED;
|
||||
}
|
||||
|
||||
BluetoothManager btManager = (BluetoothManager)context.getSystemService(Context.BLUETOOTH_SERVICE);
|
||||
if (btManager == null) {
|
||||
// This device doesn't support Bluetooth. We should never be here, because how did
|
||||
// we instantiate a device to start with?
|
||||
return BluetoothProfile.STATE_DISCONNECTED;
|
||||
}
|
||||
|
||||
return btManager.getConnectionState(mDevice, BluetoothProfile.GATT);
|
||||
}
|
||||
|
||||
public void reconnect() {
|
||||
|
||||
if (getConnectionState() != BluetoothProfile.STATE_CONNECTED) {
|
||||
mGatt.disconnect();
|
||||
mGatt = connectGatt();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
protected void checkConnectionForChromebookIssue() {
|
||||
if (!mIsChromebook) {
|
||||
// We only do this on Chromebooks, because otherwise it's really annoying to just attempt
|
||||
// over and over.
|
||||
return;
|
||||
}
|
||||
|
||||
int connectionState = getConnectionState();
|
||||
|
||||
switch (connectionState) {
|
||||
case BluetoothProfile.STATE_CONNECTED:
|
||||
if (!mIsConnected) {
|
||||
// We are in the Bad Chromebook Place. We can force a disconnect
|
||||
// to try to recover.
|
||||
Log.v(TAG, "Chromebook: We are in a very bad state; the controller shows as connected in the underlying Bluetooth layer, but we never received a callback. Forcing a reconnect.");
|
||||
mIsReconnecting = true;
|
||||
mGatt.disconnect();
|
||||
mGatt = connectGatt(false);
|
||||
break;
|
||||
}
|
||||
else if (!isRegistered()) {
|
||||
if (mGatt.getServices().size() > 0) {
|
||||
Log.v(TAG, "Chromebook: We are connected to a controller, but never got our registration. Trying to recover.");
|
||||
probeService(this);
|
||||
}
|
||||
else {
|
||||
Log.v(TAG, "Chromebook: We are connected to a controller, but never discovered services. Trying to recover.");
|
||||
mIsReconnecting = true;
|
||||
mGatt.disconnect();
|
||||
mGatt = connectGatt(false);
|
||||
break;
|
||||
}
|
||||
}
|
||||
else {
|
||||
Log.v(TAG, "Chromebook: We are connected, and registered. Everything's good!");
|
||||
return;
|
||||
}
|
||||
break;
|
||||
|
||||
case BluetoothProfile.STATE_DISCONNECTED:
|
||||
Log.v(TAG, "Chromebook: We have either been disconnected, or the Chromebook BtGatt.ContextMap bug has bitten us. Attempting a disconnect/reconnect, but we may not be able to recover.");
|
||||
|
||||
mIsReconnecting = true;
|
||||
mGatt.disconnect();
|
||||
mGatt = connectGatt(false);
|
||||
break;
|
||||
|
||||
case BluetoothProfile.STATE_CONNECTING:
|
||||
Log.v(TAG, "Chromebook: We're still trying to connect. Waiting a bit longer.");
|
||||
break;
|
||||
}
|
||||
|
||||
final HIDDeviceBLESteamController finalThis = this;
|
||||
mHandler.postDelayed(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
finalThis.checkConnectionForChromebookIssue();
|
||||
}
|
||||
}, CHROMEBOOK_CONNECTION_CHECK_INTERVAL);
|
||||
}
|
||||
|
||||
private boolean isRegistered() {
|
||||
return mIsRegistered;
|
||||
}
|
||||
|
||||
private void setRegistered() {
|
||||
mIsRegistered = true;
|
||||
}
|
||||
|
||||
private boolean probeService(HIDDeviceBLESteamController controller) {
|
||||
|
||||
if (isRegistered()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!mIsConnected) {
|
||||
return false;
|
||||
}
|
||||
|
||||
Log.v(TAG, "probeService controller=" + controller);
|
||||
|
||||
for (BluetoothGattService service : mGatt.getServices()) {
|
||||
if (service.getUuid().equals(steamControllerService)) {
|
||||
Log.v(TAG, "Found Valve steam controller service " + service.getUuid());
|
||||
|
||||
for (BluetoothGattCharacteristic chr : service.getCharacteristics()) {
|
||||
if (chr.getUuid().equals(inputCharacteristic)) {
|
||||
Log.v(TAG, "Found input characteristic");
|
||||
// Start notifications
|
||||
BluetoothGattDescriptor cccd = chr.getDescriptor(UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));
|
||||
if (cccd != null) {
|
||||
enableNotification(chr.getUuid());
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
if ((mGatt.getServices().size() == 0) && mIsChromebook && !mIsReconnecting) {
|
||||
Log.e(TAG, "Chromebook: Discovered services were empty; this almost certainly means the BtGatt.ContextMap bug has bitten us.");
|
||||
mIsConnected = false;
|
||||
mIsReconnecting = true;
|
||||
mGatt.disconnect();
|
||||
mGatt = connectGatt(false);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
private void finishCurrentGattOperation() {
|
||||
GattOperation op = null;
|
||||
synchronized (mOperations) {
|
||||
if (mCurrentOperation != null) {
|
||||
op = mCurrentOperation;
|
||||
mCurrentOperation = null;
|
||||
}
|
||||
}
|
||||
if (op != null) {
|
||||
boolean result = op.finish(); // TODO: Maybe in main thread as well?
|
||||
|
||||
// Our operation failed, let's add it back to the beginning of our queue.
|
||||
if (!result) {
|
||||
mOperations.addFirst(op);
|
||||
}
|
||||
}
|
||||
executeNextGattOperation();
|
||||
}
|
||||
|
||||
private void executeNextGattOperation() {
|
||||
synchronized (mOperations) {
|
||||
if (mCurrentOperation != null)
|
||||
return;
|
||||
|
||||
if (mOperations.isEmpty())
|
||||
return;
|
||||
|
||||
mCurrentOperation = mOperations.removeFirst();
|
||||
}
|
||||
|
||||
// Run in main thread
|
||||
mHandler.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
synchronized (mOperations) {
|
||||
if (mCurrentOperation == null) {
|
||||
Log.e(TAG, "Current operation null in executor?");
|
||||
return;
|
||||
}
|
||||
|
||||
mCurrentOperation.run();
|
||||
// now wait for the GATT callback and when it comes, finish this operation
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void queueGattOperation(GattOperation op) {
|
||||
synchronized (mOperations) {
|
||||
mOperations.add(op);
|
||||
}
|
||||
executeNextGattOperation();
|
||||
}
|
||||
|
||||
private void enableNotification(UUID chrUuid) {
|
||||
GattOperation op = HIDDeviceBLESteamController.GattOperation.enableNotification(mGatt, chrUuid);
|
||||
queueGattOperation(op);
|
||||
}
|
||||
|
||||
public void writeCharacteristic(UUID uuid, byte[] value) {
|
||||
GattOperation op = HIDDeviceBLESteamController.GattOperation.writeCharacteristic(mGatt, uuid, value);
|
||||
queueGattOperation(op);
|
||||
}
|
||||
|
||||
public void readCharacteristic(UUID uuid) {
|
||||
GattOperation op = HIDDeviceBLESteamController.GattOperation.readCharacteristic(mGatt, uuid);
|
||||
queueGattOperation(op);
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
////////////// BluetoothGattCallback overridden methods
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
public void onConnectionStateChange(BluetoothGatt g, int status, int newState) {
|
||||
//Log.v(TAG, "onConnectionStateChange status=" + status + " newState=" + newState);
|
||||
mIsReconnecting = false;
|
||||
if (newState == 2) {
|
||||
mIsConnected = true;
|
||||
// Run directly, without GattOperation
|
||||
if (!isRegistered()) {
|
||||
mHandler.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
mGatt.discoverServices();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
else if (newState == 0) {
|
||||
mIsConnected = false;
|
||||
}
|
||||
|
||||
// Disconnection is handled in SteamLink using the ACTION_ACL_DISCONNECTED Intent.
|
||||
}
|
||||
|
||||
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
|
||||
//Log.v(TAG, "onServicesDiscovered status=" + status);
|
||||
if (status == 0) {
|
||||
if (gatt.getServices().size() == 0) {
|
||||
Log.v(TAG, "onServicesDiscovered returned zero services; something has gone horribly wrong down in Android's Bluetooth stack.");
|
||||
mIsReconnecting = true;
|
||||
mIsConnected = false;
|
||||
gatt.disconnect();
|
||||
mGatt = connectGatt(false);
|
||||
}
|
||||
else {
|
||||
probeService(this);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
|
||||
//Log.v(TAG, "onCharacteristicRead status=" + status + " uuid=" + characteristic.getUuid());
|
||||
|
||||
if (characteristic.getUuid().equals(reportCharacteristic) && !mFrozen) {
|
||||
mManager.HIDDeviceFeatureReport(getId(), characteristic.getValue());
|
||||
}
|
||||
|
||||
finishCurrentGattOperation();
|
||||
}
|
||||
|
||||
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
|
||||
//Log.v(TAG, "onCharacteristicWrite status=" + status + " uuid=" + characteristic.getUuid());
|
||||
|
||||
if (characteristic.getUuid().equals(reportCharacteristic)) {
|
||||
// Only register controller with the native side once it has been fully configured
|
||||
if (!isRegistered()) {
|
||||
Log.v(TAG, "Registering Steam Controller with ID: " + getId());
|
||||
mManager.HIDDeviceConnected(getId(), getIdentifier(), getVendorId(), getProductId(), getSerialNumber(), getVersion(), getManufacturerName(), getProductName(), 0, 0, 0, 0);
|
||||
setRegistered();
|
||||
}
|
||||
}
|
||||
|
||||
finishCurrentGattOperation();
|
||||
}
|
||||
|
||||
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
|
||||
// Enable this for verbose logging of controller input reports
|
||||
//Log.v(TAG, "onCharacteristicChanged uuid=" + characteristic.getUuid() + " data=" + HexDump.dumpHexString(characteristic.getValue()));
|
||||
|
||||
if (characteristic.getUuid().equals(inputCharacteristic) && !mFrozen) {
|
||||
mManager.HIDDeviceInputReport(getId(), characteristic.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
|
||||
//Log.v(TAG, "onDescriptorRead status=" + status);
|
||||
}
|
||||
|
||||
public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
|
||||
BluetoothGattCharacteristic chr = descriptor.getCharacteristic();
|
||||
//Log.v(TAG, "onDescriptorWrite status=" + status + " uuid=" + chr.getUuid() + " descriptor=" + descriptor.getUuid());
|
||||
|
||||
if (chr.getUuid().equals(inputCharacteristic)) {
|
||||
boolean hasWrittenInputDescriptor = true;
|
||||
BluetoothGattCharacteristic reportChr = chr.getService().getCharacteristic(reportCharacteristic);
|
||||
if (reportChr != null) {
|
||||
Log.v(TAG, "Writing report characteristic to enter valve mode");
|
||||
reportChr.setValue(enterValveMode);
|
||||
gatt.writeCharacteristic(reportChr);
|
||||
}
|
||||
}
|
||||
|
||||
finishCurrentGattOperation();
|
||||
}
|
||||
|
||||
public void onReliableWriteCompleted(BluetoothGatt gatt, int status) {
|
||||
//Log.v(TAG, "onReliableWriteCompleted status=" + status);
|
||||
}
|
||||
|
||||
public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
|
||||
//Log.v(TAG, "onReadRemoteRssi status=" + status);
|
||||
}
|
||||
|
||||
public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) {
|
||||
//Log.v(TAG, "onMtuChanged status=" + status);
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
//////// Public API
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
@Override
|
||||
public int getId() {
|
||||
return mDeviceId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getVendorId() {
|
||||
// Valve Corporation
|
||||
final int VALVE_USB_VID = 0x28DE;
|
||||
return VALVE_USB_VID;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getProductId() {
|
||||
// We don't have an easy way to query from the Bluetooth device, but we know what it is
|
||||
final int D0G_BLE2_PID = 0x1106;
|
||||
return D0G_BLE2_PID;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getSerialNumber() {
|
||||
// This will be read later via feature report by Steam
|
||||
return "12345";
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getVersion() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getManufacturerName() {
|
||||
return "Valve Corporation";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getProductName() {
|
||||
return "Steam Controller";
|
||||
}
|
||||
|
||||
@Override
|
||||
public UsbDevice getDevice() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean open() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int sendFeatureReport(byte[] report) {
|
||||
if (!isRegistered()) {
|
||||
Log.e(TAG, "Attempted sendFeatureReport before Steam Controller is registered!");
|
||||
if (mIsConnected) {
|
||||
probeService(this);
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
// We need to skip the first byte, as that doesn't go over the air
|
||||
byte[] actual_report = Arrays.copyOfRange(report, 1, report.length - 1);
|
||||
//Log.v(TAG, "sendFeatureReport " + HexDump.dumpHexString(actual_report));
|
||||
writeCharacteristic(reportCharacteristic, actual_report);
|
||||
return report.length;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int sendOutputReport(byte[] report) {
|
||||
if (!isRegistered()) {
|
||||
Log.e(TAG, "Attempted sendOutputReport before Steam Controller is registered!");
|
||||
if (mIsConnected) {
|
||||
probeService(this);
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
//Log.v(TAG, "sendFeatureReport " + HexDump.dumpHexString(report));
|
||||
writeCharacteristic(reportCharacteristic, report);
|
||||
return report.length;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean getFeatureReport(byte[] report) {
|
||||
if (!isRegistered()) {
|
||||
Log.e(TAG, "Attempted getFeatureReport before Steam Controller is registered!");
|
||||
if (mIsConnected) {
|
||||
probeService(this);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
//Log.v(TAG, "getFeatureReport");
|
||||
readCharacteristic(reportCharacteristic);
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setFrozen(boolean frozen) {
|
||||
mFrozen = frozen;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void shutdown() {
|
||||
close();
|
||||
|
||||
BluetoothGatt g = mGatt;
|
||||
if (g != null) {
|
||||
g.disconnect();
|
||||
g.close();
|
||||
mGatt = null;
|
||||
}
|
||||
mManager = null;
|
||||
mIsRegistered = false;
|
||||
mIsConnected = false;
|
||||
mOperations.clear();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
691
android/app/src/main/java/org/libsdl/app/HIDDeviceManager.java
Normal file
691
android/app/src/main/java/org/libsdl/app/HIDDeviceManager.java
Normal file
@@ -0,0 +1,691 @@
|
||||
package org.libsdl.app;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.app.AlertDialog;
|
||||
import android.app.PendingIntent;
|
||||
import android.bluetooth.BluetoothAdapter;
|
||||
import android.bluetooth.BluetoothDevice;
|
||||
import android.bluetooth.BluetoothManager;
|
||||
import android.bluetooth.BluetoothProfile;
|
||||
import android.os.Build;
|
||||
import android.util.Log;
|
||||
import android.content.BroadcastReceiver;
|
||||
import android.content.Context;
|
||||
import android.content.DialogInterface;
|
||||
import android.content.Intent;
|
||||
import android.content.IntentFilter;
|
||||
import android.content.SharedPreferences;
|
||||
import android.content.pm.PackageManager;
|
||||
import android.hardware.usb.*;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
|
||||
public class HIDDeviceManager {
|
||||
private static final String TAG = "hidapi";
|
||||
private static final String ACTION_USB_PERMISSION = "org.libsdl.app.USB_PERMISSION";
|
||||
|
||||
private static HIDDeviceManager sManager;
|
||||
private static int sManagerRefCount = 0;
|
||||
|
||||
public static HIDDeviceManager acquire(Context context) {
|
||||
if (sManagerRefCount == 0) {
|
||||
sManager = new HIDDeviceManager(context);
|
||||
}
|
||||
++sManagerRefCount;
|
||||
return sManager;
|
||||
}
|
||||
|
||||
public static void release(HIDDeviceManager manager) {
|
||||
if (manager == sManager) {
|
||||
--sManagerRefCount;
|
||||
if (sManagerRefCount == 0) {
|
||||
sManager.close();
|
||||
sManager = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Context mContext;
|
||||
private HashMap<Integer, HIDDevice> mDevicesById = new HashMap<Integer, HIDDevice>();
|
||||
private HashMap<BluetoothDevice, HIDDeviceBLESteamController> mBluetoothDevices = new HashMap<BluetoothDevice, HIDDeviceBLESteamController>();
|
||||
private int mNextDeviceId = 0;
|
||||
private SharedPreferences mSharedPreferences = null;
|
||||
private boolean mIsChromebook = false;
|
||||
private UsbManager mUsbManager;
|
||||
private Handler mHandler;
|
||||
private BluetoothManager mBluetoothManager;
|
||||
private List<BluetoothDevice> mLastBluetoothDevices;
|
||||
|
||||
private final BroadcastReceiver mUsbBroadcast = new BroadcastReceiver() {
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
String action = intent.getAction();
|
||||
if (action.equals(UsbManager.ACTION_USB_DEVICE_ATTACHED)) {
|
||||
UsbDevice usbDevice = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
|
||||
handleUsbDeviceAttached(usbDevice);
|
||||
} else if (action.equals(UsbManager.ACTION_USB_DEVICE_DETACHED)) {
|
||||
UsbDevice usbDevice = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
|
||||
handleUsbDeviceDetached(usbDevice);
|
||||
} else if (action.equals(HIDDeviceManager.ACTION_USB_PERMISSION)) {
|
||||
UsbDevice usbDevice = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
|
||||
handleUsbDevicePermission(usbDevice, intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
private final BroadcastReceiver mBluetoothBroadcast = new BroadcastReceiver() {
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
String action = intent.getAction();
|
||||
// Bluetooth device was connected. If it was a Steam Controller, handle it
|
||||
if (action.equals(BluetoothDevice.ACTION_ACL_CONNECTED)) {
|
||||
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
|
||||
Log.d(TAG, "Bluetooth device connected: " + device);
|
||||
|
||||
if (isSteamController(device)) {
|
||||
connectBluetoothDevice(device);
|
||||
}
|
||||
}
|
||||
|
||||
// Bluetooth device was disconnected, remove from controller manager (if any)
|
||||
if (action.equals(BluetoothDevice.ACTION_ACL_DISCONNECTED)) {
|
||||
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
|
||||
Log.d(TAG, "Bluetooth device disconnected: " + device);
|
||||
|
||||
disconnectBluetoothDevice(device);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
private HIDDeviceManager(final Context context) {
|
||||
mContext = context;
|
||||
|
||||
HIDDeviceRegisterCallback();
|
||||
|
||||
mSharedPreferences = mContext.getSharedPreferences("hidapi", Context.MODE_PRIVATE);
|
||||
mIsChromebook = mContext.getPackageManager().hasSystemFeature("org.chromium.arc.device_management");
|
||||
|
||||
// if (shouldClear) {
|
||||
// SharedPreferences.Editor spedit = mSharedPreferences.edit();
|
||||
// spedit.clear();
|
||||
// spedit.commit();
|
||||
// }
|
||||
// else
|
||||
{
|
||||
mNextDeviceId = mSharedPreferences.getInt("next_device_id", 0);
|
||||
}
|
||||
}
|
||||
|
||||
public Context getContext() {
|
||||
return mContext;
|
||||
}
|
||||
|
||||
public int getDeviceIDForIdentifier(String identifier) {
|
||||
SharedPreferences.Editor spedit = mSharedPreferences.edit();
|
||||
|
||||
int result = mSharedPreferences.getInt(identifier, 0);
|
||||
if (result == 0) {
|
||||
result = mNextDeviceId++;
|
||||
spedit.putInt("next_device_id", mNextDeviceId);
|
||||
}
|
||||
|
||||
spedit.putInt(identifier, result);
|
||||
spedit.commit();
|
||||
return result;
|
||||
}
|
||||
|
||||
private void initializeUSB() {
|
||||
mUsbManager = (UsbManager)mContext.getSystemService(Context.USB_SERVICE);
|
||||
if (mUsbManager == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
/*
|
||||
// Logging
|
||||
for (UsbDevice device : mUsbManager.getDeviceList().values()) {
|
||||
Log.i(TAG,"Path: " + device.getDeviceName());
|
||||
Log.i(TAG,"Manufacturer: " + device.getManufacturerName());
|
||||
Log.i(TAG,"Product: " + device.getProductName());
|
||||
Log.i(TAG,"ID: " + device.getDeviceId());
|
||||
Log.i(TAG,"Class: " + device.getDeviceClass());
|
||||
Log.i(TAG,"Protocol: " + device.getDeviceProtocol());
|
||||
Log.i(TAG,"Vendor ID " + device.getVendorId());
|
||||
Log.i(TAG,"Product ID: " + device.getProductId());
|
||||
Log.i(TAG,"Interface count: " + device.getInterfaceCount());
|
||||
Log.i(TAG,"---------------------------------------");
|
||||
|
||||
// Get interface details
|
||||
for (int index = 0; index < device.getInterfaceCount(); index++) {
|
||||
UsbInterface mUsbInterface = device.getInterface(index);
|
||||
Log.i(TAG," ***** *****");
|
||||
Log.i(TAG," Interface index: " + index);
|
||||
Log.i(TAG," Interface ID: " + mUsbInterface.getId());
|
||||
Log.i(TAG," Interface class: " + mUsbInterface.getInterfaceClass());
|
||||
Log.i(TAG," Interface subclass: " + mUsbInterface.getInterfaceSubclass());
|
||||
Log.i(TAG," Interface protocol: " + mUsbInterface.getInterfaceProtocol());
|
||||
Log.i(TAG," Endpoint count: " + mUsbInterface.getEndpointCount());
|
||||
|
||||
// Get endpoint details
|
||||
for (int epi = 0; epi < mUsbInterface.getEndpointCount(); epi++)
|
||||
{
|
||||
UsbEndpoint mEndpoint = mUsbInterface.getEndpoint(epi);
|
||||
Log.i(TAG," ++++ ++++ ++++");
|
||||
Log.i(TAG," Endpoint index: " + epi);
|
||||
Log.i(TAG," Attributes: " + mEndpoint.getAttributes());
|
||||
Log.i(TAG," Direction: " + mEndpoint.getDirection());
|
||||
Log.i(TAG," Number: " + mEndpoint.getEndpointNumber());
|
||||
Log.i(TAG," Interval: " + mEndpoint.getInterval());
|
||||
Log.i(TAG," Packet size: " + mEndpoint.getMaxPacketSize());
|
||||
Log.i(TAG," Type: " + mEndpoint.getType());
|
||||
}
|
||||
}
|
||||
}
|
||||
Log.i(TAG," No more devices connected.");
|
||||
*/
|
||||
|
||||
// Register for USB broadcasts and permission completions
|
||||
IntentFilter filter = new IntentFilter();
|
||||
filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
|
||||
filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
|
||||
filter.addAction(HIDDeviceManager.ACTION_USB_PERMISSION);
|
||||
mContext.registerReceiver(mUsbBroadcast, filter);
|
||||
|
||||
for (UsbDevice usbDevice : mUsbManager.getDeviceList().values()) {
|
||||
handleUsbDeviceAttached(usbDevice);
|
||||
}
|
||||
}
|
||||
|
||||
UsbManager getUSBManager() {
|
||||
return mUsbManager;
|
||||
}
|
||||
|
||||
private void shutdownUSB() {
|
||||
try {
|
||||
mContext.unregisterReceiver(mUsbBroadcast);
|
||||
} catch (Exception e) {
|
||||
// We may not have registered, that's okay
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isHIDDeviceInterface(UsbDevice usbDevice, UsbInterface usbInterface) {
|
||||
if (usbInterface.getInterfaceClass() == UsbConstants.USB_CLASS_HID) {
|
||||
return true;
|
||||
}
|
||||
if (isXbox360Controller(usbDevice, usbInterface) || isXboxOneController(usbDevice, usbInterface)) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private boolean isXbox360Controller(UsbDevice usbDevice, UsbInterface usbInterface) {
|
||||
final int XB360_IFACE_SUBCLASS = 93;
|
||||
final int XB360_IFACE_PROTOCOL = 1; // Wired
|
||||
final int XB360W_IFACE_PROTOCOL = 129; // Wireless
|
||||
final int[] SUPPORTED_VENDORS = {
|
||||
0x0079, // GPD Win 2
|
||||
0x044f, // Thrustmaster
|
||||
0x045e, // Microsoft
|
||||
0x046d, // Logitech
|
||||
0x056e, // Elecom
|
||||
0x06a3, // Saitek
|
||||
0x0738, // Mad Catz
|
||||
0x07ff, // Mad Catz
|
||||
0x0e6f, // PDP
|
||||
0x0f0d, // Hori
|
||||
0x1038, // SteelSeries
|
||||
0x11c9, // Nacon
|
||||
0x12ab, // Unknown
|
||||
0x1430, // RedOctane
|
||||
0x146b, // BigBen
|
||||
0x1532, // Razer Sabertooth
|
||||
0x15e4, // Numark
|
||||
0x162e, // Joytech
|
||||
0x1689, // Razer Onza
|
||||
0x1949, // Lab126, Inc.
|
||||
0x1bad, // Harmonix
|
||||
0x20d6, // PowerA
|
||||
0x24c6, // PowerA
|
||||
0x2c22, // Qanba
|
||||
0x2dc8, // 8BitDo
|
||||
0x9886, // ASTRO Gaming
|
||||
};
|
||||
|
||||
if (usbInterface.getInterfaceClass() == UsbConstants.USB_CLASS_VENDOR_SPEC &&
|
||||
usbInterface.getInterfaceSubclass() == XB360_IFACE_SUBCLASS &&
|
||||
(usbInterface.getInterfaceProtocol() == XB360_IFACE_PROTOCOL ||
|
||||
usbInterface.getInterfaceProtocol() == XB360W_IFACE_PROTOCOL)) {
|
||||
int vendor_id = usbDevice.getVendorId();
|
||||
for (int supportedVid : SUPPORTED_VENDORS) {
|
||||
if (vendor_id == supportedVid) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private boolean isXboxOneController(UsbDevice usbDevice, UsbInterface usbInterface) {
|
||||
final int XB1_IFACE_SUBCLASS = 71;
|
||||
final int XB1_IFACE_PROTOCOL = 208;
|
||||
final int[] SUPPORTED_VENDORS = {
|
||||
0x03f0, // HP
|
||||
0x044f, // Thrustmaster
|
||||
0x045e, // Microsoft
|
||||
0x0738, // Mad Catz
|
||||
0x0e6f, // PDP
|
||||
0x0f0d, // Hori
|
||||
0x10f5, // Turtle Beach
|
||||
0x1532, // Razer Wildcat
|
||||
0x20d6, // PowerA
|
||||
0x24c6, // PowerA
|
||||
0x2dc8, // 8BitDo
|
||||
0x2e24, // Hyperkin
|
||||
0x3537, // GameSir
|
||||
};
|
||||
|
||||
if (usbInterface.getId() == 0 &&
|
||||
usbInterface.getInterfaceClass() == UsbConstants.USB_CLASS_VENDOR_SPEC &&
|
||||
usbInterface.getInterfaceSubclass() == XB1_IFACE_SUBCLASS &&
|
||||
usbInterface.getInterfaceProtocol() == XB1_IFACE_PROTOCOL) {
|
||||
int vendor_id = usbDevice.getVendorId();
|
||||
for (int supportedVid : SUPPORTED_VENDORS) {
|
||||
if (vendor_id == supportedVid) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private void handleUsbDeviceAttached(UsbDevice usbDevice) {
|
||||
connectHIDDeviceUSB(usbDevice);
|
||||
}
|
||||
|
||||
private void handleUsbDeviceDetached(UsbDevice usbDevice) {
|
||||
List<Integer> devices = new ArrayList<Integer>();
|
||||
for (HIDDevice device : mDevicesById.values()) {
|
||||
if (usbDevice.equals(device.getDevice())) {
|
||||
devices.add(device.getId());
|
||||
}
|
||||
}
|
||||
for (int id : devices) {
|
||||
HIDDevice device = mDevicesById.get(id);
|
||||
mDevicesById.remove(id);
|
||||
device.shutdown();
|
||||
HIDDeviceDisconnected(id);
|
||||
}
|
||||
}
|
||||
|
||||
private void handleUsbDevicePermission(UsbDevice usbDevice, boolean permission_granted) {
|
||||
for (HIDDevice device : mDevicesById.values()) {
|
||||
if (usbDevice.equals(device.getDevice())) {
|
||||
boolean opened = false;
|
||||
if (permission_granted) {
|
||||
opened = device.open();
|
||||
}
|
||||
HIDDeviceOpenResult(device.getId(), opened);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void connectHIDDeviceUSB(UsbDevice usbDevice) {
|
||||
synchronized (this) {
|
||||
int interface_mask = 0;
|
||||
for (int interface_index = 0; interface_index < usbDevice.getInterfaceCount(); interface_index++) {
|
||||
UsbInterface usbInterface = usbDevice.getInterface(interface_index);
|
||||
if (isHIDDeviceInterface(usbDevice, usbInterface)) {
|
||||
// Check to see if we've already added this interface
|
||||
// This happens with the Xbox Series X controller which has a duplicate interface 0, which is inactive
|
||||
int interface_id = usbInterface.getId();
|
||||
if ((interface_mask & (1 << interface_id)) != 0) {
|
||||
continue;
|
||||
}
|
||||
interface_mask |= (1 << interface_id);
|
||||
|
||||
HIDDeviceUSB device = new HIDDeviceUSB(this, usbDevice, interface_index);
|
||||
int id = device.getId();
|
||||
mDevicesById.put(id, device);
|
||||
HIDDeviceConnected(id, device.getIdentifier(), device.getVendorId(), device.getProductId(), device.getSerialNumber(), device.getVersion(), device.getManufacturerName(), device.getProductName(), usbInterface.getId(), usbInterface.getInterfaceClass(), usbInterface.getInterfaceSubclass(), usbInterface.getInterfaceProtocol());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void initializeBluetooth() {
|
||||
Log.d(TAG, "Initializing Bluetooth");
|
||||
|
||||
if (Build.VERSION.SDK_INT >= 31 /* Android 12 */ &&
|
||||
mContext.getPackageManager().checkPermission(android.Manifest.permission.BLUETOOTH_CONNECT, mContext.getPackageName()) != PackageManager.PERMISSION_GRANTED) {
|
||||
Log.d(TAG, "Couldn't initialize Bluetooth, missing android.permission.BLUETOOTH_CONNECT");
|
||||
return;
|
||||
}
|
||||
|
||||
if (Build.VERSION.SDK_INT <= 30 /* Android 11.0 (R) */ &&
|
||||
mContext.getPackageManager().checkPermission(android.Manifest.permission.BLUETOOTH, mContext.getPackageName()) != PackageManager.PERMISSION_GRANTED) {
|
||||
Log.d(TAG, "Couldn't initialize Bluetooth, missing android.permission.BLUETOOTH");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE) || (Build.VERSION.SDK_INT < 18 /* Android 4.3 (JELLY_BEAN_MR2) */)) {
|
||||
Log.d(TAG, "Couldn't initialize Bluetooth, this version of Android does not support Bluetooth LE");
|
||||
return;
|
||||
}
|
||||
|
||||
// Find bonded bluetooth controllers and create SteamControllers for them
|
||||
mBluetoothManager = (BluetoothManager)mContext.getSystemService(Context.BLUETOOTH_SERVICE);
|
||||
if (mBluetoothManager == null) {
|
||||
// This device doesn't support Bluetooth.
|
||||
return;
|
||||
}
|
||||
|
||||
BluetoothAdapter btAdapter = mBluetoothManager.getAdapter();
|
||||
if (btAdapter == null) {
|
||||
// This device has Bluetooth support in the codebase, but has no available adapters.
|
||||
return;
|
||||
}
|
||||
|
||||
// Get our bonded devices.
|
||||
for (BluetoothDevice device : btAdapter.getBondedDevices()) {
|
||||
|
||||
Log.d(TAG, "Bluetooth device available: " + device);
|
||||
if (isSteamController(device)) {
|
||||
connectBluetoothDevice(device);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// NOTE: These don't work on Chromebooks, to my undying dismay.
|
||||
IntentFilter filter = new IntentFilter();
|
||||
filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
|
||||
filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
|
||||
mContext.registerReceiver(mBluetoothBroadcast, filter);
|
||||
|
||||
if (mIsChromebook) {
|
||||
mHandler = new Handler(Looper.getMainLooper());
|
||||
mLastBluetoothDevices = new ArrayList<BluetoothDevice>();
|
||||
|
||||
// final HIDDeviceManager finalThis = this;
|
||||
// mHandler.postDelayed(new Runnable() {
|
||||
// @Override
|
||||
// public void run() {
|
||||
// finalThis.chromebookConnectionHandler();
|
||||
// }
|
||||
// }, 5000);
|
||||
}
|
||||
}
|
||||
|
||||
private void shutdownBluetooth() {
|
||||
try {
|
||||
mContext.unregisterReceiver(mBluetoothBroadcast);
|
||||
} catch (Exception e) {
|
||||
// We may not have registered, that's okay
|
||||
}
|
||||
}
|
||||
|
||||
// Chromebooks do not pass along ACTION_ACL_CONNECTED / ACTION_ACL_DISCONNECTED properly.
|
||||
// This function provides a sort of dummy version of that, watching for changes in the
|
||||
// connected devices and attempting to add controllers as things change.
|
||||
public void chromebookConnectionHandler() {
|
||||
if (!mIsChromebook) {
|
||||
return;
|
||||
}
|
||||
|
||||
ArrayList<BluetoothDevice> disconnected = new ArrayList<BluetoothDevice>();
|
||||
ArrayList<BluetoothDevice> connected = new ArrayList<BluetoothDevice>();
|
||||
|
||||
List<BluetoothDevice> currentConnected = mBluetoothManager.getConnectedDevices(BluetoothProfile.GATT);
|
||||
|
||||
for (BluetoothDevice bluetoothDevice : currentConnected) {
|
||||
if (!mLastBluetoothDevices.contains(bluetoothDevice)) {
|
||||
connected.add(bluetoothDevice);
|
||||
}
|
||||
}
|
||||
for (BluetoothDevice bluetoothDevice : mLastBluetoothDevices) {
|
||||
if (!currentConnected.contains(bluetoothDevice)) {
|
||||
disconnected.add(bluetoothDevice);
|
||||
}
|
||||
}
|
||||
|
||||
mLastBluetoothDevices = currentConnected;
|
||||
|
||||
for (BluetoothDevice bluetoothDevice : disconnected) {
|
||||
disconnectBluetoothDevice(bluetoothDevice);
|
||||
}
|
||||
for (BluetoothDevice bluetoothDevice : connected) {
|
||||
connectBluetoothDevice(bluetoothDevice);
|
||||
}
|
||||
|
||||
final HIDDeviceManager finalThis = this;
|
||||
mHandler.postDelayed(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
finalThis.chromebookConnectionHandler();
|
||||
}
|
||||
}, 10000);
|
||||
}
|
||||
|
||||
public boolean connectBluetoothDevice(BluetoothDevice bluetoothDevice) {
|
||||
Log.v(TAG, "connectBluetoothDevice device=" + bluetoothDevice);
|
||||
synchronized (this) {
|
||||
if (mBluetoothDevices.containsKey(bluetoothDevice)) {
|
||||
Log.v(TAG, "Steam controller with address " + bluetoothDevice + " already exists, attempting reconnect");
|
||||
|
||||
HIDDeviceBLESteamController device = mBluetoothDevices.get(bluetoothDevice);
|
||||
device.reconnect();
|
||||
|
||||
return false;
|
||||
}
|
||||
HIDDeviceBLESteamController device = new HIDDeviceBLESteamController(this, bluetoothDevice);
|
||||
int id = device.getId();
|
||||
mBluetoothDevices.put(bluetoothDevice, device);
|
||||
mDevicesById.put(id, device);
|
||||
|
||||
// The Steam Controller will mark itself connected once initialization is complete
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public void disconnectBluetoothDevice(BluetoothDevice bluetoothDevice) {
|
||||
synchronized (this) {
|
||||
HIDDeviceBLESteamController device = mBluetoothDevices.get(bluetoothDevice);
|
||||
if (device == null)
|
||||
return;
|
||||
|
||||
int id = device.getId();
|
||||
mBluetoothDevices.remove(bluetoothDevice);
|
||||
mDevicesById.remove(id);
|
||||
device.shutdown();
|
||||
HIDDeviceDisconnected(id);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isSteamController(BluetoothDevice bluetoothDevice) {
|
||||
// Sanity check. If you pass in a null device, by definition it is never a Steam Controller.
|
||||
if (bluetoothDevice == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// If the device has no local name, we really don't want to try an equality check against it.
|
||||
if (bluetoothDevice.getName() == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return bluetoothDevice.getName().equals("SteamController") && ((bluetoothDevice.getType() & BluetoothDevice.DEVICE_TYPE_LE) != 0);
|
||||
}
|
||||
|
||||
private void close() {
|
||||
shutdownUSB();
|
||||
shutdownBluetooth();
|
||||
synchronized (this) {
|
||||
for (HIDDevice device : mDevicesById.values()) {
|
||||
device.shutdown();
|
||||
}
|
||||
mDevicesById.clear();
|
||||
mBluetoothDevices.clear();
|
||||
HIDDeviceReleaseCallback();
|
||||
}
|
||||
}
|
||||
|
||||
public void setFrozen(boolean frozen) {
|
||||
synchronized (this) {
|
||||
for (HIDDevice device : mDevicesById.values()) {
|
||||
device.setFrozen(frozen);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
private HIDDevice getDevice(int id) {
|
||||
synchronized (this) {
|
||||
HIDDevice result = mDevicesById.get(id);
|
||||
if (result == null) {
|
||||
Log.v(TAG, "No device for id: " + id);
|
||||
Log.v(TAG, "Available devices: " + mDevicesById.keySet());
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
////////// JNI interface functions
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
public boolean initialize(boolean usb, boolean bluetooth) {
|
||||
Log.v(TAG, "initialize(" + usb + ", " + bluetooth + ")");
|
||||
|
||||
if (usb) {
|
||||
initializeUSB();
|
||||
}
|
||||
if (bluetooth) {
|
||||
initializeBluetooth();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean openDevice(int deviceID) {
|
||||
Log.v(TAG, "openDevice deviceID=" + deviceID);
|
||||
HIDDevice device = getDevice(deviceID);
|
||||
if (device == null) {
|
||||
HIDDeviceDisconnected(deviceID);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Look to see if this is a USB device and we have permission to access it
|
||||
UsbDevice usbDevice = device.getDevice();
|
||||
if (usbDevice != null && !mUsbManager.hasPermission(usbDevice)) {
|
||||
HIDDeviceOpenPending(deviceID);
|
||||
try {
|
||||
final int FLAG_MUTABLE = 0x02000000; // PendingIntent.FLAG_MUTABLE, but don't require SDK 31
|
||||
int flags;
|
||||
if (Build.VERSION.SDK_INT >= 31 /* Android 12.0 (S) */) {
|
||||
flags = FLAG_MUTABLE;
|
||||
} else {
|
||||
flags = 0;
|
||||
}
|
||||
mUsbManager.requestPermission(usbDevice, PendingIntent.getBroadcast(mContext, 0, new Intent(HIDDeviceManager.ACTION_USB_PERMISSION), flags));
|
||||
} catch (Exception e) {
|
||||
Log.v(TAG, "Couldn't request permission for USB device " + usbDevice);
|
||||
HIDDeviceOpenResult(deviceID, false);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
return device.open();
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "Got exception: " + Log.getStackTraceString(e));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public int sendOutputReport(int deviceID, byte[] report) {
|
||||
try {
|
||||
//Log.v(TAG, "sendOutputReport deviceID=" + deviceID + " length=" + report.length);
|
||||
HIDDevice device;
|
||||
device = getDevice(deviceID);
|
||||
if (device == null) {
|
||||
HIDDeviceDisconnected(deviceID);
|
||||
return -1;
|
||||
}
|
||||
|
||||
return device.sendOutputReport(report);
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "Got exception: " + Log.getStackTraceString(e));
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
public int sendFeatureReport(int deviceID, byte[] report) {
|
||||
try {
|
||||
//Log.v(TAG, "sendFeatureReport deviceID=" + deviceID + " length=" + report.length);
|
||||
HIDDevice device;
|
||||
device = getDevice(deviceID);
|
||||
if (device == null) {
|
||||
HIDDeviceDisconnected(deviceID);
|
||||
return -1;
|
||||
}
|
||||
|
||||
return device.sendFeatureReport(report);
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "Got exception: " + Log.getStackTraceString(e));
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
public boolean getFeatureReport(int deviceID, byte[] report) {
|
||||
try {
|
||||
//Log.v(TAG, "getFeatureReport deviceID=" + deviceID);
|
||||
HIDDevice device;
|
||||
device = getDevice(deviceID);
|
||||
if (device == null) {
|
||||
HIDDeviceDisconnected(deviceID);
|
||||
return false;
|
||||
}
|
||||
|
||||
return device.getFeatureReport(report);
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "Got exception: " + Log.getStackTraceString(e));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public void closeDevice(int deviceID) {
|
||||
try {
|
||||
Log.v(TAG, "closeDevice deviceID=" + deviceID);
|
||||
HIDDevice device;
|
||||
device = getDevice(deviceID);
|
||||
if (device == null) {
|
||||
HIDDeviceDisconnected(deviceID);
|
||||
return;
|
||||
}
|
||||
|
||||
device.close();
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "Got exception: " + Log.getStackTraceString(e));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
/////////////// Native methods
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
private native void HIDDeviceRegisterCallback();
|
||||
private native void HIDDeviceReleaseCallback();
|
||||
|
||||
native void HIDDeviceConnected(int deviceID, String identifier, int vendorId, int productId, String serial_number, int release_number, String manufacturer_string, String product_string, int interface_number, int interface_class, int interface_subclass, int interface_protocol);
|
||||
native void HIDDeviceOpenPending(int deviceID);
|
||||
native void HIDDeviceOpenResult(int deviceID, boolean opened);
|
||||
native void HIDDeviceDisconnected(int deviceID);
|
||||
|
||||
native void HIDDeviceInputReport(int deviceID, byte[] report);
|
||||
native void HIDDeviceFeatureReport(int deviceID, byte[] report);
|
||||
}
|
||||
309
android/app/src/main/java/org/libsdl/app/HIDDeviceUSB.java
Normal file
309
android/app/src/main/java/org/libsdl/app/HIDDeviceUSB.java
Normal file
@@ -0,0 +1,309 @@
|
||||
package org.libsdl.app;
|
||||
|
||||
import android.hardware.usb.*;
|
||||
import android.os.Build;
|
||||
import android.util.Log;
|
||||
import java.util.Arrays;
|
||||
|
||||
class HIDDeviceUSB implements HIDDevice {
|
||||
|
||||
private static final String TAG = "hidapi";
|
||||
|
||||
protected HIDDeviceManager mManager;
|
||||
protected UsbDevice mDevice;
|
||||
protected int mInterfaceIndex;
|
||||
protected int mInterface;
|
||||
protected int mDeviceId;
|
||||
protected UsbDeviceConnection mConnection;
|
||||
protected UsbEndpoint mInputEndpoint;
|
||||
protected UsbEndpoint mOutputEndpoint;
|
||||
protected InputThread mInputThread;
|
||||
protected boolean mRunning;
|
||||
protected boolean mFrozen;
|
||||
|
||||
public HIDDeviceUSB(HIDDeviceManager manager, UsbDevice usbDevice, int interface_index) {
|
||||
mManager = manager;
|
||||
mDevice = usbDevice;
|
||||
mInterfaceIndex = interface_index;
|
||||
mInterface = mDevice.getInterface(mInterfaceIndex).getId();
|
||||
mDeviceId = manager.getDeviceIDForIdentifier(getIdentifier());
|
||||
mRunning = false;
|
||||
}
|
||||
|
||||
public String getIdentifier() {
|
||||
return String.format("%s/%x/%x/%d", mDevice.getDeviceName(), mDevice.getVendorId(), mDevice.getProductId(), mInterfaceIndex);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getId() {
|
||||
return mDeviceId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getVendorId() {
|
||||
return mDevice.getVendorId();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getProductId() {
|
||||
return mDevice.getProductId();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getSerialNumber() {
|
||||
String result = null;
|
||||
if (Build.VERSION.SDK_INT >= 21 /* Android 5.0 (LOLLIPOP) */) {
|
||||
try {
|
||||
result = mDevice.getSerialNumber();
|
||||
}
|
||||
catch (SecurityException exception) {
|
||||
//Log.w(TAG, "App permissions mean we cannot get serial number for device " + getDeviceName() + " message: " + exception.getMessage());
|
||||
}
|
||||
}
|
||||
if (result == null) {
|
||||
result = "";
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getVersion() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getManufacturerName() {
|
||||
String result = null;
|
||||
if (Build.VERSION.SDK_INT >= 21 /* Android 5.0 (LOLLIPOP) */) {
|
||||
result = mDevice.getManufacturerName();
|
||||
}
|
||||
if (result == null) {
|
||||
result = String.format("%x", getVendorId());
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getProductName() {
|
||||
String result = null;
|
||||
if (Build.VERSION.SDK_INT >= 21 /* Android 5.0 (LOLLIPOP) */) {
|
||||
result = mDevice.getProductName();
|
||||
}
|
||||
if (result == null) {
|
||||
result = String.format("%x", getProductId());
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UsbDevice getDevice() {
|
||||
return mDevice;
|
||||
}
|
||||
|
||||
public String getDeviceName() {
|
||||
return getManufacturerName() + " " + getProductName() + "(0x" + String.format("%x", getVendorId()) + "/0x" + String.format("%x", getProductId()) + ")";
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean open() {
|
||||
mConnection = mManager.getUSBManager().openDevice(mDevice);
|
||||
if (mConnection == null) {
|
||||
Log.w(TAG, "Unable to open USB device " + getDeviceName());
|
||||
return false;
|
||||
}
|
||||
|
||||
// Force claim our interface
|
||||
UsbInterface iface = mDevice.getInterface(mInterfaceIndex);
|
||||
if (!mConnection.claimInterface(iface, true)) {
|
||||
Log.w(TAG, "Failed to claim interfaces on USB device " + getDeviceName());
|
||||
close();
|
||||
return false;
|
||||
}
|
||||
|
||||
// Find the endpoints
|
||||
for (int j = 0; j < iface.getEndpointCount(); j++) {
|
||||
UsbEndpoint endpt = iface.getEndpoint(j);
|
||||
switch (endpt.getDirection()) {
|
||||
case UsbConstants.USB_DIR_IN:
|
||||
if (mInputEndpoint == null) {
|
||||
mInputEndpoint = endpt;
|
||||
}
|
||||
break;
|
||||
case UsbConstants.USB_DIR_OUT:
|
||||
if (mOutputEndpoint == null) {
|
||||
mOutputEndpoint = endpt;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Make sure the required endpoints were present
|
||||
if (mInputEndpoint == null || mOutputEndpoint == null) {
|
||||
Log.w(TAG, "Missing required endpoint on USB device " + getDeviceName());
|
||||
close();
|
||||
return false;
|
||||
}
|
||||
|
||||
// Start listening for input
|
||||
mRunning = true;
|
||||
mInputThread = new InputThread();
|
||||
mInputThread.start();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int sendFeatureReport(byte[] report) {
|
||||
int res = -1;
|
||||
int offset = 0;
|
||||
int length = report.length;
|
||||
boolean skipped_report_id = false;
|
||||
byte report_number = report[0];
|
||||
|
||||
if (report_number == 0x0) {
|
||||
++offset;
|
||||
--length;
|
||||
skipped_report_id = true;
|
||||
}
|
||||
|
||||
res = mConnection.controlTransfer(
|
||||
UsbConstants.USB_TYPE_CLASS | 0x01 /*RECIPIENT_INTERFACE*/ | UsbConstants.USB_DIR_OUT,
|
||||
0x09/*HID set_report*/,
|
||||
(3/*HID feature*/ << 8) | report_number,
|
||||
mInterface,
|
||||
report, offset, length,
|
||||
1000/*timeout millis*/);
|
||||
|
||||
if (res < 0) {
|
||||
Log.w(TAG, "sendFeatureReport() returned " + res + " on device " + getDeviceName());
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (skipped_report_id) {
|
||||
++length;
|
||||
}
|
||||
return length;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int sendOutputReport(byte[] report) {
|
||||
int r = mConnection.bulkTransfer(mOutputEndpoint, report, report.length, 1000);
|
||||
if (r != report.length) {
|
||||
Log.w(TAG, "sendOutputReport() returned " + r + " on device " + getDeviceName());
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean getFeatureReport(byte[] report) {
|
||||
int res = -1;
|
||||
int offset = 0;
|
||||
int length = report.length;
|
||||
boolean skipped_report_id = false;
|
||||
byte report_number = report[0];
|
||||
|
||||
if (report_number == 0x0) {
|
||||
/* Offset the return buffer by 1, so that the report ID
|
||||
will remain in byte 0. */
|
||||
++offset;
|
||||
--length;
|
||||
skipped_report_id = true;
|
||||
}
|
||||
|
||||
res = mConnection.controlTransfer(
|
||||
UsbConstants.USB_TYPE_CLASS | 0x01 /*RECIPIENT_INTERFACE*/ | UsbConstants.USB_DIR_IN,
|
||||
0x01/*HID get_report*/,
|
||||
(3/*HID feature*/ << 8) | report_number,
|
||||
mInterface,
|
||||
report, offset, length,
|
||||
1000/*timeout millis*/);
|
||||
|
||||
if (res < 0) {
|
||||
Log.w(TAG, "getFeatureReport() returned " + res + " on device " + getDeviceName());
|
||||
return false;
|
||||
}
|
||||
|
||||
if (skipped_report_id) {
|
||||
++res;
|
||||
++length;
|
||||
}
|
||||
|
||||
byte[] data;
|
||||
if (res == length) {
|
||||
data = report;
|
||||
} else {
|
||||
data = Arrays.copyOfRange(report, 0, res);
|
||||
}
|
||||
mManager.HIDDeviceFeatureReport(mDeviceId, data);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
mRunning = false;
|
||||
if (mInputThread != null) {
|
||||
while (mInputThread.isAlive()) {
|
||||
mInputThread.interrupt();
|
||||
try {
|
||||
mInputThread.join();
|
||||
} catch (InterruptedException e) {
|
||||
// Keep trying until we're done
|
||||
}
|
||||
}
|
||||
mInputThread = null;
|
||||
}
|
||||
if (mConnection != null) {
|
||||
UsbInterface iface = mDevice.getInterface(mInterfaceIndex);
|
||||
mConnection.releaseInterface(iface);
|
||||
mConnection.close();
|
||||
mConnection = null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void shutdown() {
|
||||
close();
|
||||
mManager = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setFrozen(boolean frozen) {
|
||||
mFrozen = frozen;
|
||||
}
|
||||
|
||||
protected class InputThread extends Thread {
|
||||
@Override
|
||||
public void run() {
|
||||
int packetSize = mInputEndpoint.getMaxPacketSize();
|
||||
byte[] packet = new byte[packetSize];
|
||||
while (mRunning) {
|
||||
int r;
|
||||
try
|
||||
{
|
||||
r = mConnection.bulkTransfer(mInputEndpoint, packet, packetSize, 1000);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Log.v(TAG, "Exception in UsbDeviceConnection bulktransfer: " + e);
|
||||
break;
|
||||
}
|
||||
if (r < 0) {
|
||||
// Could be a timeout or an I/O error
|
||||
}
|
||||
if (r > 0) {
|
||||
byte[] data;
|
||||
if (r == packetSize) {
|
||||
data = packet;
|
||||
} else {
|
||||
data = Arrays.copyOfRange(packet, 0, r);
|
||||
}
|
||||
|
||||
if (!mFrozen) {
|
||||
mManager.HIDDeviceInputReport(mDeviceId, data);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
86
android/app/src/main/java/org/libsdl/app/SDL.java
Normal file
86
android/app/src/main/java/org/libsdl/app/SDL.java
Normal file
@@ -0,0 +1,86 @@
|
||||
package org.libsdl.app;
|
||||
|
||||
import android.content.Context;
|
||||
|
||||
import java.lang.Class;
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
/**
|
||||
SDL library initialization
|
||||
*/
|
||||
public class SDL {
|
||||
|
||||
// This function should be called first and sets up the native code
|
||||
// so it can call into the Java classes
|
||||
public static void setupJNI() {
|
||||
SDLActivity.nativeSetupJNI();
|
||||
SDLAudioManager.nativeSetupJNI();
|
||||
SDLControllerManager.nativeSetupJNI();
|
||||
}
|
||||
|
||||
// This function should be called each time the activity is started
|
||||
public static void initialize() {
|
||||
setContext(null);
|
||||
|
||||
SDLActivity.initialize();
|
||||
SDLAudioManager.initialize();
|
||||
SDLControllerManager.initialize();
|
||||
}
|
||||
|
||||
// This function stores the current activity (SDL or not)
|
||||
public static void setContext(Context context) {
|
||||
SDLAudioManager.setContext(context);
|
||||
mContext = context;
|
||||
}
|
||||
|
||||
public static Context getContext() {
|
||||
return mContext;
|
||||
}
|
||||
|
||||
public static void loadLibrary(String libraryName) throws UnsatisfiedLinkError, SecurityException, NullPointerException {
|
||||
|
||||
if (libraryName == null) {
|
||||
throw new NullPointerException("No library name provided.");
|
||||
}
|
||||
|
||||
try {
|
||||
// Let's see if we have ReLinker available in the project. This is necessary for
|
||||
// some projects that have huge numbers of local libraries bundled, and thus may
|
||||
// trip a bug in Android's native library loader which ReLinker works around. (If
|
||||
// loadLibrary works properly, ReLinker will simply use the normal Android method
|
||||
// internally.)
|
||||
//
|
||||
// To use ReLinker, just add it as a dependency. For more information, see
|
||||
// https://github.com/KeepSafe/ReLinker for ReLinker's repository.
|
||||
//
|
||||
Class<?> relinkClass = mContext.getClassLoader().loadClass("com.getkeepsafe.relinker.ReLinker");
|
||||
Class<?> relinkListenerClass = mContext.getClassLoader().loadClass("com.getkeepsafe.relinker.ReLinker$LoadListener");
|
||||
Class<?> contextClass = mContext.getClassLoader().loadClass("android.content.Context");
|
||||
Class<?> stringClass = mContext.getClassLoader().loadClass("java.lang.String");
|
||||
|
||||
// Get a 'force' instance of the ReLinker, so we can ensure libraries are reinstalled if
|
||||
// they've changed during updates.
|
||||
Method forceMethod = relinkClass.getDeclaredMethod("force");
|
||||
Object relinkInstance = forceMethod.invoke(null);
|
||||
Class<?> relinkInstanceClass = relinkInstance.getClass();
|
||||
|
||||
// Actually load the library!
|
||||
Method loadMethod = relinkInstanceClass.getDeclaredMethod("loadLibrary", contextClass, stringClass, stringClass, relinkListenerClass);
|
||||
loadMethod.invoke(relinkInstance, mContext, libraryName, null, null);
|
||||
}
|
||||
catch (final Throwable e) {
|
||||
// Fall back
|
||||
try {
|
||||
System.loadLibrary(libraryName);
|
||||
}
|
||||
catch (final UnsatisfiedLinkError ule) {
|
||||
throw ule;
|
||||
}
|
||||
catch (final SecurityException se) {
|
||||
throw se;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected static Context mContext;
|
||||
}
|
||||
2122
android/app/src/main/java/org/libsdl/app/SDLActivity.java
Normal file
2122
android/app/src/main/java/org/libsdl/app/SDLActivity.java
Normal file
File diff suppressed because it is too large
Load Diff
514
android/app/src/main/java/org/libsdl/app/SDLAudioManager.java
Normal file
514
android/app/src/main/java/org/libsdl/app/SDLAudioManager.java
Normal file
@@ -0,0 +1,514 @@
|
||||
package org.libsdl.app;
|
||||
|
||||
import android.content.Context;
|
||||
import android.media.AudioDeviceCallback;
|
||||
import android.media.AudioDeviceInfo;
|
||||
import android.media.AudioFormat;
|
||||
import android.media.AudioManager;
|
||||
import android.media.AudioRecord;
|
||||
import android.media.AudioTrack;
|
||||
import android.media.MediaRecorder;
|
||||
import android.os.Build;
|
||||
import android.util.Log;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
public class SDLAudioManager {
|
||||
protected static final String TAG = "SDLAudio";
|
||||
|
||||
protected static AudioTrack mAudioTrack;
|
||||
protected static AudioRecord mAudioRecord;
|
||||
protected static Context mContext;
|
||||
|
||||
private static final int[] NO_DEVICES = {};
|
||||
|
||||
private static AudioDeviceCallback mAudioDeviceCallback;
|
||||
|
||||
public static void initialize() {
|
||||
mAudioTrack = null;
|
||||
mAudioRecord = null;
|
||||
mAudioDeviceCallback = null;
|
||||
|
||||
if(Build.VERSION.SDK_INT >= 24 /* Android 7.0 (N) */)
|
||||
{
|
||||
mAudioDeviceCallback = new AudioDeviceCallback() {
|
||||
@Override
|
||||
public void onAudioDevicesAdded(AudioDeviceInfo[] addedDevices) {
|
||||
Arrays.stream(addedDevices).forEach(deviceInfo -> addAudioDevice(deviceInfo.isSink(), deviceInfo.getId()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAudioDevicesRemoved(AudioDeviceInfo[] removedDevices) {
|
||||
Arrays.stream(removedDevices).forEach(deviceInfo -> removeAudioDevice(deviceInfo.isSink(), deviceInfo.getId()));
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
public static void setContext(Context context) {
|
||||
mContext = context;
|
||||
if (context != null) {
|
||||
registerAudioDeviceCallback();
|
||||
}
|
||||
}
|
||||
|
||||
public static void release(Context context) {
|
||||
unregisterAudioDeviceCallback(context);
|
||||
}
|
||||
|
||||
// Audio
|
||||
|
||||
protected static String getAudioFormatString(int audioFormat) {
|
||||
switch (audioFormat) {
|
||||
case AudioFormat.ENCODING_PCM_8BIT:
|
||||
return "8-bit";
|
||||
case AudioFormat.ENCODING_PCM_16BIT:
|
||||
return "16-bit";
|
||||
case AudioFormat.ENCODING_PCM_FLOAT:
|
||||
return "float";
|
||||
default:
|
||||
return Integer.toString(audioFormat);
|
||||
}
|
||||
}
|
||||
|
||||
protected static int[] open(boolean isCapture, int sampleRate, int audioFormat, int desiredChannels, int desiredFrames, int deviceId) {
|
||||
int channelConfig;
|
||||
int sampleSize;
|
||||
int frameSize;
|
||||
|
||||
Log.v(TAG, "Opening " + (isCapture ? "capture" : "playback") + ", requested " + desiredFrames + " frames of " + desiredChannels + " channel " + getAudioFormatString(audioFormat) + " audio at " + sampleRate + " Hz");
|
||||
|
||||
/* On older devices let's use known good settings */
|
||||
if (Build.VERSION.SDK_INT < 21 /* Android 5.0 (LOLLIPOP) */) {
|
||||
if (desiredChannels > 2) {
|
||||
desiredChannels = 2;
|
||||
}
|
||||
}
|
||||
|
||||
/* AudioTrack has sample rate limitation of 48000 (fixed in 5.0.2) */
|
||||
if (Build.VERSION.SDK_INT < 22 /* Android 5.1 (LOLLIPOP_MR1) */) {
|
||||
if (sampleRate < 8000) {
|
||||
sampleRate = 8000;
|
||||
} else if (sampleRate > 48000) {
|
||||
sampleRate = 48000;
|
||||
}
|
||||
}
|
||||
|
||||
if (audioFormat == AudioFormat.ENCODING_PCM_FLOAT) {
|
||||
int minSDKVersion = (isCapture ? 23 /* Android 6.0 (M) */ : 21 /* Android 5.0 (LOLLIPOP) */);
|
||||
if (Build.VERSION.SDK_INT < minSDKVersion) {
|
||||
audioFormat = AudioFormat.ENCODING_PCM_16BIT;
|
||||
}
|
||||
}
|
||||
switch (audioFormat)
|
||||
{
|
||||
case AudioFormat.ENCODING_PCM_8BIT:
|
||||
sampleSize = 1;
|
||||
break;
|
||||
case AudioFormat.ENCODING_PCM_16BIT:
|
||||
sampleSize = 2;
|
||||
break;
|
||||
case AudioFormat.ENCODING_PCM_FLOAT:
|
||||
sampleSize = 4;
|
||||
break;
|
||||
default:
|
||||
Log.v(TAG, "Requested format " + audioFormat + ", getting ENCODING_PCM_16BIT");
|
||||
audioFormat = AudioFormat.ENCODING_PCM_16BIT;
|
||||
sampleSize = 2;
|
||||
break;
|
||||
}
|
||||
|
||||
if (isCapture) {
|
||||
switch (desiredChannels) {
|
||||
case 1:
|
||||
channelConfig = AudioFormat.CHANNEL_IN_MONO;
|
||||
break;
|
||||
case 2:
|
||||
channelConfig = AudioFormat.CHANNEL_IN_STEREO;
|
||||
break;
|
||||
default:
|
||||
Log.v(TAG, "Requested " + desiredChannels + " channels, getting stereo");
|
||||
desiredChannels = 2;
|
||||
channelConfig = AudioFormat.CHANNEL_IN_STEREO;
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
switch (desiredChannels) {
|
||||
case 1:
|
||||
channelConfig = AudioFormat.CHANNEL_OUT_MONO;
|
||||
break;
|
||||
case 2:
|
||||
channelConfig = AudioFormat.CHANNEL_OUT_STEREO;
|
||||
break;
|
||||
case 3:
|
||||
channelConfig = AudioFormat.CHANNEL_OUT_STEREO | AudioFormat.CHANNEL_OUT_FRONT_CENTER;
|
||||
break;
|
||||
case 4:
|
||||
channelConfig = AudioFormat.CHANNEL_OUT_QUAD;
|
||||
break;
|
||||
case 5:
|
||||
channelConfig = AudioFormat.CHANNEL_OUT_QUAD | AudioFormat.CHANNEL_OUT_FRONT_CENTER;
|
||||
break;
|
||||
case 6:
|
||||
channelConfig = AudioFormat.CHANNEL_OUT_5POINT1;
|
||||
break;
|
||||
case 7:
|
||||
channelConfig = AudioFormat.CHANNEL_OUT_5POINT1 | AudioFormat.CHANNEL_OUT_BACK_CENTER;
|
||||
break;
|
||||
case 8:
|
||||
if (Build.VERSION.SDK_INT >= 23 /* Android 6.0 (M) */) {
|
||||
channelConfig = AudioFormat.CHANNEL_OUT_7POINT1_SURROUND;
|
||||
} else {
|
||||
Log.v(TAG, "Requested " + desiredChannels + " channels, getting 5.1 surround");
|
||||
desiredChannels = 6;
|
||||
channelConfig = AudioFormat.CHANNEL_OUT_5POINT1;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
Log.v(TAG, "Requested " + desiredChannels + " channels, getting stereo");
|
||||
desiredChannels = 2;
|
||||
channelConfig = AudioFormat.CHANNEL_OUT_STEREO;
|
||||
break;
|
||||
}
|
||||
|
||||
/*
|
||||
Log.v(TAG, "Speaker configuration (and order of channels):");
|
||||
|
||||
if ((channelConfig & 0x00000004) != 0) {
|
||||
Log.v(TAG, " CHANNEL_OUT_FRONT_LEFT");
|
||||
}
|
||||
if ((channelConfig & 0x00000008) != 0) {
|
||||
Log.v(TAG, " CHANNEL_OUT_FRONT_RIGHT");
|
||||
}
|
||||
if ((channelConfig & 0x00000010) != 0) {
|
||||
Log.v(TAG, " CHANNEL_OUT_FRONT_CENTER");
|
||||
}
|
||||
if ((channelConfig & 0x00000020) != 0) {
|
||||
Log.v(TAG, " CHANNEL_OUT_LOW_FREQUENCY");
|
||||
}
|
||||
if ((channelConfig & 0x00000040) != 0) {
|
||||
Log.v(TAG, " CHANNEL_OUT_BACK_LEFT");
|
||||
}
|
||||
if ((channelConfig & 0x00000080) != 0) {
|
||||
Log.v(TAG, " CHANNEL_OUT_BACK_RIGHT");
|
||||
}
|
||||
if ((channelConfig & 0x00000100) != 0) {
|
||||
Log.v(TAG, " CHANNEL_OUT_FRONT_LEFT_OF_CENTER");
|
||||
}
|
||||
if ((channelConfig & 0x00000200) != 0) {
|
||||
Log.v(TAG, " CHANNEL_OUT_FRONT_RIGHT_OF_CENTER");
|
||||
}
|
||||
if ((channelConfig & 0x00000400) != 0) {
|
||||
Log.v(TAG, " CHANNEL_OUT_BACK_CENTER");
|
||||
}
|
||||
if ((channelConfig & 0x00000800) != 0) {
|
||||
Log.v(TAG, " CHANNEL_OUT_SIDE_LEFT");
|
||||
}
|
||||
if ((channelConfig & 0x00001000) != 0) {
|
||||
Log.v(TAG, " CHANNEL_OUT_SIDE_RIGHT");
|
||||
}
|
||||
*/
|
||||
}
|
||||
frameSize = (sampleSize * desiredChannels);
|
||||
|
||||
// Let the user pick a larger buffer if they really want -- but ye
|
||||
// gods they probably shouldn't, the minimums are horrifyingly high
|
||||
// latency already
|
||||
int minBufferSize;
|
||||
if (isCapture) {
|
||||
minBufferSize = AudioRecord.getMinBufferSize(sampleRate, channelConfig, audioFormat);
|
||||
} else {
|
||||
minBufferSize = AudioTrack.getMinBufferSize(sampleRate, channelConfig, audioFormat);
|
||||
}
|
||||
desiredFrames = Math.max(desiredFrames, (minBufferSize + frameSize - 1) / frameSize);
|
||||
|
||||
int[] results = new int[4];
|
||||
|
||||
if (isCapture) {
|
||||
if (mAudioRecord == null) {
|
||||
mAudioRecord = new AudioRecord(MediaRecorder.AudioSource.DEFAULT, sampleRate,
|
||||
channelConfig, audioFormat, desiredFrames * frameSize);
|
||||
|
||||
// see notes about AudioTrack state in audioOpen(), above. Probably also applies here.
|
||||
if (mAudioRecord.getState() != AudioRecord.STATE_INITIALIZED) {
|
||||
Log.e(TAG, "Failed during initialization of AudioRecord");
|
||||
mAudioRecord.release();
|
||||
mAudioRecord = null;
|
||||
return null;
|
||||
}
|
||||
|
||||
if (Build.VERSION.SDK_INT >= 24 /* Android 7.0 (N) */ && deviceId != 0) {
|
||||
mAudioRecord.setPreferredDevice(getOutputAudioDeviceInfo(deviceId));
|
||||
}
|
||||
|
||||
mAudioRecord.startRecording();
|
||||
}
|
||||
|
||||
results[0] = mAudioRecord.getSampleRate();
|
||||
results[1] = mAudioRecord.getAudioFormat();
|
||||
results[2] = mAudioRecord.getChannelCount();
|
||||
|
||||
} else {
|
||||
if (mAudioTrack == null) {
|
||||
mAudioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, sampleRate, channelConfig, audioFormat, desiredFrames * frameSize, AudioTrack.MODE_STREAM);
|
||||
|
||||
// Instantiating AudioTrack can "succeed" without an exception and the track may still be invalid
|
||||
// Ref: https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/media/java/android/media/AudioTrack.java
|
||||
// Ref: http://developer.android.com/reference/android/media/AudioTrack.html#getState()
|
||||
if (mAudioTrack.getState() != AudioTrack.STATE_INITIALIZED) {
|
||||
/* Try again, with safer values */
|
||||
|
||||
Log.e(TAG, "Failed during initialization of Audio Track");
|
||||
mAudioTrack.release();
|
||||
mAudioTrack = null;
|
||||
return null;
|
||||
}
|
||||
|
||||
if (Build.VERSION.SDK_INT >= 24 /* Android 7.0 (N) */ && deviceId != 0) {
|
||||
mAudioTrack.setPreferredDevice(getInputAudioDeviceInfo(deviceId));
|
||||
}
|
||||
|
||||
mAudioTrack.play();
|
||||
}
|
||||
|
||||
results[0] = mAudioTrack.getSampleRate();
|
||||
results[1] = mAudioTrack.getAudioFormat();
|
||||
results[2] = mAudioTrack.getChannelCount();
|
||||
}
|
||||
results[3] = desiredFrames;
|
||||
|
||||
Log.v(TAG, "Opening " + (isCapture ? "capture" : "playback") + ", got " + results[3] + " frames of " + results[2] + " channel " + getAudioFormatString(results[1]) + " audio at " + results[0] + " Hz");
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
private static AudioDeviceInfo getInputAudioDeviceInfo(int deviceId) {
|
||||
if (Build.VERSION.SDK_INT >= 24 /* Android 7.0 (N) */) {
|
||||
AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
|
||||
return Arrays.stream(audioManager.getDevices(AudioManager.GET_DEVICES_INPUTS))
|
||||
.filter(deviceInfo -> deviceInfo.getId() == deviceId)
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static AudioDeviceInfo getOutputAudioDeviceInfo(int deviceId) {
|
||||
if (Build.VERSION.SDK_INT >= 24 /* Android 7.0 (N) */) {
|
||||
AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
|
||||
return Arrays.stream(audioManager.getDevices(AudioManager.GET_DEVICES_OUTPUTS))
|
||||
.filter(deviceInfo -> deviceInfo.getId() == deviceId)
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static void registerAudioDeviceCallback() {
|
||||
if (Build.VERSION.SDK_INT >= 24 /* Android 7.0 (N) */) {
|
||||
AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
|
||||
audioManager.registerAudioDeviceCallback(mAudioDeviceCallback, null);
|
||||
}
|
||||
}
|
||||
|
||||
private static void unregisterAudioDeviceCallback(Context context) {
|
||||
if (Build.VERSION.SDK_INT >= 24 /* Android 7.0 (N) */) {
|
||||
AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
|
||||
audioManager.unregisterAudioDeviceCallback(mAudioDeviceCallback);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This method is called by SDL using JNI.
|
||||
*/
|
||||
public static int[] getAudioOutputDevices() {
|
||||
if (Build.VERSION.SDK_INT >= 24 /* Android 7.0 (N) */) {
|
||||
AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
|
||||
return Arrays.stream(audioManager.getDevices(AudioManager.GET_DEVICES_OUTPUTS)).mapToInt(AudioDeviceInfo::getId).toArray();
|
||||
} else {
|
||||
return NO_DEVICES;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This method is called by SDL using JNI.
|
||||
*/
|
||||
public static int[] getAudioInputDevices() {
|
||||
if (Build.VERSION.SDK_INT >= 24 /* Android 7.0 (N) */) {
|
||||
AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
|
||||
return Arrays.stream(audioManager.getDevices(AudioManager.GET_DEVICES_INPUTS)).mapToInt(AudioDeviceInfo::getId).toArray();
|
||||
} else {
|
||||
return NO_DEVICES;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This method is called by SDL using JNI.
|
||||
*/
|
||||
public static int[] audioOpen(int sampleRate, int audioFormat, int desiredChannels, int desiredFrames, int deviceId) {
|
||||
return open(false, sampleRate, audioFormat, desiredChannels, desiredFrames, deviceId);
|
||||
}
|
||||
|
||||
/**
|
||||
* This method is called by SDL using JNI.
|
||||
*/
|
||||
public static void audioWriteFloatBuffer(float[] buffer) {
|
||||
if (mAudioTrack == null) {
|
||||
Log.e(TAG, "Attempted to make audio call with uninitialized audio!");
|
||||
return;
|
||||
}
|
||||
|
||||
if (android.os.Build.VERSION.SDK_INT < 21 /* Android 5.0 (LOLLIPOP) */) {
|
||||
Log.e(TAG, "Attempted to make an incompatible audio call with uninitialized audio! (floating-point output is supported since Android 5.0 Lollipop)");
|
||||
return;
|
||||
}
|
||||
|
||||
for (int i = 0; i < buffer.length;) {
|
||||
int result = mAudioTrack.write(buffer, i, buffer.length - i, AudioTrack.WRITE_BLOCKING);
|
||||
if (result > 0) {
|
||||
i += result;
|
||||
} else if (result == 0) {
|
||||
try {
|
||||
Thread.sleep(1);
|
||||
} catch(InterruptedException e) {
|
||||
// Nom nom
|
||||
}
|
||||
} else {
|
||||
Log.w(TAG, "SDL audio: error return from write(float)");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This method is called by SDL using JNI.
|
||||
*/
|
||||
public static void audioWriteShortBuffer(short[] buffer) {
|
||||
if (mAudioTrack == null) {
|
||||
Log.e(TAG, "Attempted to make audio call with uninitialized audio!");
|
||||
return;
|
||||
}
|
||||
|
||||
for (int i = 0; i < buffer.length;) {
|
||||
int result = mAudioTrack.write(buffer, i, buffer.length - i);
|
||||
if (result > 0) {
|
||||
i += result;
|
||||
} else if (result == 0) {
|
||||
try {
|
||||
Thread.sleep(1);
|
||||
} catch(InterruptedException e) {
|
||||
// Nom nom
|
||||
}
|
||||
} else {
|
||||
Log.w(TAG, "SDL audio: error return from write(short)");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This method is called by SDL using JNI.
|
||||
*/
|
||||
public static void audioWriteByteBuffer(byte[] buffer) {
|
||||
if (mAudioTrack == null) {
|
||||
Log.e(TAG, "Attempted to make audio call with uninitialized audio!");
|
||||
return;
|
||||
}
|
||||
|
||||
for (int i = 0; i < buffer.length; ) {
|
||||
int result = mAudioTrack.write(buffer, i, buffer.length - i);
|
||||
if (result > 0) {
|
||||
i += result;
|
||||
} else if (result == 0) {
|
||||
try {
|
||||
Thread.sleep(1);
|
||||
} catch(InterruptedException e) {
|
||||
// Nom nom
|
||||
}
|
||||
} else {
|
||||
Log.w(TAG, "SDL audio: error return from write(byte)");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This method is called by SDL using JNI.
|
||||
*/
|
||||
public static int[] captureOpen(int sampleRate, int audioFormat, int desiredChannels, int desiredFrames, int deviceId) {
|
||||
return open(true, sampleRate, audioFormat, desiredChannels, desiredFrames, deviceId);
|
||||
}
|
||||
|
||||
/** This method is called by SDL using JNI. */
|
||||
public static int captureReadFloatBuffer(float[] buffer, boolean blocking) {
|
||||
if (Build.VERSION.SDK_INT < 23 /* Android 6.0 (M) */) {
|
||||
return 0;
|
||||
} else {
|
||||
return mAudioRecord.read(buffer, 0, buffer.length, blocking ? AudioRecord.READ_BLOCKING : AudioRecord.READ_NON_BLOCKING);
|
||||
}
|
||||
}
|
||||
|
||||
/** This method is called by SDL using JNI. */
|
||||
public static int captureReadShortBuffer(short[] buffer, boolean blocking) {
|
||||
if (Build.VERSION.SDK_INT < 23 /* Android 6.0 (M) */) {
|
||||
return mAudioRecord.read(buffer, 0, buffer.length);
|
||||
} else {
|
||||
return mAudioRecord.read(buffer, 0, buffer.length, blocking ? AudioRecord.READ_BLOCKING : AudioRecord.READ_NON_BLOCKING);
|
||||
}
|
||||
}
|
||||
|
||||
/** This method is called by SDL using JNI. */
|
||||
public static int captureReadByteBuffer(byte[] buffer, boolean blocking) {
|
||||
if (Build.VERSION.SDK_INT < 23 /* Android 6.0 (M) */) {
|
||||
return mAudioRecord.read(buffer, 0, buffer.length);
|
||||
} else {
|
||||
return mAudioRecord.read(buffer, 0, buffer.length, blocking ? AudioRecord.READ_BLOCKING : AudioRecord.READ_NON_BLOCKING);
|
||||
}
|
||||
}
|
||||
|
||||
/** This method is called by SDL using JNI. */
|
||||
public static void audioClose() {
|
||||
if (mAudioTrack != null) {
|
||||
mAudioTrack.stop();
|
||||
mAudioTrack.release();
|
||||
mAudioTrack = null;
|
||||
}
|
||||
}
|
||||
|
||||
/** This method is called by SDL using JNI. */
|
||||
public static void captureClose() {
|
||||
if (mAudioRecord != null) {
|
||||
mAudioRecord.stop();
|
||||
mAudioRecord.release();
|
||||
mAudioRecord = null;
|
||||
}
|
||||
}
|
||||
|
||||
/** This method is called by SDL using JNI. */
|
||||
public static void audioSetThreadPriority(boolean iscapture, int device_id) {
|
||||
try {
|
||||
|
||||
/* Set thread name */
|
||||
if (iscapture) {
|
||||
Thread.currentThread().setName("SDLAudioC" + device_id);
|
||||
} else {
|
||||
Thread.currentThread().setName("SDLAudioP" + device_id);
|
||||
}
|
||||
|
||||
/* Set thread priority */
|
||||
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_AUDIO);
|
||||
|
||||
} catch (Exception e) {
|
||||
Log.v(TAG, "modify thread properties failed " + e.toString());
|
||||
}
|
||||
}
|
||||
|
||||
public static native int nativeSetupJNI();
|
||||
|
||||
public static native void removeAudioDevice(boolean isCapture, int deviceId);
|
||||
|
||||
public static native void addAudioDevice(boolean isCapture, int deviceId);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,854 @@
|
||||
package org.libsdl.app;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
|
||||
import android.content.Context;
|
||||
import android.os.Build;
|
||||
import android.os.VibrationEffect;
|
||||
import android.os.Vibrator;
|
||||
import android.util.Log;
|
||||
import android.view.InputDevice;
|
||||
import android.view.KeyEvent;
|
||||
import android.view.MotionEvent;
|
||||
import android.view.View;
|
||||
|
||||
|
||||
public class SDLControllerManager
|
||||
{
|
||||
|
||||
public static native int nativeSetupJNI();
|
||||
|
||||
public static native int nativeAddJoystick(int device_id, String name, String desc,
|
||||
int vendor_id, int product_id,
|
||||
boolean is_accelerometer, int button_mask,
|
||||
int naxes, int axis_mask, int nhats, int nballs);
|
||||
public static native int nativeRemoveJoystick(int device_id);
|
||||
public static native int nativeAddHaptic(int device_id, String name);
|
||||
public static native int nativeRemoveHaptic(int device_id);
|
||||
public static native int onNativePadDown(int device_id, int keycode);
|
||||
public static native int onNativePadUp(int device_id, int keycode);
|
||||
public static native void onNativeJoy(int device_id, int axis,
|
||||
float value);
|
||||
public static native void onNativeHat(int device_id, int hat_id,
|
||||
int x, int y);
|
||||
|
||||
protected static SDLJoystickHandler mJoystickHandler;
|
||||
protected static SDLHapticHandler mHapticHandler;
|
||||
|
||||
private static final String TAG = "SDLControllerManager";
|
||||
|
||||
public static void initialize() {
|
||||
if (mJoystickHandler == null) {
|
||||
if (Build.VERSION.SDK_INT >= 19 /* Android 4.4 (KITKAT) */) {
|
||||
mJoystickHandler = new SDLJoystickHandler_API19();
|
||||
} else {
|
||||
mJoystickHandler = new SDLJoystickHandler_API16();
|
||||
}
|
||||
}
|
||||
|
||||
if (mHapticHandler == null) {
|
||||
if (Build.VERSION.SDK_INT >= 26 /* Android 8.0 (O) */) {
|
||||
mHapticHandler = new SDLHapticHandler_API26();
|
||||
} else {
|
||||
mHapticHandler = new SDLHapticHandler();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Joystick glue code, just a series of stubs that redirect to the SDLJoystickHandler instance
|
||||
public static boolean handleJoystickMotionEvent(MotionEvent event) {
|
||||
return mJoystickHandler.handleMotionEvent(event);
|
||||
}
|
||||
|
||||
/**
|
||||
* This method is called by SDL using JNI.
|
||||
*/
|
||||
public static void pollInputDevices() {
|
||||
mJoystickHandler.pollInputDevices();
|
||||
}
|
||||
|
||||
/**
|
||||
* This method is called by SDL using JNI.
|
||||
*/
|
||||
public static void pollHapticDevices() {
|
||||
mHapticHandler.pollHapticDevices();
|
||||
}
|
||||
|
||||
/**
|
||||
* This method is called by SDL using JNI.
|
||||
*/
|
||||
public static void hapticRun(int device_id, float intensity, int length) {
|
||||
mHapticHandler.run(device_id, intensity, length);
|
||||
}
|
||||
|
||||
/**
|
||||
* This method is called by SDL using JNI.
|
||||
*/
|
||||
public static void hapticStop(int device_id)
|
||||
{
|
||||
mHapticHandler.stop(device_id);
|
||||
}
|
||||
|
||||
// Check if a given device is considered a possible SDL joystick
|
||||
public static boolean isDeviceSDLJoystick(int deviceId) {
|
||||
InputDevice device = InputDevice.getDevice(deviceId);
|
||||
// We cannot use InputDevice.isVirtual before API 16, so let's accept
|
||||
// only nonnegative device ids (VIRTUAL_KEYBOARD equals -1)
|
||||
if ((device == null) || (deviceId < 0)) {
|
||||
return false;
|
||||
}
|
||||
int sources = device.getSources();
|
||||
|
||||
/* This is called for every button press, so let's not spam the logs */
|
||||
/*
|
||||
if ((sources & InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
|
||||
Log.v(TAG, "Input device " + device.getName() + " has class joystick.");
|
||||
}
|
||||
if ((sources & InputDevice.SOURCE_DPAD) == InputDevice.SOURCE_DPAD) {
|
||||
Log.v(TAG, "Input device " + device.getName() + " is a dpad.");
|
||||
}
|
||||
if ((sources & InputDevice.SOURCE_GAMEPAD) == InputDevice.SOURCE_GAMEPAD) {
|
||||
Log.v(TAG, "Input device " + device.getName() + " is a gamepad.");
|
||||
}
|
||||
*/
|
||||
|
||||
return ((sources & InputDevice.SOURCE_CLASS_JOYSTICK) != 0 ||
|
||||
((sources & InputDevice.SOURCE_DPAD) == InputDevice.SOURCE_DPAD) ||
|
||||
((sources & InputDevice.SOURCE_GAMEPAD) == InputDevice.SOURCE_GAMEPAD)
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class SDLJoystickHandler {
|
||||
|
||||
/**
|
||||
* Handles given MotionEvent.
|
||||
* @param event the event to be handled.
|
||||
* @return if given event was processed.
|
||||
*/
|
||||
public boolean handleMotionEvent(MotionEvent event) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles adding and removing of input devices.
|
||||
*/
|
||||
public void pollInputDevices() {
|
||||
}
|
||||
}
|
||||
|
||||
/* Actual joystick functionality available for API >= 12 devices */
|
||||
class SDLJoystickHandler_API16 extends SDLJoystickHandler {
|
||||
|
||||
static class SDLJoystick {
|
||||
public int device_id;
|
||||
public String name;
|
||||
public String desc;
|
||||
public ArrayList<InputDevice.MotionRange> axes;
|
||||
public ArrayList<InputDevice.MotionRange> hats;
|
||||
}
|
||||
static class RangeComparator implements Comparator<InputDevice.MotionRange> {
|
||||
@Override
|
||||
public int compare(InputDevice.MotionRange arg0, InputDevice.MotionRange arg1) {
|
||||
// Some controllers, like the Moga Pro 2, return AXIS_GAS (22) for right trigger and AXIS_BRAKE (23) for left trigger - swap them so they're sorted in the right order for SDL
|
||||
int arg0Axis = arg0.getAxis();
|
||||
int arg1Axis = arg1.getAxis();
|
||||
if (arg0Axis == MotionEvent.AXIS_GAS) {
|
||||
arg0Axis = MotionEvent.AXIS_BRAKE;
|
||||
} else if (arg0Axis == MotionEvent.AXIS_BRAKE) {
|
||||
arg0Axis = MotionEvent.AXIS_GAS;
|
||||
}
|
||||
if (arg1Axis == MotionEvent.AXIS_GAS) {
|
||||
arg1Axis = MotionEvent.AXIS_BRAKE;
|
||||
} else if (arg1Axis == MotionEvent.AXIS_BRAKE) {
|
||||
arg1Axis = MotionEvent.AXIS_GAS;
|
||||
}
|
||||
|
||||
// Make sure the AXIS_Z is sorted between AXIS_RY and AXIS_RZ.
|
||||
// This is because the usual pairing are:
|
||||
// - AXIS_X + AXIS_Y (left stick).
|
||||
// - AXIS_RX, AXIS_RY (sometimes the right stick, sometimes triggers).
|
||||
// - AXIS_Z, AXIS_RZ (sometimes the right stick, sometimes triggers).
|
||||
// This sorts the axes in the above order, which tends to be correct
|
||||
// for Xbox-ish game pads that have the right stick on RX/RY and the
|
||||
// triggers on Z/RZ.
|
||||
//
|
||||
// Gamepads that don't have AXIS_Z/AXIS_RZ but use
|
||||
// AXIS_LTRIGGER/AXIS_RTRIGGER are unaffected by this.
|
||||
//
|
||||
// References:
|
||||
// - https://developer.android.com/develop/ui/views/touch-and-input/game-controllers/controller-input
|
||||
// - https://www.kernel.org/doc/html/latest/input/gamepad.html
|
||||
if (arg0Axis == MotionEvent.AXIS_Z) {
|
||||
arg0Axis = MotionEvent.AXIS_RZ - 1;
|
||||
} else if (arg0Axis > MotionEvent.AXIS_Z && arg0Axis < MotionEvent.AXIS_RZ) {
|
||||
--arg0Axis;
|
||||
}
|
||||
if (arg1Axis == MotionEvent.AXIS_Z) {
|
||||
arg1Axis = MotionEvent.AXIS_RZ - 1;
|
||||
} else if (arg1Axis > MotionEvent.AXIS_Z && arg1Axis < MotionEvent.AXIS_RZ) {
|
||||
--arg1Axis;
|
||||
}
|
||||
|
||||
return arg0Axis - arg1Axis;
|
||||
}
|
||||
}
|
||||
|
||||
private final ArrayList<SDLJoystick> mJoysticks;
|
||||
|
||||
public SDLJoystickHandler_API16() {
|
||||
|
||||
mJoysticks = new ArrayList<SDLJoystick>();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void pollInputDevices() {
|
||||
int[] deviceIds = InputDevice.getDeviceIds();
|
||||
|
||||
for (int device_id : deviceIds) {
|
||||
if (SDLControllerManager.isDeviceSDLJoystick(device_id)) {
|
||||
SDLJoystick joystick = getJoystick(device_id);
|
||||
if (joystick == null) {
|
||||
InputDevice joystickDevice = InputDevice.getDevice(device_id);
|
||||
joystick = new SDLJoystick();
|
||||
joystick.device_id = device_id;
|
||||
joystick.name = joystickDevice.getName();
|
||||
joystick.desc = getJoystickDescriptor(joystickDevice);
|
||||
joystick.axes = new ArrayList<InputDevice.MotionRange>();
|
||||
joystick.hats = new ArrayList<InputDevice.MotionRange>();
|
||||
|
||||
List<InputDevice.MotionRange> ranges = joystickDevice.getMotionRanges();
|
||||
Collections.sort(ranges, new RangeComparator());
|
||||
for (InputDevice.MotionRange range : ranges) {
|
||||
if ((range.getSource() & InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
|
||||
if (range.getAxis() == MotionEvent.AXIS_HAT_X || range.getAxis() == MotionEvent.AXIS_HAT_Y) {
|
||||
joystick.hats.add(range);
|
||||
} else {
|
||||
joystick.axes.add(range);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
mJoysticks.add(joystick);
|
||||
SDLControllerManager.nativeAddJoystick(joystick.device_id, joystick.name, joystick.desc,
|
||||
getVendorId(joystickDevice), getProductId(joystickDevice), false,
|
||||
getButtonMask(joystickDevice), joystick.axes.size(), getAxisMask(joystick.axes), joystick.hats.size()/2, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Check removed devices */
|
||||
ArrayList<Integer> removedDevices = null;
|
||||
for (SDLJoystick joystick : mJoysticks) {
|
||||
int device_id = joystick.device_id;
|
||||
int i;
|
||||
for (i = 0; i < deviceIds.length; i++) {
|
||||
if (device_id == deviceIds[i]) break;
|
||||
}
|
||||
if (i == deviceIds.length) {
|
||||
if (removedDevices == null) {
|
||||
removedDevices = new ArrayList<Integer>();
|
||||
}
|
||||
removedDevices.add(device_id);
|
||||
}
|
||||
}
|
||||
|
||||
if (removedDevices != null) {
|
||||
for (int device_id : removedDevices) {
|
||||
SDLControllerManager.nativeRemoveJoystick(device_id);
|
||||
for (int i = 0; i < mJoysticks.size(); i++) {
|
||||
if (mJoysticks.get(i).device_id == device_id) {
|
||||
mJoysticks.remove(i);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected SDLJoystick getJoystick(int device_id) {
|
||||
for (SDLJoystick joystick : mJoysticks) {
|
||||
if (joystick.device_id == device_id) {
|
||||
return joystick;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean handleMotionEvent(MotionEvent event) {
|
||||
int actionPointerIndex = event.getActionIndex();
|
||||
int action = event.getActionMasked();
|
||||
if (action == MotionEvent.ACTION_MOVE) {
|
||||
SDLJoystick joystick = getJoystick(event.getDeviceId());
|
||||
if (joystick != null) {
|
||||
for (int i = 0; i < joystick.axes.size(); i++) {
|
||||
InputDevice.MotionRange range = joystick.axes.get(i);
|
||||
/* Normalize the value to -1...1 */
|
||||
float value = (event.getAxisValue(range.getAxis(), actionPointerIndex) - range.getMin()) / range.getRange() * 2.0f - 1.0f;
|
||||
SDLControllerManager.onNativeJoy(joystick.device_id, i, value);
|
||||
}
|
||||
for (int i = 0; i < joystick.hats.size() / 2; i++) {
|
||||
int hatX = Math.round(event.getAxisValue(joystick.hats.get(2 * i).getAxis(), actionPointerIndex));
|
||||
int hatY = Math.round(event.getAxisValue(joystick.hats.get(2 * i + 1).getAxis(), actionPointerIndex));
|
||||
SDLControllerManager.onNativeHat(joystick.device_id, i, hatX, hatY);
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public String getJoystickDescriptor(InputDevice joystickDevice) {
|
||||
String desc = joystickDevice.getDescriptor();
|
||||
|
||||
if (desc != null && !desc.isEmpty()) {
|
||||
return desc;
|
||||
}
|
||||
|
||||
return joystickDevice.getName();
|
||||
}
|
||||
public int getProductId(InputDevice joystickDevice) {
|
||||
return 0;
|
||||
}
|
||||
public int getVendorId(InputDevice joystickDevice) {
|
||||
return 0;
|
||||
}
|
||||
public int getAxisMask(List<InputDevice.MotionRange> ranges) {
|
||||
return -1;
|
||||
}
|
||||
public int getButtonMask(InputDevice joystickDevice) {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
class SDLJoystickHandler_API19 extends SDLJoystickHandler_API16 {
|
||||
|
||||
@Override
|
||||
public int getProductId(InputDevice joystickDevice) {
|
||||
return joystickDevice.getProductId();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getVendorId(InputDevice joystickDevice) {
|
||||
return joystickDevice.getVendorId();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getAxisMask(List<InputDevice.MotionRange> ranges) {
|
||||
// For compatibility, keep computing the axis mask like before,
|
||||
// only really distinguishing 2, 4 and 6 axes.
|
||||
int axis_mask = 0;
|
||||
if (ranges.size() >= 2) {
|
||||
// ((1 << SDL_GAMEPAD_AXIS_LEFTX) | (1 << SDL_GAMEPAD_AXIS_LEFTY))
|
||||
axis_mask |= 0x0003;
|
||||
}
|
||||
if (ranges.size() >= 4) {
|
||||
// ((1 << SDL_GAMEPAD_AXIS_RIGHTX) | (1 << SDL_GAMEPAD_AXIS_RIGHTY))
|
||||
axis_mask |= 0x000c;
|
||||
}
|
||||
if (ranges.size() >= 6) {
|
||||
// ((1 << SDL_GAMEPAD_AXIS_LEFT_TRIGGER) | (1 << SDL_GAMEPAD_AXIS_RIGHT_TRIGGER))
|
||||
axis_mask |= 0x0030;
|
||||
}
|
||||
// Also add an indicator bit for whether the sorting order has changed.
|
||||
// This serves to disable outdated gamecontrollerdb.txt mappings.
|
||||
boolean have_z = false;
|
||||
boolean have_past_z_before_rz = false;
|
||||
for (InputDevice.MotionRange range : ranges) {
|
||||
int axis = range.getAxis();
|
||||
if (axis == MotionEvent.AXIS_Z) {
|
||||
have_z = true;
|
||||
} else if (axis > MotionEvent.AXIS_Z && axis < MotionEvent.AXIS_RZ) {
|
||||
have_past_z_before_rz = true;
|
||||
}
|
||||
}
|
||||
if (have_z && have_past_z_before_rz) {
|
||||
// If both these exist, the compare() function changed sorting order.
|
||||
// Set a bit to indicate this fact.
|
||||
axis_mask |= 0x8000;
|
||||
}
|
||||
return axis_mask;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getButtonMask(InputDevice joystickDevice) {
|
||||
int button_mask = 0;
|
||||
int[] keys = new int[] {
|
||||
KeyEvent.KEYCODE_BUTTON_A,
|
||||
KeyEvent.KEYCODE_BUTTON_B,
|
||||
KeyEvent.KEYCODE_BUTTON_X,
|
||||
KeyEvent.KEYCODE_BUTTON_Y,
|
||||
KeyEvent.KEYCODE_BACK,
|
||||
KeyEvent.KEYCODE_MENU,
|
||||
KeyEvent.KEYCODE_BUTTON_MODE,
|
||||
KeyEvent.KEYCODE_BUTTON_START,
|
||||
KeyEvent.KEYCODE_BUTTON_THUMBL,
|
||||
KeyEvent.KEYCODE_BUTTON_THUMBR,
|
||||
KeyEvent.KEYCODE_BUTTON_L1,
|
||||
KeyEvent.KEYCODE_BUTTON_R1,
|
||||
KeyEvent.KEYCODE_DPAD_UP,
|
||||
KeyEvent.KEYCODE_DPAD_DOWN,
|
||||
KeyEvent.KEYCODE_DPAD_LEFT,
|
||||
KeyEvent.KEYCODE_DPAD_RIGHT,
|
||||
KeyEvent.KEYCODE_BUTTON_SELECT,
|
||||
KeyEvent.KEYCODE_DPAD_CENTER,
|
||||
|
||||
// These don't map into any SDL controller buttons directly
|
||||
KeyEvent.KEYCODE_BUTTON_L2,
|
||||
KeyEvent.KEYCODE_BUTTON_R2,
|
||||
KeyEvent.KEYCODE_BUTTON_C,
|
||||
KeyEvent.KEYCODE_BUTTON_Z,
|
||||
KeyEvent.KEYCODE_BUTTON_1,
|
||||
KeyEvent.KEYCODE_BUTTON_2,
|
||||
KeyEvent.KEYCODE_BUTTON_3,
|
||||
KeyEvent.KEYCODE_BUTTON_4,
|
||||
KeyEvent.KEYCODE_BUTTON_5,
|
||||
KeyEvent.KEYCODE_BUTTON_6,
|
||||
KeyEvent.KEYCODE_BUTTON_7,
|
||||
KeyEvent.KEYCODE_BUTTON_8,
|
||||
KeyEvent.KEYCODE_BUTTON_9,
|
||||
KeyEvent.KEYCODE_BUTTON_10,
|
||||
KeyEvent.KEYCODE_BUTTON_11,
|
||||
KeyEvent.KEYCODE_BUTTON_12,
|
||||
KeyEvent.KEYCODE_BUTTON_13,
|
||||
KeyEvent.KEYCODE_BUTTON_14,
|
||||
KeyEvent.KEYCODE_BUTTON_15,
|
||||
KeyEvent.KEYCODE_BUTTON_16,
|
||||
};
|
||||
int[] masks = new int[] {
|
||||
(1 << 0), // A -> A
|
||||
(1 << 1), // B -> B
|
||||
(1 << 2), // X -> X
|
||||
(1 << 3), // Y -> Y
|
||||
(1 << 4), // BACK -> BACK
|
||||
(1 << 6), // MENU -> START
|
||||
(1 << 5), // MODE -> GUIDE
|
||||
(1 << 6), // START -> START
|
||||
(1 << 7), // THUMBL -> LEFTSTICK
|
||||
(1 << 8), // THUMBR -> RIGHTSTICK
|
||||
(1 << 9), // L1 -> LEFTSHOULDER
|
||||
(1 << 10), // R1 -> RIGHTSHOULDER
|
||||
(1 << 11), // DPAD_UP -> DPAD_UP
|
||||
(1 << 12), // DPAD_DOWN -> DPAD_DOWN
|
||||
(1 << 13), // DPAD_LEFT -> DPAD_LEFT
|
||||
(1 << 14), // DPAD_RIGHT -> DPAD_RIGHT
|
||||
(1 << 4), // SELECT -> BACK
|
||||
(1 << 0), // DPAD_CENTER -> A
|
||||
(1 << 15), // L2 -> ??
|
||||
(1 << 16), // R2 -> ??
|
||||
(1 << 17), // C -> ??
|
||||
(1 << 18), // Z -> ??
|
||||
(1 << 20), // 1 -> ??
|
||||
(1 << 21), // 2 -> ??
|
||||
(1 << 22), // 3 -> ??
|
||||
(1 << 23), // 4 -> ??
|
||||
(1 << 24), // 5 -> ??
|
||||
(1 << 25), // 6 -> ??
|
||||
(1 << 26), // 7 -> ??
|
||||
(1 << 27), // 8 -> ??
|
||||
(1 << 28), // 9 -> ??
|
||||
(1 << 29), // 10 -> ??
|
||||
(1 << 30), // 11 -> ??
|
||||
(1 << 31), // 12 -> ??
|
||||
// We're out of room...
|
||||
0xFFFFFFFF, // 13 -> ??
|
||||
0xFFFFFFFF, // 14 -> ??
|
||||
0xFFFFFFFF, // 15 -> ??
|
||||
0xFFFFFFFF, // 16 -> ??
|
||||
};
|
||||
boolean[] has_keys = joystickDevice.hasKeys(keys);
|
||||
for (int i = 0; i < keys.length; ++i) {
|
||||
if (has_keys[i]) {
|
||||
button_mask |= masks[i];
|
||||
}
|
||||
}
|
||||
return button_mask;
|
||||
}
|
||||
}
|
||||
|
||||
class SDLHapticHandler_API26 extends SDLHapticHandler {
|
||||
@Override
|
||||
public void run(int device_id, float intensity, int length) {
|
||||
SDLHaptic haptic = getHaptic(device_id);
|
||||
if (haptic != null) {
|
||||
Log.d("SDL", "Rtest: Vibe with intensity " + intensity + " for " + length);
|
||||
if (intensity == 0.0f) {
|
||||
stop(device_id);
|
||||
return;
|
||||
}
|
||||
|
||||
int vibeValue = Math.round(intensity * 255);
|
||||
|
||||
if (vibeValue > 255) {
|
||||
vibeValue = 255;
|
||||
}
|
||||
if (vibeValue < 1) {
|
||||
stop(device_id);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
haptic.vib.vibrate(VibrationEffect.createOneShot(length, vibeValue));
|
||||
}
|
||||
catch (Exception e) {
|
||||
// Fall back to the generic method, which uses DEFAULT_AMPLITUDE, but works even if
|
||||
// something went horribly wrong with the Android 8.0 APIs.
|
||||
haptic.vib.vibrate(length);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class SDLHapticHandler {
|
||||
|
||||
static class SDLHaptic {
|
||||
public int device_id;
|
||||
public String name;
|
||||
public Vibrator vib;
|
||||
}
|
||||
|
||||
private final ArrayList<SDLHaptic> mHaptics;
|
||||
|
||||
public SDLHapticHandler() {
|
||||
mHaptics = new ArrayList<SDLHaptic>();
|
||||
}
|
||||
|
||||
public void run(int device_id, float intensity, int length) {
|
||||
SDLHaptic haptic = getHaptic(device_id);
|
||||
if (haptic != null) {
|
||||
haptic.vib.vibrate(length);
|
||||
}
|
||||
}
|
||||
|
||||
public void stop(int device_id) {
|
||||
SDLHaptic haptic = getHaptic(device_id);
|
||||
if (haptic != null) {
|
||||
haptic.vib.cancel();
|
||||
}
|
||||
}
|
||||
|
||||
public void pollHapticDevices() {
|
||||
|
||||
final int deviceId_VIBRATOR_SERVICE = 999999;
|
||||
boolean hasVibratorService = false;
|
||||
|
||||
int[] deviceIds = InputDevice.getDeviceIds();
|
||||
// It helps processing the device ids in reverse order
|
||||
// For example, in the case of the XBox 360 wireless dongle,
|
||||
// so the first controller seen by SDL matches what the receiver
|
||||
// considers to be the first controller
|
||||
|
||||
for (int i = deviceIds.length - 1; i > -1; i--) {
|
||||
SDLHaptic haptic = getHaptic(deviceIds[i]);
|
||||
if (haptic == null) {
|
||||
InputDevice device = InputDevice.getDevice(deviceIds[i]);
|
||||
Vibrator vib = device.getVibrator();
|
||||
if (vib.hasVibrator()) {
|
||||
haptic = new SDLHaptic();
|
||||
haptic.device_id = deviceIds[i];
|
||||
haptic.name = device.getName();
|
||||
haptic.vib = vib;
|
||||
mHaptics.add(haptic);
|
||||
SDLControllerManager.nativeAddHaptic(haptic.device_id, haptic.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Check VIBRATOR_SERVICE */
|
||||
Vibrator vib = (Vibrator) SDL.getContext().getSystemService(Context.VIBRATOR_SERVICE);
|
||||
if (vib != null) {
|
||||
hasVibratorService = vib.hasVibrator();
|
||||
|
||||
if (hasVibratorService) {
|
||||
SDLHaptic haptic = getHaptic(deviceId_VIBRATOR_SERVICE);
|
||||
if (haptic == null) {
|
||||
haptic = new SDLHaptic();
|
||||
haptic.device_id = deviceId_VIBRATOR_SERVICE;
|
||||
haptic.name = "VIBRATOR_SERVICE";
|
||||
haptic.vib = vib;
|
||||
mHaptics.add(haptic);
|
||||
SDLControllerManager.nativeAddHaptic(haptic.device_id, haptic.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Check removed devices */
|
||||
ArrayList<Integer> removedDevices = null;
|
||||
for (SDLHaptic haptic : mHaptics) {
|
||||
int device_id = haptic.device_id;
|
||||
int i;
|
||||
for (i = 0; i < deviceIds.length; i++) {
|
||||
if (device_id == deviceIds[i]) break;
|
||||
}
|
||||
|
||||
if (device_id != deviceId_VIBRATOR_SERVICE || !hasVibratorService) {
|
||||
if (i == deviceIds.length) {
|
||||
if (removedDevices == null) {
|
||||
removedDevices = new ArrayList<Integer>();
|
||||
}
|
||||
removedDevices.add(device_id);
|
||||
}
|
||||
} // else: don't remove the vibrator if it is still present
|
||||
}
|
||||
|
||||
if (removedDevices != null) {
|
||||
for (int device_id : removedDevices) {
|
||||
SDLControllerManager.nativeRemoveHaptic(device_id);
|
||||
for (int i = 0; i < mHaptics.size(); i++) {
|
||||
if (mHaptics.get(i).device_id == device_id) {
|
||||
mHaptics.remove(i);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected SDLHaptic getHaptic(int device_id) {
|
||||
for (SDLHaptic haptic : mHaptics) {
|
||||
if (haptic.device_id == device_id) {
|
||||
return haptic;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
class SDLGenericMotionListener_API12 implements View.OnGenericMotionListener {
|
||||
// Generic Motion (mouse hover, joystick...) events go here
|
||||
@Override
|
||||
public boolean onGenericMotion(View v, MotionEvent event) {
|
||||
float x, y;
|
||||
int action;
|
||||
|
||||
switch ( event.getSource() ) {
|
||||
case InputDevice.SOURCE_JOYSTICK:
|
||||
return SDLControllerManager.handleJoystickMotionEvent(event);
|
||||
|
||||
case InputDevice.SOURCE_MOUSE:
|
||||
action = event.getActionMasked();
|
||||
switch (action) {
|
||||
case MotionEvent.ACTION_SCROLL:
|
||||
x = event.getAxisValue(MotionEvent.AXIS_HSCROLL, 0);
|
||||
y = event.getAxisValue(MotionEvent.AXIS_VSCROLL, 0);
|
||||
SDLActivity.onNativeMouse(0, action, x, y, false);
|
||||
return true;
|
||||
|
||||
case MotionEvent.ACTION_HOVER_MOVE:
|
||||
x = event.getX(0);
|
||||
y = event.getY(0);
|
||||
|
||||
SDLActivity.onNativeMouse(0, action, x, y, false);
|
||||
return true;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
// Event was not managed
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean supportsRelativeMouse() {
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean inRelativeMode() {
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean setRelativeMouseEnabled(boolean enabled) {
|
||||
return false;
|
||||
}
|
||||
|
||||
public void reclaimRelativeMouseModeIfNeeded()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
public float getEventX(MotionEvent event) {
|
||||
return event.getX(0);
|
||||
}
|
||||
|
||||
public float getEventY(MotionEvent event) {
|
||||
return event.getY(0);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class SDLGenericMotionListener_API24 extends SDLGenericMotionListener_API12 {
|
||||
// Generic Motion (mouse hover, joystick...) events go here
|
||||
|
||||
private boolean mRelativeModeEnabled;
|
||||
|
||||
@Override
|
||||
public boolean onGenericMotion(View v, MotionEvent event) {
|
||||
|
||||
// Handle relative mouse mode
|
||||
if (mRelativeModeEnabled) {
|
||||
if (event.getSource() == InputDevice.SOURCE_MOUSE) {
|
||||
int action = event.getActionMasked();
|
||||
if (action == MotionEvent.ACTION_HOVER_MOVE) {
|
||||
float x = event.getAxisValue(MotionEvent.AXIS_RELATIVE_X);
|
||||
float y = event.getAxisValue(MotionEvent.AXIS_RELATIVE_Y);
|
||||
SDLActivity.onNativeMouse(0, action, x, y, true);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Event was not managed, call SDLGenericMotionListener_API12 method
|
||||
return super.onGenericMotion(v, event);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supportsRelativeMouse() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean inRelativeMode() {
|
||||
return mRelativeModeEnabled;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean setRelativeMouseEnabled(boolean enabled) {
|
||||
mRelativeModeEnabled = enabled;
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public float getEventX(MotionEvent event) {
|
||||
if (mRelativeModeEnabled) {
|
||||
return event.getAxisValue(MotionEvent.AXIS_RELATIVE_X);
|
||||
} else {
|
||||
return event.getX(0);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public float getEventY(MotionEvent event) {
|
||||
if (mRelativeModeEnabled) {
|
||||
return event.getAxisValue(MotionEvent.AXIS_RELATIVE_Y);
|
||||
} else {
|
||||
return event.getY(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class SDLGenericMotionListener_API26 extends SDLGenericMotionListener_API24 {
|
||||
// Generic Motion (mouse hover, joystick...) events go here
|
||||
private boolean mRelativeModeEnabled;
|
||||
|
||||
@Override
|
||||
public boolean onGenericMotion(View v, MotionEvent event) {
|
||||
float x, y;
|
||||
int action;
|
||||
|
||||
switch ( event.getSource() ) {
|
||||
case InputDevice.SOURCE_JOYSTICK:
|
||||
return SDLControllerManager.handleJoystickMotionEvent(event);
|
||||
|
||||
case InputDevice.SOURCE_MOUSE:
|
||||
// DeX desktop mouse cursor is a separate non-standard input type.
|
||||
case InputDevice.SOURCE_MOUSE | InputDevice.SOURCE_TOUCHSCREEN:
|
||||
action = event.getActionMasked();
|
||||
switch (action) {
|
||||
case MotionEvent.ACTION_SCROLL:
|
||||
x = event.getAxisValue(MotionEvent.AXIS_HSCROLL, 0);
|
||||
y = event.getAxisValue(MotionEvent.AXIS_VSCROLL, 0);
|
||||
SDLActivity.onNativeMouse(0, action, x, y, false);
|
||||
return true;
|
||||
|
||||
case MotionEvent.ACTION_HOVER_MOVE:
|
||||
x = event.getX(0);
|
||||
y = event.getY(0);
|
||||
SDLActivity.onNativeMouse(0, action, x, y, false);
|
||||
return true;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
break;
|
||||
|
||||
case InputDevice.SOURCE_MOUSE_RELATIVE:
|
||||
action = event.getActionMasked();
|
||||
switch (action) {
|
||||
case MotionEvent.ACTION_SCROLL:
|
||||
x = event.getAxisValue(MotionEvent.AXIS_HSCROLL, 0);
|
||||
y = event.getAxisValue(MotionEvent.AXIS_VSCROLL, 0);
|
||||
SDLActivity.onNativeMouse(0, action, x, y, false);
|
||||
return true;
|
||||
|
||||
case MotionEvent.ACTION_HOVER_MOVE:
|
||||
x = event.getX(0);
|
||||
y = event.getY(0);
|
||||
SDLActivity.onNativeMouse(0, action, x, y, true);
|
||||
return true;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
// Event was not managed
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supportsRelativeMouse() {
|
||||
return (!SDLActivity.isDeXMode() || Build.VERSION.SDK_INT >= 27 /* Android 8.1 (O_MR1) */);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean inRelativeMode() {
|
||||
return mRelativeModeEnabled;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean setRelativeMouseEnabled(boolean enabled) {
|
||||
if (!SDLActivity.isDeXMode() || Build.VERSION.SDK_INT >= 27 /* Android 8.1 (O_MR1) */) {
|
||||
if (enabled) {
|
||||
SDLActivity.getContentView().requestPointerCapture();
|
||||
} else {
|
||||
SDLActivity.getContentView().releasePointerCapture();
|
||||
}
|
||||
mRelativeModeEnabled = enabled;
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void reclaimRelativeMouseModeIfNeeded()
|
||||
{
|
||||
if (mRelativeModeEnabled && !SDLActivity.isDeXMode()) {
|
||||
SDLActivity.getContentView().requestPointerCapture();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public float getEventX(MotionEvent event) {
|
||||
// Relative mouse in capture mode will only have relative for X/Y
|
||||
return event.getX(0);
|
||||
}
|
||||
|
||||
@Override
|
||||
public float getEventY(MotionEvent event) {
|
||||
// Relative mouse in capture mode will only have relative for X/Y
|
||||
return event.getY(0);
|
||||
}
|
||||
}
|
||||
405
android/app/src/main/java/org/libsdl/app/SDLSurface.java
Normal file
405
android/app/src/main/java/org/libsdl/app/SDLSurface.java
Normal file
@@ -0,0 +1,405 @@
|
||||
package org.libsdl.app;
|
||||
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.pm.ActivityInfo;
|
||||
import android.hardware.Sensor;
|
||||
import android.hardware.SensorEvent;
|
||||
import android.hardware.SensorEventListener;
|
||||
import android.hardware.SensorManager;
|
||||
import android.os.Build;
|
||||
import android.util.DisplayMetrics;
|
||||
import android.util.Log;
|
||||
import android.view.Display;
|
||||
import android.view.InputDevice;
|
||||
import android.view.KeyEvent;
|
||||
import android.view.MotionEvent;
|
||||
import android.view.Surface;
|
||||
import android.view.SurfaceHolder;
|
||||
import android.view.SurfaceView;
|
||||
import android.view.View;
|
||||
import android.view.WindowManager;
|
||||
|
||||
|
||||
/**
|
||||
SDLSurface. This is what we draw on, so we need to know when it's created
|
||||
in order to do anything useful.
|
||||
|
||||
Because of this, that's where we set up the SDL thread
|
||||
*/
|
||||
public class SDLSurface extends SurfaceView implements SurfaceHolder.Callback,
|
||||
View.OnKeyListener, View.OnTouchListener, SensorEventListener {
|
||||
|
||||
// Sensors
|
||||
protected SensorManager mSensorManager;
|
||||
protected Display mDisplay;
|
||||
|
||||
// Keep track of the surface size to normalize touch events
|
||||
protected float mWidth, mHeight;
|
||||
|
||||
// Is SurfaceView ready for rendering
|
||||
public boolean mIsSurfaceReady;
|
||||
|
||||
// Startup
|
||||
public SDLSurface(Context context) {
|
||||
super(context);
|
||||
getHolder().addCallback(this);
|
||||
|
||||
setFocusable(true);
|
||||
setFocusableInTouchMode(true);
|
||||
requestFocus();
|
||||
setOnKeyListener(this);
|
||||
setOnTouchListener(this);
|
||||
|
||||
mDisplay = ((WindowManager)context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
|
||||
mSensorManager = (SensorManager)context.getSystemService(Context.SENSOR_SERVICE);
|
||||
|
||||
setOnGenericMotionListener(SDLActivity.getMotionListener());
|
||||
|
||||
// Some arbitrary defaults to avoid a potential division by zero
|
||||
mWidth = 1.0f;
|
||||
mHeight = 1.0f;
|
||||
|
||||
mIsSurfaceReady = false;
|
||||
}
|
||||
|
||||
public void handlePause() {
|
||||
enableSensor(Sensor.TYPE_ACCELEROMETER, false);
|
||||
}
|
||||
|
||||
public void handleResume() {
|
||||
setFocusable(true);
|
||||
setFocusableInTouchMode(true);
|
||||
requestFocus();
|
||||
setOnKeyListener(this);
|
||||
setOnTouchListener(this);
|
||||
enableSensor(Sensor.TYPE_ACCELEROMETER, true);
|
||||
}
|
||||
|
||||
public Surface getNativeSurface() {
|
||||
return getHolder().getSurface();
|
||||
}
|
||||
|
||||
// Called when we have a valid drawing surface
|
||||
@Override
|
||||
public void surfaceCreated(SurfaceHolder holder) {
|
||||
Log.v("SDL", "surfaceCreated()");
|
||||
SDLActivity.onNativeSurfaceCreated();
|
||||
}
|
||||
|
||||
// Called when we lose the surface
|
||||
@Override
|
||||
public void surfaceDestroyed(SurfaceHolder holder) {
|
||||
Log.v("SDL", "surfaceDestroyed()");
|
||||
|
||||
// Transition to pause, if needed
|
||||
SDLActivity.mNextNativeState = SDLActivity.NativeState.PAUSED;
|
||||
SDLActivity.handleNativeState();
|
||||
|
||||
mIsSurfaceReady = false;
|
||||
SDLActivity.onNativeSurfaceDestroyed();
|
||||
}
|
||||
|
||||
// Called when the surface is resized
|
||||
@Override
|
||||
public void surfaceChanged(SurfaceHolder holder,
|
||||
int format, int width, int height) {
|
||||
Log.v("SDL", "surfaceChanged()");
|
||||
|
||||
if (SDLActivity.mSingleton == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
mWidth = width;
|
||||
mHeight = height;
|
||||
int nDeviceWidth = width;
|
||||
int nDeviceHeight = height;
|
||||
try
|
||||
{
|
||||
if (Build.VERSION.SDK_INT >= 17 /* Android 4.2 (JELLY_BEAN_MR1) */) {
|
||||
DisplayMetrics realMetrics = new DisplayMetrics();
|
||||
mDisplay.getRealMetrics( realMetrics );
|
||||
nDeviceWidth = realMetrics.widthPixels;
|
||||
nDeviceHeight = realMetrics.heightPixels;
|
||||
}
|
||||
} catch(Exception ignored) {
|
||||
}
|
||||
|
||||
synchronized(SDLActivity.getContext()) {
|
||||
// In case we're waiting on a size change after going fullscreen, send a notification.
|
||||
SDLActivity.getContext().notifyAll();
|
||||
}
|
||||
|
||||
Log.v("SDL", "Window size: " + width + "x" + height);
|
||||
Log.v("SDL", "Device size: " + nDeviceWidth + "x" + nDeviceHeight);
|
||||
SDLActivity.nativeSetScreenResolution(width, height, nDeviceWidth, nDeviceHeight, mDisplay.getRefreshRate());
|
||||
SDLActivity.onNativeResize();
|
||||
|
||||
// Prevent a screen distortion glitch,
|
||||
// for instance when the device is in Landscape and a Portrait App is resumed.
|
||||
boolean skip = false;
|
||||
int requestedOrientation = SDLActivity.mSingleton.getRequestedOrientation();
|
||||
|
||||
if (requestedOrientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT || requestedOrientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT) {
|
||||
if (mWidth > mHeight) {
|
||||
skip = true;
|
||||
}
|
||||
} else if (requestedOrientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE || requestedOrientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE) {
|
||||
if (mWidth < mHeight) {
|
||||
skip = true;
|
||||
}
|
||||
}
|
||||
|
||||
// Special Patch for Square Resolution: Black Berry Passport
|
||||
if (skip) {
|
||||
double min = Math.min(mWidth, mHeight);
|
||||
double max = Math.max(mWidth, mHeight);
|
||||
|
||||
if (max / min < 1.20) {
|
||||
Log.v("SDL", "Don't skip on such aspect-ratio. Could be a square resolution.");
|
||||
skip = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Don't skip in MultiWindow.
|
||||
if (skip) {
|
||||
if (Build.VERSION.SDK_INT >= 24 /* Android 7.0 (N) */) {
|
||||
if (SDLActivity.mSingleton.isInMultiWindowMode()) {
|
||||
Log.v("SDL", "Don't skip in Multi-Window");
|
||||
skip = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (skip) {
|
||||
Log.v("SDL", "Skip .. Surface is not ready.");
|
||||
mIsSurfaceReady = false;
|
||||
return;
|
||||
}
|
||||
|
||||
/* If the surface has been previously destroyed by onNativeSurfaceDestroyed, recreate it here */
|
||||
SDLActivity.onNativeSurfaceChanged();
|
||||
|
||||
/* Surface is ready */
|
||||
mIsSurfaceReady = true;
|
||||
|
||||
SDLActivity.mNextNativeState = SDLActivity.NativeState.RESUMED;
|
||||
SDLActivity.handleNativeState();
|
||||
}
|
||||
|
||||
// Key events
|
||||
@Override
|
||||
public boolean onKey(View v, int keyCode, KeyEvent event) {
|
||||
return SDLActivity.handleKeyEvent(v, keyCode, event, null);
|
||||
}
|
||||
|
||||
// Touch events
|
||||
@Override
|
||||
public boolean onTouch(View v, MotionEvent event) {
|
||||
/* Ref: http://developer.android.com/training/gestures/multi.html */
|
||||
int touchDevId = event.getDeviceId();
|
||||
final int pointerCount = event.getPointerCount();
|
||||
int action = event.getActionMasked();
|
||||
int pointerFingerId;
|
||||
int i = -1;
|
||||
float x,y,p;
|
||||
|
||||
/*
|
||||
* Prevent id to be -1, since it's used in SDL internal for synthetic events
|
||||
* Appears when using Android emulator, eg:
|
||||
* adb shell input mouse tap 100 100
|
||||
* adb shell input touchscreen tap 100 100
|
||||
*/
|
||||
if (touchDevId < 0) {
|
||||
touchDevId -= 1;
|
||||
}
|
||||
|
||||
// 12290 = Samsung DeX mode desktop mouse
|
||||
// 12290 = 0x3002 = 0x2002 | 0x1002 = SOURCE_MOUSE | SOURCE_TOUCHSCREEN
|
||||
// 0x2 = SOURCE_CLASS_POINTER
|
||||
if (event.getSource() == InputDevice.SOURCE_MOUSE || event.getSource() == (InputDevice.SOURCE_MOUSE | InputDevice.SOURCE_TOUCHSCREEN)) {
|
||||
int mouseButton = 1;
|
||||
try {
|
||||
Object object = event.getClass().getMethod("getButtonState").invoke(event);
|
||||
if (object != null) {
|
||||
mouseButton = (Integer) object;
|
||||
}
|
||||
} catch(Exception ignored) {
|
||||
}
|
||||
|
||||
// We need to check if we're in relative mouse mode and get the axis offset rather than the x/y values
|
||||
// if we are. We'll leverage our existing mouse motion listener
|
||||
SDLGenericMotionListener_API12 motionListener = SDLActivity.getMotionListener();
|
||||
x = motionListener.getEventX(event);
|
||||
y = motionListener.getEventY(event);
|
||||
|
||||
SDLActivity.onNativeMouse(mouseButton, action, x, y, motionListener.inRelativeMode());
|
||||
} else {
|
||||
switch(action) {
|
||||
case MotionEvent.ACTION_MOVE:
|
||||
for (i = 0; i < pointerCount; i++) {
|
||||
pointerFingerId = event.getPointerId(i);
|
||||
x = event.getX(i) / mWidth;
|
||||
y = event.getY(i) / mHeight;
|
||||
p = event.getPressure(i);
|
||||
if (p > 1.0f) {
|
||||
// may be larger than 1.0f on some devices
|
||||
// see the documentation of getPressure(i)
|
||||
p = 1.0f;
|
||||
}
|
||||
SDLActivity.onNativeTouch(touchDevId, pointerFingerId, action, x, y, p);
|
||||
}
|
||||
break;
|
||||
|
||||
case MotionEvent.ACTION_UP:
|
||||
case MotionEvent.ACTION_DOWN:
|
||||
// Primary pointer up/down, the index is always zero
|
||||
i = 0;
|
||||
/* fallthrough */
|
||||
case MotionEvent.ACTION_POINTER_UP:
|
||||
case MotionEvent.ACTION_POINTER_DOWN:
|
||||
// Non primary pointer up/down
|
||||
if (i == -1) {
|
||||
i = event.getActionIndex();
|
||||
}
|
||||
|
||||
pointerFingerId = event.getPointerId(i);
|
||||
x = event.getX(i) / mWidth;
|
||||
y = event.getY(i) / mHeight;
|
||||
p = event.getPressure(i);
|
||||
if (p > 1.0f) {
|
||||
// may be larger than 1.0f on some devices
|
||||
// see the documentation of getPressure(i)
|
||||
p = 1.0f;
|
||||
}
|
||||
SDLActivity.onNativeTouch(touchDevId, pointerFingerId, action, x, y, p);
|
||||
break;
|
||||
|
||||
case MotionEvent.ACTION_CANCEL:
|
||||
for (i = 0; i < pointerCount; i++) {
|
||||
pointerFingerId = event.getPointerId(i);
|
||||
x = event.getX(i) / mWidth;
|
||||
y = event.getY(i) / mHeight;
|
||||
p = event.getPressure(i);
|
||||
if (p > 1.0f) {
|
||||
// may be larger than 1.0f on some devices
|
||||
// see the documentation of getPressure(i)
|
||||
p = 1.0f;
|
||||
}
|
||||
SDLActivity.onNativeTouch(touchDevId, pointerFingerId, MotionEvent.ACTION_UP, x, y, p);
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// Sensor events
|
||||
public void enableSensor(int sensortype, boolean enabled) {
|
||||
// TODO: This uses getDefaultSensor - what if we have >1 accels?
|
||||
if (enabled) {
|
||||
mSensorManager.registerListener(this,
|
||||
mSensorManager.getDefaultSensor(sensortype),
|
||||
SensorManager.SENSOR_DELAY_GAME, null);
|
||||
} else {
|
||||
mSensorManager.unregisterListener(this,
|
||||
mSensorManager.getDefaultSensor(sensortype));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAccuracyChanged(Sensor sensor, int accuracy) {
|
||||
// TODO
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSensorChanged(SensorEvent event) {
|
||||
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
|
||||
|
||||
// Since we may have an orientation set, we won't receive onConfigurationChanged events.
|
||||
// We thus should check here.
|
||||
int newOrientation;
|
||||
|
||||
float x, y;
|
||||
switch (mDisplay.getRotation()) {
|
||||
case Surface.ROTATION_90:
|
||||
x = -event.values[1];
|
||||
y = event.values[0];
|
||||
newOrientation = SDLActivity.SDL_ORIENTATION_LANDSCAPE;
|
||||
break;
|
||||
case Surface.ROTATION_270:
|
||||
x = event.values[1];
|
||||
y = -event.values[0];
|
||||
newOrientation = SDLActivity.SDL_ORIENTATION_LANDSCAPE_FLIPPED;
|
||||
break;
|
||||
case Surface.ROTATION_180:
|
||||
x = -event.values[0];
|
||||
y = -event.values[1];
|
||||
newOrientation = SDLActivity.SDL_ORIENTATION_PORTRAIT_FLIPPED;
|
||||
break;
|
||||
case Surface.ROTATION_0:
|
||||
default:
|
||||
x = event.values[0];
|
||||
y = event.values[1];
|
||||
newOrientation = SDLActivity.SDL_ORIENTATION_PORTRAIT;
|
||||
break;
|
||||
}
|
||||
|
||||
if (newOrientation != SDLActivity.mCurrentOrientation) {
|
||||
SDLActivity.mCurrentOrientation = newOrientation;
|
||||
SDLActivity.onNativeOrientationChanged(newOrientation);
|
||||
}
|
||||
|
||||
SDLActivity.onNativeAccel(-x / SensorManager.GRAVITY_EARTH,
|
||||
y / SensorManager.GRAVITY_EARTH,
|
||||
event.values[2] / SensorManager.GRAVITY_EARTH);
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
// Captured pointer events for API 26.
|
||||
public boolean onCapturedPointerEvent(MotionEvent event)
|
||||
{
|
||||
int action = event.getActionMasked();
|
||||
|
||||
float x, y;
|
||||
switch (action) {
|
||||
case MotionEvent.ACTION_SCROLL:
|
||||
x = event.getAxisValue(MotionEvent.AXIS_HSCROLL, 0);
|
||||
y = event.getAxisValue(MotionEvent.AXIS_VSCROLL, 0);
|
||||
SDLActivity.onNativeMouse(0, action, x, y, false);
|
||||
return true;
|
||||
|
||||
case MotionEvent.ACTION_HOVER_MOVE:
|
||||
case MotionEvent.ACTION_MOVE:
|
||||
x = event.getX(0);
|
||||
y = event.getY(0);
|
||||
SDLActivity.onNativeMouse(0, action, x, y, true);
|
||||
return true;
|
||||
|
||||
case MotionEvent.ACTION_BUTTON_PRESS:
|
||||
case MotionEvent.ACTION_BUTTON_RELEASE:
|
||||
|
||||
// Change our action value to what SDL's code expects.
|
||||
if (action == MotionEvent.ACTION_BUTTON_PRESS) {
|
||||
action = MotionEvent.ACTION_DOWN;
|
||||
} else { /* MotionEvent.ACTION_BUTTON_RELEASE */
|
||||
action = MotionEvent.ACTION_UP;
|
||||
}
|
||||
|
||||
x = event.getX(0);
|
||||
y = event.getY(0);
|
||||
int button = event.getButtonState();
|
||||
|
||||
SDLActivity.onNativeMouse(button, action, x, y, true);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,10 @@
|
||||
<resources>
|
||||
<string name="label">Minetest</string>
|
||||
<string name="loading">Loading…</string>
|
||||
<string name="notification_title">Loading Minetest</string>
|
||||
<string name="notification_description">Less than 1 minute…</string>
|
||||
<string name="notification_channel_name">General notification</string>
|
||||
<string name="notification_channel_description">Notifications from Minetest</string>
|
||||
<string name="unzip_notification_title">Loading Minetest</string>
|
||||
<string name="unzip_notification_description">Less than 1 minute…</string>
|
||||
<string name="ime_dialog_done">Done</string>
|
||||
<string name="no_web_browser">No web browser found</string>
|
||||
</resources>
|
||||
|
||||
@@ -1,22 +1,22 @@
|
||||
// Top-level build file where you can add configuration options common to all sub-projects/modules.
|
||||
|
||||
project.ext.set("versionMajor", 5) // Version Major
|
||||
project.ext.set("versionMinor", 8) // Version Minor
|
||||
project.ext.set("versionMinor", 9) // Version Minor
|
||||
project.ext.set("versionPatch", 0) // Version Patch
|
||||
// ^ keep in sync with cmake
|
||||
project.ext.set("versionCode", 46) // Android Version Code
|
||||
project.ext.set("versionCode", 48) // Android Version Code
|
||||
// NOTE: +2 after each release!
|
||||
// +1 for ARM and +1 for ARM64 APK's, because
|
||||
// each APK must have a larger `versionCode` than the previous
|
||||
|
||||
buildscript {
|
||||
ext.ndk_version = '25.2.9519653'
|
||||
ext.ndk_version = '26.2.11394342'
|
||||
repositories {
|
||||
google()
|
||||
mavenCentral()
|
||||
}
|
||||
dependencies {
|
||||
classpath 'com.android.tools.build:gradle:7.4.1'
|
||||
classpath 'com.android.tools.build:gradle:8.5.1'
|
||||
classpath 'de.undercouch:gradle-download-task:4.1.1'
|
||||
// NOTE: Do not place your application dependencies here; they belong
|
||||
// in the individual module build.gradle files
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<#if isLowMemory>
|
||||
org.gradle.jvmargs=-Xmx4G -XX:MaxPermSize=2G -XX:+HeapDumpOnOutOfMemoryError
|
||||
org.gradle.jvmargs=-Xmx4G -XX:+HeapDumpOnOutOfMemoryError
|
||||
<#else>
|
||||
org.gradle.jvmargs=-Xmx16G -XX:MaxPermSize=8G -XX:+HeapDumpOnOutOfMemoryError
|
||||
org.gradle.jvmargs=-Xmx16G -XX:+HeapDumpOnOutOfMemoryError
|
||||
</#if>
|
||||
org.gradle.daemon=true
|
||||
org.gradle.parallel=true
|
||||
@@ -9,3 +9,5 @@ org.gradle.parallel.threads=8
|
||||
org.gradle.configureondemand=true
|
||||
android.enableJetifier=false
|
||||
android.useAndroidX=true
|
||||
android.nonTransitiveRClass=false
|
||||
android.nonFinalResIds=false
|
||||
|
||||
BIN
android/gradle/wrapper/gradle-wrapper.jar
vendored
BIN
android/gradle/wrapper/gradle-wrapper.jar
vendored
Binary file not shown.
@@ -1,5 +1,7 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip
|
||||
networkTimeout=10000
|
||||
validateDistributionUrl=true
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-7.5-bin.zip
|
||||
|
||||
295
android/gradlew
vendored
295
android/gradlew
vendored
@@ -1,7 +1,7 @@
|
||||
#!/usr/bin/env sh
|
||||
#!/bin/sh
|
||||
|
||||
#
|
||||
# Copyright 2015 the original author or authors.
|
||||
# Copyright © 2015-2021 the original authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
@@ -17,78 +17,111 @@
|
||||
#
|
||||
|
||||
##############################################################################
|
||||
##
|
||||
## Gradle start up script for UN*X
|
||||
##
|
||||
#
|
||||
# Gradle start up script for POSIX generated by Gradle.
|
||||
#
|
||||
# Important for running:
|
||||
#
|
||||
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||
# noncompliant, but you have some other compliant shell such as ksh or
|
||||
# bash, then to run this script, type that shell name before the whole
|
||||
# command line, like:
|
||||
#
|
||||
# ksh Gradle
|
||||
#
|
||||
# Busybox and similar reduced shells will NOT work, because this script
|
||||
# requires all of these POSIX shell features:
|
||||
# * functions;
|
||||
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||
# * compound commands having a testable exit status, especially «case»;
|
||||
# * various built-in commands including «command», «set», and «ulimit».
|
||||
#
|
||||
# Important for patching:
|
||||
#
|
||||
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||
#
|
||||
# The "traditional" practice of packing multiple parameters into a
|
||||
# space-separated string is a well documented source of bugs and security
|
||||
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||
# options in "$@", and eventually passing that to Java.
|
||||
#
|
||||
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||
# see the in-line comments for details.
|
||||
#
|
||||
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||
# Darwin, MinGW, and NonStop.
|
||||
#
|
||||
# (3) This script is generated from the Groovy template
|
||||
# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||
# within the Gradle project.
|
||||
#
|
||||
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||
#
|
||||
##############################################################################
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
|
||||
# Resolve links: $0 may be a link
|
||||
PRG="$0"
|
||||
# Need this for relative symlinks.
|
||||
while [ -h "$PRG" ] ; do
|
||||
ls=`ls -ld "$PRG"`
|
||||
link=`expr "$ls" : '.*-> \(.*\)$'`
|
||||
if expr "$link" : '/.*' > /dev/null; then
|
||||
PRG="$link"
|
||||
else
|
||||
PRG=`dirname "$PRG"`"/$link"
|
||||
fi
|
||||
app_path=$0
|
||||
|
||||
# Need this for daisy-chained symlinks.
|
||||
while
|
||||
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||
[ -h "$app_path" ]
|
||||
do
|
||||
ls=$( ls -ld "$app_path" )
|
||||
link=${ls#*' -> '}
|
||||
case $link in #(
|
||||
/*) app_path=$link ;; #(
|
||||
*) app_path=$APP_HOME$link ;;
|
||||
esac
|
||||
done
|
||||
SAVED="`pwd`"
|
||||
cd "`dirname \"$PRG\"`/" >/dev/null
|
||||
APP_HOME="`pwd -P`"
|
||||
cd "$SAVED" >/dev/null
|
||||
|
||||
APP_NAME="Gradle"
|
||||
APP_BASE_NAME=`basename "$0"`
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
# This is normally unused
|
||||
# shellcheck disable=SC2034
|
||||
APP_BASE_NAME=${0##*/}
|
||||
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
|
||||
APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD="maximum"
|
||||
MAX_FD=maximum
|
||||
|
||||
warn () {
|
||||
echo "$*"
|
||||
}
|
||||
} >&2
|
||||
|
||||
die () {
|
||||
echo
|
||||
echo "$*"
|
||||
echo
|
||||
exit 1
|
||||
}
|
||||
} >&2
|
||||
|
||||
# OS specific support (must be 'true' or 'false').
|
||||
cygwin=false
|
||||
msys=false
|
||||
darwin=false
|
||||
nonstop=false
|
||||
case "`uname`" in
|
||||
CYGWIN* )
|
||||
cygwin=true
|
||||
;;
|
||||
Darwin* )
|
||||
darwin=true
|
||||
;;
|
||||
MINGW* )
|
||||
msys=true
|
||||
;;
|
||||
NONSTOP* )
|
||||
nonstop=true
|
||||
;;
|
||||
case "$( uname )" in #(
|
||||
CYGWIN* ) cygwin=true ;; #(
|
||||
Darwin* ) darwin=true ;; #(
|
||||
MSYS* | MINGW* ) msys=true ;; #(
|
||||
NONSTOP* ) nonstop=true ;;
|
||||
esac
|
||||
|
||||
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
||||
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD="$JAVA_HOME/jre/sh/java"
|
||||
JAVACMD=$JAVA_HOME/jre/sh/java
|
||||
else
|
||||
JAVACMD="$JAVA_HOME/bin/java"
|
||||
JAVACMD=$JAVA_HOME/bin/java
|
||||
fi
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||
@@ -97,92 +130,120 @@ Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD="java"
|
||||
command -v java >/dev/null || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
JAVACMD=java
|
||||
if ! command -v java >/dev/null 2>&1
|
||||
then
|
||||
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
fi
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
|
||||
MAX_FD_LIMIT=`ulimit -H -n`
|
||||
if [ $? -eq 0 ] ; then
|
||||
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
|
||||
MAX_FD="$MAX_FD_LIMIT"
|
||||
fi
|
||||
ulimit -n $MAX_FD
|
||||
if [ $? -ne 0 ] ; then
|
||||
warn "Could not set maximum file descriptor limit: $MAX_FD"
|
||||
fi
|
||||
else
|
||||
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
|
||||
fi
|
||||
fi
|
||||
|
||||
# For Darwin, add options to specify how the application appears in the dock
|
||||
if $darwin; then
|
||||
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
|
||||
fi
|
||||
|
||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
|
||||
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
|
||||
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
|
||||
JAVACMD=`cygpath --unix "$JAVACMD"`
|
||||
|
||||
# We build the pattern for arguments to be converted via cygpath
|
||||
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
|
||||
SEP=""
|
||||
for dir in $ROOTDIRSRAW ; do
|
||||
ROOTDIRS="$ROOTDIRS$SEP$dir"
|
||||
SEP="|"
|
||||
done
|
||||
OURCYGPATTERN="(^($ROOTDIRS))"
|
||||
# Add a user-defined pattern to the cygpath arguments
|
||||
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
|
||||
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
|
||||
fi
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
i=0
|
||||
for arg in "$@" ; do
|
||||
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
|
||||
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
|
||||
|
||||
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
|
||||
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
|
||||
else
|
||||
eval `echo args$i`="\"$arg\""
|
||||
fi
|
||||
i=$((i+1))
|
||||
done
|
||||
case $i in
|
||||
(0) set -- ;;
|
||||
(1) set -- "$args0" ;;
|
||||
(2) set -- "$args0" "$args1" ;;
|
||||
(3) set -- "$args0" "$args1" "$args2" ;;
|
||||
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
|
||||
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
|
||||
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
|
||||
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
|
||||
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
|
||||
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
|
||||
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||
case $MAX_FD in #(
|
||||
max*)
|
||||
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
MAX_FD=$( ulimit -H -n ) ||
|
||||
warn "Could not query maximum file descriptor limit"
|
||||
esac
|
||||
case $MAX_FD in #(
|
||||
'' | soft) :;; #(
|
||||
*)
|
||||
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
ulimit -n "$MAX_FD" ||
|
||||
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||
esac
|
||||
fi
|
||||
|
||||
# Escape application args
|
||||
save () {
|
||||
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
|
||||
echo " "
|
||||
}
|
||||
APP_ARGS=$(save "$@")
|
||||
# Collect all arguments for the java command, stacking in reverse order:
|
||||
# * args from the command line
|
||||
# * the main class name
|
||||
# * -classpath
|
||||
# * -D...appname settings
|
||||
# * --module-path (only if needed)
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
||||
|
||||
# Collect all arguments for the java command, following the shell quoting and substitution rules
|
||||
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
|
||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||
if "$cygwin" || "$msys" ; then
|
||||
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
|
||||
|
||||
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
|
||||
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
|
||||
cd "$(dirname "$0")"
|
||||
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
for arg do
|
||||
if
|
||||
case $arg in #(
|
||||
-*) false ;; # don't mess with options #(
|
||||
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
||||
[ -e "$t" ] ;; #(
|
||||
*) false ;;
|
||||
esac
|
||||
then
|
||||
arg=$( cygpath --path --ignore --mixed "$arg" )
|
||||
fi
|
||||
# Roll the args list around exactly as many times as the number of
|
||||
# args, so each arg winds up back in the position where it started, but
|
||||
# possibly modified.
|
||||
#
|
||||
# NB: a `for` loop captures its iteration list before it begins, so
|
||||
# changing the positional parameters here affects neither the number of
|
||||
# iterations, nor the values presented in `arg`.
|
||||
shift # remove old arg
|
||||
set -- "$@" "$arg" # push replacement arg
|
||||
done
|
||||
fi
|
||||
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
|
||||
# Collect all arguments for the java command:
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
|
||||
# and any embedded shellness will be escaped.
|
||||
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
|
||||
# treated as '${Hostname}' itself on the command line.
|
||||
|
||||
set -- \
|
||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||
-classpath "$CLASSPATH" \
|
||||
org.gradle.wrapper.GradleWrapperMain \
|
||||
"$@"
|
||||
|
||||
# Stop when "xargs" is not available.
|
||||
if ! command -v xargs >/dev/null 2>&1
|
||||
then
|
||||
die "xargs is not available"
|
||||
fi
|
||||
|
||||
# Use "xargs" to parse quoted args.
|
||||
#
|
||||
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
||||
#
|
||||
# In Bash we could simply go:
|
||||
#
|
||||
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
|
||||
# set -- "${ARGS[@]}" "$@"
|
||||
#
|
||||
# but POSIX shell has neither arrays nor command substitution, so instead we
|
||||
# post-process each arg (as a line of input to sed) to backslash-escape any
|
||||
# character that might be a shell metacharacter, then use eval to reverse
|
||||
# that process (while maintaining the separation between arguments), and wrap
|
||||
# the whole thing up as a single "set" statement.
|
||||
#
|
||||
# This will of course break if any of these variables contains a newline or
|
||||
# an unmatched quote.
|
||||
#
|
||||
|
||||
eval "set -- $(
|
||||
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
||||
xargs -n1 |
|
||||
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
|
||||
tr '\n' ' '
|
||||
)" '"$@"'
|
||||
|
||||
exec "$JAVACMD" "$@"
|
||||
|
||||
100
android/gradlew.bat
vendored
100
android/gradlew.bat
vendored
@@ -1,100 +0,0 @@
|
||||
@rem
|
||||
@rem Copyright 2015 the original author or authors.
|
||||
@rem
|
||||
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||
@rem you may not use this file except in compliance with the License.
|
||||
@rem You may obtain a copy of the License at
|
||||
@rem
|
||||
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||
@rem
|
||||
@rem Unless required by applicable law or agreed to in writing, software
|
||||
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
@rem See the License for the specific language governing permissions and
|
||||
@rem limitations under the License.
|
||||
@rem
|
||||
|
||||
@if "%DEBUG%" == "" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem Gradle startup script for Windows
|
||||
@rem
|
||||
@rem ##########################################################################
|
||||
|
||||
@rem Set local scope for the variables with windows NT shell
|
||||
if "%OS%"=="Windows_NT" setlocal
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%" == "" set DIRNAME=.
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if "%ERRORLEVEL%" == "0" goto init
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto init
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:init
|
||||
@rem Get command-line arguments, handling Windows variants
|
||||
|
||||
if not "%OS%" == "Windows_NT" goto win9xME_args
|
||||
|
||||
:win9xME_args
|
||||
@rem Slurp the command line arguments.
|
||||
set CMD_LINE_ARGS=
|
||||
set _SKIP=2
|
||||
|
||||
:win9xME_args_slurp
|
||||
if "x%~1" == "x" goto execute
|
||||
|
||||
set CMD_LINE_ARGS=%*
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
if "%ERRORLEVEL%"=="0" goto mainEnd
|
||||
|
||||
:fail
|
||||
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||
rem the _cmd.exe /c_ return code!
|
||||
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
|
||||
exit /b 1
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
||||
:omega
|
||||
@@ -2,17 +2,16 @@ apply plugin: 'com.android.library'
|
||||
apply plugin: 'de.undercouch.download'
|
||||
|
||||
android {
|
||||
compileSdkVersion 33
|
||||
buildToolsVersion '33.0.2'
|
||||
ndkVersion "$ndk_version"
|
||||
defaultConfig {
|
||||
minSdkVersion 21
|
||||
targetSdkVersion 33
|
||||
compileSdk 34
|
||||
targetSdkVersion 34
|
||||
externalNativeBuild {
|
||||
cmake {
|
||||
cmake {
|
||||
arguments "-DANDROID_STL=c++_shared",
|
||||
"-DENABLE_CURL=1", "-DENABLE_SOUND=1",
|
||||
"-DENABLE_TOUCH=1", "-DENABLE_GETTEXT=1",
|
||||
"-DENABLE_GETTEXT=1",
|
||||
"-DBUILD_UNITTESTS=0", "-DENABLE_UPDATE_CHECKER=0"
|
||||
}
|
||||
}
|
||||
@@ -36,26 +35,33 @@ android {
|
||||
buildTypes {
|
||||
release {
|
||||
ndk {
|
||||
debugSymbolLevel 'SYMBOL_TABLE'
|
||||
debugSymbolLevel 'FULL'
|
||||
}
|
||||
}
|
||||
}
|
||||
namespace 'net.minetest'
|
||||
}
|
||||
|
||||
// get precompiled deps
|
||||
task downloadDeps(type: Download) {
|
||||
def depsDir = new File(buildDir.parent, 'deps')
|
||||
def depsZip = new File(buildDir, 'deps.zip')
|
||||
def depsDir = new File(buildDir.parent, 'deps')
|
||||
if (new File(depsDir, 'armeabi-v7a').exists()) {
|
||||
task getDeps {
|
||||
doLast { logger.lifecycle('Using existing deps from {}', depsDir) }
|
||||
}
|
||||
} else {
|
||||
task downloadDeps(type: Download) {
|
||||
def depsZip = new File(buildDir, 'deps.zip')
|
||||
|
||||
src 'https://github.com/minetest/minetest_android_deps/releases/download/latest/deps.zip'
|
||||
dest depsZip
|
||||
overwrite false
|
||||
src 'https://github.com/minetest/minetest_android_deps/releases/download/latest/deps-lite.zip'
|
||||
dest depsZip
|
||||
overwrite false
|
||||
|
||||
task getDeps(dependsOn: downloadDeps, type: Copy) {
|
||||
depsDir.mkdir()
|
||||
from zipTree(depsZip)
|
||||
into depsDir
|
||||
doFirst { logger.lifecycle('Extracting to {}', depsDir) }
|
||||
task getDeps(dependsOn: downloadDeps, type: Copy) {
|
||||
depsDir.mkdir()
|
||||
from zipTree(depsZip)
|
||||
into depsDir
|
||||
doFirst { logger.lifecycle('Extracting to {}', depsDir) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1 +1 @@
|
||||
<manifest package="net.minetest" />
|
||||
<manifest />
|
||||
|
||||
@@ -7,6 +7,7 @@ dofile(clientpath .. "register.lua")
|
||||
dofile(commonpath .. "after.lua")
|
||||
dofile(commonpath .. "mod_storage.lua")
|
||||
dofile(commonpath .. "chatcommands.lua")
|
||||
dofile(commonpath .. "information_formspecs.lua")
|
||||
dofile(clientpath .. "chatcommands.lua")
|
||||
dofile(clientpath .. "death_formspec.lua")
|
||||
dofile(clientpath .. "misc.lua")
|
||||
|
||||
@@ -1,4 +1,116 @@
|
||||
local jobs = {}
|
||||
-- This is an implementation of a job sheduling mechanism. It guarantees that
|
||||
-- coexisting jobs will execute primarily in order of least expiry, and
|
||||
-- secondarily in order of first registration.
|
||||
|
||||
-- These functions implement an intrusive singly linked list of one or more
|
||||
-- elements where the first element has a pointer to the last. The next pointer
|
||||
-- is stored with key list_next. The pointer to the last is with key list_end.
|
||||
|
||||
local function list_init(first)
|
||||
first.list_end = first
|
||||
end
|
||||
|
||||
local function list_append(first, append)
|
||||
first.list_end.list_next = append
|
||||
first.list_end = append
|
||||
end
|
||||
|
||||
local function list_append_list(first, first_append)
|
||||
first.list_end.list_next = first_append
|
||||
first.list_end = first_append.list_end
|
||||
end
|
||||
|
||||
-- The jobs are stored in a map from expiration times to linked lists of jobs
|
||||
-- as above. The expiration times are also stored in an array representing a
|
||||
-- binary min heap, which is a particular arrangement of binary tree. A parent
|
||||
-- at index i has children at indices i*2 and i*2+1. Out-of-bounds indices
|
||||
-- represent nonexistent children. A parent is never greater than its children.
|
||||
-- This structure means that, if there is at least one job, the next expiration
|
||||
-- time is the first item in the array.
|
||||
|
||||
-- Push element on a binary min-heap,
|
||||
-- "bubbling up" the element by swapping with larger parents.
|
||||
local function heap_push(heap, element)
|
||||
local index = #heap + 1
|
||||
while index > 1 do
|
||||
local parent_index = math.floor(index / 2)
|
||||
local parent = heap[parent_index]
|
||||
if element < parent then
|
||||
heap[index] = parent
|
||||
index = parent_index
|
||||
else
|
||||
break
|
||||
end
|
||||
end
|
||||
heap[index] = element
|
||||
end
|
||||
|
||||
-- Pop smallest element from the heap,
|
||||
-- "sinking down" the last leaf on the last layer of the heap
|
||||
-- by swapping with the smaller child.
|
||||
local function heap_pop(heap)
|
||||
local removed_element = heap[1]
|
||||
local length = #heap
|
||||
local element = heap[length]
|
||||
heap[length] = nil
|
||||
length = length - 1
|
||||
if length > 0 then
|
||||
local index = 1
|
||||
while true do
|
||||
local old_index = index
|
||||
local smaller_element = element
|
||||
local left_index = index * 2
|
||||
local right_index = index * 2 + 1
|
||||
if left_index <= length then
|
||||
local left_element = heap[left_index]
|
||||
if left_element < smaller_element then
|
||||
index = left_index
|
||||
smaller_element = left_element
|
||||
end
|
||||
end
|
||||
if right_index <= length then
|
||||
if heap[right_index] < smaller_element then
|
||||
index = right_index
|
||||
end
|
||||
end
|
||||
if old_index ~= index then
|
||||
heap[old_index] = heap[index]
|
||||
else
|
||||
break
|
||||
end
|
||||
end
|
||||
heap[index] = element
|
||||
end
|
||||
return removed_element
|
||||
end
|
||||
|
||||
local job_map = {}
|
||||
local expiries = {}
|
||||
|
||||
-- Adds an individual job with the given expiry.
|
||||
-- The worst-case complexity is O(log n), where n is the number of distinct
|
||||
-- expiration times.
|
||||
local function add_job(expiry, job)
|
||||
local list = job_map[expiry]
|
||||
if list then
|
||||
list_append(list, job)
|
||||
else
|
||||
list_init(job)
|
||||
job_map[expiry] = job
|
||||
heap_push(expiries, expiry)
|
||||
end
|
||||
end
|
||||
|
||||
-- Removes the next expiring jobs and returns the linked list of them.
|
||||
-- The worst-case complexity is O(log n), where n is the number of distinct
|
||||
-- expiration times.
|
||||
local function remove_first_jobs()
|
||||
local removed_expiry = heap_pop(expiries)
|
||||
local removed = job_map[removed_expiry]
|
||||
job_map[removed_expiry] = nil
|
||||
return removed
|
||||
end
|
||||
|
||||
local time = 0.0
|
||||
local time_next = math.huge
|
||||
|
||||
@@ -9,42 +121,54 @@ core.register_globalstep(function(dtime)
|
||||
return
|
||||
end
|
||||
|
||||
time_next = math.huge
|
||||
-- Remove the expired jobs.
|
||||
local expired = remove_first_jobs()
|
||||
|
||||
-- Iterate backwards so that we miss any new timers added by
|
||||
-- a timer callback.
|
||||
for i = #jobs, 1, -1 do
|
||||
local job = jobs[i]
|
||||
if time >= job.expire then
|
||||
core.set_last_run_mod(job.mod_origin)
|
||||
job.func(unpack(job.arg))
|
||||
local jobs_l = #jobs
|
||||
jobs[i] = jobs[jobs_l]
|
||||
jobs[jobs_l] = nil
|
||||
elseif job.expire < time_next then
|
||||
time_next = job.expire
|
||||
-- Remove other expired jobs and append them to the list.
|
||||
while true do
|
||||
time_next = expiries[1] or math.huge
|
||||
if time_next > time then
|
||||
break
|
||||
end
|
||||
list_append_list(expired, remove_first_jobs())
|
||||
end
|
||||
|
||||
-- Run the callbacks afterward to prevent infinite loops with core.after(0, ...).
|
||||
local last_expired = expired.list_end
|
||||
while true do
|
||||
core.set_last_run_mod(expired.mod_origin)
|
||||
expired.func(unpack(expired.args, 1, expired.args.n))
|
||||
if expired == last_expired then
|
||||
break
|
||||
end
|
||||
expired = expired.list_next
|
||||
end
|
||||
end)
|
||||
|
||||
function core.after(after, func, ...)
|
||||
assert(tonumber(after) and type(func) == "function",
|
||||
"Invalid minetest.after invocation")
|
||||
local expire = time + after
|
||||
local new_job = {
|
||||
func = func,
|
||||
expire = expire,
|
||||
arg = {...},
|
||||
mod_origin = core.get_last_run_mod(),
|
||||
}
|
||||
local job_metatable = {__index = {}}
|
||||
|
||||
jobs[#jobs + 1] = new_job
|
||||
time_next = math.min(time_next, expire)
|
||||
|
||||
return {
|
||||
cancel = function()
|
||||
new_job.func = function() end
|
||||
new_job.args = {}
|
||||
end
|
||||
}
|
||||
local function dummy_func() end
|
||||
function job_metatable.__index:cancel()
|
||||
self.func = dummy_func
|
||||
self.args = {n = 0}
|
||||
end
|
||||
|
||||
function core.after(after, func, ...)
|
||||
assert(tonumber(after) and not core.is_nan(after) and type(func) == "function",
|
||||
"Invalid minetest.after invocation")
|
||||
|
||||
local new_job = {
|
||||
mod_origin = core.get_last_run_mod(),
|
||||
func = func,
|
||||
args = {
|
||||
n = select("#", ...),
|
||||
...
|
||||
},
|
||||
}
|
||||
|
||||
local expiry = time + after
|
||||
add_job(expiry, new_job)
|
||||
time_next = math.min(time_next, expiry)
|
||||
|
||||
return setmetatable(new_job, job_metatable)
|
||||
end
|
||||
|
||||
@@ -89,7 +89,7 @@ local function do_help_cmd(name, param)
|
||||
if #args > 1 then
|
||||
return false, S("Too many arguments, try using just /help <command>")
|
||||
end
|
||||
local use_gui = INIT ~= "client" and core.get_player_by_name(name)
|
||||
local use_gui = INIT == "client" or core.get_player_by_name(name)
|
||||
use_gui = use_gui and not opts:find("t")
|
||||
|
||||
if #args == 0 and not use_gui then
|
||||
@@ -163,8 +163,8 @@ end
|
||||
|
||||
if INIT == "client" then
|
||||
core.register_chatcommand("help", {
|
||||
params = core.gettext("[all | <cmd>]"),
|
||||
description = core.gettext("Get help for commands"),
|
||||
params = core.gettext("[all | <cmd>] [-t]"),
|
||||
description = core.gettext("Get help for commands (-t: output in chat)"),
|
||||
func = function(param)
|
||||
return do_help_cmd(nil, param)
|
||||
end,
|
||||
|
||||
@@ -61,15 +61,20 @@ local function build_chatcommands_formspec(name, sel, copy)
|
||||
for i, data in ipairs(mod_cmds) do
|
||||
rows[#rows + 1] = COLOR_BLUE .. ",0," .. F(data[1]) .. ","
|
||||
for j, cmds in ipairs(data[2]) do
|
||||
local has_priv = check_player_privs(name, cmds[2].privs)
|
||||
local has_priv = INIT == "client" or check_player_privs(name, cmds[2].privs)
|
||||
rows[#rows + 1] = ("%s,1,%s,%s"):format(
|
||||
has_priv and COLOR_GREEN or COLOR_GRAY,
|
||||
cmds[1], F(cmds[2].params))
|
||||
if sel == #rows then
|
||||
description = cmds[2].description
|
||||
if copy then
|
||||
core.chat_send_player(name, S("Command: @1 @2",
|
||||
core.colorize("#0FF", "/" .. cmds[1]), cmds[2].params))
|
||||
local msg = S("Command: @1 @2",
|
||||
core.colorize("#0FF", "/" .. cmds[1]), cmds[2].params)
|
||||
if INIT == "client" then
|
||||
core.display_chat_message(msg)
|
||||
else
|
||||
core.chat_send_player(name, msg)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -111,26 +116,46 @@ end
|
||||
|
||||
|
||||
-- DETAILED CHAT COMMAND INFORMATION
|
||||
if INIT == "client" then
|
||||
core.register_on_formspec_input(function(formname, fields)
|
||||
if formname ~= "__builtin:help_cmds" or fields.quit then
|
||||
return
|
||||
end
|
||||
|
||||
core.register_on_player_receive_fields(function(player, formname, fields)
|
||||
if formname ~= "__builtin:help_cmds" or fields.quit then
|
||||
return
|
||||
end
|
||||
local event = core.explode_table_event(fields.list)
|
||||
if event.type ~= "INV" then
|
||||
core.show_formspec("__builtin:help_cmds",
|
||||
build_chatcommands_formspec(nil, event.row, event.type == "DCL"))
|
||||
end
|
||||
end)
|
||||
else
|
||||
core.register_on_player_receive_fields(function(player, formname, fields)
|
||||
if formname ~= "__builtin:help_cmds" or fields.quit then
|
||||
return
|
||||
end
|
||||
|
||||
local event = core.explode_table_event(fields.list)
|
||||
if event.type ~= "INV" then
|
||||
local name = player:get_player_name()
|
||||
core.show_formspec(name, "__builtin:help_cmds",
|
||||
build_chatcommands_formspec(name, event.row, event.type == "DCL"))
|
||||
end
|
||||
end)
|
||||
local event = core.explode_table_event(fields.list)
|
||||
if event.type ~= "INV" then
|
||||
local name = player:get_player_name()
|
||||
core.show_formspec(name, "__builtin:help_cmds",
|
||||
build_chatcommands_formspec(name, event.row, event.type == "DCL"))
|
||||
end
|
||||
end)
|
||||
end
|
||||
|
||||
function core.show_general_help_formspec(name)
|
||||
core.show_formspec(name, "__builtin:help_cmds",
|
||||
build_chatcommands_formspec(name))
|
||||
if INIT == "client" then
|
||||
core.show_formspec("__builtin:help_cmds",
|
||||
build_chatcommands_formspec(name))
|
||||
else
|
||||
core.show_formspec(name, "__builtin:help_cmds",
|
||||
build_chatcommands_formspec(name))
|
||||
end
|
||||
end
|
||||
|
||||
function core.show_privs_help_formspec(name)
|
||||
core.show_formspec(name, "__builtin:help_privs",
|
||||
build_privs_formspec(name))
|
||||
if INIT ~= "client" then
|
||||
function core.show_privs_help_formspec(name)
|
||||
core.show_formspec(name, "__builtin:help_privs",
|
||||
build_privs_formspec(name))
|
||||
end
|
||||
end
|
||||
|
||||
@@ -144,6 +144,8 @@ local wallmounted_to_dir = {
|
||||
vector.new(-1, 0, 0),
|
||||
vector.new( 0, 0, 1),
|
||||
vector.new( 0, 0, -1),
|
||||
vector.new( 0, 1, 0),
|
||||
vector.new( 0, -1, 0),
|
||||
}
|
||||
function core.wallmounted_to_dir(wallmounted)
|
||||
return wallmounted_to_dir[wallmounted % 8]
|
||||
|
||||
19
builtin/common/metatable.lua
Normal file
19
builtin/common/metatable.lua
Normal file
@@ -0,0 +1,19 @@
|
||||
-- Registered metatables, used by the C++ packer
|
||||
local known_metatables = {}
|
||||
function core.register_portable_metatable(name, mt)
|
||||
assert(type(name) == "string", ("attempt to use %s value as metatable name"):format(type(name)))
|
||||
assert(type(mt) == "table", ("attempt to register a %s value as metatable"):format(type(mt)))
|
||||
assert(known_metatables[name] == nil or known_metatables[name] == mt,
|
||||
("attempt to override metatable %s"):format(name))
|
||||
known_metatables[name] = mt
|
||||
known_metatables[mt] = name
|
||||
end
|
||||
core.known_metatables = known_metatables
|
||||
|
||||
function core.register_async_metatable(...)
|
||||
core.log("deprecated", "minetest.register_async_metatable is deprecated. " ..
|
||||
"Use minetest.register_portable_metatable instead.")
|
||||
return core.register_portable_metatable(...)
|
||||
end
|
||||
|
||||
core.register_portable_metatable("__builtin:vector", vector.metatable)
|
||||
@@ -240,12 +240,15 @@ function math.factorial(x)
|
||||
return v
|
||||
end
|
||||
|
||||
|
||||
function math.round(x)
|
||||
if x >= 0 then
|
||||
return math.floor(x + 0.5)
|
||||
if x < 0 then
|
||||
local int = math.ceil(x)
|
||||
local frac = x - int
|
||||
return int - ((frac <= -0.5) and 1 or 0)
|
||||
end
|
||||
return math.ceil(x - 0.5)
|
||||
local int = math.floor(x)
|
||||
local frac = x - int
|
||||
return int + ((frac >= 0.5) and 1 or 0)
|
||||
end
|
||||
|
||||
local formspec_escapes = {
|
||||
@@ -490,6 +493,9 @@ end
|
||||
|
||||
|
||||
function table.insert_all(t, other)
|
||||
if table.move then -- LuaJIT
|
||||
return table.move(other, 1, #other, #t + 1, t)
|
||||
end
|
||||
for i=1, #other do
|
||||
t[#t + 1] = other[i]
|
||||
end
|
||||
|
||||
113
builtin/common/tests/after_spec.lua
Normal file
113
builtin/common/tests/after_spec.lua
Normal file
@@ -0,0 +1,113 @@
|
||||
_G.core = {}
|
||||
_G.vector = {metatable = {}}
|
||||
|
||||
dofile("builtin/common/vector.lua")
|
||||
dofile("builtin/common/misc_helpers.lua")
|
||||
|
||||
function core.get_last_run_mod() return "*test*" end
|
||||
function core.set_last_run_mod() end
|
||||
|
||||
local do_step
|
||||
function core.register_globalstep(func)
|
||||
do_step = func
|
||||
end
|
||||
|
||||
dofile("builtin/common/after.lua")
|
||||
|
||||
describe("after", function()
|
||||
it("executes callbacks when expected", function()
|
||||
local result = ""
|
||||
core.after(0, function()
|
||||
result = result .. "a"
|
||||
end)
|
||||
core.after(1, function()
|
||||
result = result .. "b"
|
||||
end)
|
||||
core.after(1, function()
|
||||
result = result .. "c"
|
||||
end)
|
||||
core.after(2, function()
|
||||
result = result .. "d"
|
||||
end)
|
||||
local cancel = core.after(2, function()
|
||||
result = result .. "e"
|
||||
end)
|
||||
do_step(0)
|
||||
assert.same("a", result)
|
||||
|
||||
do_step(1)
|
||||
assert.same("abc", result)
|
||||
|
||||
core.after(2, function()
|
||||
result = result .. "f"
|
||||
end)
|
||||
core.after(1, function()
|
||||
result = result .. "g"
|
||||
end)
|
||||
core.after(-1, function()
|
||||
result = result .. "h"
|
||||
end)
|
||||
cancel:cancel()
|
||||
do_step(1)
|
||||
assert.same("abchdg", result)
|
||||
|
||||
do_step(1)
|
||||
assert.same("abchdgf", result)
|
||||
end)
|
||||
|
||||
it("defers jobs with delay 0", function()
|
||||
local result = ""
|
||||
core.after(0, function()
|
||||
core.after(0, function()
|
||||
result = result .. "b"
|
||||
end)
|
||||
result = result .. "a"
|
||||
end)
|
||||
do_step(1)
|
||||
assert.same("a", result)
|
||||
do_step(1)
|
||||
assert.same("ab", result)
|
||||
end)
|
||||
|
||||
it("passes arguments", function()
|
||||
core.after(0, function(...)
|
||||
assert.same(0, select("#", ...))
|
||||
end)
|
||||
core.after(0, function(...)
|
||||
assert.same(4, select("#", ...))
|
||||
assert.same(1, (select(1, ...)))
|
||||
assert.same(nil, (select(2, ...)))
|
||||
assert.same("a", (select(3, ...)))
|
||||
assert.same(nil, (select(4, ...)))
|
||||
end, 1, nil, "a", nil)
|
||||
do_step(0)
|
||||
end)
|
||||
|
||||
it("rejects invalid arguments", function()
|
||||
assert.has.errors(function() core.after() end)
|
||||
assert.has.errors(function() core.after(nil, nil) end)
|
||||
assert.has.errors(function() core.after(0) end)
|
||||
assert.has.errors(function() core.after(0, nil) end)
|
||||
assert.has.errors(function() core.after(nil, function() end) end)
|
||||
assert.has.errors(function() core.after(0 / 0, function() end) end)
|
||||
end)
|
||||
|
||||
-- Make sure that the underlying heap is working correctly
|
||||
it("can be abused as a heapsort", function()
|
||||
local t = {}
|
||||
for i = 1, 1000 do
|
||||
t[i] = math.random(100)
|
||||
end
|
||||
local sorted = table.copy(t)
|
||||
table.sort(sorted)
|
||||
local i = 0
|
||||
for _, v in ipairs(t) do
|
||||
core.after(v, function()
|
||||
i = i + 1
|
||||
assert.equal(v, sorted[i])
|
||||
end)
|
||||
end
|
||||
do_step(math.max(unpack(t)))
|
||||
assert.equal(#t, i)
|
||||
end)
|
||||
end)
|
||||
@@ -176,3 +176,17 @@ describe("formspec_escape", function()
|
||||
assert.equal("\\[Hello\\\\\\[", core.formspec_escape("[Hello\\["))
|
||||
end)
|
||||
end)
|
||||
|
||||
describe("math", function()
|
||||
it("round()", function()
|
||||
assert.equal(0, math.round(0))
|
||||
assert.equal(10, math.round(10.3))
|
||||
assert.equal(11, math.round(10.5))
|
||||
assert.equal(11, math.round(10.7))
|
||||
assert.equal(-10, math.round(-10.3))
|
||||
assert.equal(-11, math.round(-10.5))
|
||||
assert.equal(-11, math.round(-10.7))
|
||||
assert.equal(0, math.round(0.49999999999999994))
|
||||
assert.equal(0, math.round(-0.49999999999999994))
|
||||
end)
|
||||
end)
|
||||
|
||||
56
builtin/emerge/env.lua
Normal file
56
builtin/emerge/env.lua
Normal file
@@ -0,0 +1,56 @@
|
||||
-- Reimplementations of some environment function on vmanips, since this is
|
||||
-- what the emerge environment operates on
|
||||
|
||||
-- core.vmanip = <VoxelManip> -- set by C++
|
||||
|
||||
function core.set_node(pos, node)
|
||||
return core.vmanip:set_node_at(pos, node)
|
||||
end
|
||||
|
||||
function core.bulk_set_node(pos_list, node)
|
||||
local vm = core.vmanip
|
||||
local set_node_at = vm.set_node_at
|
||||
for _, pos in ipairs(pos_list) do
|
||||
if not set_node_at(vm, pos, node) then
|
||||
return false
|
||||
end
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
core.add_node = core.set_node
|
||||
|
||||
-- we don't deal with metadata currently
|
||||
core.swap_node = core.set_node
|
||||
|
||||
function core.remove_node(pos)
|
||||
return core.vmanip:set_node_at(pos, {name="air"})
|
||||
end
|
||||
|
||||
function core.get_node(pos)
|
||||
return core.vmanip:get_node_at(pos)
|
||||
end
|
||||
|
||||
function core.get_perlin(seed, octaves, persist, spread)
|
||||
local params
|
||||
if type(seed) == "table" then
|
||||
params = table.copy(seed)
|
||||
else
|
||||
assert(type(seed) == "number")
|
||||
params = {
|
||||
seed = seed,
|
||||
octaves = octaves,
|
||||
persist = persist,
|
||||
spread = {x=spread, y=spread, z=spread},
|
||||
}
|
||||
end
|
||||
params.seed = core.get_seed(params.seed) -- add mapgen seed
|
||||
return PerlinNoise(params)
|
||||
end
|
||||
|
||||
|
||||
function core.get_perlin_map(params, size)
|
||||
local params2 = table.copy(params)
|
||||
params2.seed = core.get_seed(params.seed) -- add mapgen seed
|
||||
return PerlinNoiseMap(params2, size)
|
||||
end
|
||||
21
builtin/emerge/init.lua
Normal file
21
builtin/emerge/init.lua
Normal file
@@ -0,0 +1,21 @@
|
||||
local gamepath = core.get_builtin_path() .. "game" .. DIR_DELIM
|
||||
local commonpath = core.get_builtin_path() .. "common" .. DIR_DELIM
|
||||
local epath = core.get_builtin_path() .. "emerge" .. DIR_DELIM
|
||||
|
||||
local builtin_shared = {}
|
||||
|
||||
-- Import parts shared with "game" environment
|
||||
dofile(gamepath .. "constants.lua")
|
||||
assert(loadfile(commonpath .. "item_s.lua"))(builtin_shared)
|
||||
dofile(gamepath .. "misc_s.lua")
|
||||
dofile(gamepath .. "features.lua")
|
||||
dofile(gamepath .. "voxelarea.lua")
|
||||
|
||||
-- Now for our own stuff
|
||||
assert(loadfile(commonpath .. "register.lua"))(builtin_shared)
|
||||
assert(loadfile(epath .. "register.lua"))(builtin_shared)
|
||||
dofile(epath .. "env.lua")
|
||||
|
||||
builtin_shared.cache_content_ids()
|
||||
|
||||
core.log("info", "Initialized emerge Lua environment")
|
||||
54
builtin/emerge/register.lua
Normal file
54
builtin/emerge/register.lua
Normal file
@@ -0,0 +1,54 @@
|
||||
local builtin_shared = ...
|
||||
|
||||
-- Copy all the registration tables over
|
||||
do
|
||||
local all = assert(core.transferred_globals)
|
||||
core.transferred_globals = nil
|
||||
|
||||
all.registered_nodes = {}
|
||||
all.registered_craftitems = {}
|
||||
all.registered_tools = {}
|
||||
for k, v in pairs(all.registered_items) do
|
||||
-- Disable further modification
|
||||
setmetatable(v, {__newindex = {}})
|
||||
-- Reassemble the other tables
|
||||
if v.type == "node" then
|
||||
getmetatable(v).__index = all.nodedef_default
|
||||
all.registered_nodes[k] = v
|
||||
elseif v.type == "craft" then
|
||||
getmetatable(v).__index = all.craftitemdef_default
|
||||
all.registered_craftitems[k] = v
|
||||
elseif v.type == "tool" then
|
||||
getmetatable(v).__index = all.tooldef_default
|
||||
all.registered_tools[k] = v
|
||||
else
|
||||
getmetatable(v).__index = all.noneitemdef_default
|
||||
end
|
||||
end
|
||||
|
||||
for k, v in pairs(all) do
|
||||
core[k] = v
|
||||
end
|
||||
end
|
||||
|
||||
-- For tables that are indexed by item name:
|
||||
-- If table[X] does not exist, default to table[core.registered_aliases[X]]
|
||||
local alias_metatable = {
|
||||
__index = function(t, name)
|
||||
return rawget(t, core.registered_aliases[name])
|
||||
end
|
||||
}
|
||||
setmetatable(core.registered_items, alias_metatable)
|
||||
setmetatable(core.registered_nodes, alias_metatable)
|
||||
setmetatable(core.registered_craftitems, alias_metatable)
|
||||
setmetatable(core.registered_tools, alias_metatable)
|
||||
|
||||
--
|
||||
-- Callbacks
|
||||
--
|
||||
|
||||
local make_registration = builtin_shared.make_registration
|
||||
|
||||
core.registered_on_mods_loaded, core.register_on_mods_loaded = make_registration()
|
||||
core.registered_on_generateds, core.register_on_generated = make_registration()
|
||||
core.registered_on_shutdown, core.register_on_shutdown = make_registration()
|
||||
@@ -18,7 +18,9 @@
|
||||
|
||||
|
||||
local BASE_SPACING = 0.1
|
||||
local SCROLL_BTN_WIDTH = TOUCHSCREEN_GUI and 0.8 or 0.5
|
||||
local function get_scroll_btn_width()
|
||||
return core.settings:get_bool("enable_touch") and 0.8 or 0.5
|
||||
end
|
||||
|
||||
local function buttonbar_formspec(self)
|
||||
if self.hidden then
|
||||
@@ -39,7 +41,7 @@ local function buttonbar_formspec(self)
|
||||
|
||||
-- The number of buttons per page is always calculated as if the scroll
|
||||
-- buttons were visible.
|
||||
local avail_space = self.size.x - 2*BASE_SPACING - 2*SCROLL_BTN_WIDTH
|
||||
local avail_space = self.size.x - 2*BASE_SPACING - 2*get_scroll_btn_width()
|
||||
local btns_per_page = math.floor((avail_space - BASE_SPACING) / (btn_size + BASE_SPACING))
|
||||
|
||||
self.num_pages = math.ceil(#self.buttons / btns_per_page)
|
||||
@@ -55,7 +57,7 @@ local function buttonbar_formspec(self)
|
||||
|
||||
local btn_start_x = self.pos.x + btn_spacing
|
||||
if show_scroll_btns then
|
||||
btn_start_x = btn_start_x + BASE_SPACING + SCROLL_BTN_WIDTH
|
||||
btn_start_x = btn_start_x + BASE_SPACING + get_scroll_btn_width()
|
||||
end
|
||||
|
||||
for i = first_btn, first_btn + btns_per_page - 1 do
|
||||
@@ -80,7 +82,7 @@ local function buttonbar_formspec(self)
|
||||
y = self.pos.y + BASE_SPACING,
|
||||
}
|
||||
local btn_next_pos = {
|
||||
x = self.pos.x + self.size.x - BASE_SPACING - SCROLL_BTN_WIDTH,
|
||||
x = self.pos.x + self.size.x - BASE_SPACING - get_scroll_btn_width(),
|
||||
y = self.pos.y + BASE_SPACING,
|
||||
}
|
||||
|
||||
@@ -88,11 +90,11 @@ local function buttonbar_formspec(self)
|
||||
self.btn_prev_name, self.btn_next_name))
|
||||
|
||||
table.insert(formspec, string.format("button[%f,%f;%f,%f;%s;<]",
|
||||
btn_prev_pos.x, btn_prev_pos.y, SCROLL_BTN_WIDTH, btn_size,
|
||||
btn_prev_pos.x, btn_prev_pos.y, get_scroll_btn_width(), btn_size,
|
||||
self.btn_prev_name))
|
||||
|
||||
table.insert(formspec, string.format("button[%f,%f;%f,%f;%s;>]",
|
||||
btn_next_pos.x, btn_next_pos.y, SCROLL_BTN_WIDTH, btn_size,
|
||||
btn_next_pos.x, btn_next_pos.y, get_scroll_btn_width(), btn_size,
|
||||
self.btn_next_name))
|
||||
end
|
||||
|
||||
@@ -100,14 +102,24 @@ local function buttonbar_formspec(self)
|
||||
end
|
||||
|
||||
local function buttonbar_buttonhandler(self, fields)
|
||||
if fields[self.btn_prev_name] and self.cur_page > 1 then
|
||||
self.cur_page = self.cur_page - 1
|
||||
return true
|
||||
if fields[self.btn_prev_name] then
|
||||
if self.cur_page > 1 then
|
||||
self.cur_page = self.cur_page - 1
|
||||
return true
|
||||
elseif self.cur_page == 1 then
|
||||
self.cur_page = self.num_pages
|
||||
return true
|
||||
end
|
||||
end
|
||||
|
||||
if fields[self.btn_next_name] and self.cur_page < self.num_pages then
|
||||
self.cur_page = self.cur_page + 1
|
||||
return true
|
||||
if fields[self.btn_next_name] then
|
||||
if self.cur_page < self.num_pages then
|
||||
self.cur_page = self.cur_page + 1
|
||||
return true
|
||||
elseif self.cur_page == self.num_pages then
|
||||
self.cur_page = 1
|
||||
return true
|
||||
end
|
||||
end
|
||||
|
||||
for _, btn in ipairs(self.buttons) do
|
||||
|
||||
@@ -78,15 +78,12 @@ function dialog_create(name,get_formspec,buttonhandler,eventhandler)
|
||||
return self
|
||||
end
|
||||
|
||||
-- "message" must already be formspec-escaped, e.g. via fgettext or
|
||||
-- core.formspec_escape.
|
||||
function messagebox(name, message)
|
||||
return dialog_create(name,
|
||||
function()
|
||||
return ([[
|
||||
formspec_version[3]
|
||||
size[8,3]
|
||||
textarea[0.375,0.375;7.25,1.2;;;%s]
|
||||
button[3,1.825;2,0.8;ok;%s]
|
||||
]]):format(message, fgettext("OK"))
|
||||
return ui.get_message_formspec("", message, "ok")
|
||||
end,
|
||||
function(this, fields)
|
||||
if fields.ok then
|
||||
|
||||
@@ -50,6 +50,20 @@ function ui.find_by_name(name)
|
||||
return ui.childlist[name]
|
||||
end
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
-- "title" and "message" must already be formspec-escaped, e.g. via fgettext or
|
||||
-- core.formspec_escape.
|
||||
function ui.get_message_formspec(title, message, btn_id)
|
||||
return table.concat({
|
||||
"size[14,8]",
|
||||
"real_coordinates[true]",
|
||||
"set_focus[", btn_id, ";true]",
|
||||
"box[0.5,1.2;13,5;#000]",
|
||||
("textarea[0.5,1.2;13,5;;%s;%s]"):format(title, message),
|
||||
"button[5,6.6;4,1;", btn_id, ";" .. fgettext("OK") .. "]",
|
||||
})
|
||||
end
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
--------------------------------------------------------------------------------
|
||||
-- Internal functions not to be called from user
|
||||
@@ -76,6 +90,9 @@ function ui.update()
|
||||
}
|
||||
ui.overridden = true
|
||||
elseif gamedata ~= nil and gamedata.errormessage ~= nil then
|
||||
-- Note to API users:
|
||||
-- "gamedata.errormessage" must not be formspec-escaped yet.
|
||||
-- For translations, fgettext_ne should be used.
|
||||
local error_message = core.formspec_escape(gamedata.errormessage)
|
||||
|
||||
local error_title
|
||||
@@ -84,15 +101,7 @@ function ui.update()
|
||||
else
|
||||
error_title = fgettext("An error occurred:")
|
||||
end
|
||||
formspec = {
|
||||
"size[14,8]",
|
||||
"real_coordinates[true]",
|
||||
"set_focus[btn_error_confirm;true]",
|
||||
"box[0.5,1.2;13,5;#000]",
|
||||
("textarea[0.5,1.2;13,5;;%s;%s]"):format(
|
||||
error_title, error_message),
|
||||
"button[5,6.6;4,1;btn_error_confirm;" .. fgettext("OK") .. "]"
|
||||
}
|
||||
formspec = {ui.get_message_formspec(error_title, error_message, "btn_error_confirm")}
|
||||
ui.overridden = true
|
||||
else
|
||||
local active_toplevel_ui_elements = 0
|
||||
|
||||
@@ -87,20 +87,29 @@ core.builtin_auth_handler = {
|
||||
core.settings:get("default_password")))
|
||||
end
|
||||
|
||||
local prev_privs = auth_entry.privileges
|
||||
auth_entry.privileges = privileges
|
||||
|
||||
core_auth.save(auth_entry)
|
||||
|
||||
-- Run grant callbacks
|
||||
for priv, _ in pairs(privileges) do
|
||||
if not auth_entry.privileges[priv] then
|
||||
for priv, value in pairs(privileges) do
|
||||
-- Warnings for improper API usage
|
||||
if value == false then
|
||||
core.log('deprecated', "`false` value given to `minetest.set_player_privs`, "..
|
||||
"this is almost certainly a bug, "..
|
||||
"granting a privilege rather than revoking it")
|
||||
elseif value ~= true then
|
||||
core.log('deprecated', "non-`true` value given to `minetest.set_player_privs`")
|
||||
end
|
||||
-- Run grant callbacks
|
||||
if prev_privs[priv] == nil then
|
||||
core.run_priv_callbacks(name, priv, nil, "grant")
|
||||
end
|
||||
end
|
||||
|
||||
-- Run revoke callbacks
|
||||
for priv, _ in pairs(auth_entry.privileges) do
|
||||
if not privileges[priv] then
|
||||
for priv, _ in pairs(prev_privs) do
|
||||
if privileges[priv] == nil then
|
||||
core.run_priv_callbacks(name, priv, nil, "revoke")
|
||||
end
|
||||
end
|
||||
@@ -179,6 +188,20 @@ core.set_player_privs = auth_pass("set_privileges")
|
||||
core.remove_player_auth = auth_pass("delete_auth")
|
||||
core.auth_reload = auth_pass("reload")
|
||||
|
||||
function core.change_player_privs(name, changes)
|
||||
local privs = core.get_player_privs(name)
|
||||
for priv, change in pairs(changes) do
|
||||
if change == true then
|
||||
privs[priv] = true
|
||||
elseif change == false then
|
||||
privs[priv] = nil
|
||||
else
|
||||
error("non-bool value given to `minetest.change_player_privs`")
|
||||
end
|
||||
end
|
||||
core.set_player_privs(name, privs)
|
||||
end
|
||||
|
||||
local record_login = auth_pass("record_login")
|
||||
core.register_on_joinplayer(function(player)
|
||||
record_login(player:get_player_name())
|
||||
|
||||
@@ -2,6 +2,9 @@
|
||||
|
||||
core.detached_inventories = {}
|
||||
|
||||
local create_detached_inventory_raw = core.create_detached_inventory_raw
|
||||
core.create_detached_inventory_raw = nil
|
||||
|
||||
function core.create_detached_inventory(name, callbacks, player_name)
|
||||
local stuff = {}
|
||||
stuff.name = name
|
||||
@@ -15,10 +18,13 @@ function core.create_detached_inventory(name, callbacks, player_name)
|
||||
end
|
||||
stuff.mod_origin = core.get_current_modname() or "??"
|
||||
core.detached_inventories[name] = stuff
|
||||
return core.create_detached_inventory_raw(name, player_name)
|
||||
return create_detached_inventory_raw(name, player_name)
|
||||
end
|
||||
|
||||
local remove_detached_inventory_raw = core.remove_detached_inventory_raw
|
||||
core.remove_detached_inventory_raw = nil
|
||||
|
||||
function core.remove_detached_inventory(name)
|
||||
core.detached_inventories[name] = nil
|
||||
return core.remove_detached_inventory_raw(name)
|
||||
return remove_detached_inventory_raw(name)
|
||||
end
|
||||
|
||||
@@ -79,6 +79,9 @@ core.register_entity(":__builtin:falling_node", {
|
||||
-- Cache whether we're supposed to float on water
|
||||
self.floats = core.get_item_group(node.name, "float") ~= 0
|
||||
|
||||
-- Save liquidtype for falling water
|
||||
self.liquidtype = def.liquidtype
|
||||
|
||||
-- Set entity visuals
|
||||
if def.drawtype == "torchlike" or def.drawtype == "signlike" then
|
||||
local textures
|
||||
@@ -150,7 +153,12 @@ core.register_entity(":__builtin:falling_node", {
|
||||
|
||||
-- Rotate entity
|
||||
if def.drawtype == "torchlike" then
|
||||
self.object:set_yaw(math.pi*0.25)
|
||||
if (def.paramtype2 == "wallmounted" or def.paramtype2 == "colorwallmounted")
|
||||
and node.param2 % 8 == 7 then
|
||||
self.object:set_yaw(-math.pi*0.25)
|
||||
else
|
||||
self.object:set_yaw(math.pi*0.25)
|
||||
end
|
||||
elseif ((node.param2 ~= 0 or def.drawtype == "nodebox" or def.drawtype == "mesh")
|
||||
and (def.wield_image == "" or def.wield_image == nil))
|
||||
or def.drawtype == "signlike"
|
||||
@@ -190,6 +198,10 @@ core.register_entity(":__builtin:falling_node", {
|
||||
pitch, yaw = 0, -math.pi/2
|
||||
elseif rot == 4 then
|
||||
pitch, yaw = 0, math.pi
|
||||
elseif rot == 6 then
|
||||
pitch, yaw = math.pi/2, 0
|
||||
elseif rot == 7 then
|
||||
pitch, yaw = -math.pi/2, math.pi
|
||||
end
|
||||
else
|
||||
if rot == 1 then
|
||||
@@ -202,6 +214,10 @@ core.register_entity(":__builtin:falling_node", {
|
||||
pitch, yaw = math.pi/2, math.pi
|
||||
elseif rot == 5 then
|
||||
pitch, yaw = math.pi/2, 0
|
||||
elseif rot == 6 then
|
||||
pitch, yaw = math.pi, -math.pi/2
|
||||
elseif rot == 7 then
|
||||
pitch, yaw = 0, -math.pi/2
|
||||
end
|
||||
end
|
||||
if def.drawtype == "signlike" then
|
||||
@@ -210,10 +226,20 @@ core.register_entity(":__builtin:falling_node", {
|
||||
yaw = yaw + math.pi/2
|
||||
elseif rot == 1 then
|
||||
yaw = yaw - math.pi/2
|
||||
elseif rot == 6 then
|
||||
yaw = yaw - math.pi/2
|
||||
pitch = pitch + math.pi
|
||||
elseif rot == 7 then
|
||||
yaw = yaw + math.pi/2
|
||||
pitch = pitch + math.pi
|
||||
end
|
||||
elseif def.drawtype == "mesh" or def.drawtype == "normal" or def.drawtype == "nodebox" then
|
||||
if rot >= 0 and rot <= 1 then
|
||||
if rot == 0 or rot == 1 then
|
||||
roll = roll + math.pi
|
||||
elseif rot == 6 or rot == 7 then
|
||||
if def.drawtype ~= "normal" then
|
||||
roll = roll - math.pi/2
|
||||
end
|
||||
else
|
||||
yaw = yaw + math.pi
|
||||
end
|
||||
@@ -271,9 +297,17 @@ core.register_entity(":__builtin:falling_node", {
|
||||
end
|
||||
|
||||
-- Decide if we're replacing the node or placing on top
|
||||
-- This condition is very similar to the check in core.check_single_for_falling(p)
|
||||
local np = vector.copy(bcp)
|
||||
if bcd and bcd.buildable_to and
|
||||
(not self.floats or bcd.liquidtype == "none") then
|
||||
if bcd and bcd.buildable_to
|
||||
and -- Take "float" group into consideration:
|
||||
(
|
||||
-- Fall through non-liquids
|
||||
not self.floats or bcd.liquidtype == "none" or
|
||||
-- Only let sources fall through flowing liquids
|
||||
(self.floats and self.liquidtype ~= "none" and bcd.liquidtype ~= "source")
|
||||
) then
|
||||
|
||||
core.remove_node(bcp)
|
||||
else
|
||||
np.y = np.y + 1
|
||||
@@ -284,7 +318,7 @@ core.register_entity(":__builtin:falling_node", {
|
||||
local nd = core.registered_nodes[n2.name]
|
||||
-- If it's not air or liquid, remove node and replace it with
|
||||
-- it's drops
|
||||
if n2.name ~= "air" and (not nd or nd.liquidtype == "none") then
|
||||
if n2.name ~= "air" and (not nd or nd.liquidtype ~= "source") then
|
||||
if nd and nd.buildable_to == false then
|
||||
nd.on_dig(np, n2, nil)
|
||||
-- If it's still there, it might be protected
|
||||
@@ -532,11 +566,19 @@ function core.check_single_for_falling(p)
|
||||
local success, _ = convert_to_falling_node(p, n)
|
||||
return success
|
||||
end
|
||||
local d_falling = core.registered_nodes[n.name]
|
||||
local do_float = core.get_item_group(n.name, "float") > 0
|
||||
-- Otherwise only if the bottom node is considered "fall through"
|
||||
if not same and
|
||||
(not d_bottom.walkable or d_bottom.buildable_to) and
|
||||
(core.get_item_group(n.name, "float") == 0 or
|
||||
d_bottom.liquidtype == "none") then
|
||||
(not d_bottom.walkable or d_bottom.buildable_to)
|
||||
and -- Take "float" group into consideration:
|
||||
(
|
||||
-- Fall through non-liquids
|
||||
not do_float or d_bottom.liquidtype == "none" or
|
||||
-- Only let sources fall through flowing liquids
|
||||
(do_float and d_falling.liquidtype == "source" and d_bottom.liquidtype ~= "source")
|
||||
) then
|
||||
|
||||
local success, _ = convert_to_falling_node(p, n)
|
||||
return success
|
||||
end
|
||||
|
||||
@@ -29,6 +29,19 @@ core.features = {
|
||||
compress_zstd = true,
|
||||
sound_params_start_time = true,
|
||||
physics_overrides_v2 = true,
|
||||
hud_def_type_field = true,
|
||||
random_state_restore = true,
|
||||
after_order_expiry_registration = true,
|
||||
wallmounted_rotate = true,
|
||||
item_specific_pointabilities = true,
|
||||
blocking_pointability_type = true,
|
||||
dynamic_add_media_startup = true,
|
||||
dynamic_add_media_filepath = true,
|
||||
lsystem_decoration_type = true,
|
||||
item_meta_range = true,
|
||||
node_interaction_actor = true,
|
||||
moveresult_new_pos = true,
|
||||
override_item_remove_fields = true,
|
||||
}
|
||||
|
||||
function core.has_feature(arg)
|
||||
|
||||
261
builtin/game/hud.lua
Normal file
261
builtin/game/hud.lua
Normal file
@@ -0,0 +1,261 @@
|
||||
--[[
|
||||
Register function to easily register new builtin hud elements
|
||||
`def` is a table and contains the following fields:
|
||||
elem_def the HUD element definition which can be changed with hud_replace_builtin
|
||||
events (optional) additional event names on which the element will be updated
|
||||
("hud_changed" will always be used.)
|
||||
show_elem(player, flags, id)
|
||||
(optional) a function to decide if the element should be shown to a player
|
||||
It is called before the element gets updated.
|
||||
update_def(player, elem_def)
|
||||
(optional) a function to change the elem_def before it will be used.
|
||||
(elem_def can be changed, since the table which got set by using
|
||||
hud_replace_builtin isn't exposed to the API.)
|
||||
update_elem(player, id)
|
||||
(optional) a function to change the element after it has been updated
|
||||
(Is not called when the element is first set or recreated.)
|
||||
]]--
|
||||
|
||||
local registered_elements = {}
|
||||
local update_events = {}
|
||||
local function register_builtin_hud_element(name, def)
|
||||
registered_elements[name] = def
|
||||
for _, event in ipairs(def.events or {}) do
|
||||
update_events[event] = update_events[event] or {}
|
||||
table.insert(update_events[event], name)
|
||||
end
|
||||
end
|
||||
|
||||
-- Stores HUD ids for all players
|
||||
local hud_ids = {}
|
||||
|
||||
-- Updates one element
|
||||
-- In case the element is already added, it only calls the update_elem function from
|
||||
-- registered_elements. (To recreate the element remove it first.)
|
||||
local function update_element(player, player_hud_ids, elem_name, flags)
|
||||
local def = registered_elements[elem_name]
|
||||
local id = player_hud_ids[elem_name]
|
||||
|
||||
if def.show_elem and not def.show_elem(player, flags, id) then
|
||||
if id then
|
||||
player:hud_remove(id)
|
||||
player_hud_ids[elem_name] = nil
|
||||
end
|
||||
return
|
||||
end
|
||||
|
||||
if not id then
|
||||
if def.update_def then
|
||||
def.update_def(player, def.elem_def)
|
||||
end
|
||||
|
||||
id = player:hud_add(def.elem_def)
|
||||
player_hud_ids[elem_name] = id
|
||||
return
|
||||
end
|
||||
|
||||
if def.update_elem then
|
||||
def.update_elem(player, id)
|
||||
end
|
||||
end
|
||||
|
||||
-- Updates all elements
|
||||
-- If to_update is specified it will only update those elements.
|
||||
local function update_hud(player, to_update)
|
||||
local flags = player:hud_get_flags()
|
||||
local playername = player:get_player_name()
|
||||
hud_ids[playername] = hud_ids[playername] or {}
|
||||
local player_hud_ids = hud_ids[playername]
|
||||
|
||||
if to_update then
|
||||
for _, elem_name in ipairs(to_update) do
|
||||
update_element(player, player_hud_ids, elem_name, flags)
|
||||
end
|
||||
else
|
||||
for elem_name, _ in pairs(registered_elements) do
|
||||
update_element(player, player_hud_ids, elem_name, flags)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local function player_event_handler(player, eventname)
|
||||
assert(player:is_player())
|
||||
|
||||
if eventname == "hud_changed" then
|
||||
update_hud(player)
|
||||
return
|
||||
end
|
||||
|
||||
-- Custom events
|
||||
local to_update = update_events[eventname]
|
||||
if to_update then
|
||||
update_hud(player, to_update)
|
||||
end
|
||||
end
|
||||
|
||||
-- Returns true if successful, otherwise false,
|
||||
-- but currently the return value is not documented in the Lua API.
|
||||
function core.hud_replace_builtin(elem_name, elem_def)
|
||||
assert(type(elem_def) == "table")
|
||||
|
||||
local registered = registered_elements[elem_name]
|
||||
if not registered then
|
||||
return false
|
||||
end
|
||||
|
||||
registered.elem_def = table.copy(elem_def)
|
||||
|
||||
for playername, player_hud_ids in pairs(hud_ids) do
|
||||
local player = core.get_player_by_name(playername)
|
||||
local id = player_hud_ids[elem_name]
|
||||
if player and id then
|
||||
player:hud_remove(id)
|
||||
player_hud_ids[elem_name] = nil
|
||||
update_element(player, player_hud_ids, elem_name, player:hud_get_flags())
|
||||
end
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
local function cleanup_builtin_hud(player)
|
||||
hud_ids[player:get_player_name()] = nil
|
||||
end
|
||||
|
||||
|
||||
-- Append "update_hud" as late as possible
|
||||
-- This ensures that the HUD is hidden when the flags are updated in this callback
|
||||
core.register_on_mods_loaded(function()
|
||||
core.register_on_joinplayer(function(player)
|
||||
update_hud(player)
|
||||
end)
|
||||
end)
|
||||
core.register_on_leaveplayer(cleanup_builtin_hud)
|
||||
core.register_playerevent(player_event_handler)
|
||||
|
||||
|
||||
---- Builtin HUD Elements
|
||||
|
||||
--- Healthbar
|
||||
|
||||
-- Cache setting
|
||||
local enable_damage = core.settings:get_bool("enable_damage")
|
||||
|
||||
local function scale_to_hud_max(player, field)
|
||||
-- Scale "hp" or "breath" to the hud maximum dimensions
|
||||
local current = player["get_" .. field](player)
|
||||
local nominal
|
||||
if field == "hp" then -- HUD is called health but field is hp
|
||||
nominal = registered_elements.health.elem_def.item
|
||||
else
|
||||
nominal = registered_elements[field].elem_def.item
|
||||
end
|
||||
local max_display = math.max(player:get_properties()[field .. "_max"], current)
|
||||
return math.ceil(current / max_display * nominal)
|
||||
end
|
||||
|
||||
register_builtin_hud_element("health", {
|
||||
elem_def = {
|
||||
type = "statbar",
|
||||
position = {x = 0.5, y = 1},
|
||||
text = "heart.png",
|
||||
text2 = "heart_gone.png",
|
||||
number = core.PLAYER_MAX_HP_DEFAULT,
|
||||
item = core.PLAYER_MAX_HP_DEFAULT,
|
||||
direction = 0,
|
||||
size = {x = 24, y = 24},
|
||||
offset = {x = (-10 * 24) - 25, y = -(48 + 24 + 16)},
|
||||
},
|
||||
events = {"properties_changed", "health_changed"},
|
||||
show_elem = function(player, flags)
|
||||
return flags.healthbar and enable_damage and
|
||||
player:get_armor_groups().immortal ~= 1
|
||||
end,
|
||||
update_def = function(player, elem_def)
|
||||
elem_def.item = elem_def.item or elem_def.number or core.PLAYER_MAX_HP_DEFAULT
|
||||
elem_def.number = scale_to_hud_max(player, "hp")
|
||||
end,
|
||||
update_elem = function(player, id)
|
||||
player:hud_change(id, "number", scale_to_hud_max(player, "hp"))
|
||||
end,
|
||||
})
|
||||
|
||||
--- Breathbar
|
||||
|
||||
-- Stores core.after calls for every player
|
||||
local breathbar_removal_jobs = {}
|
||||
|
||||
register_builtin_hud_element("breath", {
|
||||
elem_def = {
|
||||
type = "statbar",
|
||||
position = {x = 0.5, y = 1},
|
||||
text = "bubble.png",
|
||||
text2 = "bubble_gone.png",
|
||||
number = core.PLAYER_MAX_BREATH_DEFAULT * 2,
|
||||
item = core.PLAYER_MAX_BREATH_DEFAULT * 2,
|
||||
direction = 0,
|
||||
size = {x = 24, y = 24},
|
||||
offset = {x = 25, y= -(48 + 24 + 16)},
|
||||
},
|
||||
events = {"properties_changed", "breath_changed"},
|
||||
show_elem = function(player, flags, id)
|
||||
local show_breathbar = flags.breathbar and enable_damage and
|
||||
player:get_armor_groups().immortal ~= 1
|
||||
if id then
|
||||
-- The element will not prematurely be removed by update_element
|
||||
-- (but may still be instantly removed if the flag changed)
|
||||
return show_breathbar
|
||||
end
|
||||
-- Don't add the element if the breath is full
|
||||
local breath_relevant = player:get_breath() < player:get_properties().breath_max
|
||||
return show_breathbar and breath_relevant
|
||||
end,
|
||||
update_def = function(player, elem_def)
|
||||
elem_def.item = elem_def.item or elem_def.number or core.PLAYER_MAX_BREATH_DEFAULT
|
||||
elem_def.number = scale_to_hud_max(player, "breath")
|
||||
end,
|
||||
update_elem = function(player, id)
|
||||
player:hud_change(id, "number", scale_to_hud_max(player, "breath"))
|
||||
|
||||
local player_name = player:get_player_name()
|
||||
local breath_relevant = player:get_breath() < player:get_properties().breath_max
|
||||
|
||||
if not breath_relevant then
|
||||
if not breathbar_removal_jobs[player_name] then
|
||||
-- The breathbar stays for some time and then gets removed.
|
||||
breathbar_removal_jobs[player_name] = core.after(1, function()
|
||||
local player = core.get_player_by_name(player_name)
|
||||
local player_hud_ids = hud_ids[player_name]
|
||||
if player and player_hud_ids and player_hud_ids.breath then
|
||||
player:hud_remove(player_hud_ids.breath)
|
||||
player_hud_ids.breath = nil
|
||||
end
|
||||
breathbar_removal_jobs[player_name] = nil
|
||||
end)
|
||||
end
|
||||
else
|
||||
-- Cancel removal
|
||||
local job = breathbar_removal_jobs[player_name]
|
||||
if job then
|
||||
job:cancel()
|
||||
breathbar_removal_jobs[player_name] = nil
|
||||
end
|
||||
end
|
||||
end,
|
||||
})
|
||||
|
||||
--- Minimap
|
||||
|
||||
register_builtin_hud_element("minimap", {
|
||||
elem_def = {
|
||||
type = "minimap",
|
||||
position = {x = 1, y = 0},
|
||||
alignment = {x = -1, y = 1},
|
||||
offset = {x = -10, y = 10},
|
||||
size = {x = 256, y = 256},
|
||||
},
|
||||
show_elem = function(player, flags)
|
||||
-- Don't add a minimap for clients which already have it hardcoded in C++.
|
||||
return flags.minimap and
|
||||
core.get_player_information(player:get_player_name()).protocol_version >= 44
|
||||
end,
|
||||
})
|
||||
@@ -18,6 +18,7 @@ if core.settings:get_bool("profiler.load") then
|
||||
end
|
||||
|
||||
dofile(commonpath .. "after.lua")
|
||||
dofile(commonpath .. "metatable.lua")
|
||||
dofile(commonpath .. "mod_storage.lua")
|
||||
dofile(gamepath .. "item_entity.lua")
|
||||
dofile(gamepath .. "deprecated.lua")
|
||||
@@ -34,7 +35,7 @@ assert(loadfile(gamepath .. "falling.lua"))(builtin_shared)
|
||||
dofile(gamepath .. "features.lua")
|
||||
dofile(gamepath .. "voxelarea.lua")
|
||||
dofile(gamepath .. "forceloading.lua")
|
||||
dofile(gamepath .. "statbars.lua")
|
||||
dofile(gamepath .. "hud.lua")
|
||||
dofile(gamepath .. "knockback.lua")
|
||||
dofile(gamepath .. "async.lua")
|
||||
|
||||
|
||||
@@ -202,7 +202,40 @@ function core.item_place_node(itemstack, placer, pointed_thing, param2,
|
||||
elseif (def.paramtype2 == "wallmounted" or
|
||||
def.paramtype2 == "colorwallmounted") and not param2 then
|
||||
local dir = vector.subtract(under, above)
|
||||
-- If you change this code, also change src/client/game.cpp
|
||||
newnode.param2 = core.dir_to_wallmounted(dir)
|
||||
if def.wallmounted_rotate_vertical and
|
||||
(newnode.param2 == 0 or newnode.param2 == 1) then
|
||||
local placer_pos = placer and placer:get_pos()
|
||||
if placer_pos then
|
||||
local pdir = {
|
||||
x = above.x - placer_pos.x,
|
||||
y = dir.y,
|
||||
z = above.z - placer_pos.z
|
||||
}
|
||||
local rotate = false
|
||||
if def.drawtype == "torchlike" then
|
||||
if not ((pdir.x < 0 and pdir.z > 0) or
|
||||
(pdir.x > 0 and pdir.z < 0)) then
|
||||
rotate = true
|
||||
end
|
||||
if pdir.y > 0 then
|
||||
rotate = not rotate
|
||||
end
|
||||
elseif def.drawtype == "signlike" then
|
||||
if math.abs(pdir.x) < math.abs(pdir.z) then
|
||||
rotate = true
|
||||
end
|
||||
else
|
||||
if math.abs(pdir.x) > math.abs(pdir.z) then
|
||||
rotate = true
|
||||
end
|
||||
end
|
||||
if rotate then
|
||||
newnode.param2 = newnode.param2 + 6
|
||||
end
|
||||
end
|
||||
end
|
||||
-- Calculate the direction for furnaces and chests and stuff
|
||||
elseif (def.paramtype2 == "facedir" or
|
||||
def.paramtype2 == "colorfacedir" or
|
||||
@@ -703,3 +736,22 @@ core.noneitemdef_default = { -- This is used for the hand and unknown items
|
||||
on_drop = nil,
|
||||
on_use = nil,
|
||||
}
|
||||
|
||||
--
|
||||
-- get_node implementation
|
||||
--
|
||||
|
||||
local get_node_raw = core.get_node_raw
|
||||
core.get_node_raw = nil
|
||||
|
||||
function core.get_node(pos)
|
||||
local content, param1, param2 = get_node_raw(pos.x, pos.y, pos.z)
|
||||
return {name = core.get_name_from_content_id(content), param1 = param1, param2 = param2}
|
||||
end
|
||||
|
||||
function core.get_node_or_nil(pos)
|
||||
local content, param1, param2, pos_ok = get_node_raw(pos.x, pos.y, pos.z)
|
||||
return pos_ok and
|
||||
{name = core.get_name_from_content_id(content), param1 = param1, param2 = param2}
|
||||
or nil
|
||||
end
|
||||
|
||||
@@ -22,14 +22,16 @@ local function vector_absmax(v)
|
||||
return max(max(abs(v.x), abs(v.y)), abs(v.z))
|
||||
end
|
||||
|
||||
core.register_on_punchplayer(function(player, hitter, time_from_last_punch, tool_capabilities, unused_dir, damage)
|
||||
core.register_on_punchplayer(function(player, hitter, time_from_last_punch, tool_capabilities, dir, damage)
|
||||
if player:get_hp() == 0 then
|
||||
return -- RIP
|
||||
end
|
||||
|
||||
-- Server::handleCommand_Interact() adds eye offset to one but not the other
|
||||
-- so the direction is slightly off, calculate it ourselves
|
||||
local dir = vector.subtract(player:get_pos(), hitter:get_pos())
|
||||
if hitter then
|
||||
-- Server::handleCommand_Interact() adds eye offset to one but not the other
|
||||
-- so the direction is slightly off, calculate it ourselves
|
||||
dir = vector.subtract(player:get_pos(), hitter:get_pos())
|
||||
end
|
||||
local d = vector.length(dir)
|
||||
if d ~= 0.0 then
|
||||
dir = vector.divide(dir, d)
|
||||
|
||||
@@ -237,8 +237,8 @@ end
|
||||
core.dynamic_media_callbacks = {}
|
||||
|
||||
|
||||
-- Transfer of certain globals into async environment
|
||||
-- see builtin/async/game.lua for the other side
|
||||
-- Transfer of certain globals into seconday Lua environments
|
||||
-- see builtin/async/game.lua or builtin/emerge/register.lua for the unpacking
|
||||
|
||||
local function copy_filtering(t, seen)
|
||||
if type(t) == "userdata" or type(t) == "function" then
|
||||
@@ -261,6 +261,9 @@ function core.get_globals_to_transfer()
|
||||
local all = {
|
||||
registered_items = copy_filtering(core.registered_items),
|
||||
registered_aliases = core.registered_aliases,
|
||||
registered_biomes = core.registered_biomes,
|
||||
registered_ores = core.registered_ores,
|
||||
registered_decorations = core.registered_decorations,
|
||||
|
||||
nodedef_default = copy_filtering(core.nodedef_default),
|
||||
craftitemdef_default = copy_filtering(core.craftitemdef_default),
|
||||
@@ -269,3 +272,29 @@ function core.get_globals_to_transfer()
|
||||
}
|
||||
return all
|
||||
end
|
||||
|
||||
do
|
||||
local function valid_object_iterator(objects)
|
||||
local i = 0
|
||||
local function next_valid_object()
|
||||
i = i + 1
|
||||
local obj = objects[i]
|
||||
if obj == nil then
|
||||
return
|
||||
end
|
||||
if obj:is_valid() then
|
||||
return obj
|
||||
end
|
||||
return next_valid_object()
|
||||
end
|
||||
return next_valid_object
|
||||
end
|
||||
|
||||
function core.objects_inside_radius(center, radius)
|
||||
return valid_object_iterator(core.get_objects_inside_radius(center, radius))
|
||||
end
|
||||
|
||||
function core.objects_in_area(min_pos, max_pos)
|
||||
return valid_object_iterator(core.get_objects_in_area(min_pos, max_pos))
|
||||
end
|
||||
end
|
||||
|
||||
@@ -64,6 +64,13 @@ function core.encode_png(width, height, data, compression)
|
||||
error("Incorrect type for 'height', expected number, got " .. type(height))
|
||||
end
|
||||
|
||||
if width < 1 then
|
||||
error("Incorrect value for 'width', must be at least 1")
|
||||
end
|
||||
if height < 1 then
|
||||
error("Incorrect value for 'height', must be at least 1")
|
||||
end
|
||||
|
||||
local expected_byte_count = width * height * 4
|
||||
|
||||
if type(data) ~= "table" and type(data) ~= "string" then
|
||||
@@ -90,3 +97,26 @@ function core.encode_png(width, height, data, compression)
|
||||
|
||||
return o_encode_png(width, height, data, compression or 6)
|
||||
end
|
||||
|
||||
-- Helper that pushes a collisionMoveResult structure
|
||||
if core.set_push_moveresult1 then
|
||||
-- must match CollisionAxis in collision.h
|
||||
local AXES = {"x", "y", "z"}
|
||||
-- <=> script/common/c_content.cpp push_collision_move_result()
|
||||
core.set_push_moveresult1(function(b0, b1, b2, axis, npx, npy, npz, v0x, v0y, v0z, v1x, v1y, v1z, v2x, v2y, v2z)
|
||||
return {
|
||||
touching_ground = b0,
|
||||
collides = b1,
|
||||
standing_on_object = b2,
|
||||
collisions = {{
|
||||
type = "node",
|
||||
axis = AXES[axis + 1],
|
||||
node_pos = vector.new(npx, npy, npz),
|
||||
new_pos = vector.new(v0x, v0y, v0z),
|
||||
old_velocity = vector.new(v1x, v1y, v1z),
|
||||
new_velocity = vector.new(v2x, v2y, v2z),
|
||||
}},
|
||||
}
|
||||
end)
|
||||
core.set_push_moveresult1 = nil
|
||||
end
|
||||
|
||||
@@ -404,7 +404,7 @@ core.register_item(":", {
|
||||
})
|
||||
|
||||
|
||||
function core.override_item(name, redefinition)
|
||||
function core.override_item(name, redefinition, del_fields)
|
||||
if redefinition.name ~= nil then
|
||||
error("Attempt to redefine name of "..name.." to "..dump(redefinition.name), 2)
|
||||
end
|
||||
@@ -418,6 +418,9 @@ function core.override_item(name, redefinition)
|
||||
for k, v in pairs(redefinition) do
|
||||
rawset(item, k, v)
|
||||
end
|
||||
for _, field in ipairs(del_fields or {}) do
|
||||
rawset(item, field, nil)
|
||||
end
|
||||
register_item_raw(item)
|
||||
end
|
||||
|
||||
|
||||
@@ -1,187 +0,0 @@
|
||||
-- cache setting
|
||||
local enable_damage = core.settings:get_bool("enable_damage")
|
||||
|
||||
local bar_definitions = {
|
||||
hp = {
|
||||
hud_elem_type = "statbar",
|
||||
position = {x = 0.5, y = 1},
|
||||
text = "heart.png",
|
||||
text2 = "heart_gone.png",
|
||||
number = core.PLAYER_MAX_HP_DEFAULT,
|
||||
item = core.PLAYER_MAX_HP_DEFAULT,
|
||||
direction = 0,
|
||||
size = {x = 24, y = 24},
|
||||
offset = {x = (-10 * 24) - 25, y = -(48 + 24 + 16)},
|
||||
},
|
||||
breath = {
|
||||
hud_elem_type = "statbar",
|
||||
position = {x = 0.5, y = 1},
|
||||
text = "bubble.png",
|
||||
text2 = "bubble_gone.png",
|
||||
number = core.PLAYER_MAX_BREATH_DEFAULT * 2,
|
||||
item = core.PLAYER_MAX_BREATH_DEFAULT * 2,
|
||||
direction = 0,
|
||||
size = {x = 24, y = 24},
|
||||
offset = {x = 25, y= -(48 + 24 + 16)},
|
||||
},
|
||||
}
|
||||
|
||||
local hud_ids = {}
|
||||
|
||||
local function scaleToHudMax(player, field)
|
||||
-- Scale "hp" or "breath" to the hud maximum dimensions
|
||||
local current = player["get_" .. field](player)
|
||||
local nominal = bar_definitions[field].item
|
||||
local max_display = math.max(player:get_properties()[field .. "_max"], current)
|
||||
return math.ceil(current / max_display * nominal)
|
||||
end
|
||||
|
||||
local function update_builtin_statbars(player)
|
||||
local name = player:get_player_name()
|
||||
|
||||
if name == "" then
|
||||
return
|
||||
end
|
||||
|
||||
local flags = player:hud_get_flags()
|
||||
if not hud_ids[name] then
|
||||
hud_ids[name] = {}
|
||||
-- flags are not transmitted to client on connect, we need to make sure
|
||||
-- our current flags are transmitted by sending them actively
|
||||
player:hud_set_flags(flags)
|
||||
end
|
||||
local hud = hud_ids[name]
|
||||
|
||||
local immortal = player:get_armor_groups().immortal == 1
|
||||
|
||||
if flags.healthbar and enable_damage and not immortal then
|
||||
local number = scaleToHudMax(player, "hp")
|
||||
if hud.id_healthbar == nil then
|
||||
local hud_def = table.copy(bar_definitions.hp)
|
||||
hud_def.number = number
|
||||
hud.id_healthbar = player:hud_add(hud_def)
|
||||
else
|
||||
player:hud_change(hud.id_healthbar, "number", number)
|
||||
end
|
||||
elseif hud.id_healthbar then
|
||||
player:hud_remove(hud.id_healthbar)
|
||||
hud.id_healthbar = nil
|
||||
end
|
||||
|
||||
local show_breathbar = flags.breathbar and enable_damage and not immortal
|
||||
|
||||
local breath = player:get_breath()
|
||||
local breath_max = player:get_properties().breath_max
|
||||
if show_breathbar and breath <= breath_max then
|
||||
local number = scaleToHudMax(player, "breath")
|
||||
if not hud.id_breathbar and breath < breath_max then
|
||||
local hud_def = table.copy(bar_definitions.breath)
|
||||
hud_def.number = number
|
||||
hud.id_breathbar = player:hud_add(hud_def)
|
||||
elseif hud.id_breathbar then
|
||||
player:hud_change(hud.id_breathbar, "number", number)
|
||||
end
|
||||
end
|
||||
|
||||
if hud.id_breathbar and (not show_breathbar or breath == breath_max) then
|
||||
core.after(1, function(player_name, breath_bar)
|
||||
local player = core.get_player_by_name(player_name)
|
||||
if player then
|
||||
player:hud_remove(breath_bar)
|
||||
end
|
||||
end, name, hud.id_breathbar)
|
||||
hud.id_breathbar = nil
|
||||
end
|
||||
end
|
||||
|
||||
local function cleanup_builtin_statbars(player)
|
||||
local name = player:get_player_name()
|
||||
|
||||
if name == "" then
|
||||
return
|
||||
end
|
||||
|
||||
hud_ids[name] = nil
|
||||
end
|
||||
|
||||
local function player_event_handler(player,eventname)
|
||||
assert(player:is_player())
|
||||
|
||||
local name = player:get_player_name()
|
||||
|
||||
if name == "" or not hud_ids[name] then
|
||||
return
|
||||
end
|
||||
|
||||
if eventname == "health_changed" then
|
||||
update_builtin_statbars(player)
|
||||
|
||||
if hud_ids[name].id_healthbar then
|
||||
return true
|
||||
end
|
||||
end
|
||||
|
||||
if eventname == "breath_changed" then
|
||||
update_builtin_statbars(player)
|
||||
|
||||
if hud_ids[name].id_breathbar then
|
||||
return true
|
||||
end
|
||||
end
|
||||
|
||||
if eventname == "hud_changed" or eventname == "properties_changed" then
|
||||
update_builtin_statbars(player)
|
||||
return true
|
||||
end
|
||||
|
||||
return false
|
||||
end
|
||||
|
||||
function core.hud_replace_builtin(hud_name, definition)
|
||||
if type(definition) ~= "table" or
|
||||
definition.hud_elem_type ~= "statbar" then
|
||||
return false
|
||||
end
|
||||
|
||||
definition = table.copy(definition)
|
||||
|
||||
if hud_name == "health" then
|
||||
definition.item = definition.item or definition.number or core.PLAYER_MAX_HP_DEFAULT
|
||||
bar_definitions.hp = definition
|
||||
|
||||
for name, ids in pairs(hud_ids) do
|
||||
local player = core.get_player_by_name(name)
|
||||
if player and ids.id_healthbar then
|
||||
player:hud_remove(ids.id_healthbar)
|
||||
ids.id_healthbar = nil
|
||||
update_builtin_statbars(player)
|
||||
end
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
if hud_name == "breath" then
|
||||
definition.item = definition.item or definition.number or core.PLAYER_MAX_BREATH_DEFAULT
|
||||
bar_definitions.breath = definition
|
||||
|
||||
for name, ids in pairs(hud_ids) do
|
||||
local player = core.get_player_by_name(name)
|
||||
if player and ids.id_breathbar then
|
||||
player:hud_remove(ids.id_breathbar)
|
||||
ids.id_breathbar = nil
|
||||
update_builtin_statbars(player)
|
||||
end
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
return false
|
||||
end
|
||||
|
||||
-- Append "update_builtin_statbars" as late as possible
|
||||
-- This ensures that the HUD is hidden when the flags are updated in this callback
|
||||
core.register_on_mods_loaded(function()
|
||||
core.register_on_joinplayer(update_builtin_statbars)
|
||||
end)
|
||||
core.register_on_leaveplayer(cleanup_builtin_statbars)
|
||||
core.register_playerevent(player_event_handler)
|
||||
84
builtin/game/tests/test_moveaction.lua
Normal file
84
builtin/game/tests/test_moveaction.lua
Normal file
@@ -0,0 +1,84 @@
|
||||
-- Table to keep track of callback executions
|
||||
-- [i + 0] = count of expected patterns of index (i + 1)
|
||||
-- [i + 1] = pattern to check
|
||||
local PATTERN_NORMAL = { 4, "allow_%w", 2, "on_take", 1, "on_put", 1 }
|
||||
local PATTERN_SWAP = { 8, "allow_%w", 4, "on_take", 2, "on_put", 2 }
|
||||
local exec_listing = {} -- List of logged callbacks (e.g. "on_take", "allow_put")
|
||||
|
||||
-- Checks whether the logged callbacks equal the expected pattern
|
||||
core.__helper_check_callbacks = function(expect_swap)
|
||||
local exec_pattern = expect_swap and PATTERN_SWAP or PATTERN_NORMAL
|
||||
local ok = #exec_listing == exec_pattern[1]
|
||||
if ok then
|
||||
local list_index = 1
|
||||
for i = 2, #exec_pattern, 2 do
|
||||
for n = 1, exec_pattern[i + 1] do
|
||||
-- Match the list for "n" occurrences of the wanted callback name pattern
|
||||
ok = exec_listing[list_index]:find(exec_pattern[i])
|
||||
list_index = list_index + 1
|
||||
if not ok then break end
|
||||
end
|
||||
if not ok then break end
|
||||
end
|
||||
end
|
||||
|
||||
if not ok then
|
||||
print("Execution order mismatch!")
|
||||
print("Expected patterns: ", dump(exec_pattern))
|
||||
print("Got list: ", dump(exec_listing))
|
||||
end
|
||||
exec_listing = {}
|
||||
return ok
|
||||
end
|
||||
|
||||
-- Uncomment the other line for easier callback debugging
|
||||
local log = function(...) end
|
||||
--local log = print
|
||||
|
||||
minetest.register_allow_player_inventory_action(function(_, action, inv, info)
|
||||
log("\tallow " .. action, info.count or info.stack:to_string())
|
||||
|
||||
if action == "move" then
|
||||
-- testMoveFillStack
|
||||
return info.count
|
||||
end
|
||||
|
||||
if action == "take" or action == "put" then
|
||||
assert(not info.stack:is_empty(), "Stack empty in: " .. action)
|
||||
|
||||
-- testMoveUnallowed
|
||||
-- testSwapFromUnallowed
|
||||
-- testSwapToUnallowed
|
||||
if info.stack:get_name() == "default:takeput_deny" then
|
||||
return 0
|
||||
end
|
||||
|
||||
-- testMovePartial
|
||||
if info.stack:get_name() == "default:takeput_max_5" then
|
||||
return 5
|
||||
end
|
||||
|
||||
-- testCallbacks
|
||||
if info.stack:get_name():find("default:takeput_cb_%d") then
|
||||
-- Log callback as executed
|
||||
table.insert(exec_listing, "allow_" .. action)
|
||||
return -- Unlimited
|
||||
end
|
||||
end
|
||||
|
||||
return -- Unlimited
|
||||
end)
|
||||
|
||||
minetest.register_on_player_inventory_action(function(_, action, inv, info)
|
||||
log("\ton " .. action, info.count or info.stack:to_string())
|
||||
|
||||
if action == "take" or action == "put" then
|
||||
assert(not info.stack:is_empty(), action)
|
||||
|
||||
if info.stack:get_name():find("default:takeput_cb_%d") then
|
||||
-- Log callback as executed
|
||||
table.insert(exec_listing, "on_" .. action)
|
||||
return
|
||||
end
|
||||
end
|
||||
end)
|
||||
@@ -26,13 +26,19 @@ do
|
||||
core.print = nil -- don't pollute our namespace
|
||||
end
|
||||
end
|
||||
math.randomseed(os.time())
|
||||
|
||||
do
|
||||
-- Note that PUC Lua just calls srand() which is already initialized by C++,
|
||||
-- but we don't want to rely on this implementation detail.
|
||||
local seed = 1048576 * (os.time() % 1048576)
|
||||
seed = seed + core.get_us_time() % 1048576
|
||||
math.randomseed(seed)
|
||||
end
|
||||
|
||||
minetest = core
|
||||
|
||||
-- Load other files
|
||||
local scriptdir = core.get_builtin_path()
|
||||
local gamepath = scriptdir .. "game" .. DIR_DELIM
|
||||
local clientpath = scriptdir .. "client" .. DIR_DELIM
|
||||
local commonpath = scriptdir .. "common" .. DIR_DELIM
|
||||
local asyncpath = scriptdir .. "async" .. DIR_DELIM
|
||||
|
||||
@@ -42,7 +48,7 @@ dofile(commonpath .. "serialize.lua")
|
||||
dofile(commonpath .. "misc_helpers.lua")
|
||||
|
||||
if INIT == "game" then
|
||||
dofile(gamepath .. "init.lua")
|
||||
dofile(scriptdir .. "game" .. DIR_DELIM .. "init.lua")
|
||||
assert(not core.get_http_api)
|
||||
elseif INIT == "mainmenu" then
|
||||
local mm_script = core.settings:get("main_menu_script")
|
||||
@@ -65,9 +71,12 @@ elseif INIT == "mainmenu" then
|
||||
elseif INIT == "async" then
|
||||
dofile(asyncpath .. "mainmenu.lua")
|
||||
elseif INIT == "async_game" then
|
||||
dofile(commonpath .. "metatable.lua")
|
||||
dofile(asyncpath .. "game.lua")
|
||||
elseif INIT == "client" then
|
||||
dofile(clientpath .. "init.lua")
|
||||
dofile(scriptdir .. "client" .. DIR_DELIM .. "init.lua")
|
||||
elseif INIT == "emerge" then
|
||||
dofile(scriptdir .. "emerge" .. DIR_DELIM .. "init.lua")
|
||||
else
|
||||
error(("Unrecognized builtin initialization type %s!"):format(tostring(INIT)))
|
||||
end
|
||||
|
||||
246
builtin/locale/__builtin.eo.tr
Normal file
246
builtin/locale/__builtin.eo.tr
Normal file
@@ -0,0 +1,246 @@
|
||||
# textdomain: __builtin
|
||||
Invalid parameters (see /help @1).=Nevalidaj parametroj (kontrolu /help @1)
|
||||
Too many arguments, try using just /help <command>=Tro da parametroj, eble provu /help <ordono>
|
||||
Available commands: @1=Nunaj ordonoj: @1
|
||||
Use '/help <cmd>' to get more information, or '/help all' to list everything.=Uzu «/help <ordono>» por specifa informo, aŭ «/help all» por listigi ĉion.
|
||||
Available commands:=Nunaj ordonoj:
|
||||
Command not available: @1=Ordono neuzebla: @1
|
||||
[all | privs | <cmd>] [-t]=[all | privs | <ordono>]
|
||||
Get help for commands or list privileges (-t: output in chat)=Listigi helpon pri ordonoj («all» aŭ <ordono>) aŭ rajtoj («privs») (kun -t: presu en babilejo)
|
||||
Available privileges:=Nunaj rajtoj:
|
||||
Command=Ordono
|
||||
Parameters=Parametroj
|
||||
For more information, click on any entry in the list.=Por pliaj informoj, klaku ajnan listeron.
|
||||
Double-click to copy the entry to the chat history.=Dufoje-klaku por kopii listeron al la babilejo.
|
||||
Command: @1 @2=Ordono: @1 @2
|
||||
Available commands: (see also: /help <cmd>)=Nunaj ordonoj: (vidu ankaŭ: /help <ordono>)
|
||||
Close=Fermi
|
||||
Privilege=Rajto
|
||||
Description=Priskribo
|
||||
Empty command.=Malplena ordono.
|
||||
Invalid command: @1=Nevalida ordono: @1
|
||||
Invalid command usage.=Nevalida ordonouzo.
|
||||
(@1 s)= (@1 s)
|
||||
Command execution took @1 s=Ruliĝo de ordono postulis @1 s
|
||||
You don't have permission to run this command (missing privileges: @1).=Vi ne rajtas uzi tiun ĉi ordonon (mankataj rajtoj: @1)
|
||||
Unable to get position of player @1.=Ne povis akiri pozicion de ludanto @1.
|
||||
Incorrect area format. Expected: (x1,y1,z1) (x2,y2,z2)=Nevalida loko-formo. Atendis: (x1,y1,z1) (x2,y2,z2)
|
||||
<action>=<ago>
|
||||
Show chat action (e.g., '/me orders a pizza' displays '<player name> orders a pizza')=Roli agon en la babilejo (ekz., «/me mendas picon» montras «<ludanto> mendas picon»)
|
||||
Show the name of the server owner=Montri nomon de la serviladministranto
|
||||
The administrator of this server is @1.=La adminstranto de tiu ĉi servilo estas @1.
|
||||
There's no administrator named in the config file.=Estas neniu agordita administranto en la agordodosiero.
|
||||
@1 does not have any privileges.=@1 havas neniun rajton.
|
||||
Privileges of @1: @2=Rajtoj de @1: @2
|
||||
[<name>]=[<nomo>]
|
||||
Show privileges of yourself or another player=Montri rajtojn de vi aŭ alia ludanto
|
||||
Player @1 does not exist.=Ludanto @1 ne ekzistas.
|
||||
<privilege>=<rajto>
|
||||
Return list of all online players with privilege=Listi ĉeretan ludanton kun specifa rajto
|
||||
Invalid parameters (see /help haspriv).=Nevalidaj parametroj (vidu /help haspriv).
|
||||
Unknown privilege!=Nekonata rajto!
|
||||
No online player has the "@1" privilege.=Neniu ĉeretulo havas la rajton «@1».
|
||||
Players online with the "@1" privilege: @2=Ĉeretuloj kun la rajto «@1»: @2
|
||||
Your privileges are insufficient.=Viaj rajtoj ne sufiĉas.
|
||||
Your privileges are insufficient. '@1' only allows you to grant: @2=Viaj rajtoj ne sufiĉas. «@1» sole lasas vin doni: @2
|
||||
Unknown privilege: @1=Nekonata rajto: @1
|
||||
@1 granted you privileges: @2=@1 donis al vi rajtojn: @2
|
||||
<name> (<privilege> [, <privilege2> [<...>]] | all)=<nomo> (<rajto> [, <rajto2> [<...>]] | all)
|
||||
Give privileges to player=Doni rajtojn al ludanto, aŭ aparte, aŭ ĉiun kune («all»)
|
||||
Invalid parameters (see /help grant).=Nevalidaj parametroj (vidu /help grant).
|
||||
<privilege> [, <privilege2> [<...>]] | all=<rajto> [, <rajto2> [<...>]] | all
|
||||
Grant privileges to yourself=Doni rajtojn al vi mem, aŭ aparte, aŭ ĉiun kune («all»)
|
||||
Invalid parameters (see /help grantme).=Nevalidaj parametroj (vidu /help grantme)
|
||||
Your privileges are insufficient. '@1' only allows you to revoke: @2=Viaj rajtoj ne sufiĉas. «@1» sole lasas vin repreni: @2
|
||||
Note: Cannot revoke in singleplayer: @1=Rimarko: Neeblas repreni rajton sole: @1
|
||||
Note: Cannot revoke from admin: @1=Rimarko: Neeblas repreni rajnton de administranto: @1
|
||||
No privileges were revoked.=Neniu rajto reprenita.
|
||||
@1 revoked privileges from you: @2=@1 reprenis rajtojn de vi: @2
|
||||
Remove privileges from player=Repreni rajtojn de ludanto, aŭ aparte, aŭ ĉiun kune («all»)
|
||||
Invalid parameters (see /help revoke).=Nevalidaj parametroj (vidu /help revoke)
|
||||
Revoke privileges from yourself=Repreni rajtojn de vi mem, aŭ aparte, aŭ ĉiun kune («all»)
|
||||
Invalid parameters (see /help revokeme).=Nevalidaj parametroj (vidu /help revokeme).
|
||||
<name> <password>=<nomo> <pasvorto>
|
||||
Set player's password (sent unencrypted, thus insecure)=Agordi pasvorton de ludanto (sendute senĉifre, kaj tiel malsekure)
|
||||
Name field required.=Nomo bezonata.
|
||||
Your password was cleared by @1.=Via pasvorto forviŝiĝis de @1.
|
||||
Password of player "@1" cleared.=Pasvorto de ludanto «@1» forviŝita.
|
||||
Your password was set by @1.=Via pasvorto agordiĝis de @1.
|
||||
Password of player "@1" set.=Pasvorto de ludanto «@1» agordita.
|
||||
<name>=<nomo>
|
||||
Set empty password for a player=Forviŝi pasvorton de ludanto
|
||||
Reload authentication data=Reenlegi aŭtentigajn datumojn
|
||||
Done.=Finite.
|
||||
Failed.=Malsukcese..
|
||||
Remove a player's data=Forviŝi datumojn de ludanto
|
||||
Player "@1" removed.=Ludanto «@1» forigita.
|
||||
No such player "@1" to remove.=Neniu ekzistanta ludanto «@1» forigebla.
|
||||
Player "@1" is connected, cannot remove.=Ludanto «@1» ĉeretas, do ne forigeblas.
|
||||
Unhandled remove_player return code @1.=Netraktata remove_player redonkodo @1.
|
||||
Cannot teleport out of map bounds!=Neeblas teleporti ekstermonden!
|
||||
Cannot get player with name @1.=Neeblas trovi ludanton nomitan «@1».
|
||||
Cannot teleport, @1 is attached to an object!=Ne povas teleporti @1, ĝi estas ligita al objekto!
|
||||
Teleporting @1 to @2.=Teleportante @1 al @2.
|
||||
One does not teleport to oneself.=Oni kutimas ne teleportu al si mem.
|
||||
Cannot get teleportee with name @1.=Ne trovis alteleportaton nomitan @1.
|
||||
Cannot get target player with name @1.=Ne trovis celatan ludanton nomitan @1.
|
||||
Teleporting @1 to @2 at @3.=Teleportante @1 al @2 ĉe @3.
|
||||
<X>,<Y>,<Z> | <to_name> | <name> <X>,<Y>,<Z> | <name> <to_name>=<X>,<Y>,<Z> | <al_nomo> | <nomo> <X>,<Y>,<Z> | <nomo> <al_nomo>
|
||||
Teleport to position or player=Teleportiĝi al pozicio aŭ ludanto
|
||||
You don't have permission to teleport other players (missing privilege: @1).=Vi ne rajtas teleporti aliajn ludantojn (mankas rajto: @1).
|
||||
([-n] <name> <value>) | <name>=([-n] <nomo> <valoro>) | <nomo>
|
||||
Set or read server configuration setting=Agordi aŭ vidi servilan agordon
|
||||
Failed. Cannot modify secure settings. Edit the settings file manually.=Malsukcese. Neeblas redakti sekurajn agordojn. Redaktu la agordodosieron permane.
|
||||
Failed. Use '/set -n <name> <value>' to create a new setting.=Malsukcese. Uzu «/set -n <nomo> <valoro>» por krei novan agordon.
|
||||
@1 @= @2=@1 @= @2
|
||||
<not set>=<ne agordita>
|
||||
Invalid parameters (see /help set).=Nevalidaj parametroj (vidu /help set).
|
||||
Finished emerging @1 blocks in @2ms.=Finenlegis @1 monderojn dum @2ms.
|
||||
emergeblocks update: @1/@2 blocks emerged (@3%)=emergeblocks ĝisdatigo: @1/@2 monderoj enlegitaj (@3%)
|
||||
(here [<radius>]) | (<pos1> <pos2>)=(here [<radius>]) | (<pos1> <pos2>)
|
||||
Load (or, if nonexistent, generate) map blocks contained in area pos1 to pos2 (<pos1> and <pos2> must be in parentheses)=Enlegi (aŭ, laŭnecese, krei) mondopecojn inter la pozicioj poz1 kaj pos2 (<poz1> kaj <poz2> devas esti inter krampoj)
|
||||
Started emerge of area ranging from @1 to @2.=Ekenlegis mondpecojn inter @1 kaj @2.
|
||||
Delete map blocks contained in area pos1 to pos2 (<pos1> and <pos2> must be in parentheses)=Forigi mondpecojn inter la pozicioj poz1 kaj poz2 (<poz1> kaj <poz2> devas esti inter krampoj)
|
||||
Successfully cleared area ranging from @1 to @2.=Sukcese forigis mondpecojn inter @1 kaj @2.
|
||||
Failed to clear one or more blocks in area.=Malsukcesis forigi unu aŭ pli da mondpecoj.
|
||||
Resets lighting in the area between pos1 and pos2 (<pos1> and <pos2> must be in parentheses)=Reŝarĝas lumojn inter la pozicioj poz1 kaj poz2 (<poz1> kaj <poz2> devas esti inter krampoj)
|
||||
Successfully reset light in the area ranging from @1 to @2.=Sukcesis reŝarĝi lumojn inter @1 kaj @2.
|
||||
Failed to load one or more blocks in area.=Malsukcesis enlegante unu aŭ pli da monderoj.
|
||||
List mods installed on the server=Listigi modifaĵojn instalitajn de la servilo.
|
||||
No mods installed.=Neniu modifaĵ instalita.
|
||||
Cannot give an empty item.=Neeblas doni neniun portaĵon.
|
||||
Cannot give an unknown item.=Neeblas doni nekonatan portaĵon.
|
||||
Giving 'ignore' is not allowed.=Doni «ignore» estas ne permesita.
|
||||
@1 is not a known player.=@1 ne estas konata ludanto.
|
||||
@1 partially added to inventory.=@1 parte enmetiĝis al portaĵujon.
|
||||
@1 could not be added to inventory.=@1 ne enmetiĝis al portaĵujon.
|
||||
@1 added to inventory.=@1 enmetiĝis al portaĵujon.
|
||||
@1 partially added to inventory of @2.=@1 parte enmetiĝis al portaĵujon de @2.
|
||||
@1 could not be added to inventory of @2.=@1 ne enmetiĝis al portaĵujon de @2.
|
||||
@1 added to inventory of @2.=@1 enmetiĝis al portaĵujon de @2.
|
||||
<name> <ItemString> [<count> [<wear>]]=<nomo> <PortaĵNomo> [<kvanto> <portu>]]
|
||||
Give item to player=Doni portaĵon al ludanto
|
||||
Name and ItemString required.=Nomo kaj PortaĵNomo postualtaj.
|
||||
<ItemString> [<count> [<wear>]]=<PortaĵNomo> [<kvanto> [<portu>]]
|
||||
Give item to yourself=Doni portaĵon al vi mem.
|
||||
ItemString required.=PortaĵNomo postulata.
|
||||
<EntityName> [<X>,<Y>,<Z>]=<EstaĵoNomo> [<X>, <Y>, <Z>]
|
||||
Spawn entity at given (or your) position=Estigi estaĵon ĉe la donita (aŭ la via) pozicio
|
||||
EntityName required.=EstaĵNomo postulata.
|
||||
Unable to spawn entity, player is nil.=Ne povis estigi estaĵon, ĉar ludanto estas nil.
|
||||
Cannot spawn an unknown entity.=Neeblas estigi nekonatan estaĵon.
|
||||
Invalid parameters (@1).=Nevalidaj parametroj (@1).
|
||||
@1 spawned.=@1 naskiĝis.
|
||||
@1 failed to spawn.=@1 ne naskiĝis.
|
||||
Destroy item in hand=Detrui portaĵon enmanan
|
||||
Unable to pulverize, no player.=Ne povis detrui, neniu ludanto.
|
||||
Unable to pulverize, no item in hand.=Ne povis detrui, ĉar nenio estas tenata.
|
||||
An item was pulverized.=Portaĵo detruiĝis.
|
||||
[<range>] [<seconds>] [<limit>]=[<intertempo>] [<sekundoj>] [<limo>]
|
||||
Check who last touched a node or a node near it within the time specified by <seconds>. Default: range @= 0, seconds @= 86400 @= 24h, limit @= 5. Set <seconds> to inf for no time limit=Kontroli kiu lastafoje tuŝis monderon aŭ monderon proksiman al ĝi dum
|
||||
Rollback functions are disabled.=Malfaraj funkcioj estas malŝaltitaj.
|
||||
That limit is too high!=Tiu limo troaltas!
|
||||
Checking @1 ...=Kontrolas @1…
|
||||
Nobody has touched the specified location in @1 seconds.=Neniu tuŝis tiun lokon dum @1 sekundoj.
|
||||
@1 @2 @3 -> @4 @5 seconds ago.=@1 @2 @3 -> @4 @5 sekundoj antaŭe.
|
||||
Punch a node (range@=@1, seconds@=@2, limit@=@3).=Frapi monderon (intertempo@=@1, sekundoj@=@2, limo@=@3).
|
||||
(<name> [<seconds>]) | (:<actor> [<seconds>])=(<nomo> [<sekundoj>]) | (:<aganto> [<sekundoj>])
|
||||
Revert actions of a player. Default for <seconds> is 60. Set <seconds> to inf for no time limit=Malfari agojn de ludanto. Implicita valoro de <sekundoj> estas 60. Metu <sekundoj> kiel «inf» por neniu tempolimo
|
||||
Invalid parameters. See /help rollback and /help rollback_check.=Nevalidaj parametroj. Vidu /help rollback kaj /help rollback_check.
|
||||
Reverting actions of player '@1' since @2 seconds.=Malfaras agojn de ludanto «@1» ekde @2 sekundoj antaŭ nun.
|
||||
Reverting actions of @1 since @2 seconds.=Malfaras agojn de @1 ekde @2 sekundoj antaŭ nun.
|
||||
(log is too long to show)=(protokolo trolongas por montri)
|
||||
Reverting actions succeeded.=Sukcesis malfari agojn.
|
||||
Reverting actions FAILED.=MALsukcesis malfari agojn.
|
||||
Show server status=Montri staton de servilon.
|
||||
This command was disabled by a mod or game.=Tiun ordonon malŝaltis modifaĵo aŭ ludo.
|
||||
[<0..23>:<0..59> | <0..24000>]=[<0..23>:<0..59> | <0..24000>]
|
||||
Show or set time of day=Montri aŭ ŝanĝi la horon
|
||||
Current time is @1:@2.=Nun estas @1:@2.
|
||||
You don't have permission to run this command (missing privilege: @1).=Vi ne rajtas rulu tiun orodnon (mankata rajto: @1).
|
||||
Invalid time (must be between 0 and 24000).=Nevalida tempo (estu inter 0 kaj 24000)
|
||||
Time of day changed.=Horo ŝanĝita.
|
||||
Invalid hour (must be between 0 and 23 inclusive).=Nevalida horo (estu inter 0 kaj 23, inkluzive).
|
||||
Invalid minute (must be between 0 and 59 inclusive).=Nevalida minuto (estu inter 0 kaj 59, inkluzive).
|
||||
Show day count since world creation=Montri pasitajn tagojn ekde mondokreo
|
||||
Current day is @1.=Nuna tago estas @1.
|
||||
[<delay_in_seconds> | -1] [-r] [<message>]=[<prokrasto_sekunde> | -1] [-r] [<mesaĝo>]
|
||||
Shutdown server (-1 cancels a delayed shutdown, -r allows players to reconnect)=Malŝalti servilon (-1 nuligas planitan malŝalton, -r lasas ludantojn rekonektiĝi)
|
||||
Server shutting down (operator request).=Servilo malŝaltiĝas (laŭ prizorganta peto)
|
||||
Ban the IP of a player or show the ban list=Forbari la IP-adreson de ludanto, aŭ listigi forbaritojn
|
||||
The ban list is empty.=La forbaritolisto malplenas.
|
||||
Ban list: @1=Forbaritoj: @1
|
||||
You cannot ban players in singleplayer!=Vi ne povas forbari ludantojn en unuludanta reĝimo!
|
||||
Player is not online.=Ludanto ne ĉeretas.
|
||||
Failed to ban player.=Malsukcesis forbari ludanton.
|
||||
Banned @1.=Forbaris @1.
|
||||
<name> | <IP_address>=<nomo> | <IP_adreso>
|
||||
Remove IP ban belonging to a player/IP=Nuligi IP-forbaron de ludanto/IP
|
||||
Failed to unban player/IP.=Malsukcesis nuligi forbaron de ludanto/IP-adreso
|
||||
Unbanned @1.=Malforbaris @1.
|
||||
<name> [<reason>]=<nomo> [<kialo>]
|
||||
Kick a player=Elĵeti ludanton
|
||||
Failed to kick player @1.=Malsukcesis elĵeti ludanton @1.
|
||||
Kicked @1.=Elĵetis @1.
|
||||
[full | quick]=[full | quick]
|
||||
Clear all objects in world=Forigu ĉiujn lasitajn portaĵojn en la mondo
|
||||
Invalid usage, see /help clearobjects.=Nevalida uzo, vidu /help clearobjects.
|
||||
Clearing all objects. This may take a long time. You may experience a timeout. (by @1)=Forigante ĉiun lasitan portaĵon. Tio ĉi eble postulos longan tempon. Vi eble malkonektiĝos pro tempo-elĉerpo. (de @1)
|
||||
Cleared all objects.=Forigis ĉiun lasitan portaĵon.
|
||||
<name> <message>=<nomo> <mesaĝo>
|
||||
Send a direct message to a player=Sendu rekte privatan mesaĝon al ludanto
|
||||
Invalid usage, see /help msg.=Nevalida uzo, vidu /help msg.
|
||||
The player @1 is not online.=La ludanto @1 ne ĉeretas.
|
||||
DM from @1: @2=Privata mesaĝo de @1: @2
|
||||
Message sent.=Mesaĝo sendita.
|
||||
Get the last login time of a player or yourself=Vidi la lastan salutotempon de ludanto, aŭ vi mem
|
||||
@1's last login time was @2.=Lasta salutotempo de @1 estas @2.
|
||||
@1's last login time is unknown.=Lasta salutotempo de @1 estas nesciata.
|
||||
Clear the inventory of yourself or another player=Malplenigi la portaĵujon de vi aŭ alia ludanto.
|
||||
You don't have permission to clear another player's inventory (missing privilege: @1).=Vi ne rajtas malplenigi portaĵujon de alia ludanto (mankata rajto: @1).
|
||||
@1 cleared your inventory.=@1 malplenigis vian portaĵujon.
|
||||
Cleared @1's inventory.=Malplenigis portaĵujon de @1.
|
||||
Player must be online to clear inventory!=Por malplenigi onian portaĵujon, tiu devas ĉereti!
|
||||
Players can't be killed, damage has been disabled.=Nemortigeblas ludantoj, ĉar vundado estas malŝaltita.
|
||||
Player @1 is not online.=Ludanto @1 ne ĉeretas.
|
||||
You are already dead.=Vi jam estas mortinta.
|
||||
@1 is already dead.=@1 estas mortinta.
|
||||
@1 has been killed.=@1 estas murdita.
|
||||
Kill player or yourself=Mortigi ludanton aŭ vin mem
|
||||
@1 joined the game.=@1 aliĝis la ludon.
|
||||
@1 left the game.=@1 foriris de la ludo.
|
||||
@1 left the game (timed out).=@1 foriris de la ludo (tempo-elĉerpo)
|
||||
(no description)=(neniu priskribo)
|
||||
Can interact with things and modify the world=Povas interfaci kaj redakti la mondon
|
||||
Can speak in chat=Povas paroli babileje
|
||||
Can modify basic privileges (@1)=Povas redakti bazajn rajtojn (@1)
|
||||
Can modify privileges=Povas redakti rajtojn
|
||||
Can teleport self=Povas teleporti sin
|
||||
Can teleport other players=Povas teleporti aliajn ludantojn
|
||||
Can set the time of day using /time=Povas ŝanĝi la tempon per /time
|
||||
Can do server maintenance stuff=Povas fari servilestrajn aferojn
|
||||
Can bypass node protection in the world=Povas malatenti monderajn protektojn de la mondo
|
||||
Can ban and unban players=Povas forbari kaj malforbari ludantojn
|
||||
Can kick players=Povas elĵeti ludantojn
|
||||
Can use /give and /giveme=Povas uzi /give kaj /giveme
|
||||
Can use /setpassword and /clearpassword=Povas uzi /setpassword kaj /clearpassword
|
||||
Can use fly mode=Povas ŝalti flugan reĝimon
|
||||
Can use fast mode=Povas ŝalti rapidegan reĝimon
|
||||
Can fly through solid nodes using noclip mode=Povas traflugi monderojn per trapasa reĝimo
|
||||
Can use the rollback functionality=Povas uzi malfarajn funkciojn
|
||||
Can enable wireframe=Povas ŝalti ĉirkaŭkadron
|
||||
Unknown Item=Nekonata portaĵo
|
||||
Air=Aero
|
||||
Ignore=Malatenti
|
||||
You can't place 'ignore' nodes!=Vi ne povas meti «malatentajn» monderojn!
|
||||
print [<filter>] | dump [<filter>] | save [<format> [<filter>]] | reset=print [<filtrilo>] | dump [<filtrilo>] | save [<formo> [<filtrilo>]] | reset
|
||||
Handle the profiler and profiling data=Trakti la analizilon kaj analizajn datumojn
|
||||
Statistics written to action log.=Analizoj skribitaj al agoprotokolo.
|
||||
Statistics were reset.=Analizoj forviŝitaj.
|
||||
Usage: @1=Uzado: @1
|
||||
Format can be one of txt, csv, lua, json, json_pretty (structures may be subject to change).=Formo povas estas txt, csv, lua, json, aŭ json_pretty (struktuoj eble iam ŝanĝiĝos).
|
||||
Values below show absolute/relative times spend per server step by the instrumented function.=Valoroj subaj montras la malrelativan/relativan tempon pasigitan de la servilo je ĉiu paŝo de la funkcio.
|
||||
A total of @1 sample(s) were taken.=Sume @1 ekzemplero(j) konserviĝis.
|
||||
The output is limited to '@1'.=La eligo estas limigita al «@1».
|
||||
Saving of profile failed: @1=Konservado de profilo malsukcesis: @1
|
||||
Profile saved to @1=Profilo konservita al @1
|
||||
246
builtin/locale/__builtin.fr.tr
Normal file
246
builtin/locale/__builtin.fr.tr
Normal file
@@ -0,0 +1,246 @@
|
||||
# textdomain: __builtin
|
||||
Invalid parameters (see /help @1).=Paramètres invalides (voir /help @1).
|
||||
Too many arguments, try using just /help <command>=Trop de paramètres, essayez /help <command>
|
||||
Available commands: @1=Commandes disponibles : @1
|
||||
Use '/help <cmd>' to get more information, or '/help all' to list everything.=Essayez '/help <cmd>' pour obtenir plus d'informations, ou '/help all' pour tout lister.
|
||||
Available commands:=Commandes disponibles :
|
||||
Command not available: @1=Commande non disponible : @1
|
||||
[all | privs | <cmd>] [-t]=[all | privs | <cmd>] [-t]
|
||||
Get help for commands or list privileges (-t: output in chat)=Obtenir de l'aide pour les commandes ou pour lister les privilèges (-t : affichage dans le tchat)
|
||||
Available privileges:=Privilèges disponibles :
|
||||
Command=Commande
|
||||
Parameters=Paramètres
|
||||
For more information, click on any entry in the list.=Pour plus d'informations, cliquez sur une entrée dans la liste.
|
||||
Double-click to copy the entry to the chat history.=Double-cliquez pour copier une entrée dans l'historique du tchat.
|
||||
Command: @1 @2=Commande : @1 @2
|
||||
Available commands: (see also: /help <cmd>)=Commandes disponibles : (voir aussi : /help <cmd>)
|
||||
Close=Fermer
|
||||
Privilege=Privilège
|
||||
Description=Description
|
||||
Empty command.=Commande vide.
|
||||
Invalid command: @1=Commande invalide : @1
|
||||
Invalid command usage.=Usage invalide de la commande.
|
||||
(@1 s)= (@1 s)
|
||||
Command execution took @1 s=L'exécution de la commande a pris @1 s.
|
||||
You don't have permission to run this command (missing privileges: @1).=Vous n'avez pas la permission d'exécuter cette commande (privilèges manquants : @1)
|
||||
Unable to get position of player @1.=Impossible d'obtenir la position du joueur @1.
|
||||
Incorrect area format. Expected: (x1,y1,z1) (x2,y2,z2)=Format incorrect de la zone. Demandé : (x1, y1, z1) (x2, y2, z2)
|
||||
<action>=<action>
|
||||
Show chat action (e.g., '/me orders a pizza' displays '<player name> orders a pizza')=Affiche une action de tchat (ex : '/me commande une pizza' affichage '<joueur> commande une pizza')
|
||||
Show the name of the server owner=Affiche le nom du propriétaire du serveur
|
||||
The administrator of this server is @1.=L'administrateur de ce serveur est @1.
|
||||
There's no administrator named in the config file.=Il n'y a pas d'administrateur indiqué dans le fichier de configuration.
|
||||
@1 does not have any privileges.=@1 ne possède aucun privilège.
|
||||
Privileges of @1: @2=Privilège(s) de @1 : @2
|
||||
[<name>]=[<nom>]
|
||||
Show privileges of yourself or another player=Affiche vos privilèges ou ceux d'un autre joueur.
|
||||
Player @1 does not exist.=Le joueur @1 n'existe pas.
|
||||
<privilege>=<privilège>
|
||||
Return list of all online players with privilege=Renvoie la liste de tous les joueurs en ligne avec un privilège.
|
||||
Invalid parameters (see /help haspriv).=Paramètres invalides (voir /help haspriv)
|
||||
Unknown privilege!=Privilège inconnu !
|
||||
No online player has the "@1" privilege.=Aucun joueur en ligne avant le privilège « @1 »
|
||||
Players online with the "@1" privilege: @2=Joueurs en ligne avec le privilège « @1 » : @2
|
||||
Your privileges are insufficient.=Vos privilèges sont insuffisants.
|
||||
Your privileges are insufficient. '@1' only allows you to grant: @2=Vos privilèges sont insuffisants. '@1' vous autorise seulement d'accorder : @2
|
||||
Unknown privilege: @1=Privilège inconnu : @1
|
||||
@1 granted you privileges: @2=@1 vous a accordé les privilèges : @2
|
||||
<name> (<privilege> [, <privilege2> [<...>]] | all)=<nom> (<privilège> [, <privilège2> [<...>]] | all)
|
||||
Give privileges to player=Accorder le privilège au joueur
|
||||
Invalid parameters (see /help grant).=Paramètres invalides (voir /help grant)
|
||||
<privilege> [, <privilege2> [<...>]] | all=<privilège> [, <privilège2> [<...>]] | all
|
||||
Grant privileges to yourself=Accorder des privilèges à vous-même
|
||||
Invalid parameters (see /help grantme).=Paramètres invalides (voir /help grantme)
|
||||
Your privileges are insufficient. '@1' only allows you to revoke: @2=Vos privilèges sont insuffisants. '@1' vous autorise seulement à révoquer : @2
|
||||
Note: Cannot revoke in singleplayer: @1=Note : Impossible de révoquer en solo : @1
|
||||
Note: Cannot revoke from admin: @1=Note : Impossible de révoquer à l'administrateur : @1
|
||||
No privileges were revoked.=Aucun privilège n'a été révoqué.
|
||||
@1 revoked privileges from you: @2=@1 vous a révoqué le privilège : @2
|
||||
Remove privileges from player=Révoquer les privilèges au joueur
|
||||
Invalid parameters (see /help revoke).=Paramètres invalides (voir /help revoke).
|
||||
Revoke privileges from yourself=Révoquer des privilèges à vous-même
|
||||
Invalid parameters (see /help revokeme).=Paramètres invalides (voir /help revokeme).
|
||||
<name> <password>=<nom> <mot de passe>
|
||||
Set player's password (sent unencrypted, thus insecure)=Voir le mot de passe d'un joueur (envoyé non crypté, soit non sécurisé)
|
||||
Name field required.=Le champ « nom » est requis.
|
||||
Your password was cleared by @1.=Votre mot de passe a été effacé par @1.
|
||||
Password of player "@1" cleared.=Mot de passe du joueur « @1 » effacé.
|
||||
Your password was set by @1.=Votre mot de passe a été défini par @1.
|
||||
Password of player "@1" set.=Mot de passe « @1 » défini.
|
||||
<name>=<nom>
|
||||
Set empty password for a player=Définir un mot de passe pour un joueur
|
||||
Reload authentication data=Recharger les données d'authentification
|
||||
Done.=Fait.
|
||||
Failed.=Échoué.
|
||||
Remove a player's data=Supprimer les données d'un joueur
|
||||
Player "@1" removed.=Joueur « @1 » supprimé.
|
||||
No such player "@1" to remove.=Aucun joueur « @1 » à supprimer.
|
||||
Player "@1" is connected, cannot remove.=Le joueur « @1 » est connecté, impossible de supprimer.
|
||||
Unhandled remove_player return code @1.=La commande remove_player non gérée a retourné le code @1.
|
||||
Cannot teleport out of map bounds!=Impossible de téléporter en dehors des limites de la carte !
|
||||
Cannot get player with name @1.=Impossible d'obtenir le joueur @1.
|
||||
Cannot teleport, @1 is attached to an object!=Impossible de téléporter, @1 est lié à un objet !
|
||||
Teleporting @1 to @2.=Téléportation de @1 vers @2.
|
||||
One does not teleport to oneself.=Impossible de se téléporter vers soi-même.
|
||||
Cannot get teleportee with name @1.=Impossible d'obtenir le téléporté @1.
|
||||
Cannot get target player with name @1.=Impossible d'obtenir le joueur cible @1.
|
||||
Teleporting @1 to @2 at @3.=Téléportation de @1 vers @2 à @3.
|
||||
<X>,<Y>,<Z> | <to_name> | <name> <X>,<Y>,<Z> | <name> <to_name>=<X>, <Y>, <Z> | <vers_nom> | <nom> <X>, <Y>, <Z> | <nom> <vers_nom>
|
||||
Teleport to position or player=Se téléporter vers une position ou un joueur.
|
||||
You don't have permission to teleport other players (missing privilege: @1).=Vous n'avez pas la permission de téléporter des joueurs (privilège manquant : @1).
|
||||
([-n] <name> <value>) | <name>=([-n] <nom> <valeur>) | <nom>
|
||||
Set or read server configuration setting=Définir ou lire un paramètre de configuration du serveur.
|
||||
Failed. Cannot modify secure settings. Edit the settings file manually.=Échoué. Impossible de modifier les paramètres sécurisés. Éditez le fichier manuellement.
|
||||
Failed. Use '/set -n <name> <value>' to create a new setting.=Échoué. Utilisez '/set -n <nom> <valeur>' pour créer un nouveau paramètre.
|
||||
@1 @= @2=@1 @= @2
|
||||
<not set>=<non défini>
|
||||
Invalid parameters (see /help set).=Paramètres invalides (voir /help set).
|
||||
Finished emerging @1 blocks in @2ms.=Fini de générer @1 blocks en @2 ms.
|
||||
emergeblocks update: @1/@2 blocks emerged (@3%)=Mise à jour de emergeblocks : @1/@2 de blocs générés (@3%)
|
||||
(here [<radius>]) | (<pos1> <pos2>)=(here [<rayon>]) | (<pos1> <pos1>)
|
||||
Load (or, if nonexistent, generate) map blocks contained in area pos1 to pos2 (<pos1> and <pos2> must be in parentheses)=Charger (ou, si inexistant, générer), des blocs contenus dans la zone de pos1 à pos2 (<pos1> et <pos2> doivent être entre parenthèses)
|
||||
Started emerge of area ranging from @1 to @2.=Début de la génération de la zone de @1 à @2.
|
||||
Delete map blocks contained in area pos1 to pos2 (<pos1> and <pos2> must be in parentheses)=Supprimer les blocs contenus dans la zone de pos1 à pos2 (<pos1> et <pos2> doivent être entre parenthèses)
|
||||
Successfully cleared area ranging from @1 to @2.=La zone de @1 à @2 a été nettoyée avec succès.
|
||||
Failed to clear one or more blocks in area.=Le nettoyage d'un ou plusieurs blocs dans la zone a echoué.
|
||||
Resets lighting in the area between pos1 and pos2 (<pos1> and <pos2> must be in parentheses)=Réinitialiser l'éclairage dans la zone de pos1 à pos2 (<pos1> et <pos2> doivent être entre parenthèses)
|
||||
Successfully reset light in the area ranging from @1 to @2.=L'éclairage dans la zone de @1 à @2 a été réinitialisé avec succès.
|
||||
Failed to load one or more blocks in area.=Le chargement d'un ou plusieurs blocs dans la zone a échoué.
|
||||
List mods installed on the server=Liste les modules installés sur le serveur.
|
||||
No mods installed.=Aucun module installé.
|
||||
Cannot give an empty item.=Impossible de donner un objet vide.
|
||||
Cannot give an unknown item.=Impossible de donner un objet inconnu.
|
||||
Giving 'ignore' is not allowed.=Donner 'ignore' n'est pas autorisé.
|
||||
@1 is not a known player.=Le joueur @1 est inconnu.
|
||||
@1 partially added to inventory.=@1 été partiellement rajouté à l'inventaire.
|
||||
@1 could not be added to inventory.=@1 n'a pas pu être rajouté à l'inventaire.
|
||||
@1 added to inventory.=@1 a été rajouté à l'inventaire.
|
||||
@1 partially added to inventory of @2.=@1 a été partiellement rajouté à l'inventaire de @2.
|
||||
@1 could not be added to inventory of @2.=@1 n'a pas pu être rajouté à l'inventaire de @2.
|
||||
@1 added to inventory of @2.=@1 a été rajouté à l'inventaire de @2.
|
||||
<name> <ItemString> [<count> [<wear>]]=<nom> <CodeObjet> [<nombre> [<usure>]]
|
||||
Give item to player=Donner un objet à un joueur
|
||||
Name and ItemString required.=Le nom et le code de l'objet sont requis
|
||||
<ItemString> [<count> [<wear>]]=<CodeObjet> [<nombre> [<usure>]]
|
||||
Give item to yourself=Donner un objet à vous-même
|
||||
ItemString required.=Code objet requis.
|
||||
<EntityName> [<X>,<Y>,<Z>]=<NomEntité> [<X>, <Y>, <Z>]
|
||||
Spawn entity at given (or your) position=Faire apparaître une entité à une position donnée (ou la vôtre)
|
||||
EntityName required.=Nom de l'entité requis.
|
||||
Unable to spawn entity, player is nil.=Impossible de faire apparaître l'entité, le joueur est inexistant.
|
||||
Cannot spawn an unknown entity.=Impossible de faire apparaître une entité inconnue.
|
||||
Invalid parameters (@1).=Paramètres invalides (@1).
|
||||
@1 spawned.=@1 a apparu.
|
||||
@1 failed to spawn.=@1 a échoué à apparaître.
|
||||
Destroy item in hand=Détruire l'objet dans la main
|
||||
Unable to pulverize, no player.=Impossible de détruire, pas de joueur.
|
||||
Unable to pulverize, no item in hand.=Impossible de détruire, pas d'objet dans la main.
|
||||
An item was pulverized.=Un objet a été détruit.
|
||||
[<range>] [<seconds>] [<limit>]=[<rayon>] [<secondes>] [<limite>]
|
||||
Check who last touched a node or a node near it within the time specified by <seconds>. Default: range @= 0, seconds @= 86400 @= 24h, limit @= 5. Set <seconds> to inf for no time limit=Vérifier qui a le dernier touché un nœud ou un autre aux environs dans le temps spécifié par <secondes>. Par défaut : rayon @= 0, secondes @= 86400 @= 24h, limite @= 5. Définissez <secondes> à inf pour aucune limite de temps.
|
||||
Rollback functions are disabled.=Les fonctions retour sont désactivées.
|
||||
That limit is too high!=Cette limite est trop grande !
|
||||
Checking @1 ...=Vérification de @1 ...
|
||||
Nobody has touched the specified location in @1 seconds.=Personne n'as touché la position spécificée dans les dernières @1 secondes.
|
||||
@1 @2 @3 -> @4 @5 seconds ago.=@1 @2 @3 -> @4 il y a @5 secondes.
|
||||
Punch a node (range@=@1, seconds@=@2, limit@=@3).=Taper un nœud (rayon @= @1, secondes @= @2, limite @= @3).
|
||||
(<name> [<seconds>]) | (:<actor> [<seconds>])=(<nom> [<secondes>]) | (:<acteur> [<secondes>])
|
||||
Revert actions of a player. Default for <seconds> is 60. Set <seconds> to inf for no time limit=Annuler les actions d'un joueur. La valeur par défaut de <secondes> est 60. Définissez <secondes> à inf pour aucune limite de temps.
|
||||
Invalid parameters. See /help rollback and /help rollback_check.=Paramètres invalides. Voir /help rollback et /help rollback_check.
|
||||
Reverting actions of player '@1' since @2 seconds.=Annuler les actions du joueur '@1' depuis @2 secondes.
|
||||
Reverting actions of @1 since @2 seconds.=Annuler les actions de @1 depuis @2 secondes.
|
||||
(log is too long to show)=(le journal est trop long à afficher)
|
||||
Reverting actions succeeded.=Les actions ont été annulées avec succès.
|
||||
Reverting actions FAILED.=L'annulation des actions a échoué.
|
||||
Show server status=Afficher le statut du serveur.
|
||||
This command was disabled by a mod or game.=Cette commande a été désactivée par un module ou un jeu.
|
||||
[<0..23>:<0..59> | <0..24000>]=[<0..23>:<0..59> | <0.24000>]
|
||||
Show or set time of day=Afficher ou définir l'heure du jour.
|
||||
Current time is @1:@2.=L'heure actuelle est @1:@2.
|
||||
You don't have permission to run this command (missing privilege: @1).=Vous n'avez pas la permission d'exécuter cette commande (privilège manquant : @1)
|
||||
Invalid time (must be between 0 and 24000).=Heure invalide (doit être comprise entre 0 et 24000).
|
||||
Time of day changed.=L'heure du jour a changé.
|
||||
Invalid hour (must be between 0 and 23 inclusive).=Heure invalide (doit être comprise entre 0 et 23 inclus).
|
||||
Invalid minute (must be between 0 and 59 inclusive).=Minute invalide (doit être comprise entre 0 et 59 inclus).
|
||||
Show day count since world creation=Afficher le nombre de jours écoulés depuis la création du monde.
|
||||
Current day is @1.=Le jour actuel est @1.
|
||||
[<delay_in_seconds> | -1] [-r] [<message>]=[<délai_en_secondes> | -1] [-r] [<message>]
|
||||
Shutdown server (-1 cancels a delayed shutdown, -r allows players to reconnect)=Éteindre le serveur (-1 annule une extinction programmée, -r autorise les joueurs à se reconnecter)
|
||||
Server shutting down (operator request).=Extinction du serveur (requête de l'opérateur).
|
||||
Ban the IP of a player or show the ban list=Bannir l'IP d'un joueur ou affiche la liste des bans.
|
||||
The ban list is empty.=La liste des bans est vide.
|
||||
Ban list: @1=Liste de bans : @1
|
||||
You cannot ban players in singleplayer!=Vous ne pouvez pas bannir des joueurs en solo !
|
||||
Player is not online.=Le joueur n'est pas en ligne.
|
||||
Failed to ban player.=Le bannissement du joueur a échoué.
|
||||
Banned @1.=@1 a été banni.
|
||||
<name> | <IP_address>=<nom> | <adresse_IP>
|
||||
Remove IP ban belonging to a player/IP=Rétablir un IP appartenant à un joueur ou une adresse IP.
|
||||
Failed to unban player/IP.=Le rétablissement du joueur ou de l'adresse IP a échoué.
|
||||
Unbanned @1.=@1 a été rétabli.
|
||||
<name> [<reason>]=<nom> [<motif>]
|
||||
Kick a player=Expulser un joueur
|
||||
Failed to kick player @1.=L'expulsion du joueur @1 a échoué.
|
||||
Kicked @1.=@1 a été expulsé.
|
||||
[full | quick]=[full | quick]
|
||||
Clear all objects in world=Nettoyer tous les objets dans le monde
|
||||
Invalid usage, see /help clearobjects.=Usage invalide, voir /help clearobjects.
|
||||
Clearing all objects. This may take a long time. You may experience a timeout. (by @1)=Nettoyage de tous les objects. Cela peut prendre du temps. Une inactivité peut surveni (par @1).
|
||||
Cleared all objects.=Tous les objets ont été nettoyés.
|
||||
<name> <message>=<nom> <message>
|
||||
Send a direct message to a player=Envoyer un message privé à un joueur.
|
||||
Invalid usage, see /help msg.=Usage invalide, voir /help msg.
|
||||
The player @1 is not online.=Le joueur @1 n'est pas en ligne.
|
||||
DM from @1: @2=Message privé de @1 : @2
|
||||
Message sent.=Message privé envoyé.
|
||||
Get the last login time of a player or yourself=Obtenir l'horodatage de la dernière connexion d'un joueur ou de vous-même.
|
||||
@1's last login time was @2.=@1 s'est connecté pour la dernière fois au @2.
|
||||
@1's last login time is unknown.=L'horodatage de la dernière connexion de @1 est inconnu.
|
||||
Clear the inventory of yourself or another player=Vider votre inventaire ou celui d'un autre joueur.
|
||||
You don't have permission to clear another player's inventory (missing privilege: @1).=Vous n'avez pas la permission de vider l'inventaire d'un autre joueur (privilège manquant : @1).
|
||||
@1 cleared your inventory.=@1 a vidé votre inventaire.
|
||||
Cleared @1's inventory.=L'inventaire de @1 a été vidé.
|
||||
Player must be online to clear inventory!=Le joueur doit être en ligne pour pouvoir vider son inventaire.
|
||||
Players can't be killed, damage has been disabled.=Les joueurs ne peuvent pas être tués, les dommages ont été désactivés.
|
||||
Player @1 is not online.=Le joueur @1 n'est pas en ligne.
|
||||
You are already dead.=Vous êtes déjà mort.
|
||||
@1 is already dead.=@1 est déjà mort.
|
||||
@1 has been killed.=@1 a été tué.
|
||||
Kill player or yourself=Tuer un joueur ou vous-même.
|
||||
@1 joined the game.=@1 a rejoint la partie.
|
||||
@1 left the game.=@1 a quitté la partie.
|
||||
@1 left the game (timed out).=@1 a quitté la partie (inactivité).
|
||||
(no description)=(sans description)
|
||||
Can interact with things and modify the world=Peut interagir avec des éléments ou modifier le monde.
|
||||
Can speak in chat=Peut écrire dans le tchat.
|
||||
Can modify basic privileges (@1)=Peut modifier les privilèges basiques (@1)
|
||||
Can modify privileges=Peut modifier les privilèges
|
||||
Can teleport self=Peut se téléporter
|
||||
Can teleport other players=Peut téléporter d'autres joueurs
|
||||
Can set the time of day using /time=Peut définir l'heure du jour avec /time
|
||||
Can do server maintenance stuff=Peut effectuer des tâches de maintenance du serveur
|
||||
Can bypass node protection in the world=Peut outrepasser la protection des nœuds dans le monde.
|
||||
Can ban and unban players=Peut bannir et rétablir des joueurs.
|
||||
Can kick players=Peut expulser des joueurs.
|
||||
Can use /give and /giveme=Peut utiliser /give et /giveme
|
||||
Can use /setpassword and /clearpassword=Peut utiliser /setpassword et /clearpassword
|
||||
Can use fly mode=Peut utiliser le mode vol
|
||||
Can use fast mode=Peut utiliser le mode rapide
|
||||
Can fly through solid nodes using noclip mode=Peut voler à travers des nœuds solides en utilisant le mode de collisions désactivées.
|
||||
Can use the rollback functionality=Peut utiliser la fonctionnalité de retour
|
||||
Can enable wireframe=Peut activer la vue fil de fer
|
||||
Unknown Item=Objet inconnu
|
||||
Air=Air
|
||||
Ignore=Ignorer
|
||||
You can't place 'ignore' nodes!=Vous ne pouvez pas placé de nœuds 'ignorés' !
|
||||
print [<filter>] | dump [<filter>] | save [<format> [<filter>]] | reset=print [<filtre>] | dump [<filtre>] | save [<format> [<filtre>]] | reset
|
||||
Handle the profiler and profiling data=Traiter le profileur et les données de profilage
|
||||
Statistics written to action log.=Les statistiques sont écrites dans les journaux d'actions.
|
||||
Statistics were reset.=Les statistiques ont été réinitialisées.
|
||||
Usage: @1=Usage : @1
|
||||
Format can be one of txt, csv, lua, json, json_pretty (structures may be subject to change).=Le format peut être txt, csv, lua, json ou json_pretty (les structures sont sujettes au changement).
|
||||
Values below show absolute/relative times spend per server step by the instrumented function.=Les valeurs inférieures affichent les temps absolu et relatif dépensés par étape du serveur par la fonction utilisée.
|
||||
A total of @1 sample(s) were taken.=@1 échantillons ont été collectés.
|
||||
The output is limited to '@1'.=La sortie est limitée à '@1'.
|
||||
Saving of profile failed: @1=La sauvegarde du profil a échoué : @1
|
||||
Profile saved to @1=Le profil a été sauvegardé dans @1
|
||||
246
builtin/locale/__builtin.pt_BR.tr
Normal file
246
builtin/locale/__builtin.pt_BR.tr
Normal file
@@ -0,0 +1,246 @@
|
||||
# textdomain: __builtin
|
||||
Invalid parameters (see /help @1).=Parâmetros inválidos (veja /help @1).
|
||||
Too many arguments, try using just /help <command>=Muitos argumentos, tente usar apenas /help <comando>
|
||||
Available commands: @1=Comandos disponíveis: @1
|
||||
Use '/help <cmd>' to get more information, or '/help all' to list everything.=Use '/help <cmd>' para obter mais informações, ou '/help all' para listar tudo.
|
||||
Available commands:=Comandos disponíveis:
|
||||
Command not available: @1=Comando não disponível: @1
|
||||
[all | privs | <cmd>] [-t]=[all | privs | <cmd>] [-t]
|
||||
Get help for commands or list privileges (-t: output in chat)=Obtenha ajuda para comandos ou liste privilégios (-t: saída no chat)
|
||||
Available privileges:=Privilégios disponíveis:
|
||||
Command=Comando
|
||||
Parameters=Parâmetros
|
||||
For more information, click on any entry in the list.=Para mais informações, clique em qualquer entrada na lista.
|
||||
Double-click to copy the entry to the chat history.=Clique duas vezes para copiar a entrada para o histórico do chat.
|
||||
Command: @1 @2=Comando: @1 @2
|
||||
Available commands: (see also: /help <cmd>)=Comandos disponíveis: (veja também: /help <cmd>)
|
||||
Close=Fechar
|
||||
Privilege=Privilégio
|
||||
Description=Descrição
|
||||
Empty command.=Comando vazio.
|
||||
Invalid command: @1=Comando inválido: @1
|
||||
Invalid command usage.=Uso de comando inválido.
|
||||
(@1 s)= (@1 s)
|
||||
Command execution took @1 s=A execução do comando levou @1 s
|
||||
You don't have permission to run this command (missing privileges: @1).=Você não tem permissão para executar este comando (privilégios faltando: @1).
|
||||
Unable to get position of player @1.=Incapaz de obter a posição do jogador @1.
|
||||
Incorrect area format. Expected: (x1,y1,z1) (x2,y2,z2)=Formato de área incorreto. Esperado: (x1,y1,z1) (x2,y2,z2)
|
||||
<action>=<ação>
|
||||
Show chat action (e.g., '/me orders a pizza' displays '<player name> orders a pizza')=Mostra a ação do chat (por exemplo, '/me orders a pizza' exibe '<nome do jogador> pede uma pizza')
|
||||
Show the name of the server owner=Mostra o nome do dono do servidor
|
||||
The administrator of this server is @1.=O administrador deste servidor é @1.
|
||||
There's no administrator named in the config file.=Não há administrador nomeado no arquivo de configuração.
|
||||
@1 does not have any privileges.=@1 não tem nenhum privilégio.
|
||||
Privileges of @1: @2=Privilégios de @1: @2
|
||||
[<name>]=[<nome>]
|
||||
Show privileges of yourself or another player=Mostrar privilégios seus ou de outro jogador
|
||||
Player @1 does not exist.=O jogador @1 não existe.
|
||||
<privilege>=<privilégio>
|
||||
Return list of all online players with privilege=Retornar lista de todos os jogadores online com privilégio
|
||||
Invalid parameters (see /help haspriv).=Parâmetros inválidos (veja /help haspriv).
|
||||
Unknown privilege!=Privilégio desconhecido!
|
||||
No online player has the "@1" privilege.=Nenhum jogador online tem o privilégio "@1".
|
||||
Players online with the "@1" privilege: @2=Jogadores online com o privilégio "@1": @2
|
||||
Your privileges are insufficient.=Seus privilégios são insuficientes.
|
||||
Your privileges are insufficient. '@1' only allows you to grant: @2=Seus privilégios são insuficientes. '@1' só permite que você conceda: @2
|
||||
Unknown privilege: @1=Privilégio desconhecido: @1
|
||||
@1 granted you privileges: @2=@1 concedeu-lhe privilégios: @2
|
||||
<name> (<privilege> [, <privilege2> [<...>]] | all)=<nome> (<privilégio> [, <privilégio2> [<...>]] | all)
|
||||
Give privileges to player=Conceder privilégios ao jogador
|
||||
Invalid parameters (see /help grant).=Parâmetros inválidos (veja /help grant).
|
||||
<privilege> [, <privilege2> [<...>]] | all=<privilégio> [, <privilégio2> [<...>]] | all
|
||||
Grant privileges to yourself=Concede privilégios a você mesmo
|
||||
Invalid parameters (see /help grantme).=Parâmetros inválidos (veja /help grantme).
|
||||
Your privileges are insufficient. '@1' only allows you to revoke: @2=Seus privilégios são insuficientes. '@1' só permite que você revogue: @2
|
||||
Note: Cannot revoke in singleplayer: @1=Nota: Não é possível revogar em singleplayer: @1
|
||||
Note: Cannot revoke from admin: @1=Nota: Não é possível revogar do administrador: @1
|
||||
No privileges were revoked.=Nenhum privilégio foi revogado.
|
||||
@1 revoked privileges from you: @2=@1 revogou seus privilégios: @2
|
||||
Remove privileges from player=Remover privilégios do jogador
|
||||
Invalid parameters (see /help revoke).=Parâmetros inválidos (veja /help revoke).
|
||||
Revoke privileges from yourself=Revogar privilégios de si mesmo
|
||||
Invalid parameters (see /help revokeme).=Parâmetros inválidos (veja /help revokeme).
|
||||
<name> <password>=<nome> <senha>
|
||||
Set player's password (sent unencrypted, thus insecure)=Definir a senha do jogador (enviada sem criptografia, portanto insegura)
|
||||
Name field required.=Campo de nome obrigatório.
|
||||
Your password was cleared by @1.=Sua senha foi limpa por @1.
|
||||
Password of player "@1" cleared.=Senha do jogador "@1" limpa.
|
||||
Your password was set by @1.=Sua senha foi definida por @1.
|
||||
Password of player "@1" set.=Senha do jogador "@1" definida.
|
||||
<name>=<nome>
|
||||
Set empty password for a player=Definir senha vazia para um jogador
|
||||
Reload authentication data=Recarregar dados de autenticação
|
||||
Done.=Pronto.
|
||||
Failed.=Erro.
|
||||
Remove a player's data=Remover dados de um jogador
|
||||
Player "@1" removed.=Jogador "@1" removido.
|
||||
No such player "@1" to remove.=Não existe tal jogador "@1" para remover.
|
||||
Player "@1" is connected, cannot remove.=Jogador "@1" está conectado, não pode ser removido.
|
||||
Unhandled remove_player return code @1.=Código de retorno remove_player não tratado @1.
|
||||
Cannot teleport out of map bounds!=Não é possível teleportar para fora dos limites do mapa!
|
||||
Cannot get player with name @1.=Não é possível obter jogador com o nome @1.
|
||||
Cannot teleport, @1 is attached to an object!=Não é possível teleportar, @1 está anexado a um objeto!
|
||||
Teleporting @1 to @2.=Teleportando @1 para @2.
|
||||
One does not teleport to oneself.=Não tem como se teletransportar para você mesmo.
|
||||
Cannot get teleportee with name @1.=Não é possível teletransportar com o nome @1.
|
||||
Cannot get target player with name @1.=Não é possível obter jogador alvo com o nome @1.
|
||||
Teleporting @1 to @2 at @3.=Teleportando @1 para @2 em @3.
|
||||
<X>,<Y>,<Z> | <to_name> | <name> <X>,<Y>,<Z> | <name> <to_name>=<X>,<Y>,<Z> | <para_nome> | <nome> <X>,<Y>,<Z> | <nome> <para_nome>
|
||||
Teleport to position or player=Teleportar para posição ou um jogador
|
||||
You don't have permission to teleport other players (missing privilege: @1).=Você não tem permissão para teleportar outros jogadores (privilégio faltando: @1).
|
||||
([-n] <name> <value>) | <name>=([-n] <nome> <valor>) | <nome>
|
||||
Set or read server configuration setting=Definir ou ler configuração do servidor
|
||||
Failed. Cannot modify secure settings. Edit the settings file manually.=Falha. Não é possível modificar configurações seguras. Edite o arquivo de configurações manualmente.
|
||||
Failed. Use '/set -n <name> <value>' to create a new setting.=Falhou. Use '/set -n <nome> <valor>' para criar uma nova configuração.
|
||||
@1 @= @2=@1 @= @2
|
||||
<not set>=<não definido>
|
||||
Invalid parameters (see /help set).=Parâmetros inválidos (veja /help set).
|
||||
Finished emerging @1 blocks in @2ms.=Finalizada a emergência de @1 blocos em @2ms.
|
||||
emergeblocks update: @1/@2 blocks emerged (@3%)=atualização de emergeblocks: @1/@2 blocos emergidos (@3%)
|
||||
(here [<radius>]) | (<pos1> <pos2>)=(aqui [<raio>]) | (<pos1> <pos2>)
|
||||
Load (or, if nonexistent, generate) map blocks contained in area pos1 to pos2 (<pos1> and <pos2> must be in parentheses)=Carregar (ou, se inexistente, gerar) blocos de mapa contidos na área pos1 a pos2 (<pos1> e <pos2> devem estar entre parênteses)
|
||||
Started emerge of area ranging from @1 to @2.=Iniciada o surgimento de áreas que vão de @1 a @2.
|
||||
Delete map blocks contained in area pos1 to pos2 (<pos1> and <pos2> must be in parentheses)=Excluir blocos de mapa contidos na área pos1 a pos2 (<pos1> e <pos2> devem estar entre parênteses)
|
||||
Successfully cleared area ranging from @1 to @2.=Área limpa com sucesso variando de @1 a @2.
|
||||
Failed to clear one or more blocks in area.=Falha ao limpar um ou mais blocos na área.
|
||||
Resets lighting in the area between pos1 and pos2 (<pos1> and <pos2> must be in parentheses)=Redefine a iluminação na área entre pos1 e pos2 (<pos1> e <pos2> devem estar entre parênteses)
|
||||
Successfully reset light in the area ranging from @1 to @2.=Iluminação redefinida com sucesso na área variando de @1 a @2.
|
||||
Failed to load one or more blocks in area.=Falha ao carregar um ou mais blocos na área.
|
||||
List mods installed on the server=Listar mods instalados no servidor
|
||||
No mods installed.=Sem mods instalados.
|
||||
Cannot give an empty item.=Não é possível dar um item vazio.
|
||||
Cannot give an unknown item.=Não é possível dar um item desconhecido.
|
||||
Giving 'ignore' is not allowed.=Não é permitido dar 'ignore'.
|
||||
@1 is not a known player.=@1 não é um jogador conhecido.
|
||||
@1 partially added to inventory.=@1 parcialmente adicionado ao inventário.
|
||||
@1 could not be added to inventory.=@1 não pôde ser adicionado ao inventário.
|
||||
@1 added to inventory.=@1 adicionado ao inventário.
|
||||
@1 partially added to inventory of @2.=@1 parcialmente adicionado ao inventário de @2.
|
||||
@1 could not be added to inventory of @2.=@1 não pôde ser adicionado ao inventário de @2.
|
||||
@1 added to inventory of @2.=@1 adicionado ao inventário de @2.
|
||||
<name> <ItemString> [<count> [<wear>]]=<nome> <ItemString> [<quantidade> [<desgaste>]]
|
||||
Give item to player=Dar item ao jogador
|
||||
Name and ItemString required.=Nome e ItemString são obrigatórios.
|
||||
<ItemString> [<count> [<wear>]]=<ItemString> [<quantidade> [<desgaste>]]
|
||||
Give item to yourself=Dar item a si mesmo
|
||||
ItemString required.=ItemString é obrigatório.
|
||||
<EntityName> [<X>,<Y>,<Z>]=<NomeDaEntidade> [<X>,<Y>,<Z>]
|
||||
Spawn entity at given (or your) position=Gerar entidade na posição fornecida (ou na sua)
|
||||
EntityName required.=NomeDaEntidade é obrigatório.
|
||||
Unable to spawn entity, player is nil.=Não é possível gerar a entidade, jogador é nulo.
|
||||
Cannot spawn an unknown entity.=Não é possível gerar uma entidade desconhecida.
|
||||
Invalid parameters (@1).=Parâmetros inválidos (@1).
|
||||
@1 spawned.=@1 gerado.
|
||||
@1 failed to spawn.=Falha ao gerar @1.
|
||||
Destroy item in hand=Destruir item na mão
|
||||
Unable to pulverize, no player.=Incapaz de pulverizar, sem jogador.
|
||||
Unable to pulverize, no item in hand.=Incapaz de pulverizar, sem item na mão.
|
||||
An item was pulverized.=Um item foi pulverizado.
|
||||
[<range>] [<seconds>] [<limit>]=[<alcance>] [<segundos>] [<limite>]
|
||||
Check who last touched a node or a node near it within the time specified by <seconds>. Default: range @= 0, seconds @= 86400 @= 24h, limit @= 5. Set <seconds> to inf for no time limit=Verificar quem tocou pela última vez um nó ou um nó próximo dentro do tempo especificado por <segundos>. Padrão: alcance @= 0, segundos @= 86400 @= 24h, limite @= 5. Defina <segundos> como inf para sem limite de tempo
|
||||
Rollback functions are disabled.=Funções de rollback estão desativadas.
|
||||
That limit is too high!=Esse limite é muito alto!
|
||||
Checking @1 ...=Verificando @1 ...
|
||||
Nobody has touched the specified location in @1 seconds.=Ninguém tocou a localização especificada em @1 segundos.
|
||||
@1 @2 @3 -> @4 @5 seconds ago.=@1 @2 @3 -> @4 @5 segundos atrás.
|
||||
Punch a node (range@=@1, seconds@=@2, limit@=@3).=Golpeie um nó (alcance@=@1, segundos@=@2, limite@=@3).
|
||||
(<name> [<seconds>]) | (:<actor> [<seconds>])=(<nome> [<segundos>]) | (:<ator> [<segundos>])
|
||||
Revert actions of a player. Default for <seconds> is 60. Set <seconds> to inf for no time limit=Reverter ações de um jogador. O padrão para <segundos> é 60. Defina <segundos> como inf para sem limite de tempo
|
||||
Invalid parameters. See /help rollback and /help rollback_check.=Parâmetros inválidos. Veja /help rollback e /help rollback_check.
|
||||
Reverting actions of player '@1' since @2 seconds.=Revertendo ações do jogador '@1' desde @2 segundos.
|
||||
Reverting actions of @1 since @2 seconds.=Revertendo ações de @1 desde @2 segundos.
|
||||
(log is too long to show)=O log é muito longo para mostrar
|
||||
Reverting actions succeeded.=Ações revertidas com sucesso.
|
||||
Reverting actions FAILED.=Reversão de ações FALHOU.
|
||||
Show server status=Mostrar status do servidor
|
||||
This command was disabled by a mod or game.=Este comando foi desativado por um mod ou jogo.
|
||||
[<0..23>:<0..59> | <0..24000>]=[<0..23>:<0..59> | <0..24000>]
|
||||
Show or set time of day=Mostrar ou definir hora do dia
|
||||
Current time is @1:@2.=A hora atual é @1:@2.
|
||||
You don't have permission to run this command (missing privilege: @1).=Você não tem permissão para executar este comando (privilégio faltando: @1).
|
||||
Invalid time (must be between 0 and 24000).=Hora inválida (deve estar entre 0 e 24000).
|
||||
Time of day changed.=Hora do dia alterada.
|
||||
Invalid hour (must be between 0 and 23 inclusive).=Hora inválida (deve estar entre 0 e 23 inclusivo).
|
||||
Invalid minute (must be between 0 and 59 inclusive).=Minuto inválido (deve estar entre 0 e 59 inclusivo).
|
||||
Show day count since world creation=Mostrar contagem de dias desde a criação do mundo
|
||||
Current day is @1.=O dia atual é @1.
|
||||
[<delay_in_seconds> | -1] [-r] [<message>]=[<atraso_em_segundos> | -1] [-r] [<mensagem>]
|
||||
Shutdown server (-1 cancels a delayed shutdown, -r allows players to reconnect)=Desligar servidor (-1 cancela o desligamento adiado, -r permite que os jogadores se reconectem)
|
||||
Server shutting down (operator request).=Servidor desligando (solicitação do operador).
|
||||
Ban the IP of a player or show the ban list=Banir o IP de um jogador ou mostrar a lista de banimentos
|
||||
The ban list is empty.=A lista de banimentos está vazia.
|
||||
Ban list: @1=Lista de banimentos: @1
|
||||
You cannot ban players in singleplayer!=Você não pode banir jogadores em singleplayer!
|
||||
Player is not online.=Jogador não está online.
|
||||
Failed to ban player.=Falha ao banir jogador.
|
||||
Banned @1.=Banido @1.
|
||||
<name> | <IP_address>=<nome> | <endereço_IP>
|
||||
Remove IP ban belonging to a player/IP=Remover banimento de IP pertencente a um jogador/IP
|
||||
Failed to unban player/IP.=Falha ao desbanir jogador/IP.
|
||||
Unbanned @1.=Desbanido @1.
|
||||
<name> [<reason>]=<nome> [<motivo>]
|
||||
Kick a player=Expulsar um jogador
|
||||
Failed to kick player @1.=Falha ao expulsar jogador @1.
|
||||
Kicked @1.=Expulso @1.
|
||||
[full | quick]=[full | quick]
|
||||
Clear all objects in world=Limpar todos os objetos no mundo
|
||||
Invalid usage, see /help clearobjects.=Uso inválido, veja /help clearobjects.
|
||||
Clearing all objects. This may take a long time. You may experience a timeout. (by @1)=Limpeza de todos os objetos. Isso pode levar muito tempo. Você pode experimentar um tempo limite. (por @1)
|
||||
Cleared all objects.=Todos os objetos foram limpos.
|
||||
<name> <message>=<nome> <mensagem>
|
||||
Send a direct message to a player=Enviar uma mensagem direta a um jogador
|
||||
Invalid usage, see /help msg.=Uso inválido, veja /help msg.
|
||||
The player @1 is not online.=O jogador @1 não está online.
|
||||
DM from @1: @2=DM de @1: @2
|
||||
Message sent.=Mensagem enviada.
|
||||
Get the last login time of a player or yourself=Pegue o último horário de login de um jogador ou de você mesmo
|
||||
@1's last login time was @2.=O último login de @1 foi às @2.
|
||||
@1's last login time is unknown.=O último login de @1 é desconhecido.
|
||||
Clear the inventory of yourself or another player=Limpar o inventário de você mesmo ou de outro jogador
|
||||
You don't have permission to clear another player's inventory (missing privilege: @1).=Você não tem permissão para limpar o inventário de outro jogador (privilégio faltando: @1).
|
||||
@1 cleared your inventory.=@1 limpou seu inventário.
|
||||
Cleared @1's inventory.=Inventário de @1 limpo.
|
||||
Player must be online to clear inventory!=O jogador deve estar online para limpar o inventário!
|
||||
Players can't be killed, damage has been disabled.=Jogadores não podem ser mortos, o dano foi desativado.
|
||||
Player @1 is not online.=Jogador @1 não está online.
|
||||
You are already dead.=Você já está morto.
|
||||
@1 is already dead.=@1 já está morto.
|
||||
@1 has been killed.=@1 foi morto.
|
||||
Kill player or yourself=Matar jogador ou a si mesmo
|
||||
@1 joined the game.=@1 entrou no jogo.
|
||||
@1 left the game.=@1 saiu do jogo.
|
||||
@1 left the game (timed out).=@1 saiu do jogo (tempo esgotado)
|
||||
(no description)=(sem descrição)
|
||||
Can interact with things and modify the world=Pode interagir com as coisas e modificar o mundo
|
||||
Can speak in chat=Pode falar no chat
|
||||
Can modify basic privileges (@1)=Pode modificar privilégios básicos (@1)
|
||||
Can modify privileges=Pode modificar privilégios
|
||||
Can teleport self=Pode se teletransportar
|
||||
Can teleport other players=Pode teletransportar outros jogadores
|
||||
Can set the time of day using /time=Pode definir a hora do dia usando /time
|
||||
Can do server maintenance stuff=Pode realizar tarefas de manutenção do servidor
|
||||
Can bypass node protection in the world=Pode ignorar a proteção de nós no mundo
|
||||
Can ban and unban players=Pode banir e desbanir jogadores
|
||||
Can kick players=Pode chutar jogadores
|
||||
Can use /give and /giveme=Pode usar /give e /giveme
|
||||
Can use /setpassword and /clearpassword=Pode usar /setpassword e /clearpassword
|
||||
Can use fly mode=Pode usar o modo voar
|
||||
Can use fast mode=Pode usar o modo rápido
|
||||
Can fly through solid nodes using noclip mode=Pode voar através de nós sólidos usando o modo noclip
|
||||
Can use the rollback functionality=Pode usar a funcionalidade de reversão
|
||||
Can enable wireframe=Pode ativar wireframe
|
||||
Unknown Item=Item desconhecido
|
||||
Air=Ar
|
||||
Ignore=Ignorar
|
||||
You can't place 'ignore' nodes!=Você não pode colocar nós 'ignorar'!
|
||||
print [<filter>] | dump [<filter>] | save [<format> [<filter>]] | reset=print [<filtro>] | dump [<filtro>] | save [<formato> [<filtro>]] | reset
|
||||
Handle the profiler and profiling data=Lidar com o criador de perfil e os dados de criação de perfil
|
||||
Statistics written to action log.=Estatísticas salvas no log de ações.
|
||||
Statistics were reset.=As estatísticas foram redefinidas.
|
||||
Usage: @1=Uso: @1
|
||||
Format can be one of txt, csv, lua, json, json_pretty (structures may be subject to change).=O formato pode ser txt, csv, lua, json, json_pretty (as estruturas podem estar sujeitas a alterações).
|
||||
Values below show absolute/relative times spend per server step by the instrumented function.=Os valores abaixo mostram os tempos absolutos/relativos gastos por etapa do servidor pela função instrumentada.
|
||||
A total of @1 sample(s) were taken.=Um total de @1 amostra(s) foi coletada.
|
||||
The output is limited to '@1'.=A saída é limitada a '@1'.
|
||||
Saving of profile failed: @1=Falha ao salvar o perfil: @1
|
||||
Profile saved to @1=Perfil salvo em @1
|
||||
@@ -18,6 +18,26 @@
|
||||
-- Global menu data
|
||||
menudata = {}
|
||||
|
||||
-- located in user cache path, for remembering this like e.g. last update check
|
||||
cache_settings = Settings(core.get_cache_path() .. DIR_DELIM .. "common.conf")
|
||||
|
||||
--- Checks if the given key contains a timestamp less than a certain age.
|
||||
--- Pair this with a call to `cache_settings:set(key, tostring(os.time()))`
|
||||
--- after successfully refreshing the cache.
|
||||
--- @param key Name of entry in cache_settings
|
||||
--- @param max_age Age to check against, in seconds
|
||||
--- @return true if the max age is not reached
|
||||
function check_cache_age(key, max_age)
|
||||
local time_now = os.time()
|
||||
local time_checked = tonumber(cache_settings:get(key)) or 0
|
||||
return time_now - time_checked < max_age
|
||||
end
|
||||
|
||||
function core.on_before_close()
|
||||
-- called before the menu is closed, either exit or to join a game
|
||||
cache_settings:write()
|
||||
end
|
||||
|
||||
-- Local cached values
|
||||
local min_supp_proto, max_supp_proto
|
||||
|
||||
@@ -27,6 +47,16 @@ function common_update_cached_supp_proto()
|
||||
end
|
||||
common_update_cached_supp_proto()
|
||||
|
||||
-- Other global functions
|
||||
|
||||
function core.sound_stop(handle, ...)
|
||||
return handle:stop(...)
|
||||
end
|
||||
|
||||
function os.tmpname()
|
||||
error('do not use') -- instead: core.get_temp_path()
|
||||
end
|
||||
|
||||
-- Menu helper functions
|
||||
|
||||
local function render_client_count(n)
|
||||
@@ -140,11 +170,6 @@ function render_serverlist_row(spec)
|
||||
|
||||
return table.concat(details, ",")
|
||||
end
|
||||
---------------------------------------------------------------------------------
|
||||
os.tmpname = function()
|
||||
error('do not use') -- instead use core.get_temp_path()
|
||||
end
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
function menu_render_worldlist()
|
||||
local retval = {}
|
||||
|
||||
583
builtin/mainmenu/content/contentdb.lua
Normal file
583
builtin/mainmenu/content/contentdb.lua
Normal file
@@ -0,0 +1,583 @@
|
||||
--Minetest
|
||||
--Copyright (C) 2018-24 rubenwardy
|
||||
--
|
||||
--This program is free software; you can redistribute it and/or modify
|
||||
--it under the terms of the GNU Lesser General Public License as published by
|
||||
--the Free Software Foundation; either version 2.1 of the License, or
|
||||
--(at your option) any later version.
|
||||
--
|
||||
--This program is distributed in the hope that it will be useful,
|
||||
--but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
--GNU Lesser General Public License for more details.
|
||||
--
|
||||
--You should have received a copy of the GNU Lesser General Public License along
|
||||
--with this program; if not, write to the Free Software Foundation, Inc.,
|
||||
--51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
|
||||
if not core.get_http_api then
|
||||
return
|
||||
end
|
||||
|
||||
|
||||
contentdb = {
|
||||
loading = false,
|
||||
load_ok = false,
|
||||
load_error = false,
|
||||
|
||||
-- Unordered preserves the original order of the ContentDB API,
|
||||
-- before the package list is ordered based on installed state.
|
||||
packages = {},
|
||||
packages_full = {},
|
||||
packages_full_unordered = {},
|
||||
package_by_id = {},
|
||||
aliases = {},
|
||||
|
||||
number_downloading = 0,
|
||||
download_queue = {},
|
||||
|
||||
REASON_NEW = "new",
|
||||
REASON_UPDATE = "update",
|
||||
REASON_DEPENDENCY = "dependency",
|
||||
}
|
||||
|
||||
|
||||
local function get_download_url(package, reason)
|
||||
local base_url = core.settings:get("contentdb_url")
|
||||
local ret = base_url .. ("/packages/%s/releases/%d/download/"):format(
|
||||
package.url_part, package.release)
|
||||
if reason then
|
||||
ret = ret .. "?reason=" .. reason
|
||||
end
|
||||
return ret
|
||||
end
|
||||
|
||||
|
||||
local function download_and_extract(param)
|
||||
local package = param.package
|
||||
|
||||
local filename = core.get_temp_path(true)
|
||||
if filename == "" or not core.download_file(param.url, filename) then
|
||||
core.log("error", "Downloading " .. dump(param.url) .. " failed")
|
||||
return {
|
||||
msg = fgettext_ne("Failed to download \"$1\"", package.title)
|
||||
}
|
||||
end
|
||||
|
||||
local tempfolder = core.get_temp_path()
|
||||
if tempfolder ~= "" and not core.extract_zip(filename, tempfolder) then
|
||||
tempfolder = ""
|
||||
end
|
||||
os.remove(filename)
|
||||
if tempfolder == "" then
|
||||
return {
|
||||
msg = fgettext_ne("Failed to extract \"$1\" " ..
|
||||
"(insufficient disk space, unsupported file type or broken archive)",
|
||||
package.title),
|
||||
}
|
||||
end
|
||||
|
||||
return {
|
||||
path = tempfolder
|
||||
}
|
||||
end
|
||||
|
||||
|
||||
local function start_install(package, reason)
|
||||
local params = {
|
||||
package = package,
|
||||
url = get_download_url(package, reason),
|
||||
}
|
||||
|
||||
contentdb.number_downloading = contentdb.number_downloading + 1
|
||||
|
||||
local function callback(result)
|
||||
if result.msg then
|
||||
gamedata.errormessage = result.msg
|
||||
else
|
||||
local path, msg = pkgmgr.install_dir(package.type, result.path, package.name, package.path)
|
||||
core.delete_dir(result.path)
|
||||
if not path then
|
||||
gamedata.errormessage = fgettext_ne("Error installing \"$1\": $2", package.title, msg)
|
||||
else
|
||||
core.log("action", "Installed package to " .. path)
|
||||
|
||||
local conf_path
|
||||
local name_is_title = false
|
||||
if package.type == "mod" then
|
||||
local actual_type = pkgmgr.get_folder_type(path)
|
||||
if actual_type.type == "modpack" then
|
||||
conf_path = path .. DIR_DELIM .. "modpack.conf"
|
||||
else
|
||||
conf_path = path .. DIR_DELIM .. "mod.conf"
|
||||
end
|
||||
elseif package.type == "game" then
|
||||
conf_path = path .. DIR_DELIM .. "game.conf"
|
||||
name_is_title = true
|
||||
elseif package.type == "txp" then
|
||||
conf_path = path .. DIR_DELIM .. "texture_pack.conf"
|
||||
end
|
||||
|
||||
if conf_path then
|
||||
local conf = Settings(conf_path)
|
||||
if not conf:get("title") then
|
||||
conf:set("title", package.title)
|
||||
end
|
||||
if not name_is_title then
|
||||
conf:set("name", package.name)
|
||||
end
|
||||
if not conf:get("description") then
|
||||
conf:set("description", package.short_description)
|
||||
end
|
||||
conf:set("author", package.author)
|
||||
conf:set("release", package.release)
|
||||
conf:write()
|
||||
end
|
||||
|
||||
pkgmgr.reload_by_type(package.type)
|
||||
end
|
||||
end
|
||||
|
||||
package.downloading = false
|
||||
|
||||
contentdb.number_downloading = contentdb.number_downloading - 1
|
||||
|
||||
local next = contentdb.download_queue[1]
|
||||
if next then
|
||||
table.remove(contentdb.download_queue, 1)
|
||||
|
||||
start_install(next.package, next.reason)
|
||||
end
|
||||
ui.update()
|
||||
end
|
||||
|
||||
package.queued = false
|
||||
package.downloading = true
|
||||
|
||||
if not core.handle_async(download_and_extract, params, callback) then
|
||||
core.log("error", "ERROR: async event failed")
|
||||
gamedata.errormessage = fgettext_ne("Failed to download $1", package.name)
|
||||
return
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
function contentdb.queue_download(package, reason)
|
||||
if package.queued or package.downloading then
|
||||
return
|
||||
end
|
||||
|
||||
local max_concurrent_downloads = tonumber(core.settings:get("contentdb_max_concurrent_downloads"))
|
||||
if contentdb.number_downloading < math.max(max_concurrent_downloads, 1) then
|
||||
start_install(package, reason)
|
||||
else
|
||||
table.insert(contentdb.download_queue, { package = package, reason = reason })
|
||||
package.queued = true
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
function contentdb.get_package_by_id(id)
|
||||
return contentdb.package_by_id[id]
|
||||
end
|
||||
|
||||
|
||||
-- Create a coroutine from `fn` and provide results to `callback` when complete (dead).
|
||||
-- Returns a resumer function.
|
||||
local function make_callback_coroutine(fn, callback)
|
||||
local co = coroutine.create(fn)
|
||||
|
||||
local function resumer(...)
|
||||
local ok, result = coroutine.resume(co, ...)
|
||||
|
||||
if not ok then
|
||||
error(result)
|
||||
elseif coroutine.status(co) == "dead" then
|
||||
callback(result)
|
||||
end
|
||||
end
|
||||
|
||||
return resumer
|
||||
end
|
||||
|
||||
|
||||
local function get_raw_dependencies_async(package)
|
||||
local url_fmt = "/api/packages/%s/dependencies/?only_hard=1&protocol_version=%s&engine_version=%s"
|
||||
local version = core.get_version()
|
||||
local base_url = core.settings:get("contentdb_url")
|
||||
local url = base_url .. url_fmt:format(package.url_part, core.get_max_supp_proto(), core.urlencode(version.string))
|
||||
|
||||
local http = core.get_http_api()
|
||||
local response = http.fetch_sync({ url = url })
|
||||
if not response.succeeded then
|
||||
return nil
|
||||
end
|
||||
return core.parse_json(response.data) or {}
|
||||
end
|
||||
|
||||
|
||||
local function get_raw_dependencies_co(package, resumer)
|
||||
if package.type ~= "mod" then
|
||||
return {}
|
||||
end
|
||||
if package.raw_deps then
|
||||
return package.raw_deps
|
||||
end
|
||||
|
||||
core.handle_async(get_raw_dependencies_async, package, resumer)
|
||||
local data = coroutine.yield()
|
||||
if not data then
|
||||
return nil
|
||||
end
|
||||
|
||||
for id, raw_deps in pairs(data) do
|
||||
local package2 = contentdb.package_by_id[id:lower()]
|
||||
if package2 and not package2.raw_deps then
|
||||
package2.raw_deps = raw_deps
|
||||
|
||||
for _, dep in pairs(raw_deps) do
|
||||
local packages = {}
|
||||
for i=1, #dep.packages do
|
||||
packages[#packages + 1] = contentdb.package_by_id[dep.packages[i]:lower()]
|
||||
end
|
||||
dep.packages = packages
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
return package.raw_deps
|
||||
end
|
||||
|
||||
|
||||
local function has_hard_deps_co(package, resumer)
|
||||
local raw_deps = get_raw_dependencies_co(package, resumer)
|
||||
if not raw_deps then
|
||||
return nil
|
||||
end
|
||||
|
||||
for i=1, #raw_deps do
|
||||
if not raw_deps[i].is_optional then
|
||||
return true
|
||||
end
|
||||
end
|
||||
|
||||
return false
|
||||
end
|
||||
|
||||
|
||||
function contentdb.has_hard_deps(package, callback)
|
||||
local resumer = make_callback_coroutine(has_hard_deps_co, callback)
|
||||
resumer(package, resumer)
|
||||
end
|
||||
|
||||
|
||||
-- Recursively resolve dependencies, given the installed mods
|
||||
local function resolve_dependencies_2_co(raw_deps, installed_mods, out, resumer)
|
||||
local function resolve_dep(dep)
|
||||
-- Check whether it's already installed
|
||||
if installed_mods[dep.name] then
|
||||
return {
|
||||
is_optional = dep.is_optional,
|
||||
name = dep.name,
|
||||
installed = true,
|
||||
}
|
||||
end
|
||||
|
||||
-- Find exact name matches
|
||||
local fallback
|
||||
for _, package in pairs(dep.packages) do
|
||||
if package.type ~= "game" then
|
||||
if package.name == dep.name then
|
||||
return {
|
||||
is_optional = dep.is_optional,
|
||||
name = dep.name,
|
||||
installed = false,
|
||||
package = package,
|
||||
}
|
||||
elseif not fallback then
|
||||
fallback = package
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- Otherwise, find the first mod that fulfills it
|
||||
if fallback then
|
||||
return {
|
||||
is_optional = dep.is_optional,
|
||||
name = dep.name,
|
||||
installed = false,
|
||||
package = fallback,
|
||||
}
|
||||
end
|
||||
|
||||
return {
|
||||
is_optional = dep.is_optional,
|
||||
name = dep.name,
|
||||
installed = false,
|
||||
}
|
||||
end
|
||||
|
||||
for _, dep in pairs(raw_deps) do
|
||||
if not dep.is_optional and not out[dep.name] then
|
||||
local result = resolve_dep(dep)
|
||||
out[dep.name] = result
|
||||
if result and result.package and not result.installed then
|
||||
local raw_deps2 = get_raw_dependencies_co(result.package, resumer)
|
||||
if raw_deps2 then
|
||||
resolve_dependencies_2_co(raw_deps2, installed_mods, out, resumer)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
return true
|
||||
end
|
||||
|
||||
|
||||
local function resolve_dependencies_co(package, game, resumer)
|
||||
assert(game)
|
||||
|
||||
local raw_deps = get_raw_dependencies_co(package, resumer)
|
||||
local installed_mods = {}
|
||||
|
||||
local mods = {}
|
||||
pkgmgr.get_game_mods(game, mods)
|
||||
for _, mod in pairs(mods) do
|
||||
installed_mods[mod.name] = true
|
||||
end
|
||||
|
||||
for _, mod in pairs(pkgmgr.global_mods:get_list()) do
|
||||
installed_mods[mod.name] = true
|
||||
end
|
||||
|
||||
local out = {}
|
||||
if not resolve_dependencies_2_co(raw_deps, installed_mods, out, resumer) then
|
||||
return nil
|
||||
end
|
||||
|
||||
local retval = {}
|
||||
for _, dep in pairs(out) do
|
||||
retval[#retval + 1] = dep
|
||||
end
|
||||
|
||||
table.sort(retval, function(a, b)
|
||||
return a.name < b.name
|
||||
end)
|
||||
|
||||
return retval
|
||||
end
|
||||
|
||||
|
||||
-- Resolve dependencies for a package, calls the recursive version.
|
||||
function contentdb.resolve_dependencies(package, game, callback)
|
||||
local resumer = make_callback_coroutine(resolve_dependencies_co, callback)
|
||||
resumer(package, game, resumer)
|
||||
end
|
||||
|
||||
|
||||
local function fetch_pkgs(params)
|
||||
local version = core.get_version()
|
||||
local base_url = core.settings:get("contentdb_url")
|
||||
local url = base_url ..
|
||||
"/api/packages/?type=mod&type=game&type=txp&protocol_version=" ..
|
||||
core.get_max_supp_proto() .. "&engine_version=" .. core.urlencode(version.string)
|
||||
|
||||
for _, item in pairs(core.settings:get("contentdb_flag_blacklist"):split(",")) do
|
||||
item = item:trim()
|
||||
if item ~= "" then
|
||||
url = url .. "&hide=" .. core.urlencode(item)
|
||||
end
|
||||
end
|
||||
|
||||
local languages
|
||||
local current_language = core.get_language()
|
||||
if current_language ~= "" then
|
||||
languages = { current_language, "en;q=0.8" }
|
||||
else
|
||||
languages = { "en" }
|
||||
end
|
||||
|
||||
local http = core.get_http_api()
|
||||
local response = http.fetch_sync({
|
||||
url = url,
|
||||
extra_headers = {
|
||||
"Accept-Language: " .. table.concat(languages, ", ")
|
||||
},
|
||||
})
|
||||
if not response.succeeded then
|
||||
return
|
||||
end
|
||||
|
||||
local packages = core.parse_json(response.data)
|
||||
if not packages or #packages == 0 then
|
||||
return
|
||||
end
|
||||
local aliases = {}
|
||||
|
||||
for _, package in pairs(packages) do
|
||||
local name_len = #package.name
|
||||
-- This must match what contentdb.update_paths() does!
|
||||
package.id = package.author:lower() .. "/"
|
||||
if package.type == "game" and name_len > 5 and package.name:sub(name_len - 4) == "_game" then
|
||||
package.id = package.id .. package.name:sub(1, name_len - 5)
|
||||
else
|
||||
package.id = package.id .. package.name
|
||||
end
|
||||
|
||||
package.url_part = core.urlencode(package.author) .. "/" .. core.urlencode(package.name)
|
||||
|
||||
if package.aliases then
|
||||
for _, alias in ipairs(package.aliases) do
|
||||
-- We currently don't support name changing
|
||||
local suffix = "/" .. package.name
|
||||
if alias:sub(-#suffix) == suffix then
|
||||
aliases[alias:lower()] = package.id
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
return { packages = packages, aliases = aliases }
|
||||
end
|
||||
|
||||
|
||||
function contentdb.fetch_pkgs(callback)
|
||||
contentdb.loading = true
|
||||
core.handle_async(fetch_pkgs, nil, function(result)
|
||||
if result then
|
||||
contentdb.load_ok = true
|
||||
contentdb.load_error = false
|
||||
contentdb.packages = result.packages
|
||||
contentdb.packages_full = result.packages
|
||||
contentdb.packages_full_unordered = result.packages
|
||||
contentdb.aliases = result.aliases
|
||||
|
||||
for _, package in ipairs(result.packages) do
|
||||
contentdb.package_by_id[package.id] = package
|
||||
end
|
||||
else
|
||||
contentdb.load_error = true
|
||||
end
|
||||
|
||||
contentdb.loading = false
|
||||
callback(result)
|
||||
end)
|
||||
end
|
||||
|
||||
|
||||
function contentdb.update_paths()
|
||||
pkgmgr.load_all()
|
||||
|
||||
local mod_hash = {}
|
||||
for _, mod in pairs(pkgmgr.global_mods:get_list()) do
|
||||
local cdb_id = pkgmgr.get_contentdb_id(mod)
|
||||
if cdb_id then
|
||||
mod_hash[contentdb.aliases[cdb_id] or cdb_id] = mod
|
||||
end
|
||||
end
|
||||
|
||||
local game_hash = {}
|
||||
for _, game in pairs(pkgmgr.games) do
|
||||
local cdb_id = pkgmgr.get_contentdb_id(game)
|
||||
if cdb_id then
|
||||
game_hash[contentdb.aliases[cdb_id] or cdb_id] = game
|
||||
end
|
||||
end
|
||||
|
||||
local txp_hash = {}
|
||||
for _, txp in pairs(pkgmgr.texture_packs) do
|
||||
local cdb_id = pkgmgr.get_contentdb_id(txp)
|
||||
if cdb_id then
|
||||
txp_hash[contentdb.aliases[cdb_id] or cdb_id] = txp
|
||||
end
|
||||
end
|
||||
|
||||
for _, package in pairs(contentdb.packages_full) do
|
||||
local content
|
||||
if package.type == "mod" then
|
||||
content = mod_hash[package.id]
|
||||
elseif package.type == "game" then
|
||||
content = game_hash[package.id]
|
||||
elseif package.type == "txp" then
|
||||
content = txp_hash[package.id]
|
||||
end
|
||||
|
||||
if content then
|
||||
package.path = content.path
|
||||
package.installed_release = content.release or 0
|
||||
else
|
||||
package.path = nil
|
||||
package.installed_release = nil
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
function contentdb.sort_packages()
|
||||
local ret = {}
|
||||
|
||||
-- Add installed content
|
||||
for _, pkg in ipairs(contentdb.packages_full_unordered) do
|
||||
if pkg.path then
|
||||
ret[#ret + 1] = pkg
|
||||
end
|
||||
end
|
||||
|
||||
-- Sort installed content first by "is there an update available?", then by title
|
||||
table.sort(ret, function(a, b)
|
||||
local a_updatable = a.installed_release < a.release
|
||||
local b_updatable = b.installed_release < b.release
|
||||
if a_updatable and not b_updatable then
|
||||
return true
|
||||
elseif b_updatable and not a_updatable then
|
||||
return false
|
||||
end
|
||||
|
||||
return a.title < b.title
|
||||
end)
|
||||
|
||||
-- Add uninstalled content
|
||||
for _, pkg in ipairs(contentdb.packages_full_unordered) do
|
||||
if not pkg.path then
|
||||
ret[#ret + 1] = pkg
|
||||
end
|
||||
end
|
||||
|
||||
contentdb.packages_full = ret
|
||||
end
|
||||
|
||||
|
||||
function contentdb.filter_packages(query, by_type)
|
||||
if query == "" and by_type == nil then
|
||||
contentdb.packages = contentdb.packages_full
|
||||
return
|
||||
end
|
||||
|
||||
local keywords = {}
|
||||
for word in query:lower():gmatch("%S+") do
|
||||
table.insert(keywords, word)
|
||||
end
|
||||
|
||||
local function matches_keywords(package)
|
||||
for k = 1, #keywords do
|
||||
local keyword = keywords[k]
|
||||
|
||||
if string.find(package.name:lower(), keyword, 1, true) or
|
||||
string.find(package.title:lower(), keyword, 1, true) or
|
||||
string.find(package.author:lower(), keyword, 1, true) or
|
||||
string.find(package.short_description:lower(), keyword, 1, true) then
|
||||
return true
|
||||
end
|
||||
end
|
||||
|
||||
return false
|
||||
end
|
||||
|
||||
contentdb.packages = {}
|
||||
for _, package in pairs(contentdb.packages_full) do
|
||||
if (query == "" or matches_keywords(package)) and
|
||||
(by_type == nil or package.type == by_type) then
|
||||
contentdb.packages[#contentdb.packages + 1] = package
|
||||
end
|
||||
end
|
||||
end
|
||||
511
builtin/mainmenu/content/dlg_contentdb.lua
Normal file
511
builtin/mainmenu/content/dlg_contentdb.lua
Normal file
@@ -0,0 +1,511 @@
|
||||
--Minetest
|
||||
--Copyright (C) 2018-20 rubenwardy
|
||||
--
|
||||
--This program is free software; you can redistribute it and/or modify
|
||||
--it under the terms of the GNU Lesser General Public License as published by
|
||||
--the Free Software Foundation; either version 2.1 of the License, or
|
||||
--(at your option) any later version.
|
||||
--
|
||||
--This program is distributed in the hope that it will be useful,
|
||||
--but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
--GNU Lesser General Public License for more details.
|
||||
--
|
||||
--You should have received a copy of the GNU Lesser General Public License along
|
||||
--with this program; if not, write to the Free Software Foundation, Inc.,
|
||||
--51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
|
||||
if not core.get_http_api then
|
||||
function create_contentdb_dlg()
|
||||
return messagebox("contentdb",
|
||||
fgettext("ContentDB is not available when Minetest was compiled without cURL"))
|
||||
end
|
||||
return
|
||||
end
|
||||
|
||||
-- Filter
|
||||
local search_string = ""
|
||||
local cur_page = 1
|
||||
local num_per_page = 5
|
||||
local filter_type = 1
|
||||
local filter_types_titles = {
|
||||
fgettext("All packages"),
|
||||
fgettext("Games"),
|
||||
fgettext("Mods"),
|
||||
fgettext("Texture packs"),
|
||||
}
|
||||
|
||||
-- Automatic package installation
|
||||
local auto_install_spec = nil
|
||||
|
||||
local filter_types_type = {
|
||||
nil,
|
||||
"game",
|
||||
"mod",
|
||||
"txp",
|
||||
}
|
||||
|
||||
|
||||
local function install_or_update_package(this, package)
|
||||
local install_parent
|
||||
if package.type == "mod" then
|
||||
install_parent = core.get_modpath()
|
||||
elseif package.type == "game" then
|
||||
install_parent = core.get_gamepath()
|
||||
elseif package.type == "txp" then
|
||||
install_parent = core.get_texturepath()
|
||||
else
|
||||
error("Unknown package type: " .. package.type)
|
||||
end
|
||||
|
||||
if package.queued or package.downloading then
|
||||
return
|
||||
end
|
||||
|
||||
local function on_confirm()
|
||||
local dlg = create_install_dialog(package)
|
||||
dlg:set_parent(this)
|
||||
this:hide()
|
||||
dlg:show()
|
||||
|
||||
dlg:load_deps()
|
||||
end
|
||||
|
||||
if package.type == "mod" and #pkgmgr.games == 0 then
|
||||
local dlg = messagebox("install_game",
|
||||
fgettext("You need to install a game before you can install a mod"))
|
||||
dlg:set_parent(this)
|
||||
this:hide()
|
||||
dlg:show()
|
||||
elseif not package.path and core.is_dir(install_parent .. DIR_DELIM .. package.name) then
|
||||
local dlg = create_confirm_overwrite(package, on_confirm)
|
||||
dlg:set_parent(this)
|
||||
this:hide()
|
||||
dlg:show()
|
||||
else
|
||||
on_confirm()
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
-- Resolves the package specification stored in auto_install_spec into an actual package.
|
||||
-- May only be called after the package list has been loaded successfully.
|
||||
local function resolve_auto_install_spec()
|
||||
assert(contentdb.load_ok)
|
||||
|
||||
if not auto_install_spec then
|
||||
return nil
|
||||
end
|
||||
|
||||
local spec = contentdb.aliases[auto_install_spec] or auto_install_spec
|
||||
local resolved = nil
|
||||
|
||||
for _, pkg in ipairs(contentdb.packages_full_unordered) do
|
||||
if pkg.id == spec then
|
||||
resolved = pkg
|
||||
break
|
||||
end
|
||||
end
|
||||
|
||||
if not resolved then
|
||||
gamedata.errormessage = fgettext_ne("The package $1 was not found.", auto_install_spec)
|
||||
ui.update()
|
||||
|
||||
auto_install_spec = nil
|
||||
end
|
||||
|
||||
return resolved
|
||||
end
|
||||
|
||||
|
||||
-- Installs the package specified by auto_install_spec.
|
||||
-- Only does something if:
|
||||
-- a. The package list has been loaded successfully.
|
||||
-- b. The ContentDB dialog is currently visible.
|
||||
local function do_auto_install()
|
||||
if not contentdb.load_ok then
|
||||
return
|
||||
end
|
||||
|
||||
local pkg = resolve_auto_install_spec()
|
||||
if not pkg then
|
||||
return
|
||||
end
|
||||
|
||||
local contentdb_dlg = ui.find_by_name("contentdb")
|
||||
if not contentdb_dlg or contentdb_dlg.hidden then
|
||||
return
|
||||
end
|
||||
|
||||
install_or_update_package(contentdb_dlg, pkg)
|
||||
auto_install_spec = nil
|
||||
end
|
||||
|
||||
|
||||
local function sort_and_filter_pkgs()
|
||||
contentdb.update_paths()
|
||||
contentdb.sort_packages()
|
||||
contentdb.filter_packages(search_string, filter_types_type[filter_type])
|
||||
|
||||
local auto_install_pkg = resolve_auto_install_spec()
|
||||
if auto_install_pkg then
|
||||
local idx = table.indexof(contentdb.packages, auto_install_pkg)
|
||||
if idx ~= -1 then
|
||||
table.remove(contentdb.packages, idx)
|
||||
table.insert(contentdb.packages, 1, auto_install_pkg)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
local function load()
|
||||
if contentdb.load_ok then
|
||||
sort_and_filter_pkgs()
|
||||
return
|
||||
end
|
||||
if contentdb.loading then
|
||||
return
|
||||
end
|
||||
contentdb.fetch_pkgs(function(result)
|
||||
if result then
|
||||
sort_and_filter_pkgs()
|
||||
do_auto_install()
|
||||
end
|
||||
ui.update()
|
||||
end)
|
||||
end
|
||||
|
||||
|
||||
local function get_info_formspec(text)
|
||||
local H = 9.5
|
||||
return table.concat({
|
||||
"formspec_version[6]",
|
||||
"size[15.75,9.5]",
|
||||
core.settings:get_bool("enable_touch") and "padding[0.01,0.01]" or "position[0.5,0.55]",
|
||||
|
||||
"label[4,4.35;", text, "]",
|
||||
"container[0,", H - 0.8 - 0.375, "]",
|
||||
"button[0.375,0;5,0.8;back;", fgettext("Back to Main Menu"), "]",
|
||||
"container_end[]",
|
||||
})
|
||||
end
|
||||
|
||||
|
||||
local function get_formspec(dlgdata)
|
||||
if contentdb.loading then
|
||||
return get_info_formspec(fgettext("Loading..."))
|
||||
end
|
||||
if contentdb.load_error then
|
||||
return get_info_formspec(fgettext("No packages could be retrieved"))
|
||||
end
|
||||
assert(contentdb.load_ok)
|
||||
|
||||
contentdb.update_paths()
|
||||
|
||||
dlgdata.pagemax = math.max(math.ceil(#contentdb.packages / num_per_page), 1)
|
||||
if cur_page > dlgdata.pagemax then
|
||||
cur_page = 1
|
||||
end
|
||||
|
||||
local W = 15.75
|
||||
local H = 9.5
|
||||
local formspec = {
|
||||
"formspec_version[6]",
|
||||
"size[15.75,9.5]",
|
||||
core.settings:get_bool("enable_touch") and "padding[0.01,0.01]" or "position[0.5,0.55]",
|
||||
|
||||
"style[status,downloading,queued;border=false]",
|
||||
|
||||
"container[0.375,0.375]",
|
||||
"field[0,0;7.225,0.8;search_string;;", core.formspec_escape(search_string), "]",
|
||||
"field_enter_after_edit[search_string;true]",
|
||||
"image_button[7.3,0;0.8,0.8;", core.formspec_escape(defaulttexturedir .. "search.png"), ";search;]",
|
||||
"image_button[8.125,0;0.8,0.8;", core.formspec_escape(defaulttexturedir .. "clear.png"), ";clear;]",
|
||||
"dropdown[9.175,0;2.7875,0.8;type;", table.concat(filter_types_titles, ","), ";", filter_type, "]",
|
||||
"container_end[]",
|
||||
|
||||
-- Page nav buttons
|
||||
"container[0,", H - 0.8 - 0.375, "]",
|
||||
"button[0.375,0;5,0.8;back;", fgettext("Back to Main Menu"), "]",
|
||||
|
||||
"container[", W - 0.375 - 0.8*4 - 2, ",0]",
|
||||
"image_button[0,0;0.8,0.8;", core.formspec_escape(defaulttexturedir), "start_icon.png;pstart;]",
|
||||
"image_button[0.8,0;0.8,0.8;", core.formspec_escape(defaulttexturedir), "prev_icon.png;pback;]",
|
||||
"style[pagenum;border=false]",
|
||||
"button[1.6,0;2,0.8;pagenum;", tonumber(cur_page), " / ", tonumber(dlgdata.pagemax), "]",
|
||||
"image_button[3.6,0;0.8,0.8;", core.formspec_escape(defaulttexturedir), "next_icon.png;pnext;]",
|
||||
"image_button[4.4,0;0.8,0.8;", core.formspec_escape(defaulttexturedir), "end_icon.png;pend;]",
|
||||
"container_end[]",
|
||||
|
||||
"container_end[]",
|
||||
}
|
||||
|
||||
if contentdb.number_downloading > 0 then
|
||||
formspec[#formspec + 1] = "button[12.5875,0.375;2.7875,0.8;downloading;"
|
||||
if #contentdb.download_queue > 0 then
|
||||
formspec[#formspec + 1] = fgettext("$1 downloading,\n$2 queued",
|
||||
contentdb.number_downloading, #contentdb.download_queue)
|
||||
else
|
||||
formspec[#formspec + 1] = fgettext("$1 downloading...", contentdb.number_downloading)
|
||||
end
|
||||
formspec[#formspec + 1] = "]"
|
||||
else
|
||||
local num_avail_updates = 0
|
||||
for i=1, #contentdb.packages_full do
|
||||
local package = contentdb.packages_full[i]
|
||||
if package.path and package.installed_release < package.release and
|
||||
not (package.downloading or package.queued) then
|
||||
num_avail_updates = num_avail_updates + 1
|
||||
end
|
||||
end
|
||||
|
||||
if num_avail_updates == 0 then
|
||||
formspec[#formspec + 1] = "button[12.5875,0.375;2.7875,0.8;status;"
|
||||
formspec[#formspec + 1] = fgettext("No updates")
|
||||
formspec[#formspec + 1] = "]"
|
||||
else
|
||||
formspec[#formspec + 1] = "button[12.5875,0.375;2.7875,0.8;update_all;"
|
||||
formspec[#formspec + 1] = fgettext("Update All [$1]", num_avail_updates)
|
||||
formspec[#formspec + 1] = "]"
|
||||
end
|
||||
end
|
||||
|
||||
if #contentdb.packages == 0 then
|
||||
formspec[#formspec + 1] = "label[4,4.75;"
|
||||
formspec[#formspec + 1] = fgettext("No results")
|
||||
formspec[#formspec + 1] = "]"
|
||||
end
|
||||
|
||||
-- download/queued tooltips always have the same message
|
||||
local tooltip_colors = ";#dff6f5;#302c2e]"
|
||||
formspec[#formspec + 1] = "tooltip[downloading;" .. fgettext("Downloading...") .. tooltip_colors
|
||||
formspec[#formspec + 1] = "tooltip[queued;" .. fgettext("Queued") .. tooltip_colors
|
||||
|
||||
local start_idx = (cur_page - 1) * num_per_page + 1
|
||||
for i=start_idx, math.min(#contentdb.packages, start_idx+num_per_page-1) do
|
||||
local package = contentdb.packages[i]
|
||||
local container_y = (i - start_idx) * 1.375 + (2*0.375 + 0.8)
|
||||
formspec[#formspec + 1] = "container[0.375,"
|
||||
formspec[#formspec + 1] = container_y
|
||||
formspec[#formspec + 1] = "]"
|
||||
|
||||
-- image
|
||||
formspec[#formspec + 1] = "image[0,0;1.5,1;"
|
||||
formspec[#formspec + 1] = core.formspec_escape(get_screenshot(package))
|
||||
formspec[#formspec + 1] = "]"
|
||||
|
||||
-- title
|
||||
formspec[#formspec + 1] = "label[1.875,0.1;"
|
||||
formspec[#formspec + 1] = core.formspec_escape(
|
||||
core.colorize(mt_color_green, package.title) ..
|
||||
core.colorize("#BFBFBF", " by " .. package.author))
|
||||
formspec[#formspec + 1] = "]"
|
||||
|
||||
-- buttons
|
||||
local description_width = W - 2.625 - 2 * 0.7 - 2 * 0.15
|
||||
|
||||
local second_base = "image_button[-1.55,0;0.7,0.7;" .. core.formspec_escape(defaulttexturedir)
|
||||
local third_base = "image_button[-2.4,0;0.7,0.7;" .. core.formspec_escape(defaulttexturedir)
|
||||
formspec[#formspec + 1] = "container["
|
||||
formspec[#formspec + 1] = W - 0.375*2
|
||||
formspec[#formspec + 1] = ",0.1]"
|
||||
|
||||
if package.downloading then
|
||||
formspec[#formspec + 1] = "animated_image[-1.7,-0.15;1,1;downloading;"
|
||||
formspec[#formspec + 1] = core.formspec_escape(defaulttexturedir)
|
||||
formspec[#formspec + 1] = "cdb_downloading.png;3;400;]"
|
||||
elseif package.queued then
|
||||
formspec[#formspec + 1] = second_base
|
||||
formspec[#formspec + 1] = "cdb_queued.png;queued;]"
|
||||
elseif not package.path then
|
||||
local elem_name = "install_" .. i .. ";"
|
||||
formspec[#formspec + 1] = "style[" .. elem_name .. "bgcolor=#71aa34]"
|
||||
formspec[#formspec + 1] = second_base .. "cdb_add.png;" .. elem_name .. "]"
|
||||
formspec[#formspec + 1] = "tooltip[" .. elem_name .. fgettext("Install") .. tooltip_colors
|
||||
else
|
||||
if package.installed_release < package.release then
|
||||
-- The install_ action also handles updating
|
||||
local elem_name = "install_" .. i .. ";"
|
||||
formspec[#formspec + 1] = "style[" .. elem_name .. "bgcolor=#28ccdf]"
|
||||
formspec[#formspec + 1] = third_base .. "cdb_update.png;" .. elem_name .. "]"
|
||||
formspec[#formspec + 1] = "tooltip[" .. elem_name .. fgettext("Update") .. tooltip_colors
|
||||
|
||||
description_width = description_width - 0.7 - 0.15
|
||||
end
|
||||
|
||||
local elem_name = "uninstall_" .. i .. ";"
|
||||
formspec[#formspec + 1] = "style[" .. elem_name .. "bgcolor=#a93b3b]"
|
||||
formspec[#formspec + 1] = second_base .. "cdb_clear.png;" .. elem_name .. "]"
|
||||
formspec[#formspec + 1] = "tooltip[" .. elem_name .. fgettext("Uninstall") .. tooltip_colors
|
||||
end
|
||||
|
||||
local web_elem_name = "view_" .. i .. ";"
|
||||
formspec[#formspec + 1] = "image_button[-0.7,0;0.7,0.7;" ..
|
||||
core.formspec_escape(defaulttexturedir) .. "cdb_viewonline.png;" .. web_elem_name .. "]"
|
||||
formspec[#formspec + 1] = "tooltip[" .. web_elem_name ..
|
||||
fgettext("View more information in a web browser") .. tooltip_colors
|
||||
formspec[#formspec + 1] = "container_end[]"
|
||||
|
||||
-- description
|
||||
formspec[#formspec + 1] = "textarea[1.855,0.3;"
|
||||
formspec[#formspec + 1] = tostring(description_width)
|
||||
formspec[#formspec + 1] = ",0.8;;;"
|
||||
formspec[#formspec + 1] = core.formspec_escape(package.short_description)
|
||||
formspec[#formspec + 1] = "]"
|
||||
|
||||
formspec[#formspec + 1] = "container_end[]"
|
||||
end
|
||||
|
||||
return table.concat(formspec)
|
||||
end
|
||||
|
||||
|
||||
local function handle_submit(this, fields)
|
||||
if fields.search or fields.key_enter_field == "search_string" then
|
||||
search_string = fields.search_string:trim()
|
||||
cur_page = 1
|
||||
contentdb.filter_packages(search_string, filter_types_type[filter_type])
|
||||
return true
|
||||
end
|
||||
|
||||
if fields.clear then
|
||||
search_string = ""
|
||||
cur_page = 1
|
||||
contentdb.filter_packages("", filter_types_type[filter_type])
|
||||
return true
|
||||
end
|
||||
|
||||
if fields.back then
|
||||
this:delete()
|
||||
return true
|
||||
end
|
||||
|
||||
if fields.pstart then
|
||||
cur_page = 1
|
||||
return true
|
||||
end
|
||||
|
||||
if fields.pend then
|
||||
cur_page = this.data.pagemax
|
||||
return true
|
||||
end
|
||||
|
||||
if fields.pnext then
|
||||
cur_page = cur_page + 1
|
||||
if cur_page > this.data.pagemax then
|
||||
cur_page = 1
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
if fields.pback then
|
||||
if cur_page == 1 then
|
||||
cur_page = this.data.pagemax
|
||||
else
|
||||
cur_page = cur_page - 1
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
if fields.type then
|
||||
local new_type = table.indexof(filter_types_titles, fields.type)
|
||||
if new_type ~= filter_type then
|
||||
filter_type = new_type
|
||||
cur_page = 1
|
||||
contentdb.filter_packages(search_string, filter_types_type[filter_type])
|
||||
return true
|
||||
end
|
||||
end
|
||||
|
||||
if fields.update_all then
|
||||
for i=1, #contentdb.packages_full do
|
||||
local package = contentdb.packages_full[i]
|
||||
if package.path and package.installed_release < package.release and
|
||||
not (package.downloading or package.queued) then
|
||||
contentdb.queue_download(package, contentdb.REASON_UPDATE)
|
||||
end
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
local start_idx = (cur_page - 1) * num_per_page + 1
|
||||
assert(start_idx ~= nil)
|
||||
for i=start_idx, math.min(#contentdb.packages, start_idx+num_per_page-1) do
|
||||
local package = contentdb.packages[i]
|
||||
assert(package)
|
||||
|
||||
if fields["install_" .. i] then
|
||||
install_or_update_package(this, package)
|
||||
return true
|
||||
end
|
||||
|
||||
if fields["uninstall_" .. i] then
|
||||
local dlg = create_delete_content_dlg(package)
|
||||
dlg:set_parent(this)
|
||||
this:hide()
|
||||
dlg:show()
|
||||
return true
|
||||
end
|
||||
|
||||
if fields["view_" .. i] then
|
||||
local url = ("%s/packages/%s?protocol_version=%d"):format(
|
||||
core.settings:get("contentdb_url"), package.url_part,
|
||||
core.get_max_supp_proto())
|
||||
core.open_url(url)
|
||||
return true
|
||||
end
|
||||
end
|
||||
|
||||
return false
|
||||
end
|
||||
|
||||
|
||||
local function handle_events(event)
|
||||
if event == "DialogShow" then
|
||||
-- On touchscreen, don't show the "MINETEST" header behind the dialog.
|
||||
mm_game_theme.set_engine(core.settings:get_bool("enable_touch"))
|
||||
|
||||
-- If ContentDB is already loaded, auto-install packages here.
|
||||
do_auto_install()
|
||||
|
||||
return true
|
||||
end
|
||||
|
||||
return false
|
||||
end
|
||||
|
||||
|
||||
--- Creates a ContentDB dialog.
|
||||
---
|
||||
--- @param type string | nil
|
||||
--- Sets initial package filter. "game", "mod", "txp" or nil (no filter).
|
||||
--- @param install_spec table | nil
|
||||
--- ContentDB ID of package as returned by pkgmgr.get_contentdb_id().
|
||||
--- Sets package to install or update automatically.
|
||||
function create_contentdb_dlg(type, install_spec)
|
||||
search_string = ""
|
||||
cur_page = 1
|
||||
if type then
|
||||
-- table.indexof does not work on tables that contain `nil`
|
||||
for i, v in pairs(filter_types_type) do
|
||||
if v == type then
|
||||
filter_type = i
|
||||
break
|
||||
end
|
||||
end
|
||||
else
|
||||
filter_type = 1
|
||||
end
|
||||
|
||||
-- Keep the old auto_install_spec if the caller doesn't specify one.
|
||||
if install_spec then
|
||||
auto_install_spec = install_spec
|
||||
end
|
||||
|
||||
load()
|
||||
|
||||
return dialog_create("contentdb",
|
||||
get_formspec,
|
||||
handle_submit,
|
||||
handle_events)
|
||||
end
|
||||
File diff suppressed because it is too large
Load Diff
246
builtin/mainmenu/content/dlg_install.lua
Normal file
246
builtin/mainmenu/content/dlg_install.lua
Normal file
@@ -0,0 +1,246 @@
|
||||
--Minetest
|
||||
--Copyright (C) 2018-24 rubenwardy
|
||||
--
|
||||
--This program is free software; you can redistribute it and/or modify
|
||||
--it under the terms of the GNU Lesser General Public License as published by
|
||||
--the Free Software Foundation; either version 2.1 of the License, or
|
||||
--(at your option) any later version.
|
||||
--
|
||||
--This program is distributed in the hope that it will be useful,
|
||||
--but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
--GNU Lesser General Public License for more details.
|
||||
--
|
||||
--You should have received a copy of the GNU Lesser General Public License along
|
||||
--with this program; if not, write to the Free Software Foundation, Inc.,
|
||||
--51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
|
||||
local function is_still_visible(dlg)
|
||||
local this = ui.find_by_name("install_dialog")
|
||||
return this == dlg and not dlg.hidden
|
||||
end
|
||||
|
||||
|
||||
local function get_loading_formspec()
|
||||
local ENABLE_TOUCH = core.settings:get_bool("enable_touch")
|
||||
local w = ENABLE_TOUCH and 14 or 7
|
||||
|
||||
local formspec = {
|
||||
"formspec_version[3]",
|
||||
"size[", w, ",9.05]",
|
||||
ENABLE_TOUCH and "padding[0.01,0.01]" or "position[0.5,0.55]",
|
||||
"label[3,4.525;", fgettext("Loading..."), "]",
|
||||
}
|
||||
return table.concat(formspec)
|
||||
end
|
||||
|
||||
|
||||
local function get_formspec(data)
|
||||
if not data.has_hard_deps_ready then
|
||||
return get_loading_formspec()
|
||||
end
|
||||
|
||||
local selected_game, selected_game_idx = pkgmgr.find_by_gameid(core.settings:get("menu_last_game"))
|
||||
if not selected_game_idx then
|
||||
selected_game_idx = 1
|
||||
selected_game = pkgmgr.games[1]
|
||||
end
|
||||
|
||||
local game_list = {}
|
||||
for i, game in ipairs(pkgmgr.games) do
|
||||
game_list[i] = core.formspec_escape(game.title)
|
||||
end
|
||||
|
||||
if not data.deps_ready[selected_game_idx] and
|
||||
not data.deps_loading[selected_game_idx] then
|
||||
data.deps_loading[selected_game_idx] = true
|
||||
|
||||
contentdb.resolve_dependencies(data.package, selected_game, function(deps)
|
||||
if not is_still_visible(data.dlg) then
|
||||
return
|
||||
end
|
||||
data.deps_ready[selected_game_idx] = deps
|
||||
ui.update()
|
||||
end)
|
||||
end
|
||||
|
||||
-- The value of `data.deps_ready[selected_game_idx]` may have changed
|
||||
-- since the last if statement since `contentdb.resolve_dependencies`
|
||||
-- calls the callback immediately if the dependencies are already cached.
|
||||
if not data.deps_ready[selected_game_idx] then
|
||||
return get_loading_formspec()
|
||||
end
|
||||
|
||||
local package = data.package
|
||||
local will_install_deps = data.will_install_deps
|
||||
|
||||
local deps_to_install = 0
|
||||
local deps_not_found = 0
|
||||
|
||||
data.deps_chosen = data.deps_ready[selected_game_idx]
|
||||
local formatted_deps = {}
|
||||
for _, dep in pairs(data.deps_chosen) do
|
||||
formatted_deps[#formatted_deps + 1] = "#fff"
|
||||
formatted_deps[#formatted_deps + 1] = core.formspec_escape(dep.name)
|
||||
if dep.installed then
|
||||
formatted_deps[#formatted_deps + 1] = "#ccf"
|
||||
formatted_deps[#formatted_deps + 1] = fgettext("Already installed")
|
||||
elseif dep.package then
|
||||
formatted_deps[#formatted_deps + 1] = "#cfc"
|
||||
formatted_deps[#formatted_deps + 1] = fgettext("$1 by $2", dep.package.title, dep.package.author)
|
||||
deps_to_install = deps_to_install + 1
|
||||
else
|
||||
formatted_deps[#formatted_deps + 1] = "#f00"
|
||||
formatted_deps[#formatted_deps + 1] = fgettext("Not found")
|
||||
deps_not_found = deps_not_found + 1
|
||||
end
|
||||
end
|
||||
|
||||
local message_bg = "#3333"
|
||||
local message
|
||||
if will_install_deps then
|
||||
message = fgettext("$1 and $2 dependencies will be installed.", package.title, deps_to_install)
|
||||
else
|
||||
message = fgettext("$1 will be installed, and $2 dependencies will be skipped.", package.title, deps_to_install)
|
||||
end
|
||||
if deps_not_found > 0 then
|
||||
message = fgettext("$1 required dependencies could not be found.", deps_not_found) ..
|
||||
" " .. fgettext("Please check that the base game is correct.", deps_not_found) ..
|
||||
"\n" .. message
|
||||
message_bg = mt_color_orange
|
||||
end
|
||||
|
||||
local ENABLE_TOUCH = core.settings:get_bool("enable_touch")
|
||||
|
||||
local w = ENABLE_TOUCH and 14 or 7
|
||||
local padded_w = w - 2*0.375
|
||||
local dropdown_w = ENABLE_TOUCH and 10.2 or 4.25
|
||||
local button_w = (padded_w - 0.25) / 3
|
||||
local button_pad = button_w / 2
|
||||
|
||||
local formspec = {
|
||||
"formspec_version[3]",
|
||||
"size[", w, ",9.05]",
|
||||
ENABLE_TOUCH and "padding[0.01,0.01]" or "position[0.5,0.55]",
|
||||
"style[title;border=false]",
|
||||
"box[0,0;", w, ",0.8;#3333]",
|
||||
"button[0,0;", w, ",0.8;title;", fgettext("Install $1", package.title) , "]",
|
||||
|
||||
"container[0.375,1]",
|
||||
|
||||
"label[0,0.4;", fgettext("Base Game:"), "]",
|
||||
"dropdown[", padded_w - dropdown_w, ",0;", dropdown_w, ",0.8;selected_game;",
|
||||
table.concat(game_list, ","), ";", selected_game_idx, "]",
|
||||
|
||||
"label[0,1.1;", fgettext("Dependencies:"), "]",
|
||||
|
||||
"tablecolumns[color;text;color;text]",
|
||||
"table[0,1.4;", padded_w, ",3;packages;", table.concat(formatted_deps, ","), "]",
|
||||
|
||||
"container_end[]",
|
||||
|
||||
"checkbox[0.375,5.7;will_install_deps;",
|
||||
fgettext("Install missing dependencies"), ";",
|
||||
will_install_deps and "true" or "false", "]",
|
||||
|
||||
"box[0,6;", w, ",1.8;", message_bg, "]",
|
||||
"textarea[0.375,6.1;", padded_w, ",1.6;;;", message, "]",
|
||||
|
||||
"container[", 0.375 + button_pad, ",8.05]",
|
||||
"button[0,0;", button_w, ",0.8;install_all;", fgettext("Install"), "]",
|
||||
"button[", 0.25 + button_w, ",0;", button_w, ",0.8;cancel;", fgettext("Cancel"), "]",
|
||||
"container_end[]",
|
||||
}
|
||||
|
||||
return table.concat(formspec)
|
||||
end
|
||||
|
||||
|
||||
local function handle_submit(this, fields)
|
||||
local data = this.data
|
||||
if fields.cancel then
|
||||
this:delete()
|
||||
return true
|
||||
end
|
||||
|
||||
if fields.will_install_deps ~= nil then
|
||||
data.will_install_deps = core.is_yes(fields.will_install_deps)
|
||||
return true
|
||||
end
|
||||
|
||||
if fields.install_all then
|
||||
contentdb.queue_download(data.package, contentdb.REASON_NEW)
|
||||
|
||||
if data.will_install_deps then
|
||||
for _, dep in pairs(data.deps_chosen) do
|
||||
if not dep.is_optional and not dep.installed and dep.package then
|
||||
contentdb.queue_download(dep.package, contentdb.REASON_DEPENDENCY)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
this:delete()
|
||||
return true
|
||||
end
|
||||
|
||||
if fields.selected_game then
|
||||
for _, game in pairs(pkgmgr.games) do
|
||||
if game.title == fields.selected_game then
|
||||
core.settings:set("menu_last_game", game.id)
|
||||
break
|
||||
end
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
return false
|
||||
end
|
||||
|
||||
|
||||
local function load_deps(dlg)
|
||||
local package = dlg.data.package
|
||||
|
||||
contentdb.has_hard_deps(package, function(result)
|
||||
if not is_still_visible(dlg) then
|
||||
return
|
||||
end
|
||||
|
||||
if result == nil then
|
||||
local parent = dlg.parent
|
||||
dlg:delete()
|
||||
local dlg2 = messagebox("error_checking_deps",
|
||||
fgettext("Error getting dependencies for package $1", package.url_part))
|
||||
dlg2:set_parent(parent)
|
||||
parent:hide()
|
||||
dlg2:show()
|
||||
elseif result == false then
|
||||
contentdb.queue_download(package, package.path and contentdb.REASON_UPDATE or contentdb.REASON_NEW)
|
||||
dlg:delete()
|
||||
else
|
||||
assert(result == true)
|
||||
dlg.data.has_hard_deps_ready = true
|
||||
end
|
||||
ui.update()
|
||||
end)
|
||||
end
|
||||
|
||||
|
||||
function create_install_dialog(package)
|
||||
local dlg = dialog_create("install_dialog", get_formspec, handle_submit, nil)
|
||||
dlg.data.deps_chosen = nil
|
||||
dlg.data.package = package
|
||||
dlg.data.will_install_deps = true
|
||||
|
||||
dlg.data.has_hard_deps_ready = false
|
||||
dlg.data.deps_ready = {}
|
||||
dlg.data.deps_loading = {}
|
||||
|
||||
dlg.load_deps = load_deps
|
||||
|
||||
-- `get_formspec` needs to access `dlg` to check whether it's still open.
|
||||
-- It doesn't suffice to check that any "install_dialog" instance is open
|
||||
-- via `ui.find_by_name`, it's necessary to check for this exact instance.
|
||||
dlg.data.dlg = dlg
|
||||
|
||||
return dlg
|
||||
end
|
||||
53
builtin/mainmenu/content/dlg_overwrite.lua
Normal file
53
builtin/mainmenu/content/dlg_overwrite.lua
Normal file
@@ -0,0 +1,53 @@
|
||||
--Minetest
|
||||
--Copyright (C) 2018-24 rubenwardy
|
||||
--
|
||||
--This program is free software; you can redistribute it and/or modify
|
||||
--it under the terms of the GNU Lesser General Public License as published by
|
||||
--the Free Software Foundation; either version 2.1 of the License, or
|
||||
--(at your option) any later version.
|
||||
--
|
||||
--This program is distributed in the hope that it will be useful,
|
||||
--but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
--GNU Lesser General Public License for more details.
|
||||
--
|
||||
--You should have received a copy of the GNU Lesser General Public License along
|
||||
--with this program; if not, write to the Free Software Foundation, Inc.,
|
||||
--51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
|
||||
function get_formspec(data)
|
||||
local package = data.package
|
||||
|
||||
return confirmation_formspec(
|
||||
fgettext("\"$1\" already exists. Would you like to overwrite it?", package.name),
|
||||
'install', fgettext("Overwrite"),
|
||||
'cancel', fgettext("Cancel"))
|
||||
end
|
||||
|
||||
|
||||
local function handle_submit(this, fields)
|
||||
local data = this.data
|
||||
if fields.cancel then
|
||||
this:delete()
|
||||
return true
|
||||
end
|
||||
|
||||
if fields.install then
|
||||
this:delete()
|
||||
data.callback()
|
||||
return true
|
||||
end
|
||||
|
||||
return false
|
||||
end
|
||||
|
||||
|
||||
function create_confirm_overwrite(package, callback)
|
||||
assert(type(package) == "table")
|
||||
assert(type(callback) == "function")
|
||||
|
||||
local dlg = dialog_create("data", get_formspec, handle_submit, nil)
|
||||
dlg.data.package = package
|
||||
dlg.data.callback = callback
|
||||
return dlg
|
||||
end
|
||||
@@ -18,5 +18,9 @@
|
||||
local path = core.get_mainmenu_path() .. DIR_DELIM .. "content"
|
||||
|
||||
dofile(path .. DIR_DELIM .. "pkgmgr.lua")
|
||||
dofile(path .. DIR_DELIM .. "contentdb.lua")
|
||||
dofile(path .. DIR_DELIM .. "update_detector.lua")
|
||||
dofile(path .. DIR_DELIM .. "dlg_contentstore.lua")
|
||||
dofile(path .. DIR_DELIM .. "screenshots.lua")
|
||||
dofile(path .. DIR_DELIM .. "dlg_install.lua")
|
||||
dofile(path .. DIR_DELIM .. "dlg_overwrite.lua")
|
||||
dofile(path .. DIR_DELIM .. "dlg_contentdb.lua")
|
||||
|
||||
@@ -110,7 +110,7 @@ pkgmgr = {}
|
||||
-- @param modpack Currently processing modpack or nil/"" if none (recursion)
|
||||
function pkgmgr.get_mods(path, virtual_path, listing, modpack)
|
||||
local mods = core.get_dir_list(path, true)
|
||||
|
||||
local added = {}
|
||||
for _, name in ipairs(mods) do
|
||||
if name:sub(1, 1) ~= "." then
|
||||
local mod_path = path .. DIR_DELIM .. name
|
||||
@@ -120,6 +120,7 @@ function pkgmgr.get_mods(path, virtual_path, listing, modpack)
|
||||
parent_dir = path,
|
||||
}
|
||||
listing[#listing + 1] = toadd
|
||||
added[#added + 1] = toadd
|
||||
|
||||
-- Get config file
|
||||
local mod_conf
|
||||
@@ -169,6 +170,8 @@ function pkgmgr.get_mods(path, virtual_path, listing, modpack)
|
||||
end
|
||||
end
|
||||
|
||||
pkgmgr.update_translations(added)
|
||||
|
||||
if not modpack then
|
||||
-- Sort all when the recursion is done
|
||||
table.sort(listing, function(a, b)
|
||||
@@ -178,26 +181,31 @@ function pkgmgr.get_mods(path, virtual_path, listing, modpack)
|
||||
end
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
function pkgmgr.get_texture_packs()
|
||||
function pkgmgr.reload_texture_packs()
|
||||
local txtpath = core.get_texturepath()
|
||||
local txtpath_system = core.get_texturepath_share()
|
||||
local retval = {}
|
||||
|
||||
load_texture_packs(txtpath, retval)
|
||||
|
||||
-- on portable versions these two paths coincide. It avoids loading the path twice
|
||||
if txtpath ~= txtpath_system then
|
||||
load_texture_packs(txtpath_system, retval)
|
||||
end
|
||||
|
||||
pkgmgr.update_translations(retval)
|
||||
|
||||
table.sort(retval, function(a, b)
|
||||
return a.title:lower() < b.title:lower()
|
||||
end)
|
||||
|
||||
return retval
|
||||
pkgmgr.texture_packs = retval
|
||||
end
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
function pkgmgr.get_all()
|
||||
pkgmgr.load_all()
|
||||
|
||||
local result = {}
|
||||
|
||||
for _, mod in pairs(pkgmgr.global_mods:get_list()) do
|
||||
@@ -206,7 +214,7 @@ function pkgmgr.get_all()
|
||||
for _, game in pairs(pkgmgr.games) do
|
||||
result[#result + 1] = game
|
||||
end
|
||||
for _, txp in pairs(pkgmgr.get_texture_packs()) do
|
||||
for _, txp in pairs(pkgmgr.texture_packs) do
|
||||
result[#result + 1] = txp
|
||||
end
|
||||
|
||||
@@ -284,7 +292,7 @@ end
|
||||
function pkgmgr.render_packagelist(render_list, use_technical_names, with_icon)
|
||||
if not render_list then
|
||||
if not pkgmgr.global_mods then
|
||||
pkgmgr.refresh_globals()
|
||||
pkgmgr.reload_global_mods()
|
||||
end
|
||||
render_list = pkgmgr.global_mods
|
||||
end
|
||||
@@ -545,6 +553,7 @@ function pkgmgr.get_worldconfig(worldpath)
|
||||
end
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
-- Caller is responsible for reloading content types (see reload_by_type)
|
||||
function pkgmgr.install_dir(expected_type, path, basename, targetpath)
|
||||
assert(type(expected_type) == "string")
|
||||
assert(type(path) == "string")
|
||||
@@ -611,12 +620,6 @@ function pkgmgr.install_dir(expected_type, path, basename, targetpath)
|
||||
fgettext_ne("Failed to install $1 to $2", basename, targetpath)
|
||||
end
|
||||
|
||||
if basefolder.type == "game" then
|
||||
pkgmgr.update_gamelist()
|
||||
else
|
||||
pkgmgr.refresh_globals()
|
||||
end
|
||||
|
||||
return targetpath, nil
|
||||
end
|
||||
|
||||
@@ -738,7 +741,7 @@ function pkgmgr.comparemod(elem1,elem2)
|
||||
end
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
function pkgmgr.refresh_globals()
|
||||
function pkgmgr.reload_global_mods()
|
||||
local function is_equal(element,uid) --uid match
|
||||
if element.name == uid then
|
||||
return true
|
||||
@@ -770,11 +773,60 @@ function pkgmgr.get_game_mods(gamespec, retval)
|
||||
end
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
function pkgmgr.update_gamelist()
|
||||
function pkgmgr.reload_games()
|
||||
pkgmgr.games = core.get_games()
|
||||
table.sort(pkgmgr.games, function(a, b)
|
||||
return a.title:lower() < b.title:lower()
|
||||
end)
|
||||
pkgmgr.update_translations(pkgmgr.games)
|
||||
end
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
function pkgmgr.reload_by_type(type)
|
||||
if type == "game" then
|
||||
pkgmgr.reload_games()
|
||||
elseif type == "txp" then
|
||||
pkgmgr.reload_texture_packs()
|
||||
elseif type == "mod" or type == "modpack" then
|
||||
pkgmgr.reload_global_mods()
|
||||
else
|
||||
error("Unknown package type: " .. type)
|
||||
end
|
||||
end
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
function pkgmgr.load_all()
|
||||
if not pkgmgr.global_mods then
|
||||
pkgmgr.reload_global_mods()
|
||||
end
|
||||
if not pkgmgr.games then
|
||||
pkgmgr.reload_games()
|
||||
end
|
||||
if not pkgmgr.texture_packs then
|
||||
pkgmgr.reload_texture_packs()
|
||||
end
|
||||
end
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
function pkgmgr.update_translations(list)
|
||||
for _, item in ipairs(list) do
|
||||
local info = core.get_content_info(item.path)
|
||||
assert(info.path)
|
||||
assert(info.textdomain)
|
||||
|
||||
assert(not item.is_translated)
|
||||
item.is_translated = true
|
||||
|
||||
if info.title and info.title ~= "" then
|
||||
item.title = core.get_content_translation(info.path, info.textdomain,
|
||||
core.translate(info.textdomain, info.title))
|
||||
end
|
||||
|
||||
if info.description and info.description ~= "" then
|
||||
item.description = core.get_content_translation(info.path, info.textdomain,
|
||||
core.translate(info.textdomain, info.description))
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
@@ -804,4 +856,4 @@ end
|
||||
--------------------------------------------------------------------------------
|
||||
-- read initial data
|
||||
--------------------------------------------------------------------------------
|
||||
pkgmgr.update_gamelist()
|
||||
pkgmgr.reload_games()
|
||||
|
||||
78
builtin/mainmenu/content/screenshots.lua
Normal file
78
builtin/mainmenu/content/screenshots.lua
Normal file
@@ -0,0 +1,78 @@
|
||||
--Minetest
|
||||
--Copyright (C) 2023-24 rubenwardy
|
||||
--
|
||||
--This program is free software; you can redistribute it and/or modify
|
||||
--it under the terms of the GNU Lesser General Public License as published by
|
||||
--the Free Software Foundation; either version 2.1 of the License, or
|
||||
--(at your option) any later version.
|
||||
--
|
||||
--This program is distributed in the hope that it will be useful,
|
||||
--but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
--GNU Lesser General Public License for more details.
|
||||
--
|
||||
--You should have received a copy of the GNU Lesser General Public License along
|
||||
--with this program; if not, write to the Free Software Foundation, Inc.,
|
||||
--51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
|
||||
|
||||
-- Screenshot
|
||||
local screenshot_dir = core.get_cache_path() .. DIR_DELIM .. "cdb"
|
||||
assert(core.create_dir(screenshot_dir))
|
||||
local screenshot_downloading = {}
|
||||
local screenshot_downloaded = {}
|
||||
|
||||
|
||||
local function get_file_extension(path)
|
||||
local parts = path:split(".")
|
||||
return parts[#parts]
|
||||
end
|
||||
|
||||
|
||||
function get_screenshot(package)
|
||||
if not package.thumbnail then
|
||||
return defaulttexturedir .. "no_screenshot.png"
|
||||
elseif screenshot_downloading[package.thumbnail] then
|
||||
return defaulttexturedir .. "loading_screenshot.png"
|
||||
end
|
||||
|
||||
-- Get tmp screenshot path
|
||||
local ext = get_file_extension(package.thumbnail)
|
||||
local filepath = screenshot_dir .. DIR_DELIM ..
|
||||
("%s-%s-%s.%s"):format(package.type, package.author, package.name, ext)
|
||||
|
||||
-- Return if already downloaded
|
||||
local file = io.open(filepath, "r")
|
||||
if file then
|
||||
file:close()
|
||||
return filepath
|
||||
end
|
||||
|
||||
-- Show error if we've failed to download before
|
||||
if screenshot_downloaded[package.thumbnail] then
|
||||
return defaulttexturedir .. "error_screenshot.png"
|
||||
end
|
||||
|
||||
-- Download
|
||||
|
||||
local function download_screenshot(params)
|
||||
return core.download_file(params.url, params.dest)
|
||||
end
|
||||
local function callback(success)
|
||||
screenshot_downloading[package.thumbnail] = nil
|
||||
screenshot_downloaded[package.thumbnail] = true
|
||||
if not success then
|
||||
core.log("warning", "Screenshot download failed for some reason")
|
||||
end
|
||||
ui.update()
|
||||
end
|
||||
if core.handle_async(download_screenshot,
|
||||
{ dest = filepath, url = package.thumbnail }, callback) then
|
||||
screenshot_downloading[package.thumbnail] = true
|
||||
else
|
||||
core.log("error", "ERROR: async event failed")
|
||||
return defaulttexturedir .. "error_screenshot.png"
|
||||
end
|
||||
|
||||
return defaulttexturedir .. "loading_screenshot.png"
|
||||
end
|
||||
@@ -46,6 +46,9 @@ local function reset()
|
||||
function core.get_texturepath()
|
||||
return txp_dir
|
||||
end
|
||||
function core.get_texturepath_share()
|
||||
return txp_dir
|
||||
end
|
||||
function core.get_modpath()
|
||||
return mods_dir
|
||||
end
|
||||
@@ -59,13 +62,6 @@ local function reset()
|
||||
setfenv(loadfile("builtin/common/misc_helpers.lua"), env)()
|
||||
setfenv(loadfile("builtin/mainmenu/content/pkgmgr.lua"), env)()
|
||||
|
||||
function env.pkgmgr.update_gamelist()
|
||||
table.insert(calls, { "update_gamelist" })
|
||||
end
|
||||
function env.pkgmgr.refresh_globals()
|
||||
table.insert(calls, { "refresh_globals" })
|
||||
end
|
||||
|
||||
function env.assert_calls(list)
|
||||
assert.are.same(list, calls)
|
||||
end
|
||||
@@ -113,7 +109,6 @@ describe("install_dir", function()
|
||||
env.assert_calls({
|
||||
{ "delete_dir", mods_dir .. "/mymod" },
|
||||
{ "copy_dir", "/tmp/123", mods_dir .. "/mymod", false },
|
||||
{ "refresh_globals" },
|
||||
})
|
||||
end)
|
||||
|
||||
@@ -129,7 +124,6 @@ describe("install_dir", function()
|
||||
env.assert_calls({
|
||||
{ "delete_dir", mods_dir .. "/mymod" },
|
||||
{ "copy_dir", "/tmp/123", mods_dir .. "/mymod", false },
|
||||
{ "refresh_globals" },
|
||||
})
|
||||
end)
|
||||
|
||||
@@ -145,7 +139,6 @@ describe("install_dir", function()
|
||||
env.assert_calls({
|
||||
{ "delete_dir", games_dir .. "/mygame" },
|
||||
{ "copy_dir", "/tmp/123", games_dir .. "/mygame", false },
|
||||
{ "update_gamelist" },
|
||||
})
|
||||
end)
|
||||
|
||||
@@ -161,7 +154,6 @@ describe("install_dir", function()
|
||||
env.assert_calls({
|
||||
{ "delete_dir", mods_dir .. "/123" },
|
||||
{ "copy_dir", "/tmp/123", mods_dir .. "/123", false },
|
||||
{ "refresh_globals" },
|
||||
})
|
||||
end)
|
||||
|
||||
@@ -188,7 +180,6 @@ describe("install_dir", function()
|
||||
env.assert_calls({
|
||||
{ "delete_dir", "/tmp/alt-target" },
|
||||
{ "copy_dir", "/tmp/123", "/tmp/alt-target", false },
|
||||
{ "refresh_globals" },
|
||||
})
|
||||
end)
|
||||
|
||||
@@ -238,6 +229,5 @@ describe("install_dir", function()
|
||||
path, message = env.pkgmgr.install_dir("txp", "/tmp/123", "name", nil)
|
||||
assert.is._not._nil(path)
|
||||
assert.is._nil(message)
|
||||
|
||||
end)
|
||||
end)
|
||||
|
||||
@@ -26,8 +26,25 @@ if not core.get_http_api then
|
||||
end
|
||||
|
||||
|
||||
assert(core.create_dir(core.get_cache_path() .. DIR_DELIM .. "cdb"))
|
||||
local cache_file_path = core.get_cache_path() .. DIR_DELIM .. "cdb" .. DIR_DELIM .. "updates.json"
|
||||
local has_fetched = false
|
||||
local latest_releases
|
||||
do
|
||||
if check_cache_age("cdb_updates_last_checked", 24 * 3600) then
|
||||
local f = io.open(cache_file_path, "r")
|
||||
local data = ""
|
||||
if f then
|
||||
data = f:read("*a")
|
||||
f:close()
|
||||
end
|
||||
data = data ~= "" and core.parse_json(data) or nil
|
||||
if type(data) == "table" then
|
||||
latest_releases = data
|
||||
has_fetched = true
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
local function fetch_latest_releases()
|
||||
@@ -55,9 +72,6 @@ end
|
||||
|
||||
|
||||
local function has_packages_from_cdb()
|
||||
pkgmgr.refresh_globals()
|
||||
pkgmgr.update_gamelist()
|
||||
|
||||
for _, content in pairs(pkgmgr.get_all()) do
|
||||
if pkgmgr.get_contentdb_id(content) then
|
||||
return true
|
||||
@@ -89,8 +103,10 @@ local function fetch()
|
||||
has_fetched = false
|
||||
return
|
||||
end
|
||||
|
||||
latest_releases = lowercase_keys(releases)
|
||||
core.safe_file_write(cache_file_path, core.write_json(latest_releases))
|
||||
cache_settings:set("cdb_updates_last_checked", tostring(os.time()))
|
||||
|
||||
if update_detector.get_count() > 0 then
|
||||
local maintab = ui.find_by_name("maintab")
|
||||
if not maintab.hidden then
|
||||
@@ -108,9 +124,6 @@ function update_detector.get_all()
|
||||
return {}
|
||||
end
|
||||
|
||||
pkgmgr.refresh_globals()
|
||||
pkgmgr.update_gamelist()
|
||||
|
||||
local ret = {}
|
||||
local all_content = pkgmgr.get_all()
|
||||
for _, content in ipairs(all_content) do
|
||||
|
||||
@@ -334,7 +334,7 @@ local function handle_buttons(this, fields)
|
||||
if fields.btn_config_world_cdb then
|
||||
this.data.list = nil
|
||||
|
||||
local dlg = create_store_dlg("mod")
|
||||
local dlg = create_contentdb_dlg("mod")
|
||||
dlg:set_parent(this)
|
||||
this:hide()
|
||||
dlg:show()
|
||||
|
||||
@@ -70,6 +70,8 @@ local flag_checkboxes = {
|
||||
{ "trees", fgettext("Trees and jungle grass") },
|
||||
{ "flat", fgettext("Flat terrain") },
|
||||
{ "mudflow", fgettext("Mud flow"), fgettext("Terrain surface erosion") },
|
||||
{ "temples", fgettext("Desert temples"),
|
||||
fgettext("Different dungeon variant generated in desert biomes (only if dungeons enabled)") },
|
||||
-- Biome settings are in mgv6_biomes below
|
||||
},
|
||||
}
|
||||
@@ -279,7 +281,7 @@ local function create_world_formspec(dialogdata)
|
||||
end
|
||||
|
||||
local retval =
|
||||
"size[12.25,7,true]" ..
|
||||
"size[12.25,7.4,true]" ..
|
||||
|
||||
-- Left side
|
||||
"container[0,0]"..
|
||||
@@ -321,8 +323,10 @@ local function create_world_formspec(dialogdata)
|
||||
"container_end[]"..
|
||||
|
||||
-- Menu buttons
|
||||
"button[3.25,6.5;3,0.5;world_create_confirm;" .. fgettext("Create") .. "]" ..
|
||||
"button[6.25,6.5;3,0.5;world_create_cancel;" .. fgettext("Cancel") .. "]"
|
||||
"container[0,6.9]"..
|
||||
"button[3.25,0;3,0.5;world_create_confirm;" .. fgettext("Create") .. "]" ..
|
||||
"button[6.25,0;3,0.5;world_create_cancel;" .. fgettext("Cancel") .. "]" ..
|
||||
"container_end[]"
|
||||
|
||||
return retval
|
||||
|
||||
@@ -331,7 +335,7 @@ end
|
||||
local function create_world_buttonhandler(this, fields)
|
||||
|
||||
if fields["world_create_open_cdb"] then
|
||||
local dlg = create_store_dlg("game")
|
||||
local dlg = create_contentdb_dlg("game")
|
||||
dlg:set_parent(this.parent)
|
||||
this:delete()
|
||||
this.parent:hide()
|
||||
|
||||
@@ -37,11 +37,7 @@ local function delete_content_buttonhandler(this, fields)
|
||||
gamedata.errormessage = fgettext_ne("pkgmgr: failed to delete \"$1\"", this.data.content.path)
|
||||
end
|
||||
|
||||
if this.data.content.type == "game" then
|
||||
pkgmgr.update_gamelist()
|
||||
else
|
||||
pkgmgr.refresh_globals()
|
||||
end
|
||||
pkgmgr.reload_by_type(this.data.content.type)
|
||||
else
|
||||
gamedata.errormessage = fgettext_ne("pkgmgr: invalid path \"$1\"", this.data.content.path)
|
||||
end
|
||||
|
||||
@@ -15,15 +15,30 @@
|
||||
--with this program; if not, write to the Free Software Foundation, Inc.,
|
||||
--51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
|
||||
---- IMPORTANT ----
|
||||
-- This whole file can be removed after a while.
|
||||
-- It was only directly useful for upgrades from 5.7.0 to 5.8.0, but
|
||||
-- maybe some odd fellow directly upgrades from 5.6.1 to 5.9.0 in the future...
|
||||
-- see <https://github.com/minetest/minetest/pull/13850> in case it's not obvious
|
||||
---- ----
|
||||
|
||||
local SETTING_NAME = "no_mtg_notification"
|
||||
|
||||
function check_reinstall_mtg()
|
||||
if core.settings:get_bool("no_mtg_notification") then
|
||||
-- used to be in minetest.conf
|
||||
if core.settings:get_bool(SETTING_NAME) then
|
||||
cache_settings:set_bool(SETTING_NAME, true)
|
||||
core.settings:remove(SETTING_NAME)
|
||||
end
|
||||
|
||||
if cache_settings:get_bool(SETTING_NAME) then
|
||||
return
|
||||
end
|
||||
|
||||
local games = core.get_games()
|
||||
for _, game in ipairs(games) do
|
||||
if game.id == "minetest" then
|
||||
core.settings:set_bool("no_mtg_notification", true)
|
||||
cache_settings:set_bool(SETTING_NAME, true)
|
||||
return
|
||||
end
|
||||
end
|
||||
@@ -37,7 +52,7 @@ function check_reinstall_mtg()
|
||||
end
|
||||
end
|
||||
if not mtg_world_found then
|
||||
core.settings:set_bool("no_mtg_notification", true)
|
||||
cache_settings:set_bool(SETTING_NAME, true)
|
||||
return
|
||||
end
|
||||
|
||||
@@ -78,7 +93,7 @@ local function buttonhandler(this, fields)
|
||||
|
||||
local maintab = ui.find_by_name("maintab")
|
||||
|
||||
local dlg = create_store_dlg(nil, "minetest/minetest")
|
||||
local dlg = create_contentdb_dlg(nil, "minetest/minetest")
|
||||
dlg:set_parent(maintab)
|
||||
maintab:hide()
|
||||
dlg:show()
|
||||
@@ -87,7 +102,7 @@ local function buttonhandler(this, fields)
|
||||
end
|
||||
|
||||
if fields.dismiss then
|
||||
core.settings:set_bool("no_mtg_notification", true)
|
||||
cache_settings:set_bool("no_mtg_notification", true)
|
||||
this:delete()
|
||||
return true
|
||||
end
|
||||
@@ -111,5 +126,3 @@ function create_reinstall_mtg_dlg()
|
||||
buttonhandler, eventhandler)
|
||||
return dlg
|
||||
end
|
||||
|
||||
|
||||
|
||||
@@ -45,7 +45,7 @@ local function rename_modpack_buttonhandler(this, fields)
|
||||
local oldpath = this.data.mod.path
|
||||
local targetpath = this.data.mod.parent_dir .. DIR_DELIM .. fields["te_modpack_name"]
|
||||
os.rename(oldpath, targetpath)
|
||||
pkgmgr.refresh_globals()
|
||||
pkgmgr.reload_global_mods()
|
||||
pkgmgr.selected_mod = pkgmgr.global_mods:get_current_index(
|
||||
pkgmgr.global_mods:raw_index_by_uid(fields["te_modpack_name"]))
|
||||
|
||||
|
||||
@@ -51,12 +51,13 @@ end
|
||||
local function version_info_buttonhandler(this, fields)
|
||||
if fields.version_check_remind then
|
||||
-- Erase last known, user will be reminded again at next check
|
||||
core.settings:set("update_last_known", "")
|
||||
cache_settings:set("update_last_known", "")
|
||||
this:delete()
|
||||
return true
|
||||
end
|
||||
if fields.version_check_never then
|
||||
core.settings:set("update_last_checked", "disabled")
|
||||
-- clear checked URL
|
||||
core.settings:set("update_information_url", "")
|
||||
this:delete()
|
||||
return true
|
||||
end
|
||||
@@ -116,7 +117,7 @@ local function on_version_info_received(json)
|
||||
return
|
||||
end
|
||||
|
||||
local known_update = tonumber(core.settings:get("update_last_known")) or 0
|
||||
local known_update = tonumber(cache_settings:get("update_last_known")) or 0
|
||||
|
||||
-- Format: MMNNPPP (Major, Minor, Patch)
|
||||
local new_number = type(json.latest) == "table" and json.latest.version_code
|
||||
@@ -135,7 +136,7 @@ local function on_version_info_received(json)
|
||||
return
|
||||
end
|
||||
|
||||
core.settings:set("update_last_known", tostring(new_number))
|
||||
cache_settings:set("update_last_known", tostring(new_number))
|
||||
|
||||
-- Show version info dialog (once)
|
||||
maintab:hide()
|
||||
@@ -149,20 +150,20 @@ end
|
||||
|
||||
function check_new_version()
|
||||
local url = core.settings:get("update_information_url")
|
||||
if core.settings:get("update_last_checked") == "disabled" or
|
||||
url == "" then
|
||||
if url == "" then
|
||||
-- Never show any updates
|
||||
return
|
||||
end
|
||||
|
||||
local time_now = os.time()
|
||||
local time_checked = tonumber(core.settings:get("update_last_checked")) or 0
|
||||
if time_now - time_checked < 2 * 24 * 3600 then
|
||||
-- Check interval of 2 entire days
|
||||
-- every 2 days
|
||||
if check_cache_age("update_last_checked", 2 * 24 * 3600) then
|
||||
return
|
||||
end
|
||||
cache_settings:set("update_last_checked", tostring(os.time()))
|
||||
|
||||
core.settings:set("update_last_checked", tostring(time_now))
|
||||
-- Clean old leftovers (this can be removed after 5.9.0 or so)
|
||||
core.settings:remove("update_last_checked")
|
||||
core.settings:remove("update_last_known")
|
||||
|
||||
core.handle_async(function(params)
|
||||
local http = core.get_http_api()
|
||||
|
||||
@@ -28,8 +28,6 @@ local basepath = core.get_builtin_path()
|
||||
defaulttexturedir = core.get_texturepath_share() .. DIR_DELIM .. "base" ..
|
||||
DIR_DELIM .. "pack" .. DIR_DELIM
|
||||
|
||||
dofile(menupath .. DIR_DELIM .. "misc.lua")
|
||||
|
||||
dofile(basepath .. "common" .. DIR_DELIM .. "filterlist.lua")
|
||||
dofile(basepath .. "fstk" .. DIR_DELIM .. "buttonbar.lua")
|
||||
dofile(basepath .. "fstk" .. DIR_DELIM .. "dialog.lua")
|
||||
|
||||
@@ -1,6 +0,0 @@
|
||||
|
||||
-- old non-method sound function
|
||||
|
||||
function core.sound_stop(handle, ...)
|
||||
return handle:stop(...)
|
||||
end
|
||||
@@ -17,7 +17,7 @@
|
||||
|
||||
serverlistmgr = {
|
||||
-- continent code we detected for ourselves
|
||||
my_continent = core.get_once("continent"),
|
||||
my_continent = nil,
|
||||
|
||||
-- list of locally favorites servers
|
||||
favorites = nil,
|
||||
@@ -26,6 +26,15 @@ serverlistmgr = {
|
||||
servers = nil,
|
||||
}
|
||||
|
||||
do
|
||||
if check_cache_age("geoip_last_checked", 3600) then
|
||||
local tmp = cache_settings:get("geoip") or ""
|
||||
if tmp:match("^[A-Z][A-Z]$") then
|
||||
serverlistmgr.my_continent = tmp
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
-- Efficient data structure for normalizing arbitrary scores attached to objects
|
||||
-- e.g. {{"a", 3.14}, {"b", 3.14}, {"c", 20}, {"d", 0}}
|
||||
@@ -71,7 +80,8 @@ local WEIGHT_SORT = 2
|
||||
-- how much the estimated latency contributes to the final ranking
|
||||
local WEIGHT_LATENCY = 1
|
||||
|
||||
local function order_server_list(list)
|
||||
--- @param list of servers, will be modified.
|
||||
local function order_server_list_internal(list)
|
||||
-- calculate the scores
|
||||
local s1 = Normalizer:new()
|
||||
local s2 = Normalizer:new()
|
||||
@@ -90,28 +100,58 @@ local function order_server_list(list)
|
||||
s1 = s1:calc()
|
||||
s2 = s2:calc()
|
||||
|
||||
-- make a shallow copy and pre-calculate ordering
|
||||
local res, order = {}, {}
|
||||
for i = 1, #list do
|
||||
local fav = list[i]
|
||||
res[i] = fav
|
||||
|
||||
local n = s1[fav] * WEIGHT_SORT + s2[fav] * WEIGHT_LATENCY
|
||||
order[fav] = n
|
||||
-- pre-calculate ordering
|
||||
local order = {}
|
||||
for _, fav in ipairs(list) do
|
||||
order[fav] = s1[fav] * WEIGHT_SORT + s2[fav] * WEIGHT_LATENCY
|
||||
end
|
||||
|
||||
-- now sort the list
|
||||
table.sort(res, function(fav1, fav2)
|
||||
table.sort(list, function(fav1, fav2)
|
||||
return order[fav1] > order[fav2]
|
||||
end)
|
||||
end
|
||||
|
||||
return res
|
||||
local function order_server_list(list)
|
||||
-- split the list into two parts and sort them separately, to keep empty
|
||||
-- servers at the bottom.
|
||||
local nonempty, empty = {}, {}
|
||||
|
||||
for _, fav in ipairs(list) do
|
||||
if (fav.clients or 0) > 0 then
|
||||
table.insert(nonempty, fav)
|
||||
else
|
||||
table.insert(empty, fav)
|
||||
end
|
||||
end
|
||||
|
||||
order_server_list_internal(nonempty)
|
||||
order_server_list_internal(empty)
|
||||
|
||||
table.insert_all(nonempty, empty)
|
||||
return nonempty
|
||||
end
|
||||
|
||||
local public_downloading = false
|
||||
local geoip_downloading = false
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
local function fetch_geoip()
|
||||
local http = core.get_http_api()
|
||||
local url = core.settings:get("serverlist_url") .. "/geoip"
|
||||
|
||||
local response = http.fetch_sync({ url = url })
|
||||
if not response.succeeded then
|
||||
return
|
||||
end
|
||||
|
||||
local retval = core.parse_json(response.data)
|
||||
if type(retval) ~= "table" then
|
||||
return
|
||||
end
|
||||
return type(retval.continent) == "string" and retval.continent
|
||||
end
|
||||
|
||||
function serverlistmgr.sync()
|
||||
if not serverlistmgr.servers then
|
||||
serverlistmgr.servers = {{
|
||||
@@ -129,37 +169,23 @@ function serverlistmgr.sync()
|
||||
return
|
||||
end
|
||||
|
||||
-- only fetched once per MT instance
|
||||
if not serverlistmgr.my_continent and not geoip_downloading then
|
||||
geoip_downloading = true
|
||||
core.handle_async(
|
||||
function(param)
|
||||
local http = core.get_http_api()
|
||||
local url = core.settings:get("serverlist_url") .. "/geoip"
|
||||
|
||||
local response = http.fetch_sync({ url = url })
|
||||
if not response.succeeded then
|
||||
return
|
||||
end
|
||||
|
||||
local retval = core.parse_json(response.data)
|
||||
return retval and type(retval.continent) == "string" and retval.continent
|
||||
end,
|
||||
nil,
|
||||
function(result)
|
||||
geoip_downloading = false
|
||||
if not result then
|
||||
return
|
||||
end
|
||||
serverlistmgr.my_continent = result
|
||||
core.set_once("continent", result)
|
||||
-- reorder list if we already have it
|
||||
if serverlistmgr.servers then
|
||||
serverlistmgr.servers = order_server_list(serverlistmgr.servers)
|
||||
core.event_handler("Refresh")
|
||||
end
|
||||
core.handle_async(fetch_geoip, nil, function(result)
|
||||
geoip_downloading = false
|
||||
if not result then
|
||||
return
|
||||
end
|
||||
)
|
||||
serverlistmgr.my_continent = result
|
||||
cache_settings:set("geoip", result)
|
||||
cache_settings:set("geoip_last_checked", tostring(os.time()))
|
||||
|
||||
-- re-sort list if applicable
|
||||
if serverlistmgr.servers then
|
||||
serverlistmgr.servers = order_server_list(serverlistmgr.servers)
|
||||
core.event_handler("Refresh")
|
||||
end
|
||||
end)
|
||||
end
|
||||
|
||||
if public_downloading then
|
||||
@@ -167,6 +193,7 @@ function serverlistmgr.sync()
|
||||
end
|
||||
public_downloading = true
|
||||
|
||||
-- note: this isn't cached because it's way too dynamic
|
||||
core.handle_async(
|
||||
function(param)
|
||||
local http = core.get_http_api()
|
||||
|
||||
@@ -306,17 +306,36 @@ function make.flags(setting)
|
||||
"label[0,0.1;" .. get_label(setting) .. "]",
|
||||
}
|
||||
|
||||
local value = core.settings:get(setting.name) or setting.default
|
||||
self.resettable = core.settings:has(setting.name)
|
||||
|
||||
checkboxes = {}
|
||||
for _, name in ipairs(value:split(",")) do
|
||||
name = name:trim()
|
||||
if name:sub(1, 2) == "no" then
|
||||
checkboxes[name:sub(3)] = false
|
||||
elseif name ~= "" then
|
||||
checkboxes[name] = true
|
||||
for _, name in ipairs(setting.possible) do
|
||||
checkboxes[name] = false
|
||||
end
|
||||
local function apply_flags(flag_string, what)
|
||||
local prefixed_flags = {}
|
||||
for _, name in ipairs(flag_string:split(",")) do
|
||||
prefixed_flags[name:trim()] = true
|
||||
end
|
||||
for _, name in ipairs(setting.possible) do
|
||||
local enabled = prefixed_flags[name]
|
||||
local disabled = prefixed_flags["no" .. name]
|
||||
if enabled and disabled then
|
||||
core.log("warning", "Flag " .. name .. " in " .. what .. " " ..
|
||||
setting.name .. " both enabled and disabled, ignoring")
|
||||
elseif enabled then
|
||||
checkboxes[name] = true
|
||||
elseif disabled then
|
||||
checkboxes[name] = false
|
||||
end
|
||||
end
|
||||
end
|
||||
-- First apply the default, which is necessary since flags
|
||||
-- which are not overridden may be missing from the value.
|
||||
apply_flags(setting.default, "default for setting")
|
||||
local value = core.settings:get(setting.name)
|
||||
if value then
|
||||
apply_flags(value, "setting")
|
||||
end
|
||||
|
||||
local columns = math.max(math.floor(avail_w / 2.5), 1)
|
||||
@@ -325,18 +344,16 @@ function make.flags(setting)
|
||||
local y = 0.55
|
||||
|
||||
for _, possible in ipairs(setting.possible) do
|
||||
if possible:sub(1, 2) ~= "no" then
|
||||
if x >= avail_w then
|
||||
x = 0
|
||||
y = y + 0.5
|
||||
end
|
||||
|
||||
local is_checked = checkboxes[possible]
|
||||
fs[#fs + 1] = ("checkbox[%f,%f;%s;%s;%s]"):format(
|
||||
x, y, setting.name .. "_" .. possible,
|
||||
core.formspec_escape(possible), tostring(is_checked))
|
||||
x = x + column_width
|
||||
if x >= avail_w then
|
||||
x = 0
|
||||
y = y + 0.5
|
||||
end
|
||||
|
||||
local is_checked = checkboxes[possible]
|
||||
fs[#fs + 1] = ("checkbox[%f,%f;%s;%s;%s]"):format(
|
||||
x, y, setting.name .. "_" .. possible,
|
||||
core.formspec_escape(possible), tostring(is_checked))
|
||||
x = x + column_width
|
||||
end
|
||||
|
||||
return table.concat(fs, ""), y + 0.25
|
||||
@@ -355,12 +372,10 @@ function make.flags(setting)
|
||||
if changed then
|
||||
local values = {}
|
||||
for _, name in ipairs(setting.possible) do
|
||||
if name:sub(1, 2) ~= "no" then
|
||||
if checkboxes[name] then
|
||||
table.insert(values, name)
|
||||
else
|
||||
table.insert(values, "no" .. name)
|
||||
end
|
||||
if checkboxes[name] then
|
||||
table.insert(values, name)
|
||||
else
|
||||
table.insert(values, "no" .. name)
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
@@ -22,16 +22,27 @@ local component_funcs = dofile(core.get_mainmenu_path() .. DIR_DELIM ..
|
||||
local shadows_component = dofile(core.get_mainmenu_path() .. DIR_DELIM ..
|
||||
"settings" .. DIR_DELIM .. "shadows_component.lua")
|
||||
|
||||
|
||||
local full_settings = settingtypes.parse_config_file(false, true)
|
||||
local loaded = false
|
||||
local full_settings
|
||||
local info_icon_path = core.formspec_escape(defaulttexturedir .. "settings_info.png")
|
||||
local reset_icon_path = core.formspec_escape(defaulttexturedir .. "settings_reset.png")
|
||||
|
||||
local all_pages = {}
|
||||
local page_by_id = {}
|
||||
local filtered_pages = all_pages
|
||||
local filtered_page_by_id = page_by_id
|
||||
|
||||
|
||||
local function get_setting_info(name)
|
||||
for _, entry in ipairs(full_settings) do
|
||||
if entry.type ~= "category" and entry.name == name then
|
||||
return entry
|
||||
end
|
||||
end
|
||||
|
||||
return nil
|
||||
end
|
||||
|
||||
|
||||
local function add_page(page)
|
||||
assert(type(page.id) == "string")
|
||||
assert(type(page.title) == "string")
|
||||
@@ -46,49 +57,6 @@ local function add_page(page)
|
||||
end
|
||||
|
||||
|
||||
local change_keys = {
|
||||
query_text = "Change Keys",
|
||||
requires = {
|
||||
keyboard_mouse = true,
|
||||
},
|
||||
get_formspec = function(self, avail_w)
|
||||
local btn_w = math.min(avail_w, 3)
|
||||
return ("button[0,0;%f,0.8;btn_change_keys;%s]"):format(btn_w, fgettext("Change Keys")), 0.8
|
||||
end,
|
||||
on_submit = function(self, fields)
|
||||
if fields.btn_change_keys then
|
||||
core.show_keys_menu()
|
||||
end
|
||||
end,
|
||||
}
|
||||
|
||||
|
||||
add_page({
|
||||
id = "accessibility",
|
||||
title = fgettext_ne("Accessibility"),
|
||||
content = {
|
||||
"language",
|
||||
{ heading = fgettext_ne("General") },
|
||||
"font_size",
|
||||
"chat_font_size",
|
||||
"gui_scaling",
|
||||
"hud_scaling",
|
||||
"show_nametag_backgrounds",
|
||||
{ heading = fgettext_ne("Chat") },
|
||||
"console_height",
|
||||
"console_alpha",
|
||||
"console_color",
|
||||
{ heading = fgettext_ne("Controls") },
|
||||
"autojump",
|
||||
"safe_dig_and_place",
|
||||
{ heading = fgettext_ne("Movement") },
|
||||
"arm_inertia",
|
||||
"view_bobbing_amount",
|
||||
"fall_bobbing_amount",
|
||||
},
|
||||
})
|
||||
|
||||
|
||||
local function load_settingtypes()
|
||||
local page = nil
|
||||
local section = nil
|
||||
@@ -129,94 +97,134 @@ local function load_settingtypes()
|
||||
end
|
||||
end
|
||||
end
|
||||
load_settingtypes()
|
||||
|
||||
table.insert(page_by_id.controls_keyboard_and_mouse.content, 1, change_keys)
|
||||
do
|
||||
local content = page_by_id.graphics_and_audio_shaders.content
|
||||
local idx = table.indexof(content, "enable_dynamic_shadows")
|
||||
table.insert(content, idx, shadows_component)
|
||||
end
|
||||
|
||||
|
||||
local function get_setting_info(name)
|
||||
for _, entry in ipairs(full_settings) do
|
||||
if entry.type ~= "category" and entry.name == name then
|
||||
return entry
|
||||
end
|
||||
local function load()
|
||||
if loaded then
|
||||
return
|
||||
end
|
||||
loaded = true
|
||||
|
||||
full_settings = settingtypes.parse_config_file(false, true)
|
||||
|
||||
local change_keys = {
|
||||
query_text = "Controls",
|
||||
requires = {
|
||||
keyboard_mouse = true,
|
||||
},
|
||||
get_formspec = function(self, avail_w)
|
||||
local btn_w = math.min(avail_w, 3)
|
||||
return ("button[0,0;%f,0.8;btn_change_keys;%s]"):format(btn_w, fgettext("Controls")), 0.8
|
||||
end,
|
||||
on_submit = function(self, fields)
|
||||
if fields.btn_change_keys then
|
||||
core.show_keys_menu()
|
||||
end
|
||||
end,
|
||||
}
|
||||
|
||||
add_page({
|
||||
id = "accessibility",
|
||||
title = fgettext_ne("Accessibility"),
|
||||
content = {
|
||||
"language",
|
||||
{ heading = fgettext_ne("General") },
|
||||
"font_size",
|
||||
"chat_font_size",
|
||||
"gui_scaling",
|
||||
"hud_scaling",
|
||||
"show_nametag_backgrounds",
|
||||
{ heading = fgettext_ne("Chat") },
|
||||
"console_height",
|
||||
"console_alpha",
|
||||
"console_color",
|
||||
{ heading = fgettext_ne("Controls") },
|
||||
"autojump",
|
||||
"safe_dig_and_place",
|
||||
{ heading = fgettext_ne("Movement") },
|
||||
"arm_inertia",
|
||||
"view_bobbing_amount",
|
||||
"fall_bobbing_amount",
|
||||
},
|
||||
})
|
||||
|
||||
load_settingtypes()
|
||||
|
||||
table.insert(page_by_id.controls_keyboard_and_mouse.content, 1, change_keys)
|
||||
do
|
||||
local content = page_by_id.graphics_and_audio_shaders.content
|
||||
local idx = table.indexof(content, "enable_dynamic_shadows")
|
||||
table.insert(content, idx, shadows_component)
|
||||
end
|
||||
|
||||
return nil
|
||||
-- These must not be translated, as they need to show in the local
|
||||
-- language no matter the user's current language.
|
||||
-- This list must be kept in sync with src/unsupported_language_list.txt.
|
||||
get_setting_info("language").option_labels = {
|
||||
[""] = fgettext_ne("(Use system language)"),
|
||||
--ar = " [ar]", blacklisted
|
||||
be = "Беларуская [be]",
|
||||
bg = "Български [bg]",
|
||||
ca = "Català [ca]",
|
||||
cs = "Česky [cs]",
|
||||
cy = "Cymraeg [cy]",
|
||||
da = "Dansk [da]",
|
||||
de = "Deutsch [de]",
|
||||
--dv = " [dv]", blacklisted
|
||||
el = "Ελληνικά [el]",
|
||||
en = "English [en]",
|
||||
eo = "Esperanto [eo]",
|
||||
es = "Español [es]",
|
||||
et = "Eesti [et]",
|
||||
eu = "Euskara [eu]",
|
||||
fi = "Suomi [fi]",
|
||||
fil = "Wikang Filipino [fil]",
|
||||
fr = "Français [fr]",
|
||||
gd = "Gàidhlig [gd]",
|
||||
gl = "Galego [gl]",
|
||||
--he = " [he]", blacklisted
|
||||
--hi = " [hi]", blacklisted
|
||||
hu = "Magyar [hu]",
|
||||
id = "Bahasa Indonesia [id]",
|
||||
it = "Italiano [it]",
|
||||
ja = "日本語 [ja]",
|
||||
jbo = "Lojban [jbo]",
|
||||
kk = "Қазақша [kk]",
|
||||
--kn = " [kn]", blacklisted
|
||||
ko = "한국어 [ko]",
|
||||
ky = "Kırgızca / Кыргызча [ky]",
|
||||
lt = "Lietuvių [lt]",
|
||||
lv = "Latviešu [lv]",
|
||||
mn = "Монгол [mn]",
|
||||
mr = "मराठी [mr]",
|
||||
ms = "Bahasa Melayu [ms]",
|
||||
--ms_Arab = " [ms_Arab]", blacklisted
|
||||
nb = "Norsk Bokmål [nb]",
|
||||
nl = "Nederlands [nl]",
|
||||
nn = "Norsk Nynorsk [nn]",
|
||||
oc = "Occitan [oc]",
|
||||
pl = "Polski [pl]",
|
||||
pt = "Português [pt]",
|
||||
pt_BR = "Português do Brasil [pt_BR]",
|
||||
ro = "Română [ro]",
|
||||
ru = "Русский [ru]",
|
||||
sk = "Slovenčina [sk]",
|
||||
sl = "Slovenščina [sl]",
|
||||
sr_Cyrl = "Српски [sr_Cyrl]",
|
||||
sr_Latn = "Srpski (Latinica) [sr_Latn]",
|
||||
sv = "Svenska [sv]",
|
||||
sw = "Kiswahili [sw]",
|
||||
--th = " [th]", blacklisted
|
||||
tr = "Türkçe [tr]",
|
||||
tt = "Tatarça [tt]",
|
||||
uk = "Українська [uk]",
|
||||
vi = "Tiếng Việt [vi]",
|
||||
zh_CN = "中文 (简体) [zh_CN]",
|
||||
zh_TW = "正體中文 (繁體) [zh_TW]",
|
||||
}
|
||||
end
|
||||
|
||||
|
||||
-- These must not be translated, as they need to show in the local
|
||||
-- language no matter the user's current language.
|
||||
-- This list must be kept in sync with src/unsupported_language_list.txt.
|
||||
get_setting_info("language").option_labels = {
|
||||
[""] = fgettext_ne("(Use system language)"),
|
||||
--ar = " [ar]", blacklisted
|
||||
be = "Беларуская [be]",
|
||||
bg = "Български [bg]",
|
||||
ca = "Català [ca]",
|
||||
cs = "Česky [cs]",
|
||||
cy = "Cymraeg [cy]",
|
||||
da = "Dansk [da]",
|
||||
de = "Deutsch [de]",
|
||||
--dv = " [dv]", blacklisted
|
||||
el = "Ελληνικά [el]",
|
||||
en = "English [en]",
|
||||
eo = "Esperanto [eo]",
|
||||
es = "Español [es]",
|
||||
et = "Eesti [et]",
|
||||
eu = "Euskara [eu]",
|
||||
fi = "Suomi [fi]",
|
||||
fil = "Wikang Filipino [fil]",
|
||||
fr = "Français [fr]",
|
||||
gd = "Gàidhlig [gd]",
|
||||
gl = "Galego [gl]",
|
||||
--he = " [he]", blacklisted
|
||||
--hi = " [hi]", blacklisted
|
||||
hu = "Magyar [hu]",
|
||||
id = "Bahasa Indonesia [id]",
|
||||
it = "Italiano [it]",
|
||||
ja = "日本語 [ja]",
|
||||
jbo = "Lojban [jbo]",
|
||||
kk = "Қазақша [kk]",
|
||||
--kn = " [kn]", blacklisted
|
||||
ko = "한국어 [ko]",
|
||||
ky = "Kırgızca / Кыргызча [ky]",
|
||||
lt = "Lietuvių [lt]",
|
||||
lv = "Latviešu [lv]",
|
||||
mn = "Монгол [mn]",
|
||||
mr = "मराठी [mr]",
|
||||
ms = "Bahasa Melayu [ms]",
|
||||
--ms_Arab = " [ms_Arab]", blacklisted
|
||||
nb = "Norsk Bokmål [nb]",
|
||||
nl = "Nederlands [nl]",
|
||||
nn = "Norsk Nynorsk [nn]",
|
||||
oc = "Occitan [oc]",
|
||||
pl = "Polski [pl]",
|
||||
pt = "Português [pt]",
|
||||
pt_BR = "Português do Brasil [pt_BR]",
|
||||
ro = "Română [ro]",
|
||||
ru = "Русский [ru]",
|
||||
sk = "Slovenčina [sk]",
|
||||
sl = "Slovenščina [sl]",
|
||||
sr_Cyrl = "Српски [sr_Cyrl]",
|
||||
sr_Latn = "Srpski (Latinica) [sr_Latn]",
|
||||
sv = "Svenska [sv]",
|
||||
sw = "Kiswahili [sw]",
|
||||
--th = " [th]", blacklisted
|
||||
tr = "Türkçe [tr]",
|
||||
tt = "Tatarça [tt]",
|
||||
uk = "Українська [uk]",
|
||||
vi = "Tiếng Việt [vi]",
|
||||
zh_CN = "中文 (简体) [zh_CN]",
|
||||
zh_TW = "正體中文 (繁體) [zh_TW]",
|
||||
}
|
||||
|
||||
|
||||
-- See if setting matches keywords
|
||||
local function get_setting_match_weight(entry, query_keywords)
|
||||
local setting_score = 0
|
||||
@@ -312,12 +320,12 @@ local function check_requirements(name, requires)
|
||||
end
|
||||
|
||||
local video_driver = core.get_active_driver()
|
||||
local shaders_support = video_driver == "opengl" or video_driver == "ogles2"
|
||||
local shaders_support = video_driver == "opengl" or video_driver == "opengl3" or video_driver == "ogles2"
|
||||
local special = {
|
||||
android = PLATFORM == "Android",
|
||||
desktop = PLATFORM ~= "Android",
|
||||
touchscreen_gui = TOUCHSCREEN_GUI,
|
||||
keyboard_mouse = not TOUCHSCREEN_GUI,
|
||||
touchscreen_gui = core.settings:get_bool("enable_touch"),
|
||||
keyboard_mouse = not core.settings:get_bool("enable_touch"),
|
||||
shaders_support = shaders_support,
|
||||
shaders = core.settings:get_bool("enable_shaders") and shaders_support,
|
||||
opengl = video_driver == "opengl",
|
||||
@@ -449,13 +457,14 @@ local function get_formspec(dialogdata)
|
||||
|
||||
local extra_h = 1 -- not included in tabsize.height
|
||||
local tabsize = {
|
||||
width = TOUCHSCREEN_GUI and 16.5 or 15.5,
|
||||
height = TOUCHSCREEN_GUI and (10 - extra_h) or 12,
|
||||
width = core.settings:get_bool("enable_touch") and 16.5 or 15.5,
|
||||
height = core.settings:get_bool("enable_touch") and (10 - extra_h) or 12,
|
||||
}
|
||||
|
||||
local scrollbar_w = TOUCHSCREEN_GUI and 0.6 or 0.4
|
||||
local scrollbar_w = core.settings:get_bool("enable_touch") and 0.6 or 0.4
|
||||
|
||||
local left_pane_width = TOUCHSCREEN_GUI and 4.5 or 4.25
|
||||
local left_pane_width = core.settings:get_bool("enable_touch") and 4.5 or 4.25
|
||||
local left_pane_padding = 0.25
|
||||
local search_width = left_pane_width + scrollbar_w - (0.75 * 2)
|
||||
|
||||
local back_w = 3
|
||||
@@ -468,7 +477,7 @@ local function get_formspec(dialogdata)
|
||||
local fs = {
|
||||
"formspec_version[6]",
|
||||
"size[", tostring(tabsize.width), ",", tostring(tabsize.height + extra_h), "]",
|
||||
TOUCHSCREEN_GUI and "padding[0.01,0.01]" or "",
|
||||
core.settings:get_bool("enable_touch") and "padding[0.01,0.01]" or "",
|
||||
"bgcolor[#0000]",
|
||||
|
||||
-- HACK: this is needed to allow resubmitting the same formspec
|
||||
@@ -516,9 +525,9 @@ local function get_formspec(dialogdata)
|
||||
y = y + 0.82
|
||||
end
|
||||
fs[#fs + 1] = ("box[0,%f;%f,0.8;%s]"):format(
|
||||
y, left_pane_width, other_page.id == page_id and "#467832FF" or "#3339")
|
||||
y, left_pane_width-left_pane_padding, other_page.id == page_id and "#467832FF" or "#3339")
|
||||
fs[#fs + 1] = ("button[0,%f;%f,0.8;page_%s;%s]")
|
||||
:format(y, left_pane_width, other_page.id, fgettext(other_page.title))
|
||||
:format(y, left_pane_width-left_pane_padding, other_page.id, fgettext(other_page.title))
|
||||
y = y + 0.82
|
||||
end
|
||||
|
||||
@@ -608,6 +617,16 @@ local function get_formspec(dialogdata)
|
||||
end
|
||||
|
||||
|
||||
-- On Android, closing the app via the "Recents screen" won't result in a clean
|
||||
-- exit, discarding any setting changes made by the user.
|
||||
-- To avoid that, we write the settings file in more cases on Android.
|
||||
function write_settings_early()
|
||||
if PLATFORM == "Android" then
|
||||
core.settings:write()
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
local function buttonhandler(this, fields)
|
||||
local dialogdata = this.data
|
||||
dialogdata.leftscroll = core.explode_scrollbar_event(fields.leftscroll).value or dialogdata.leftscroll
|
||||
@@ -622,17 +641,31 @@ local function buttonhandler(this, fields)
|
||||
if fields.show_technical_names ~= nil then
|
||||
local value = core.is_yes(fields.show_technical_names)
|
||||
core.settings:set_bool("show_technical_names", value)
|
||||
write_settings_early()
|
||||
|
||||
return true
|
||||
end
|
||||
|
||||
if fields.show_advanced ~= nil then
|
||||
local value = core.is_yes(fields.show_advanced)
|
||||
core.settings:set_bool("show_advanced", value)
|
||||
write_settings_early()
|
||||
end
|
||||
|
||||
-- enable_touch is a checkbox in a setting component. We handle this
|
||||
-- setting differently so we can hide/show pages using the next if-statement
|
||||
if fields.enable_touch ~= nil then
|
||||
local value = core.is_yes(fields.enable_touch)
|
||||
core.settings:set_bool("enable_touch", value)
|
||||
write_settings_early()
|
||||
end
|
||||
|
||||
if fields.show_advanced ~= nil or fields.enable_touch ~= nil then
|
||||
local suggested_page_id = update_filtered_pages(dialogdata.query)
|
||||
|
||||
dialogdata.components = nil
|
||||
|
||||
if not filtered_page_by_id[dialogdata.page_id] then
|
||||
dialogdata.components = nil
|
||||
dialogdata.leftscroll = 0
|
||||
dialogdata.rightscroll = 0
|
||||
|
||||
@@ -672,12 +705,15 @@ local function buttonhandler(this, fields)
|
||||
|
||||
for i, comp in ipairs(dialogdata.components) do
|
||||
if comp.on_submit and comp:on_submit(fields, this) then
|
||||
write_settings_early()
|
||||
|
||||
-- Clear components so they regenerate
|
||||
dialogdata.components = nil
|
||||
return true
|
||||
end
|
||||
if comp.setting and fields["reset_" .. i] then
|
||||
core.settings:remove(comp.setting.name)
|
||||
write_settings_early()
|
||||
|
||||
-- Clear components so they regenerate
|
||||
dialogdata.components = nil
|
||||
@@ -695,12 +731,18 @@ local function eventhandler(event)
|
||||
mm_game_theme.set_engine(true)
|
||||
return true
|
||||
end
|
||||
if event == "FullscreenChange" then
|
||||
-- Refresh the formspec to keep the fullscreen checkbox up to date.
|
||||
ui.update()
|
||||
return true
|
||||
end
|
||||
|
||||
return false
|
||||
end
|
||||
|
||||
|
||||
function create_settings_dlg()
|
||||
load()
|
||||
local dlg = dialog_create("dlg_settings", get_formspec, buttonhandler, eventhandler)
|
||||
|
||||
dlg.data.page_id = update_filtered_pages("")
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user