aboutsummaryrefslogtreecommitdiff
path: root/src/util/serialize.cpp
blob: 61d369bc487f3a5ae8099c228cb09568237bc47d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
/*
Minetest
Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>

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.
*/

#include "serialize.h"
#include "pointer.h"
#include "porting.h"
#include "util/string.h"
#include "../exceptions.h"
#include "../irrlichttypes.h"

#include <sstream>
#include <iomanip>
#include <vector>

SerializationError eof_ser_err("Attempted read past end of data");

////
//// BufReader
////

bool BufReader::getStringNoEx(std::string *val)
{
	u16 num_chars;
	if (!getU16NoEx(&num_chars))
		return false;

	if (pos + num_chars > size) {
		pos -= sizeof(num_chars);
		return false;
	}

	val->assign((const char *)data + pos, num_chars);
	pos += num_chars;

	return true;
}

bool BufReader::getWideStringNoEx(std::wstring *val)
{
	u16 num_chars;
	if (!getU16NoEx(&num_chars))
		return false;

	if (pos + num_chars * 2 > size) {
		pos -= sizeof(num_chars);
		return false;
	}

	for (size_t i = 0; i != num_chars; i++) {
		val->push_back(readU16(data + pos));
		pos += 2;
	}

	return true;
}

bool BufReader::getLongStringNoEx(std::string *val)
{
	u32 num_chars;
	if (!getU32NoEx(&num_chars))
		return false;

	if (pos + num_chars > size) {
		pos -= sizeof(num_chars);
		return false;
	}

	val->assign((const char *)data + pos, num_chars);
	pos += num_chars;

	return true;
}

bool BufReader::getRawDataNoEx(void *val, size_t len)
{
	if (pos + len > size)
		return false;

	memcpy(val, data + pos, len);
	pos += len;

	return true;
}


////
//// String
////

std::string serializeString(const std::string &plain)
{
	std::string s;
	char buf[2];

	if (plain.size() > STRING_MAX_LEN)
		throw SerializationError("String too long for serializeString");

	writeU16((u8 *)&buf[0], plain.size());
	s.append(buf, 2);

	s.append(plain);
	return s;
}

std::string deSerializeString(std::istream &is)
{
	std::string s;
	char buf[2];

	is.read(buf, 2);
	if (is.gcount() != 2)
		throw SerializationError("deSerializeString: size not read");

	u16 s_size = readU16((u8 *)buf);
	if (s_size == 0)
		return s;

	Buffer<char> buf2(s_size);
	is.read(&buf2[0], s_size);
	if (is.gcount() != s_size)
		throw SerializationError("deSerializeString: couldn't read all chars");

	s.reserve(s_size);
	s.append(&buf2[0], s_size);
	return s;
}

////
//// Wide String
////

std::string serializeWideString(const std::wstring &plain)
{
	std::string s;
	char buf[2];

	if (plain.size() > WIDE_STRING_MAX_LEN)
		throw SerializationError("String too long for serializeWideString");

	writeU16((u8 *)buf, plain.size());
	s.append(buf, 2);

	for (u32 i = 0; i < plain.size(); i++) {
		writeU16((u8 *)buf, plain[i]);
		s.append(buf, 2);
	}
	return s;
}

std::wstring deSerializeWideString(std::istream &is)
{
	std::wstring s;
	char buf[2];

	is.read(buf, 2);
	if (is.gcount() != 2)
		throw SerializationError("deSerializeWideString: size not read");

	u16 s_size = readU16((u8 *)buf);
	if (s_size == 0)
		return s;

	s.reserve(s_size);
	for (u32 i = 0; i < s_size; i++) {
		is.read(&buf[0], 2);
		if (is.gcount() != 2) {
			throw SerializationError(
				"deSerializeWideString: couldn't read all chars");
		}

		wchar_t c16 = readU16((u8 *)buf);
		s.append(&c16, 1);
	}
	return s;
}

////
//// Long String
////

std::string serializeLongString(const std::string &plain)
{
	char buf[4];

	if (plain.size() > LONG_STRING_MAX_LEN)
		throw SerializationError("String too long for serializeLongString");

	writeU32((u8*)&buf[0], plain.size());
	std::string s;
	s.append(buf, 4);
	s.append(plain);
	return s;
}

std::string deSerializeLongString(std::istream &is)
{
	std::string s;
	char buf[4];

	is.read(buf, 4);
	if (is.gcount() != 4)
		throw SerializationError("deSerializeLongString: size not read");

	u32 s_size = readU32((u8 *)buf);
	if (s_size == 0)
		return s;

	// We don't really want a remote attacker to force us to allocate 4GB...
	if (s_size > LONG_STRING_MAX_LEN) {
		throw SerializationError("deSerializeLongString: "
			"string too long: " + itos(s_size) + " bytes");
	}

	Buffer<char> buf2(s_size);
	is.read(&buf2[0], s_size);
	if ((u32)is.gcount() != s_size)
		throw SerializationError("deSerializeLongString: couldn't read all chars");

	s.reserve(s_size);
	s.append(&buf2[0], s_size);
	return s;
}

////
//// JSON
////

std::string serializeJsonString(const std::string &plain)
{
	std::ostringstream os(std::ios::binary);
	os << "\"";

	for (size_t i = 0; i < plain.size(); i++) {
		char c = plain[i];
		switch (c) {
			case '"':
				os << "\\\"";
				break;
			case '\\':
				os << "\\\\";
				break;
			case '/':
				os << "\\/";
				break;
			case '\b':
				os << "\\b";
				break;
			case '\f':
				os << "\\f";
				break;
			case '\n':
				os << "\\n";
				break;
			case '\r':
				os << "\\r";
				break;
			case '\t':
				os << "\\t";
				break;
			default: {
				if (c >= 32 && c <= 126) {
					os << c;
				} else {
					u32 cnum = (u8)c;
					os << "\\u" << std::hex << std::setw(4)
						<< std::setfill('0') << cnum;
				}
				break;
			}
		}
	}

	os << "\"";
	return os.str();
}

std::string deSerializeJsonString(std::istream &is)
{
	std::ostringstream os(std::ios::binary);
	char c, c2;

	// Parse initial doublequote
	is >> c;
	if (c != '"')
		throw SerializationError("JSON string must start with doublequote");

	// Parse characters
	for (;;) {
		c = is.get();
		if (is.eof())
			throw SerializationError("JSON string ended prematurely");

		if (c == '"') {
			return os.str();
		} else if (c == '\\') {
			c2 = is.get();
			if (is.eof())
				throw SerializationError("JSON string ended prematurely");
			switch (c2) {
				case 'b':
					os << '\b';
					break;
				case 'f':
					os << '\f';
					break;
				case 'n':
					os << '\n';
					break;
				case 'r':
					os << '\r';
					break;
				case 't':
					os << '\t';
					break;
				case 'u': {
					int hexnumber;
					char hexdigits[4 + 1];

					is.read(hexdigits, 4);
					if (is.eof())
						throw SerializationError("JSON string ended prematurely");
					hexdigits[4] = 0;

					std::istringstream tmp_is(hexdigits, std::ios::binary);
					tmp_is >> std::hex >> hexnumber;
					os << (char)hexnumber;
					break;
				}
				default:
					os << c2;
					break;
			}
		} else {
			os << c;
		}
	}

	return os.str();
}

std::string serializeJsonStringIfNeeded(const std::string &s)
{
	for (size_t i = 0; i < s.size(); ++i) {
		if (s[i] <= 0x1f || s[i] >= 0x7f || s[i] == ' ' || s[i] == '\"')
			return serializeJsonString(s);
	}
	return s;
}

std::string deSerializeJsonStringIfNeeded(std::istream &is)
{
	std::ostringstream tmp_os;
	bool expect_initial_quote = true;
	bool is_json = false;
	bool was_backslash = false;
	for (;;) {
		char c = is.get();
		if (is.eof())
			break;

		if (expect_initial_quote && c == '"') {
			tmp_os << c;
			is_json = true;
		} else if(is_json) {
			tmp_os << c;
			if (was_backslash)
				was_backslash = false;
			else if (c == '\\')
				was_backslash = true;
			else if (c == '"')
				break; // Found end of string
		} else {
			if (c == ' ') {
				// Found end of word
				is.unget();
				break;
			} else {
				tmp_os << c;
			}
		}
		expect_initial_quote = false;
	}
	if (is_json) {
		std::istringstream tmp_is(tmp_os.str(), std::ios::binary);
		return deSerializeJsonString(tmp_is);
	} else
		return tmp_os.str();
}

////
//// String/Struct conversions
////

bool deSerializeStringToStruct(std::string valstr,
	std::string format, void *out, size_t olen)
{
	size_t len = olen;
	std::vector<std::string *> strs_alloced;
	std::string *str;
	char *f, *snext;
	size_t pos;

	char *s = &valstr[0];
	char *buf = new char[len];
	char *bufpos = buf;

	char *fmtpos, *fmt = &format[0];
	while ((f = strtok_r(fmt, ",", &fmtpos)) && s) {
		fmt = NULL;

		bool is_unsigned = false;
		int width = 0;
		char valtype = *f;

		width = (int)strtol(f + 1, &f, 10);
		if (width && valtype == 's')
			valtype = 'i';

		switch (valtype) {
			case 'u':
				is_unsigned = true;
				/* FALLTHROUGH */
			case 'i':
				if (width == 16) {
					bufpos += PADDING(bufpos, u16);
					if ((bufpos - buf) + sizeof(u16) <= len) {
						if (is_unsigned)
							*(u16 *)bufpos = (u16)strtoul(s, &s, 10);
						else
							*(s16 *)bufpos = (s16)strtol(s, &s, 10);
					}
					bufpos += sizeof(u16);
				} else if (width == 32) {
					bufpos += PADDING(bufpos, u32);
					if ((bufpos - buf) + sizeof(u32) <= len) {
						if (is_unsigned)
							*(u32 *)bufpos = (u32)strtoul(s, &s, 10);
						else
							*(s32 *)bufpos = (s32)strtol(s, &s, 10);
					}
					bufpos += sizeof(u32);
				} else if (width == 64) {
					bufpos += PADDING(bufpos, u64);
					if ((bufpos - buf) + sizeof(u64) <= len) {
						if (is_unsigned)
							*(u64 *)bufpos = (u64)strtoull(s, &s, 10);
						else
							*(s64 *)bufpos = (s64)strtoll(s, &s, 10);
					}
					bufpos += sizeof(u64);
				}
				s = strchr(s, ',');
				break;
			case 'b':
				snext = strchr(s, ',');
				if (snext)
					*snext++ = 0;

				bufpos += PADDING(bufpos, bool);
				if ((bufpos - buf) + sizeof(bool) <= len)
					*(bool *)bufpos = is_yes(std::string(s));
				bufpos += sizeof(bool);

				s = snext;
				break;
			case 'f':
				bufpos += PADDING(bufpos, float);
				if ((bufpos - buf) + sizeof(float) <= len)
					*(float *)bufpos = strtof(s, &s);
				bufpos += sizeof(float);

				s = strchr(s, ',');
				break;
			case 's':
				while (*s == ' ' || *s == '\t')
					s++;
				if (*s++ != '"') //error, expected string
					goto fail;
				snext = s;

				while (snext[0] && !(snext[-1] != '\\' && snext[0] == '"'))
					snext++;
				*snext++ = 0;

				bufpos += PADDING(bufpos, std::string *);

				str = new std::string(s);
				pos = 0;
				while ((pos = str->find("\\\"", pos)) != std::string::npos)
					str->erase(pos, 1);

				if ((bufpos - buf) + sizeof(std::string *) <= len)
					*(std::string **)bufpos = str;
				bufpos += sizeof(std::string *);
				strs_alloced.push_back(str);

				s = *snext ? snext + 1 : NULL;
				break;
			case 'v':
				while (*s == ' ' || *s == '\t')
					s++;
				if (*s++ != '(') //error, expected vector
					goto fail;

				if (width == 2) {
					bufpos += PADDING(bufpos, v2f);

					if ((bufpos - buf) + sizeof(v2f) <= len) {
					v2f *v = (v2f *)bufpos;
						v->X = strtof(s, &s);
						s++;
						v->Y = strtof(s, &s);
					}

					bufpos += sizeof(v2f);
				} else if (width == 3) {
					bufpos += PADDING(bufpos, v3f);
					if ((bufpos - buf) + sizeof(v3f) <= len) {
						v3f *v = (v3f *)bufpos;
						v->X = strtof(s, &s);
						s++;
						v->Y = strtof(s, &s);
						s++;
						v->Z = strtof(s, &s);
					}

					bufpos += sizeof(v3f);
				}
				s = strchr(s, ',');
				break;
			default: //error, invalid format specifier
				goto fail;
		}

		if (s && *s == ',')
			s++;

		if ((size_t)(bufpos - buf) > len) //error, buffer too small
			goto fail;
	}

	if (f && *f) { //error, mismatched number of fields and values
fail:
		for (size_t i = 0; i != strs_alloced.size(); i++)
			delete strs_alloced[i];
		delete[] buf;
		return false;
	}

	memcpy(out, buf, olen);
	delete[] buf;
	return true;
}

// Casts *buf to a signed or unsigned fixed-width integer of 'w' width
#define SIGN_CAST(w, buf) (is_unsigned ? *((u##w *) buf) : *((s##w *) buf))

bool serializeStructToString(std::string *out,
	std::string format, void *value)
{
	std::ostringstream os;
	std::string str;
	char *f;
	size_t strpos;

	char *bufpos = (char *) value;
	char *fmtpos, *fmt = &format[0];
	while ((f = strtok_r(fmt, ",", &fmtpos))) {
		fmt = NULL;
		bool is_unsigned = false;
		int width = 0;
		char valtype = *f;

		width = (int)strtol(f + 1, &f, 10);
		if (width && valtype == 's')
			valtype = 'i';

		switch (valtype) {
			case 'u':
				is_unsigned = true;
				/* FALLTHROUGH */
			case 'i':
				if (width == 16) {
					bufpos += PADDING(bufpos, u16);
					os << SIGN_CAST(16, bufpos);
					bufpos += sizeof(u16);
				} else if (width == 32) {
					bufpos += PADDING(bufpos, u32);
					os << SIGN_CAST(32, bufpos);
					bufpos += sizeof(u32);
				} else if (width == 64) {
					bufpos += PADDING(bufpos, u64);
					os << SIGN_CAST(64, bufpos);
					bufpos += sizeof(u64);
				}
				break;
			case 'b':
				bufpos += PADDING(bufpos, bool);
				os << std::boolalpha << *((bool *) bufpos);
				bufpos += sizeof(bool);
				break;
			case 'f':
				bufpos += PADDING(bufpos, float);
				os << *((float *) bufpos);
				bufpos += sizeof(float);
				break;
			case 's':
				bufpos += PADDING(bufpos, std::string *);
				str = **((std::string **) bufpos);

				strpos = 0;
				while ((strpos = str.find('"', strpos)) != std::string::npos) {
					str.insert(strpos, 1, '\\');
					strpos += 2;
				}

				os << str;
				bufpos += sizeof(std::string *);
				break;
			case 'v':
				if (width == 2) {
					bufpos += PADDING(bufpos, v2f);
					v2f *v = (v2f *) bufpos;
					os << '(' << v->X << ", " << v->Y << ')';
					bufpos += sizeof(v2f);
				} else {
					bufpos += PADDING(bufpos, v3f);
					v3f *v = (v3f *) bufpos;
					os << '(' << v->X << ", " << v->Y << ", " << v->Z << ')';
					bufpos += sizeof(v3f);
				}
				break;
			default:
				return false;
		}
		os << ", ";
	}
	*out = os.str();

	// Trim off the trailing comma and space
	if (out->size() >= 2)
		out->resize(out->size() - 2);

	return true;
}

#undef SIGN_CAST

////
//// Other
////

std::string serializeHexString(const std::string &data, bool insert_spaces)
{
	std::string result;
	result.reserve(data.size() * (2 + insert_spaces));

	static const char hex_chars[] = "0123456789abcdef";

	const size_t len = data.size();
	for (size_t i = 0; i != len; i++) {
		u8 byte = data[i];
		result.push_back(hex_chars[(byte >> 4) & 0x0F]);
		result.push_back(hex_chars[(byte >> 0) & 0x0F]);
		if (insert_spaces && i != len - 1)
			result.push_back(' ');
	}

	return result;
}
span> self.old_acceleration_vector) or self.old_yaw~=yaw or updatepct_timer_elapsed then--only send update packet if something changed self.object:setpos(pos) self.object:setvelocity(velocityvec) self.object:setacceleration(accelerationvec) if #self.seats > 0 and self.old_yaw ~= yaw then if not self.player_yaw then self.player_yaw = {} end if not self.old_yaw then self.old_yaw=yaw end for _,name in pairs(data.seatp) do local p = minetest.get_player_by_name(name) if p then if not self.turning then -- save player looking direction offset self.player_yaw[name] = p:get_look_horizontal()-self.old_yaw end -- set player looking direction using calculated offset p:set_look_horizontal((self.player_yaw[name] or 0)+yaw) end end self.turning = true elseif self.old_yaw == yaw then -- train is no longer turning self.turning = false end if self.object.set_rotation then local pitch = math.atan2(vdir.y, math.hypot(vdir.x, vdir.z)) if data.wagon_flipped then pitch = -pitch end self.object:set_rotation({x=pitch, y=yaw, z=0}) else self.object:setyaw(yaw) end self.updatepct_timer=2 if self.update_animation then self:update_animation(train.velocity, self.old_velocity) end if self.custom_on_velocity_change then self:custom_on_velocity_change(train.velocity, self.old_velocity or 0, dtime) end -- remove discouple object, because it will be in a wrong location if not updatepct_timer_elapsed and self.discouple then self.discouple.object:remove() end end self.old_velocity_vector=velocityvec self.old_velocity = train.velocity self.old_acceleration_vector=accelerationvec self.old_yaw=yaw atprintbm("wagon step", t) end) end function wagon:on_rightclick(clicker) return advtrains.pcall(function() if not self:ensure_init() then return end if not clicker or not clicker:is_player() then return end local data = advtrains.wagons[self.id] local pname=clicker:get_player_name() local no=self:get_seatno(pname) if no then if self.seat_groups then local poss={} local sgr=self.seats[no].group for _,access in ipairs(self.seat_groups[sgr].access_to) do if self:check_seat_group_access(pname, access) then poss[#poss+1]={name=self.seat_groups[access].name, key="sgr_"..access} end end if self.has_inventory and self.get_inventory_formspec and advtrains.check_driving_couple_protection(pname, data.owner, data.whitelist) then poss[#poss+1]={name=attrans("Show Inventory"), key="inv"} end if self.seat_groups[sgr].driving_ctrl_access and advtrains.check_driving_couple_protection(pname, data.owner, data.whitelist) then poss[#poss+1]={name=attrans("Onboard Computer"), key="bordcom"} end if data.owner==pname then poss[#poss+1]={name=attrans("Wagon properties"), key="prop"} end if not self.seat_groups[sgr].require_doors_open or self:train().door_open~=0 then poss[#poss+1]={name=attrans("Get off"), key="off"} else if clicker:get_player_control().sneak then poss[#poss+1]={name=attrans("Get off (forced)"), key="off"} else poss[#poss+1]={name=attrans("(Doors closed)"), key="dcwarn"} end end if #poss==0 then --can't do anything. elseif #poss==1 then self:seating_from_key_helper(pname, {[poss[1].key]=true}, no) else local form = "size[5,"..1+(#poss).."]" for pos,ent in ipairs(poss) do form = form .. "button_exit[0.5,"..(pos-0.5)..";4,1;"..ent.key..";"..ent.name.."]" end minetest.show_formspec(pname, "advtrains_seating_"..self.id, form) end else self:get_off(no) end else --do not attach if already on a train if advtrains.player_to_train_mapping[pname] then return end if self.seat_groups then if #self.seats==0 then if self.has_inventory and self.get_inventory_formspec and advtrains.check_driving_couple_protection(pname, data.owner, data.whitelist) then minetest.show_formspec(pname, "advtrains_inv_"..self.id, self:get_inventory_formspec(pname, make_inv_name(self.id))) end return end local doors_open = self:train().door_open~=0 or clicker:get_player_control().sneak local allow, rsn=false, "Wagon has no seats!" for _,sgr in ipairs(self.assign_to_seat_group) do allow, rsn = self:check_seat_group_access(pname, sgr) if allow then for seatid, seatdef in ipairs(self.seats) do if seatdef.group==sgr then if (not self.seat_groups[sgr].require_doors_open or doors_open) then if not data.seatp[seatid] then self:get_on(clicker, seatid) return else rsn="Wagon is full." end else rsn="Doors are closed! (try holding sneak key!)" end end end end end minetest.chat_send_player(pname, attrans("Can't get on: "..rsn)) else self:show_get_on_form(pname) end end end) end function wagon:get_on(clicker, seatno) local data = advtrains.wagons[self.id] if not data.seatp then data.seatp={}end if not self.seatpc then self.seatpc={}end--player controls in driver stands if not self.seats[seatno] then return end local oldno=self:get_seatno(clicker:get_player_name()) if oldno then atprint("get_on: clearing oldno",seatno) advtrains.player_to_train_mapping[clicker:get_player_name()]=nil advtrains.clear_driver_hud(clicker:get_player_name()) data.seatp[oldno]=nil end if data.seatp[seatno] and data.seatp[seatno]~=clicker:get_player_name() then atprint("get_on: throwing off",data.seatp[seatno],"from seat",seatno) self:get_off(seatno) end atprint("get_on: attaching",clicker:get_player_name()) data.seatp[seatno] = clicker:get_player_name() self.seatpc[seatno] = clicker:get_player_control_bits() advtrains.player_to_train_mapping[clicker:get_player_name()]=data.train_id clicker:set_attach(self.object, "", self.seats[seatno].attach_offset, {x=0,y=0,z=0}) clicker:set_eye_offset(self.seats[seatno].view_offset, self.seats[seatno].view_offset) end function wagon:get_off_plr(pname) local no=self:get_seatno(pname) if no then self:get_off(no) end end function wagon:get_seatno(pname) local data = advtrains.wagons[self.id] for no, cont in pairs(data.seatp) do if cont==pname then return no end end return nil end function wagon:get_off(seatno) local data = advtrains.wagons[self.id] if not data.seatp[seatno] then return end local pname = data.seatp[seatno] local clicker = minetest.get_player_by_name(pname) advtrains.player_to_train_mapping[pname]=nil advtrains.clear_driver_hud(pname) data.seatp[seatno]=nil self.seatpc[seatno]=nil if clicker then atprint("get_off: detaching",clicker:get_player_name()) clicker:set_detach() clicker:set_eye_offset({x=0,y=0,z=0}, {x=0,y=0,z=0}) local train=self:train() --code as in step - automatic get on if self.door_entry and train.door_open and train.door_open~=0 and train.velocity==0 and train.index and train.path then local index = advtrains.path_get_index_by_offset(train, train.index, -data.pos_in_train) for i, ino in ipairs(self.door_entry) do --atdebug("using door-based",i,ino) local fct=data.wagon_flipped and -1 or 1 local aci = advtrains.path_get_index_by_offset(train, index, ino*fct) local ix1, ix2 = advtrains.path_get_adjacent(train, aci) local d = train.door_open if self.wagon_width then d = d * math.floor(self.wagon_width/2) end -- the two wanted positions are ix1 and ix2 + (2nd-1st rotated by 90deg) -- (x z) rotated by 90deg is (-z x) (http://stackoverflow.com/a/4780141) local add = { x = (ix2.z-ix1.z)*d, y = 0, z = (ix1.x-ix2.x)*d } local oadd = { x = (ix2.z-ix1.z)*(d+train.door_open), y = 1, z = (ix1.x-ix2.x)*(d+train.door_open)} local platpos=vector.round(vector.add(ix1, add)) local offpos=vector.round(vector.add(ix1, oadd)) --atdebug("platpos:", platpos, "offpos:", offpos) if minetest.get_item_group(minetest.get_node(platpos).name, "platform")>0 then minetest.after(GETOFF_TP_DELAY, function() clicker:setpos(offpos) end) --atdebug("tp",offpos) return end --atdebug("nope") end end --if not door_entry, or paths missing, fall back to old method --atdebug("using fallback") local objpos=advtrains.round_vector_floor_y(self.object:getpos()) local yaw=self.object:getyaw() local isx=(yaw < math.pi/4) or (yaw > 3*math.pi/4 and yaw < 5*math.pi/4) or (yaw > 7*math.pi/4) local offp --abuse helper function for _,r in ipairs({-1, 1}) do --atdebug("offset",r) local p=vector.add({x=isx and r or 0, y=0, z=not isx and r or 0}, objpos) offp=vector.add({x=isx and r*2 or 0, y=1, z=not isx and r*2 or 0}, objpos) --atdebug("platpos:", p, "offpos:", offp) if minetest.get_item_group(minetest.get_node(p).name, "platform")>0 then minetest.after(GETOFF_TP_DELAY, function() clicker:setpos(offp) end) --atdebug("tp",offp) return end end --atdebug("nope") end end function wagon:show_get_on_form(pname) if not self.initialized then return end local data = advtrains.wagons[self.id] if #self.seats==0 then if self.has_inventory and self.get_inventory_formspec and advtrains.check_driving_couple_protection(pname, data.owner, data.whitelist) then minetest.show_formspec(pname, "advtrains_inv_"..self.id, self:get_inventory_formspec(pname, make_inv_name(self.id))) end return end local form, comma="size[5,8]label[0.5,0.5;"..attrans("Select seat:").."]textlist[0.5,1;4,6;seat;", "" for seatno, seattbl in ipairs(self.seats) do local addtext, colorcode="", "" if data.seatp and data.seatp[seatno] then colorcode="#FF0000" addtext=" ("..data.seatp[seatno]..")" end form=form..comma..colorcode..seattbl.name..addtext comma="," end form=form..";0,false]" if self.has_inventory and self.get_inventory_formspec then form=form.."button_exit[1,7;3,1;inv;"..attrans("Show Inventory").."]" end minetest.show_formspec(pname, "advtrains_geton_"..self.id, form) end function wagon:show_wagon_properties(pname) --[[ fields: field: driving/couple whitelist button: save ]] local data = advtrains.wagons[self.id] local form="size[5,5]" form = form .. "field[0.5,1;4,1;whitelist;Allow these players to drive your wagon:;"..(data.whitelist or "").."]" --seat groups access lists were here form=form.."button_exit[0.5,3;4,1;save;"..attrans("Save wagon properties").."]" minetest.show_formspec(pname, "advtrains_prop_"..self.id, form) end --BordCom local function checkcouple(ent) if not ent or not ent:getyaw() then return nil end local le = ent:get_luaentity() if not le or not le.is_couple then return nil end return le end local function checklock(pname, own1, own2, wl1, wl2) return advtrains.check_driving_couple_protection(pname, own1, wl1) or advtrains.check_driving_couple_protection(pname, own2, wl2) end function wagon:show_bordcom(pname) if not self:train() then return end local train = self:train() local data = advtrains.wagons[self.id] local form = "size[11,9]label[0.5,0;AdvTrains Boardcom v0.1]" form=form.."textarea[0.5,1.5;7,1;text_outside;"..attrans("Text displayed outside on train")..";"..(minetest.formspec_escape(train.text_outside or "")).."]" form=form.."textarea[0.5,3;7,1;text_inside;"..attrans("Text displayed inside train")..";"..(minetest.formspec_escape(train.text_inside or "")).."]" form=form.."field[7.5,1.75;3,1;line;"..attrans("Line")..";"..(minetest.formspec_escape(train.line or "")).."]" form=form.."field[7.5,3.25;3,1;routingcode;"..attrans("Routingcode")..";"..(minetest.formspec_escape(train.routingcode or "")).."]" --row 5 : train overview and autocoupling if train.velocity==0 then form=form.."label[0.5,4.5;Train overview /coupling control:]" linhei=5 local pre_own, pre_wl, owns_any = nil, nil, minetest.check_player_privs(pname, "train_admin") for i, tpid in ipairs(train.trainparts) do local ent = advtrains.wagons[tpid] if ent then local ename = ent.type form = form .. "item_image["..i..","..linhei..";1,1;"..ename.."]" if i~=1 then if checklock(pname, ent.owner, pre_own, ent.whitelist, pre_wl) then form = form .. "image_button["..(i-0.5)..","..(linhei+1)..";1,1;advtrains_discouple.png;dcpl_"..i..";]" end end if i == data.pos_in_trainparts then form = form .. "box["..(i-0.1)..","..(linhei-0.1)..";1,1;green]" end pre_own = ent.owner pre_wl = ent.whitelist owns_any = owns_any or (not ent.owner or ent.owner==pname) end end if train.movedir==1 then form = form .. "label["..(#train.trainparts+1)..","..(linhei)..";-->]" else form = form .. "label[0.5,"..(linhei)..";<--]" end --check cpl_eid_front and _back of train local couple_front = checkcouple(train.cpl_front) local couple_back = checkcouple(train.cpl_back) if couple_front then form = form .. "image_button[0.5,"..(linhei+1)..";1,1;advtrains_couple.png;cpl_f;]" end if couple_back then form = form .. "image_button["..(#train.trainparts+0.5)..","..(linhei+1)..";1,1;advtrains_couple.png;cpl_b;]" end else form=form.."label[0.5,4.5;Train overview / coupling control is only shown when the train stands.]" end form = form .. "button[0.5,8;3,1;save;Save]" -- Interlocking functionality: If the interlocking module is loaded, you can set the signal aspect -- from inside the train if advtrains.interlocking and train.lzb and #train.lzb.oncoming > 0 then local i=1 while train.lzb.oncoming[i] do local oci = train.lzb.oncoming[i] if oci.udata and oci.udata.signal_pos then if advtrains.interlocking.db.get_sigd_for_signal(oci.udata.signal_pos) then form = form .. "button[4.5,8;5,1;ilrs;Remote Routesetting]" break end end i=i+1 end end minetest.show_formspec(pname, "advtrains_bordcom_"..self.id, form) end function wagon:handle_bordcom_fields(pname, formname, fields) local data = advtrains.wagons[self.id] local seatno=self:get_seatno(pname) if not seatno or not self.seat_groups[self.seats[seatno].group].driving_ctrl_access or not advtrains.check_driving_couple_protection(pname, data.owner, data.whitelist) then return end local train = self:train() if not train then return end if fields.text_outside then if fields.text_outside~="" then train.text_outside=fields.text_outside else train.text_outside=nil end end if fields.text_inside then if fields.text_inside~="" then train.text_inside=fields.text_inside else train.text_inside=nil end end if fields.line then if fields.line~="" then if fields.line ~= train.line then train.line=fields.line minetest.after(0, advtrains.invalidate_path, train.id) end else train.line=nil end end if fields.routingcode then if fields.routingcode~="" then if fields.routingcode ~= train.routingcode then train.routingcode=fields.routingcode minetest.after(0, advtrains.invalidate_path, train.id) end else train.routingcode=nil end end for i, tpid in ipairs(train.trainparts) do if fields["dcpl_"..i] then advtrains.safe_decouple_wagon(tpid, pname) end end --check cpl_eid_front and _back of train local couple_front = checkcouple(train.cpl_front) local couple_back = checkcouple(train.cpl_back) if fields.cpl_f and couple_front then couple_front:on_rightclick(pname) end if fields.cpl_b and couple_back then couple_back:on_rightclick(pname) end -- Interlocking functionality: If the interlocking module is loaded, you can set the signal aspect -- from inside the train if fields.ilrs and advtrains.interlocking and train.lzb and #train.lzb.oncoming > 0 then local i=1 while train.lzb.oncoming[i] do local oci = train.lzb.oncoming[i] if oci.udata and oci.udata.signal_pos then local sigd = advtrains.interlocking.db.get_sigd_for_signal(oci.udata.signal_pos) if sigd then advtrains.interlocking.show_signalling_form(sigd, pname) return end end i=i+1 end end if not fields.quit then self:show_bordcom(pname) end end minetest.register_on_player_receive_fields(function(player, formname, fields) return advtrains.pcall(function() local uid=string.match(formname, "^advtrains_geton_(.+)$") if uid then for _,wagon in pairs(minetest.luaentities) do if wagon.is_wagon and wagon.initialized and wagon.id==uid then local data = advtrains.wagons[wagon.id] if fields.inv then if wagon.has_inventory and wagon.get_inventory_formspec then minetest.show_formspec(player:get_player_name(), "advtrains_inv_"..uid, wagon:get_inventory_formspec(player:get_player_name(), make_inv_name(uid))) end elseif fields.seat then local val=minetest.explode_textlist_event(fields.seat) if val and val.type~="INV" and not data.seatp[player:get_player_name()] then --get on wagon:get_on(player, val.index) --will work with the new close_formspec functionality. close exactly this formspec. minetest.show_formspec(player:get_player_name(), formname, "") end end end end end uid=string.match(formname, "^advtrains_seating_(.+)$") if uid then for _,wagon in pairs(minetest.luaentities) do if wagon.is_wagon and wagon.initialized and wagon.id==uid then local pname=player:get_player_name() local no=wagon:get_seatno(pname) if no then if wagon.seat_groups then wagon:seating_from_key_helper(pname, fields, no) end end end end end uid=string.match(formname, "^advtrains_prop_(.+)$") if uid then local pname=player:get_player_name() local data = advtrains.wagons[uid] if pname~=data.owner and not minetest.check_player_privs(pname, {train_admin = true}) then return true end if fields.save or not fields.quit then if fields.whitelist then data.whitelist = fields.whitelist end end end uid=string.match(formname, "^advtrains_bordcom_(.+)$") if uid then for _,wagon in pairs(minetest.luaentities) do if wagon.is_wagon and wagon.initialized and wagon.id==uid then wagon:handle_bordcom_fields(player:get_player_name(), formname, fields) end end end end) end) function wagon:seating_from_key_helper(pname, fields, no) local data = advtrains.wagons[self.id] local sgr=self.seats[no].group for _,access in ipairs(self.seat_groups[sgr].access_to) do if fields["sgr_"..access] and self:check_seat_group_access(pname, access) then for seatid, seatdef in ipairs(self.seats) do if seatdef.group==access and not data.seatp[seatid] then self:get_on(minetest.get_player_by_name(pname), seatid) return end end end end if fields.inv and self.has_inventory and self.get_inventory_formspec then minetest.show_formspec(player:get_player_name(), "advtrains_inv_"..self.id, self:get_inventory_formspec(player:get_player_name(), make_inv_name(self.id))) end if fields.prop and data.owner==pname then self:show_wagon_properties(pname) end if fields.bordcom and self.seat_groups[sgr].driving_ctrl_access and advtrains.check_driving_couple_protection(pname, data.owner, data.whitelist) then self:show_bordcom(pname) end if fields.dcwarn then minetest.chat_send_player(pname, attrans("Doors are closed! Use Sneak+rightclick to ignore the closed doors and get off!")) end if fields.off then self:get_off(no) end end function wagon:check_seat_group_access(pname, sgr) local data = advtrains.wagons[self.id] if self.seat_groups[sgr].driving_ctrl_access and not (advtrains.check_driving_couple_protection(pname, data.owner, data.whitelist)) then return false, "Not allowed to access a driver stand!" end if self.seat_groups[sgr].driving_ctrl_access then advtrains.log("Drive", pname, self.object:getpos(), self:train().text_outside) end return true end function wagon:reattach_all() local data = advtrains.wagons[self.id] if not data.seatp then data.seatp={} end for seatno, pname in pairs(data.seatp) do local p=minetest.get_player_by_name(pname) if p then self:get_on(p ,seatno) end end end local function check_twagon_owner(train, b_first, pname) local wtp = b_first and 1 or #train.trainparts local wid = train.trainparts[wtp] local wdata = advtrains.wagons[wid] if wdata then return advtrains.check_driving_couple_protection(pname, wdata.owner, wdata.whitelist) end return false end function advtrains.safe_couple_trains(id1, id2, t1f, t2f, pname, try_run) if not minetest.check_player_privs(pname, "train_operator") then minetest.chat_send_player(pname, "Missing train_operator privilege") return false end local train1=advtrains.trains[id1] local train2=advtrains.trains[id2] if not advtrains.train_ensure_init(id1, train1) or not advtrains.train_ensure_init(id2, train2) then return false end local wck_t1 = check_twagon_owner(train1, t1f, pname) local wck_t2 = check_twagon_owner(train2, t2f, pname) if wck_t1 or wck_t2 then if try_run then return true end if t1f then if t2f then advtrains.invert_train(id1) advtrains.do_connect_trains(id1, id2) else advtrains.do_connect_trains(id2, id1) end else if t2f then advtrains.do_connect_trains(id1, id2) else advtrains.invert_train(id2) advtrains.do_connect_trains(id1, id2) end end return true else minetest.chat_send_player(pname, "You must be authorized for at least one wagon.") return false end end function advtrains.safe_decouple_wagon(w_id, pname, try_run) if not minetest.check_player_privs(pname, "train_operator") then minetest.chat_send_player(pname, "Missing train_operator privilege") return false end local data = advtrains.wagons[w_id] local dpt = data.pos_in_trainparts if not dpt or dpt <= 1 then return false end local train = advtrains.trains[data.train_id] local owid = train.trainparts[dpt-1] local owdata = advtrains.wagons[owid] if not owdata then return end if not checklock(pname, data.owner, owdata.owner, data.whitelist, owdata.whitelist) then minetest.chat_send_player(pname, "Not allowed to do this.") return false end if try_run then return true end advtrains.log("Discouple", pname, train.last_pos, train.text_outside) advtrains.split_train_at_wagon(w_id) return true end function advtrains.get_wagon_prototype(data) local wt = data.type if not wt then -- LEGACY: Field was called "entity_name" in previous versions wt = data.entity_name data.type = data.entity_name data.entity_name = nil end if not wt or not advtrains.wagon_prototypes[wt] then atwarn("Unable to load wagon type",wt,", using placeholder") wt="advtrains:wagon_placeholder" end return wt, advtrains.wagon_prototypes[wt] end function advtrains.register_wagon(sysname_p, prototype, desc, inv_img, nincreative) local sysname = sysname_p if not string.match(sysname, ":") then sysname = "advtrains:"..sysname_p end setmetatable(prototype, {__index=wagon}) minetest.register_entity(":"..sysname,prototype) advtrains.wagon_prototypes[sysname] = prototype minetest.register_craftitem(":"..sysname, { description = desc, inventory_image = inv_img, wield_image = inv_img, stack_max = 1, groups = { not_in_creative_inventory = nincreative and 1 or 0}, on_place = function(itemstack, placer, pointed_thing) return advtrains.pcall(function() if not pointed_thing.type == "node" then return end local pname = placer:get_player_name() local node=minetest.get_node_or_nil(pointed_thing.under) if not node then atprint("[advtrains]Ignore at placer position") return itemstack end local nodename=node.name if(not advtrains.is_track_and_drives_on(nodename, prototype.drives_on)) then atprint("no track here, not placing.") return itemstack end if not minetest.check_player_privs(placer, {train_operator = true }) then minetest.chat_send_player(pname, "You don't have the train_operator privilege.") return itemstack end if not minetest.check_player_privs(placer, {train_admin = true }) and minetest.is_protected(pointed_thing.under, placer:get_player_name()) then return itemstack end local tconns=advtrains.get_track_connections(node.name, node.param2) local yaw = placer:get_look_horizontal() local plconnid = advtrains.yawToClosestConn(yaw, tconns) local prevpos = advtrains.get_adjacent_rail(pointed_thing.under, tconns, plconnid, prototype.drives_on) if not prevpos then minetest.chat_send_player(pname, "The track you are trying to place the wagon on is not long enough!") return end local wid = advtrains.create_wagon(sysname, pname) local id=advtrains.create_new_train_at(pointed_thing.under, plconnid, 0, {wid}) if not advtrains.is_creative(pname) then itemstack:take_item() end return itemstack end) end, }) end -- Placeholder wagon. Will be spawned whenever a mod is missing advtrains.register_wagon("advtrains:wagon_placeholder", { visual="sprite", textures = {"advtrains_wagon_placeholder.png"}, collisionbox = {-0.3,-0.3,-0.3, 0.3,0.3,0.3}, visual_size = {x=0.7, y=0.7}, initial_sprite_basepos = {x=0, y=0}, drives_on = advtrains.all_tracktypes, max_speed = 5, seats = { }, seat_groups = { }, assign_to_seat_group = {}, wagon_span=1, drops={}, }, "Wagon placeholder", "advtrains_wagon_placeholder.png", true)