aboutsummaryrefslogtreecommitdiff
path: root/src/script/lua_api/l_item.cpp
blob: 207a04c6cab5254f250968afe5a485095fce4e94 (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
/*
Minetest
Copyright (C) 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 "lua_api/l_item.h"
#include "lua_api/l_itemstackmeta.h"
#include "lua_api/l_internal.h"
#include "common/c_converter.h"
#include "common/c_content.h"
#include "itemdef.h"
#include "nodedef.h"
#include "server.h"
#include "content_sao.h"
#include "inventory.h"
#include "log.h"


// garbage collector
int LuaItemStack::gc_object(lua_State *L)
{
	LuaItemStack *o = *(LuaItemStack **)(lua_touserdata(L, 1));
	delete o;
	return 0;
}

// is_empty(self) -> true/false
int LuaItemStack::l_is_empty(lua_State *L)
{
	NO_MAP_LOCK_REQUIRED;
	LuaItemStack *o = checkobject(L, 1);
	ItemStack &item = o->m_stack;
	lua_pushboolean(L, item.empty());
	return 1;
}

// get_name(self) -> string
int LuaItemStack::l_get_name(lua_State *L)
{
	NO_MAP_LOCK_REQUIRED;
	LuaItemStack *o = checkobject(L, 1);
	ItemStack &item = o->m_stack;
	lua_pushstring(L, item.name.c_str());
	return 1;
}

// set_name(self, name)
int LuaItemStack::l_set_name(lua_State *L)
{
	NO_MAP_LOCK_REQUIRED;
	LuaItemStack *o = checkobject(L, 1);
	ItemStack &item = o->m_stack;

	bool status = true;
	item.name = luaL_checkstring(L, 2);
	if (item.name.empty() || item.empty()) {
		item.clear();
		status = false;
	}

	lua_pushboolean(L, status);
	return 1;
}

// get_count(self) -> number
int LuaItemStack::l_get_count(lua_State *L)
{
	NO_MAP_LOCK_REQUIRED;
	LuaItemStack *o = checkobject(L, 1);
	ItemStack &item = o->m_stack;
	lua_pushinteger(L, item.count);
	return 1;
}

// set_count(self, number)
int LuaItemStack::l_set_count(lua_State *L)
{
	NO_MAP_LOCK_REQUIRED;
	LuaItemStack *o = checkobject(L, 1);
	ItemStack &item = o->m_stack;

	bool status;
	lua_Integer count = luaL_checkinteger(L, 2);
	if (count > 0 && count <= 65535) {
		item.count = count;
		status = true;
	} else {
		item.clear();
		status = false;
	}

	lua_pushboolean(L, status);
	return 1;
}

// get_wear(self) -> number
int LuaItemStack::l_get_wear(lua_State *L)
{
	NO_MAP_LOCK_REQUIRED;
	LuaItemStack *o = checkobject(L, 1);
	ItemStack &item = o->m_stack;
	lua_pushinteger(L, item.wear);
	return 1;
}

// set_wear(self, number)
int LuaItemStack::l_set_wear(lua_State *L)
{
	NO_MAP_LOCK_REQUIRED;
	LuaItemStack *o = checkobject(L, 1);
	ItemStack &item = o->m_stack;

	bool status;
	lua_Integer wear = luaL_checkinteger(L, 2);
	if (wear <= 65535) {
		item.wear = wear;
		status = true;
	} else {
		item.clear();
		status = false;
	}

	lua_pushboolean(L, status);
	return 1;
}

// get_meta(self) -> string
int LuaItemStack::l_get_meta(lua_State *L)
{
	NO_MAP_LOCK_REQUIRED;
	LuaItemStack *o = checkobject(L, 1);
	ItemStackMetaRef::create(L, &o->m_stack);
	return 1;
}

// DEPRECATED
// get_metadata(self) -> string
int LuaItemStack::l_get_metadata(lua_State *L)
{
	NO_MAP_LOCK_REQUIRED;
	LuaItemStack *o = checkobject(L, 1);
	ItemStack &item = o->m_stack;
	const std::string &value = item.metadata.getString("");
	lua_pushlstring(L, value.c_str(), value.size());
	return 1;
}

// DEPRECATED
// set_metadata(self, string)
int LuaItemStack::l_set_metadata(lua_State *L)
{
	NO_MAP_LOCK_REQUIRED;
	LuaItemStack *o = checkobject(L, 1);
	ItemStack &item = o->m_stack;

	size_t len = 0;
	const char *ptr = luaL_checklstring(L, 2, &len);
	item.metadata.setString("", std::string(ptr, len));

	lua_pushboolean(L, true);
	return 1;
}

// clear(self) -> true
int LuaItemStack::l_clear(lua_State *L)
{
	NO_MAP_LOCK_REQUIRED;
	LuaItemStack *o = checkobject(L, 1);
	o->m_stack.clear();
	lua_pushboolean(L, true);
	return 1;
}

// replace(self, itemstack or itemstring or table or nil) -> true
int LuaItemStack::l_replace(lua_State *L)
{
	NO_MAP_LOCK_REQUIRED;
	LuaItemStack *o = checkobject(L, 1);
	o->m_stack = read_item(L, 2, getGameDef(L)->idef());
	lua_pushboolean(L, true);
	return 1;
}

// to_string(self) -> string
int LuaItemStack::l_to_string(lua_State *L)
{
	NO_MAP_LOCK_REQUIRED;
	LuaItemStack *o = checkobject(L, 1);
	std::string itemstring = o->m_stack.getItemString();
	lua_pushstring(L, itemstring.c_str());
	return 1;
}

// to_table(self) -> table or nil
int LuaItemStack::l_to_table(lua_State *L)
{
	NO_MAP_LOCK_REQUIRED;
	LuaItemStack *o = checkobject(L, 1);
	const ItemStack &item = o->m_stack;
	if(item.empty())
	{
		lua_pushnil(L);
	}
	else
	{
		lua_newtable(L);
		lua_pushstring(L, item.name.c_str());
		lua_setfield(L, -2, "name");
		lua_pushinteger(L, item.count);
		lua_setfield(L, -2, "count");
		lua_pushinteger(L, item.wear);
		lua_setfield(L, -2, "wear");

		const std::string &metadata_str = item.metadata.getString("");
		lua_pushlstring(L, metadata_str.c_str(), metadata_str.size());
		lua_setfield(L, -2, "metadata");

		lua_newtable(L);
		const StringMap &fields = item.metadata.getStrings();
		for (const auto &field : fields) {
			const std::string &name = field.first;
			if (name.empty())
				continue;
			const std::string &value = field.second;
			lua_pushlstring(L, name.c_str(), name.size());
			lua_pushlstring(L, value.c_str(), value.size());
			lua_settable(L, -3);
		}
		lua_setfield(L, -2, "meta");
	}
	return 1;
}

// get_stack_max(self) -> number
int LuaItemStack::l_get_stack_max(lua_State *L)
{
	NO_MAP_LOCK_REQUIRED;
	LuaItemStack *o = checkobject(L, 1);
	ItemStack &item = o->m_stack;
	lua_pushinteger(L, item.getStackMax(getGameDef(L)->idef()));
	return 1;
}

// get_free_space(self) -> number
int LuaItemStack::l_get_free_space(lua_State *L)
{
	NO_MAP_LOCK_REQUIRED;
	LuaItemStack *o = checkobject(L, 1);
	ItemStack &item = o->m_stack;
	lua_pushinteger(L, item.freeSpace(getGameDef(L)->idef()));
	return 1;
}

// is_known(self) -> true/false
// Checks if the item is defined.
int LuaItemStack::l_is_known(lua_State *L)
{
	NO_MAP_LOCK_REQUIRED;
	LuaItemStack *o = checkobject(L, 1);
	ItemStack &item = o->m_stack;
	bool is_known = item.isKnown(getGameDef(L)->idef());
	lua_pushboolean(L, is_known);
	return 1;
}

// get_definition(self) -> table
// Returns the item definition table from registered_items,
// or a fallback one (name="unknown")
int LuaItemStack::l_get_definition(lua_State *L)
{
	NO_MAP_LOCK_REQUIRED;
	LuaItemStack *o = checkobject(L, 1);
	ItemStack &item = o->m_stack;

	// Get registered_items[name]
	lua_getglobal(L, "core");
	lua_getfield(L, -1, "registered_items");
	luaL_checktype(L, -1, LUA_TTABLE);
	lua_getfield(L, -1, item.name.c_str());
	if(lua_isnil(L, -1))
	{
		lua_pop(L, 1);
		lua_getfield(L, -1, "unknown");
	}
	return 1;
}

// get_tool_capabilities(self) -> table
// Returns the effective tool digging properties.
// Returns those of the hand ("") if this item has none associated.
int LuaItemStack::l_get_tool_capabilities(lua_State *L)
{
	NO_MAP_LOCK_REQUIRED;
	LuaItemStack *o = checkobject(L, 1);
	ItemStack &item = o->m_stack;
	const ToolCapabilities &prop =
		item.getToolCapabilities(getGameDef(L)->idef());
	push_tool_capabilities(L, prop);
	return 1;
}

// add_wear(self, amount) -> true/false
// The range for "amount" is [0,65535]. Wear is only added if the item
// is a tool. Adding wear might destroy the item.
// Returns true if the item is (or was) a tool.
int LuaItemStack::l_add_wear(lua_State *L)
{
	NO_MAP_LOCK_REQUIRED;
	LuaItemStack *o = checkobject(L, 1);
	ItemStack &item = o->m_stack;
	int amount = lua_tointeger(L, 2);
	bool result = item.addWear(amount, getGameDef(L)->idef());
	lua_pushboolean(L, result);
	return 1;
}

// add_item(self, itemstack or itemstring or table or nil) -> itemstack
// Returns leftover item stack
int LuaItemStack::l_add_item(lua_State *L)
{
	NO_MAP_LOCK_REQUIRED;
	LuaItemStack *o = checkobject(L, 1);
	ItemStack &item = o->m_stack;
	ItemStack newitem = read_item(L, -1, getGameDef(L)->idef());
	ItemStack leftover = item.addItem(newitem, getGameDef(L)->idef());
	create(L, leftover);
	return 1;
}

// item_fits(self, itemstack or itemstring or table or nil) -> true/false, itemstack
// First return value is true iff the new item fits fully into the stack
// Second return value is the would-be-left-over item stack
int LuaItemStack::l_item_fits(lua_State *L)
{
	NO_MAP_LOCK_REQUIRED;
	LuaItemStack *o = checkobject(L, 1);
	ItemStack &item = o->m_stack;
	ItemStack newitem = read_item(L, 2, getGameDef(L)->idef());
	ItemStack restitem;
	bool fits = item.itemFits(newitem, &restitem, getGameDef(L)->idef());
	lua_pushboolean(L, fits);  // first return value
	create(L, restitem);       // second return value
	return 2;
}

// take_item(self, takecount=1) -> itemstack
int LuaItemStack::l_take_item(lua_State *L)
{
	NO_MAP_LOCK_REQUIRED;
	LuaItemStack *o = checkobject(L, 1);
	ItemStack &item = o->m_stack;
	u32 takecount = 1;
	if(!lua_isnone(L, 2))
		takecount = luaL_checkinteger(L, 2);
	ItemStack taken = item.takeItem(takecount);
	create(L, taken);
	return 1;
}

// peek_item(self, peekcount=1) -> itemstack
int LuaItemStack::l_peek_item(lua_State *L)
{
	NO_MAP_LOCK_REQUIRED;
	LuaItemStack *o = checkobject(L, 1);
	ItemStack &item = o->m_stack;
	u32 peekcount = 1;
	if(!lua_isnone(L, 2))
		peekcount = lua_tointeger(L, 2);
	ItemStack peekaboo = item.peekItem(peekcount);
	create(L, peekaboo);
	return 1;
}

LuaItemStack::LuaItemStack(const ItemStack &item):
	m_stack(item)
{
}

const ItemStack& LuaItemStack::getItem() const
{
	return m_stack;
}
ItemStack& LuaItemStack::getItem()
{
	return m_stack;
}

// LuaItemStack(itemstack or itemstring or table or nil)
// Creates an LuaItemStack and leaves it on top of stack
int LuaItemStack::create_object(lua_State *L)
{
	NO_MAP_LOCK_REQUIRED;
	ItemStack item = read_item(L, 1, getGameDef(L)->idef());
	LuaItemStack *o = new LuaItemStack(item);
	*(void **)(lua_newuserdata(L, sizeof(void *))) = o;
	luaL_getmetatable(L, className);
	lua_setmetatable(L, -2);
	return 1;
}
// Not callable from Lua
int LuaItemStack::create(lua_State *L, const ItemStack &item)
{
	NO_MAP_LOCK_REQUIRED;
	LuaItemStack *o = new LuaItemStack(item);
	*(void **)(lua_newuserdata(L, sizeof(void *))) = o;
	luaL_getmetatable(L, className);
	lua_setmetatable(L, -2);
	return 1;
}

LuaItemStack* LuaItemStack::checkobject(lua_State *L, int narg)
{
	luaL_checktype(L, narg, LUA_TUSERDATA);
	void *ud = luaL_checkudata(L, narg, className);
	if(!ud) luaL_typerror(L, narg, className);
	return *(LuaItemStack**)ud;  // unbox pointer
}

void LuaItemStack::Register(lua_State *L)
{
	lua_newtable(L);
	int methodtable = lua_gettop(L);
	luaL_newmetatable(L, className);
	int metatable = lua_gettop(L);

	lua_pushliteral(L, "__metatable");
	lua_pushvalue(L, methodtable);
	lua_settable(L, metatable);  // hide metatable from Lua getmetatable()

	lua_pushliteral(L, "__index");
	lua_pushvalue(L, methodtable);
	lua_settable(L, metatable);

	lua_pushliteral(L, "__gc");
	lua_pushcfunction(L, gc_object);
	lua_settable(L, metatable);

	lua_pop(L, 1);  // drop metatable

	luaL_openlib(L, 0, methods, 0);  // fill methodtable
	lua_pop(L, 1);  // drop methodtable

	// Can be created from Lua (LuaItemStack(itemstack or itemstring or table or nil))
	lua_register(L, className, create_object);
}

const char LuaItemStack::className[] = "ItemStack";
const luaL_Reg LuaItemStack::methods[] = {
	luamethod(LuaItemStack, is_empty),
	luamethod(LuaItemStack, get_name),
	luamethod(LuaItemStack, set_name),
	luamethod(LuaItemStack, get_count),
	luamethod(LuaItemStack, set_count),
	luamethod(LuaItemStack, get_wear),
	luamethod(LuaItemStack, set_wear),
	luamethod(LuaItemStack, get_meta),
	luamethod(LuaItemStack, get_metadata),
	luamethod(LuaItemStack, set_metadata),
	luamethod(LuaItemStack, clear),
	luamethod(LuaItemStack, replace),
	luamethod(LuaItemStack, to_string),
	luamethod(LuaItemStack, to_table),
	luamethod(LuaItemStack, get_stack_max),
	luamethod(LuaItemStack, get_free_space),
	luamethod(LuaItemStack, is_known),
	luamethod(LuaItemStack, get_definition),
	luamethod(LuaItemStack, get_tool_capabilities),
	luamethod(LuaItemStack, add_wear),
	luamethod(LuaItemStack, add_item),
	luamethod(LuaItemStack, item_fits),
	luamethod(LuaItemStack, take_item),
	luamethod(LuaItemStack, peek_item),
	{0,0}
};

/*
	ItemDefinition
*/

// register_item_raw({lots of stuff})
int ModApiItemMod::l_register_item_raw(lua_State *L)
{
	NO_MAP_LOCK_REQUIRED;
	luaL_checktype(L, 1, LUA_TTABLE);
	int table = 1;

	// Get the writable item and node definition managers from the server
	IWritableItemDefManager *idef =
			getServer(L)->getWritableItemDefManager();
	IWritableNodeDefManager *ndef =
			getServer(L)->getWritableNodeDefManager();

	// Check if name is defined
	std::string name;
	lua_getfield(L, table, "name");
	if(lua_isstring(L, -1)){
		name = lua_tostring(L, -1);
		verbosestream<<"register_item_raw: "<<name<<std::endl;
	} else {
		throw LuaError("register_item_raw: name is not defined or not a string");
	}

	// Check if on_use is defined

	ItemDefinition def;
	// Set a distinctive default value to check if this is set
	def.node_placement_prediction = "__default";

	// Read the item definition
	read_item_definition(L, table, def, def);

	// Default to having client-side placement prediction for nodes
	// ("" in item definition sets it off)
	if(def.node_placement_prediction == "__default"){
		if(def.type == ITEM_NODE)
			def.node_placement_prediction = name;
		else
			def.node_placement_prediction = "";
	}

	// Register item definition
	idef->registerItem(def);

	// Read the node definition (content features) and register it
	if(def.type == ITEM_NODE){
		ContentFeatures f = read_content_features(L, table);
		content_t id = ndef->set(f.name, f);

		if(id > MAX_REGISTERED_CONTENT){
			throw LuaError("Number of registerable nodes ("
					+ itos(MAX_REGISTERED_CONTENT+1)
					+ ") exceeded (" + name + ")");
		}
	}

	return 0; /* number of results */
}

// unregister_item(name)
int ModApiItemMod::l_unregister_item_raw(lua_State *L)
{
	NO_MAP_LOCK_REQUIRED;
	std::string name = luaL_checkstring(L, 1);

	IWritableItemDefManager *idef =
			getServer(L)->getWritableItemDefManager();

	// Unregister the node
	if (idef->get(name).type == ITEM_NODE) {
		IWritableNodeDefManager *ndef =
			getServer(L)->getWritableNodeDefManager();
		ndef->removeNode(name);
	}

	idef->unregisterItem(name);

	return 0; /* number of results */
}

// register_alias_raw(name, convert_to_name)
int ModApiItemMod::l_register_alias_raw(lua_State *L)
{
	NO_MAP_LOCK_REQUIRED;
	std::string name = luaL_checkstring(L, 1);
	std::string convert_to = luaL_checkstring(L, 2);

	// Get the writable item definition manager from the server
	IWritableItemDefManager *idef =
			getServer(L)->getWritableItemDefManager();

	idef->registerAlias(name, convert_to);

	return 0; /* number of results */
}

// get_content_id(name)
int ModApiItemMod::l_get_content_id(lua_State *L)
{
	NO_MAP_LOCK_REQUIRED;
	std::string name = luaL_checkstring(L, 1);

	INodeDefManager *ndef = getGameDef(L)->getNodeDefManager();
	content_t c = ndef->getId(name);

	lua_pushinteger(L, c);
	return 1; /* number of results */
}

// get_name_from_content_id(name)
int ModApiItemMod::l_get_name_from_content_id(lua_State *L)
{
	NO_MAP_LOCK_REQUIRED;
	content_t c = luaL_checkint(L, 1);

	INodeDefManager *ndef = getGameDef(L)->getNodeDefManager();
	const char *name = ndef->get(c).name.c_str();

	lua_pushstring(L, name);
	return 1; /* number of results */
}

void ModApiItemMod::Initialize(lua_State *L, int top)
{
	API_FCT(register_item_raw);
	API_FCT(unregister_item_raw);
	API_FCT(register_alias_raw);
	API_FCT(get_content_id);
	API_FCT(get_name_from_content_id);
}
> */ addUpdateMeshTaskWithEdge(p, true); } void Client::handleCommand_Inventory(NetworkPacket* pkt) { if (pkt->getSize() < 1) return; std::string datastring(pkt->getString(0), pkt->getSize()); std::istringstream is(datastring, std::ios_base::binary); LocalPlayer *player = m_env.getLocalPlayer(); assert(player != NULL); player->inventory.deSerialize(is); m_update_wielded_item = true; delete m_inventory_from_server; m_inventory_from_server = new Inventory(player->inventory); m_inventory_from_server_age = 0.0; } void Client::handleCommand_TimeOfDay(NetworkPacket* pkt) { if (pkt->getSize() < 2) return; u16 time_of_day; *pkt >> time_of_day; time_of_day = time_of_day % 24000; float time_speed = 0; if (pkt->getSize() >= 2 + 4) { *pkt >> time_speed; } else { // Old message; try to approximate speed of time by ourselves float time_of_day_f = (float)time_of_day / 24000.0f; float tod_diff_f = 0; if (time_of_day_f < 0.2 && m_last_time_of_day_f > 0.8) tod_diff_f = time_of_day_f - m_last_time_of_day_f + 1.0f; else tod_diff_f = time_of_day_f - m_last_time_of_day_f; m_last_time_of_day_f = time_of_day_f; float time_diff = m_time_of_day_update_timer; m_time_of_day_update_timer = 0; if (m_time_of_day_set) { time_speed = (3600.0f * 24.0f) * tod_diff_f / time_diff; infostream << "Client: Measured time_of_day speed (old format): " << time_speed << " tod_diff_f=" << tod_diff_f << " time_diff=" << time_diff << std::endl; } } // Update environment m_env.setTimeOfDay(time_of_day); m_env.setTimeOfDaySpeed(time_speed); m_time_of_day_set = true; //u32 dr = m_env.getDayNightRatio(); //infostream << "Client: time_of_day=" << time_of_day // << " time_speed=" << time_speed // << " dr=" << dr << std::endl; } void Client::handleCommand_ChatMessage(NetworkPacket *pkt) { /* u8 version u8 message_type u16 sendername length wstring sendername u16 length wstring message */ ChatMessage *chatMessage = new ChatMessage(); u8 version, message_type; *pkt >> version >> message_type; if (version != 1 || message_type >= CHATMESSAGE_TYPE_MAX) { delete chatMessage; return; } u64 timestamp; *pkt >> chatMessage->sender >> chatMessage->message >> timestamp; chatMessage->timestamp = static_cast<std::time_t>(timestamp); chatMessage->type = (ChatMessageType) message_type; // @TODO send this to CSM using ChatMessage object if (modsLoaded() && m_script->on_receiving_message( wide_to_utf8(chatMessage->message))) { // Message was consumed by CSM and should not be handled by client delete chatMessage; } else { pushToChatQueue(chatMessage); } } void Client::handleCommand_ActiveObjectRemoveAdd(NetworkPacket* pkt) { /* u16 count of removed objects for all removed objects { u16 id } u16 count of added objects for all added objects { u16 id u8 type u32 initialization data length string initialization data } */ try { u8 type; u16 removed_count, added_count, id; // Read removed objects *pkt >> removed_count; for (u16 i = 0; i < removed_count; i++) { *pkt >> id; m_env.removeActiveObject(id); } // Read added objects *pkt >> added_count; for (u16 i = 0; i < added_count; i++) { *pkt >> id >> type; m_env.addActiveObject(id, type, pkt->readLongString()); } } catch (PacketError &e) { infostream << "handleCommand_ActiveObjectRemoveAdd: " << e.what() << ". The packet is unreliable, ignoring" << std::endl; } // m_activeobjects_received is false before the first // TOCLIENT_ACTIVE_OBJECT_REMOVE_ADD packet is received m_activeobjects_received = true; } void Client::handleCommand_ActiveObjectMessages(NetworkPacket* pkt) { /* for all objects { u16 id u16 message length string message } */ std::string datastring(pkt->getString(0), pkt->getSize()); std::istringstream is(datastring, std::ios_base::binary); try { while (is.good()) { u16 id = readU16(is); if (!is.good()) break; std::string message = deSerializeString16(is); // Pass on to the environment m_env.processActiveObjectMessage(id, message); } } catch (SerializationError &e) { errorstream << "Client::handleCommand_ActiveObjectMessages: " << "caught SerializationError: " << e.what() << std::endl; } } void Client::handleCommand_Movement(NetworkPacket* pkt) { LocalPlayer *player = m_env.getLocalPlayer(); assert(player != NULL); float mad, maa, maf, msw, mscr, msf, mscl, msj, lf, lfs, ls, g; *pkt >> mad >> maa >> maf >> msw >> mscr >> msf >> mscl >> msj >> lf >> lfs >> ls >> g; player->movement_acceleration_default = mad * BS; player->movement_acceleration_air = maa * BS; player->movement_acceleration_fast = maf * BS; player->movement_speed_walk = msw * BS; player->movement_speed_crouch = mscr * BS; player->movement_speed_fast = msf * BS; player->movement_speed_climb = mscl * BS; player->movement_speed_jump = msj * BS; player->movement_liquid_fluidity = lf * BS; player->movement_liquid_fluidity_smooth = lfs * BS; player->movement_liquid_sink = ls * BS; player->movement_gravity = g * BS; } void Client::handleCommand_Fov(NetworkPacket *pkt) { f32 fov; bool is_multiplier = false; f32 transition_time = 0.0f; *pkt >> fov >> is_multiplier; // Wrap transition_time extraction within a // try-catch to preserve backwards compat try { *pkt >> transition_time; } catch (PacketError &e) {}; LocalPlayer *player = m_env.getLocalPlayer(); assert(player); player->setFov({ fov, is_multiplier, transition_time }); m_camera->notifyFovChange(); } void Client::handleCommand_HP(NetworkPacket *pkt) { LocalPlayer *player = m_env.getLocalPlayer(); assert(player != NULL); u16 oldhp = player->hp; u16 hp; *pkt >> hp; player->hp = hp; if (modsLoaded()) m_script->on_hp_modification(hp); if (hp < oldhp) { // Add to ClientEvent queue ClientEvent *event = new ClientEvent(); event->type = CE_PLAYER_DAMAGE; event->player_damage.amount = oldhp - hp; m_client_event_queue.push(event); } } void Client::handleCommand_Breath(NetworkPacket* pkt) { LocalPlayer *player = m_env.getLocalPlayer(); assert(player != NULL); u16 breath; *pkt >> breath; player->setBreath(breath); } void Client::handleCommand_MovePlayer(NetworkPacket* pkt) { LocalPlayer *player = m_env.getLocalPlayer(); assert(player != NULL); v3f pos; f32 pitch, yaw; *pkt >> pos >> pitch >> yaw; player->setPosition(pos); infostream << "Client got TOCLIENT_MOVE_PLAYER" << " pos=(" << pos.X << "," << pos.Y << "," << pos.Z << ")" << " pitch=" << pitch << " yaw=" << yaw << std::endl; /* Add to ClientEvent queue. This has to be sent to the main program because otherwise it would just force the pitch and yaw values to whatever the camera points to. */ ClientEvent *event = new ClientEvent(); event->type = CE_PLAYER_FORCE_MOVE; event->player_force_move.pitch = pitch; event->player_force_move.yaw = yaw; m_client_event_queue.push(event); } void Client::handleCommand_DeathScreen(NetworkPacket* pkt) { bool set_camera_point_target; v3f camera_point_target; *pkt >> set_camera_point_target; *pkt >> camera_point_target; ClientEvent *event = new ClientEvent(); event->type = CE_DEATHSCREEN; event->deathscreen.set_camera_point_target = set_camera_point_target; event->deathscreen.camera_point_target_x = camera_point_target.X; event->deathscreen.camera_point_target_y = camera_point_target.Y; event->deathscreen.camera_point_target_z = camera_point_target.Z; m_client_event_queue.push(event); } void Client::handleCommand_AnnounceMedia(NetworkPacket* pkt) { u16 num_files; *pkt >> num_files; infostream << "Client: Received media announcement: packet size: " << pkt->getSize() << std::endl; if (m_media_downloader == NULL || m_media_downloader->isStarted()) { const char *problem = m_media_downloader ? "we already saw another announcement" : "all media has been received already"; errorstream << "Client: Received media announcement but " << problem << "! " << " files=" << num_files << " size=" << pkt->getSize() << std::endl; return; } // Mesh update thread must be stopped while // updating content definitions sanity_check(!m_mesh_update_thread.isRunning()); for (u16 i = 0; i < num_files; i++) { std::string name, sha1_base64; *pkt >> name >> sha1_base64; std::string sha1_raw = base64_decode(sha1_base64); m_media_downloader->addFile(name, sha1_raw); } { std::string str; *pkt >> str; Strfnd sf(str); while (!sf.at_end()) { std::string baseurl = trim(sf.next(",")); if (!baseurl.empty()) { m_remote_media_servers.emplace_back(baseurl); m_media_downloader->addRemoteServer(baseurl); } } } m_media_downloader->step(this); } void Client::handleCommand_Media(NetworkPacket* pkt) { /* u16 command u16 total number of file bunches u16 index of this bunch u32 number of files in this bunch for each file { u16 length of name string name u32 length of data data } */ u16 num_bunches; u16 bunch_i; u32 num_files; *pkt >> num_bunches >> bunch_i >> num_files; infostream << "Client: Received files: bunch " << bunch_i << "/" << num_bunches << " files=" << num_files << " size=" << pkt->getSize() << std::endl; if (num_files == 0) return; bool init_phase = m_media_downloader && m_media_downloader->isStarted(); if (init_phase) { // Mesh update thread must be stopped while // updating content definitions sanity_check(!m_mesh_update_thread.isRunning()); } for (u32 i = 0; i < num_files; i++) { std::string name, data; *pkt >> name; data = pkt->readLongString(); bool ok = false; if (init_phase) { ok = m_media_downloader->conventionalTransferDone(name, data, this); } else { // Check pending dynamic transfers, one of them must be it for (const auto &it : m_pending_media_downloads) { if (it.second->conventionalTransferDone(name, data, this)) { ok = true; break; } } } if (!ok) { errorstream << "Client: Received media \"" << name << "\" but no downloads pending. " << num_bunches << " bunches, " << num_files << " in this one. (init_phase=" << init_phase << ")" << std::endl; } } } void Client::handleCommand_NodeDef(NetworkPacket* pkt) { infostream << "Client: Received node definitions: packet size: " << pkt->getSize() << std::endl; // Mesh update thread must be stopped while // updating content definitions sanity_check(!m_mesh_update_thread.isRunning()); // Decompress node definitions std::istringstream tmp_is(pkt->readLongString(), std::ios::binary); std::stringstream tmp_os(std::ios::binary | std::ios::in | std::ios::out); decompressZlib(tmp_is, tmp_os); // Deserialize node definitions m_nodedef->deSerialize(tmp_os); m_nodedef_received = true; } void Client::handleCommand_ItemDef(NetworkPacket* pkt) { infostream << "Client: Received item definitions: packet size: " << pkt->getSize() << std::endl; // Mesh update thread must be stopped while // updating content definitions sanity_check(!m_mesh_update_thread.isRunning()); // Decompress item definitions std::istringstream tmp_is(pkt->readLongString(), std::ios::binary); std::stringstream tmp_os(std::ios::binary | std::ios::in | std::ios::out); decompressZlib(tmp_is, tmp_os); // Deserialize node definitions m_itemdef->deSerialize(tmp_os); m_itemdef_received = true; } void Client::handleCommand_PlaySound(NetworkPacket* pkt) { /* [0] u32 server_id [4] u16 name length [6] char name[len] [ 6 + len] f32 gain [10 + len] u8 type [11 + len] (f32 * 3) pos [23 + len] u16 object_id [25 + len] bool loop [26 + len] f32 fade [30 + len] f32 pitch [34 + len] bool ephemeral */ s32 server_id; std::string name; float gain; u8 type; // 0=local, 1=positional, 2=object v3f pos; u16 object_id; bool loop; float fade = 0.0f; float pitch = 1.0f; bool ephemeral = false; *pkt >> server_id >> name >> gain >> type >> pos >> object_id >> loop; try { *pkt >> fade; *pkt >> pitch; *pkt >> ephemeral; } catch (PacketError &e) {}; // Start playing int client_id = -1; switch(type) { case 0: // local client_id = m_sound->playSound(name, loop, gain, fade, pitch); break; case 1: // positional client_id = m_sound->playSoundAt(name, loop, gain, pos, pitch); break; case 2: { // object ClientActiveObject *cao = m_env.getActiveObject(object_id); if (cao) pos = cao->getPosition(); client_id = m_sound->playSoundAt(name, loop, gain, pos, pitch); break; } default: break; } if (client_id != -1) { // for ephemeral sounds, server_id is not meaningful if (!ephemeral) { m_sounds_server_to_client[server_id] = client_id; m_sounds_client_to_server[client_id] = server_id; } if (object_id != 0) m_sounds_to_objects[client_id] = object_id; } } void Client::handleCommand_StopSound(NetworkPacket* pkt) { s32 server_id; *pkt >> server_id; std::unordered_map<s32, int>::iterator i = m_sounds_server_to_client.find(server_id); if (i != m_sounds_server_to_client.end()) { int client_id = i->second; m_sound->stopSound(client_id); } } void Client::handleCommand_FadeSound(NetworkPacket *pkt) { s32 sound_id; float step; float gain; *pkt >> sound_id >> step >> gain; std::unordered_map<s32, int>::const_iterator i = m_sounds_server_to_client.find(sound_id); if (i != m_sounds_server_to_client.end()) m_sound->fadeSound(i->second, step, gain); } void Client::handleCommand_Privileges(NetworkPacket* pkt) { m_privileges.clear(); infostream << "Client: Privileges updated: "; u16 num_privileges; *pkt >> num_privileges; for (u16 i = 0; i < num_privileges; i++) { std::string priv; *pkt >> priv; m_privileges.insert(priv); infostream << priv << " "; } infostream << std::endl; } void Client::handleCommand_InventoryFormSpec(NetworkPacket* pkt) { LocalPlayer *player = m_env.getLocalPlayer(); assert(player != NULL); // Store formspec in LocalPlayer player->inventory_formspec = pkt->readLongString(); } void Client::handleCommand_DetachedInventory(NetworkPacket* pkt) { std::string name; bool keep_inv = true; *pkt >> name >> keep_inv; infostream << "Client: Detached inventory update: \"" << name << "\", mode=" << (keep_inv ? "update" : "remove") << std::endl; const auto &inv_it = m_detached_inventories.find(name); if (!keep_inv) { if (inv_it != m_detached_inventories.end()) { delete inv_it->second; m_detached_inventories.erase(inv_it); } return; } Inventory *inv = nullptr; if (inv_it == m_detached_inventories.end()) { inv = new Inventory(m_itemdef); m_detached_inventories[name] = inv; } else { inv = inv_it->second; } u16 ignore; *pkt >> ignore; // this used to be the length of the following string, ignore it std::string contents(pkt->getRemainingString(), pkt->getRemainingBytes()); std::istringstream is(contents, std::ios::binary); inv->deSerialize(is); } void Client::handleCommand_ShowFormSpec(NetworkPacket* pkt) { std::string formspec = pkt->readLongString(); std::string formname; *pkt >> formname; ClientEvent *event = new ClientEvent(); event->type = CE_SHOW_FORMSPEC; // pointer is required as event is a struct only! // adding a std:string to a struct isn't possible event->show_formspec.formspec = new std::string(formspec); event->show_formspec.formname = new std::string(formname); m_client_event_queue.push(event); } void Client::handleCommand_SpawnParticle(NetworkPacket* pkt) { std::string datastring(pkt->getString(0), pkt->getSize()); std::istringstream is(datastring, std::ios_base::binary); ParticleParameters p; p.deSerialize(is, m_proto_ver); ClientEvent *event = new ClientEvent(); event->type = CE_SPAWN_PARTICLE; event->spawn_particle = new ParticleParameters(p); m_client_event_queue.push(event); } void Client::handleCommand_AddParticleSpawner(NetworkPacket* pkt) { std::string datastring(pkt->getString(0), pkt->getSize()); std::istringstream is(datastring, std::ios_base::binary); ParticleSpawnerParameters p; u32 server_id; u16 attached_id = 0; p.amount = readU16(is); p.time = readF32(is); p.minpos = readV3F32(is); p.maxpos = readV3F32(is); p.minvel = readV3F32(is); p.maxvel = readV3F32(is); p.minacc = readV3F32(is); p.maxacc = readV3F32(is); p.minexptime = readF32(is); p.maxexptime = readF32(is); p.minsize = readF32(is); p.maxsize = readF32(is); p.collisiondetection = readU8(is); p.texture = deSerializeString32(is); server_id = readU32(is); p.vertical = readU8(is); p.collision_removal = readU8(is); attached_id = readU16(is); p.animation.deSerialize(is, m_proto_ver); p.glow = readU8(is); p.object_collision = readU8(is); // This is kinda awful do { u16 tmp_param0 = readU16(is); if (is.eof()) break; p.node.param0 = tmp_param0; p.node.param2 = readU8(is); p.node_tile = readU8(is); } while (0); auto event = new ClientEvent(); event->type = CE_ADD_PARTICLESPAWNER; event->add_particlespawner.p = new ParticleSpawnerParameters(p); event->add_particlespawner.attached_id = attached_id; event->add_particlespawner.id = server_id; m_client_event_queue.push(event); } void Client::handleCommand_DeleteParticleSpawner(NetworkPacket* pkt) { u32 server_id; *pkt >> server_id; ClientEvent *event = new ClientEvent(); event->type = CE_DELETE_PARTICLESPAWNER; event->delete_particlespawner.id = server_id; m_client_event_queue.push(event); } void Client::handleCommand_HudAdd(NetworkPacket* pkt) { u32 server_id; u8 type; v2f pos; std::string name; v2f scale; std::string text; u32 number; u32 item; u32 dir; v2f align; v2f offset; v3f world_pos; v2s32 size; s16 z_index = 0; std::string text2; u32 style = 0; *pkt >> server_id >> type >> pos >> name >> scale >> text >> number >> item >> dir >> align >> offset; try { *pkt >> world_pos; *pkt >> size; *pkt >> z_index; *pkt >> text2; *pkt >> style; } catch(PacketError &e) {}; ClientEvent *event = new ClientEvent(); event->type = CE_HUDADD; event->hudadd = new ClientEventHudAdd(); event->hudadd->server_id = server_id; event->hudadd->type = type; event->hudadd->pos = pos; event->hudadd->name = name; event->hudadd->scale = scale; event->hudadd->text = text; event->hudadd->number = number; event->hudadd->item = item; event->hudadd->dir = dir; event->hudadd->align = align; event->hudadd->offset = offset; event->hudadd->world_pos = world_pos; event->hudadd->size = size; event->hudadd->z_index = z_index; event->hudadd->text2 = text2; event->hudadd->style = style; m_client_event_queue.push(event); } void Client::handleCommand_HudRemove(NetworkPacket* pkt) { u32 server_id; *pkt >> server_id; ClientEvent *event = new ClientEvent(); event->type = CE_HUDRM; event->hudrm.id = server_id; m_client_event_queue.push(event); } void Client::handleCommand_HudChange(NetworkPacket* pkt) { std::string sdata; v2f v2fdata; v3f v3fdata; u32 intdata = 0; v2s32 v2s32data; u32 server_id; u8 stat; *pkt >> server_id >> stat; // Keep in sync with:server.cpp -> SendHUDChange switch ((HudElementStat)stat) { case HUD_STAT_POS: case HUD_STAT_SCALE: case HUD_STAT_ALIGN: case HUD_STAT_OFFSET: *pkt >> v2fdata; break; case HUD_STAT_NAME: case HUD_STAT_TEXT: case HUD_STAT_TEXT2: *pkt >> sdata; break; case HUD_STAT_WORLD_POS: *pkt >> v3fdata; break; case HUD_STAT_SIZE: *pkt >> v2s32data; break; default: *pkt >> intdata; break; } ClientEvent *event = new ClientEvent(); event->type = CE_HUDCHANGE; event->hudchange = new ClientEventHudChange(); event->hudchange->id = server_id; event->hudchange->stat = static_cast<HudElementStat>(stat); event->hudchange->v2fdata = v2fdata; event->hudchange->v3fdata = v3fdata; event->hudchange->sdata = sdata; event->hudchange->data = intdata; event->hudchange->v2s32data = v2s32data; m_client_event_queue.push(event); } void Client::handleCommand_HudSetFlags(NetworkPacket* pkt) { u32 flags, mask; *pkt >> flags >> mask; LocalPlayer *player = m_env.getLocalPlayer(); assert(player != NULL); bool was_minimap_visible = player->hud_flags & HUD_FLAG_MINIMAP_VISIBLE; bool was_minimap_radar_visible = player->hud_flags & HUD_FLAG_MINIMAP_RADAR_VISIBLE; player->hud_flags &= ~mask; player->hud_flags |= flags; m_minimap_disabled_by_server = !(player->hud_flags & HUD_FLAG_MINIMAP_VISIBLE); bool m_minimap_radar_disabled_by_server = !(player->hud_flags & HUD_FLAG_MINIMAP_RADAR_VISIBLE); // Not so satisying code to keep compatibility with old fixed mode system // --> // Hide minimap if it has been disabled by the server if (m_minimap && m_minimap_disabled_by_server && was_minimap_visible) // defers a minimap update, therefore only call it if really // needed, by checking that minimap was visible before m_minimap->setModeIndex(0); // If radar has been disabled, try to find a non radar mode or fall back to 0 if (m_minimap && m_minimap_radar_disabled_by_server && was_minimap_radar_visible) { while (m_minimap->getModeIndex() > 0 && m_minimap->getModeDef().type == MINIMAP_TYPE_RADAR) m_minimap->nextMode(); } // <-- // End of 'not so satifying code' } void Client::handleCommand_HudSetParam(NetworkPacket* pkt) { u16 param; std::string value; *pkt >> param >> value; LocalPlayer *player = m_env.getLocalPlayer(); assert(player != NULL); if (param == HUD_PARAM_HOTBAR_ITEMCOUNT && value.size() == 4) { s32 hotbar_itemcount = readS32((u8*) value.c_str()); if (hotbar_itemcount > 0 && hotbar_itemcount <= HUD_HOTBAR_ITEMCOUNT_MAX) player->hud_hotbar_itemcount = hotbar_itemcount; } else if (param == HUD_PARAM_HOTBAR_IMAGE) { player->hotbar_image = value; } else if (param == HUD_PARAM_HOTBAR_SELECTED_IMAGE) { player->hotbar_selected_image = value; } } void Client::handleCommand_HudSetSky(NetworkPacket* pkt) { if (m_proto_ver < 39) { // Handle Protocol 38 and below servers with old set_sky, // ensuring the classic look is kept. std::string datastring(pkt->getString(0), pkt->getSize()); std::istringstream is(datastring, std::ios_base::binary); SkyboxParams skybox; skybox.bgcolor = video::SColor(readARGB8(is)); skybox.type = std::string(deSerializeString16(is)); u16 count = readU16(is); for (size_t i = 0; i < count; i++) skybox.textures.emplace_back(deSerializeString16(is)); skybox.clouds = true; try { skybox.clouds = readU8(is); } catch (...) {} // Use default skybox settings: SunParams sun = SkyboxDefaults::getSunDefaults(); MoonParams moon = SkyboxDefaults::getMoonDefaults(); StarParams stars = SkyboxDefaults::getStarDefaults(); // Fix for "regular" skies, as color isn't kept: if (skybox.type == "regular") { skybox.sky_color = SkyboxDefaults::getSkyColorDefaults(); skybox.fog_tint_type = "default"; skybox.fog_moon_tint = video::SColor(255, 255, 255, 255); skybox.fog_sun_tint = video::SColor(255, 255, 255, 255); } else { sun.visible = false; sun.sunrise_visible = false; moon.visible = false; stars.visible = false; } // Skybox, sun, moon and stars ClientEvents: ClientEvent *sky_event = new ClientEvent(); sky_event->type = CE_SET_SKY; sky_event->set_sky = new SkyboxParams(skybox); m_client_event_queue.push(sky_event); ClientEvent *sun_event = new ClientEvent(); sun_event->type = CE_SET_SUN; sun_event->sun_params = new SunParams(sun); m_client_event_queue.push(sun_event); ClientEvent *moon_event = new ClientEvent(); moon_event->type = CE_SET_MOON; moon_event->moon_params = new MoonParams(moon); m_client_event_queue.push(moon_event); ClientEvent *star_event = new ClientEvent(); star_event->type = CE_SET_STARS; star_event->star_params = new StarParams(stars); m_client_event_queue.push(star_event); } else { SkyboxParams skybox; u16 texture_count; std::string texture; *pkt >> skybox.bgcolor >> skybox.type >> skybox.clouds >> skybox.fog_sun_tint >> skybox.fog_moon_tint >> skybox.fog_tint_type; if (skybox.type == "skybox") { *pkt >> texture_count; for (int i = 0; i < texture_count; i++) { *pkt >> texture; skybox.textures.emplace_back(texture); } } else if (skybox.type == "regular") { *pkt >> skybox.sky_color.day_sky >> skybox.sky_color.day_horizon >> skybox.sky_color.dawn_sky >> skybox.sky_color.dawn_horizon >> skybox.sky_color.night_sky >> skybox.sky_color.night_horizon >> skybox.sky_color.indoors; } ClientEvent *event = new ClientEvent(); event->type = CE_SET_SKY; event->set_sky = new SkyboxParams(skybox); m_client_event_queue.push(event); } } void Client::handleCommand_HudSetSun(NetworkPacket *pkt) { SunParams sun; *pkt >> sun.visible >> sun.texture>> sun.tonemap >> sun.sunrise >> sun.sunrise_visible >> sun.scale; ClientEvent *event = new ClientEvent(); event->type = CE_SET_SUN; event->sun_params = new SunParams(sun); m_client_event_queue.push(event); } void Client::handleCommand_HudSetMoon(NetworkPacket *pkt) { MoonParams moon; *pkt >> moon.visible >> moon.texture >> moon.tonemap >> moon.scale; ClientEvent *event = new ClientEvent(); event->type = CE_SET_MOON; event->moon_params = new MoonParams(moon); m_client_event_queue.push(event); } void Client::handleCommand_HudSetStars(NetworkPacket *pkt) { StarParams stars; *pkt >> stars.visible >> stars.count >> stars.starcolor >> stars.scale; ClientEvent *event = new ClientEvent(); event->type = CE_SET_STARS; event->star_params = new StarParams(stars); m_client_event_queue.push(event); } void Client::handleCommand_CloudParams(NetworkPacket* pkt) { f32 density; video::SColor color_bright; video::SColor color_ambient; f32 height; f32 thickness; v2f speed; *pkt >> density >> color_bright >> color_ambient >> height >> thickness >> speed; ClientEvent *event = new ClientEvent(); event->type = CE_CLOUD_PARAMS; event->cloud_params.density = density; // use the underlying u32 representation, because we can't // use struct members with constructors here, and this way // we avoid using new() and delete() for no good reason event->cloud_params.color_bright = color_bright.color; event->cloud_params.color_ambient = color_ambient.color; event->cloud_params.height = height; event->cloud_params.thickness = thickness; // same here: deconstruct to skip constructor event->cloud_params.speed_x = speed.X; event->cloud_params.speed_y = speed.Y; m_client_event_queue.push(event); } void Client::handleCommand_OverrideDayNightRatio(NetworkPacket* pkt) { bool do_override; u16 day_night_ratio_u; *pkt >> do_override >> day_night_ratio_u; float day_night_ratio_f = (float)day_night_ratio_u / 65536; ClientEvent *event = new ClientEvent(); event->type = CE_OVERRIDE_DAY_NIGHT_RATIO; event->override_day_night_ratio.do_override = do_override; event->override_day_night_ratio.ratio_f = day_night_ratio_f; m_client_event_queue.push(event); } void Client::handleCommand_LocalPlayerAnimations(NetworkPacket* pkt) { LocalPlayer *player = m_env.getLocalPlayer(); assert(player != NULL); *pkt >> player->local_animations[0]; *pkt >> player->local_animations[1]; *pkt >> player->local_animations[2]; *pkt >> player->local_animations[3]; *pkt >> player->local_animation_speed; player->last_animation = -1; } void Client::handleCommand_EyeOffset(NetworkPacket* pkt) { LocalPlayer *player = m_env.getLocalPlayer(); assert(player != NULL); *pkt >> player->eye_offset_first >> player->eye_offset_third; } void Client::handleCommand_UpdatePlayerList(NetworkPacket* pkt) { u8 type; u16 num_players; *pkt >> type >> num_players; PlayerListModifer notice_type = (PlayerListModifer) type; for (u16 i = 0; i < num_players; i++) { std::string name; *pkt >> name; switch (notice_type) { case PLAYER_LIST_INIT: case PLAYER_LIST_ADD: m_env.addPlayerName(name); continue; case PLAYER_LIST_REMOVE: m_env.removePlayerName(name); continue; } } } void Client::handleCommand_SrpBytesSandB(NetworkPacket* pkt) { if (m_chosen_auth_mech != AUTH_MECHANISM_SRP && m_chosen_auth_mech != AUTH_MECHANISM_LEGACY_PASSWORD) { errorstream << "Client: Received SRP S_B login message," << " but wasn't supposed to (chosen_mech=" << m_chosen_auth_mech << ")." << std::endl; return; } char *bytes_M = 0; size_t len_M = 0; SRPUser *usr = (SRPUser *) m_auth_data; std::string s; std::string B; *pkt >> s >> B; infostream << "Client: Received TOCLIENT_SRP_BYTES_S_B." << std::endl; srp_user_process_challenge(usr, (const unsigned char *) s.c_str(), s.size(), (const unsigned char *) B.c_str(), B.size(), (unsigned char **) &bytes_M, &len_M); if ( !bytes_M ) { errorstream << "Client: SRP-6a S_B safety check violation!" << std::endl; return; } NetworkPacket resp_pkt(TOSERVER_SRP_BYTES_M, 0); resp_pkt << std::string(bytes_M, len_M); Send(&resp_pkt); } void Client::handleCommand_FormspecPrepend(NetworkPacket *pkt) { LocalPlayer *player = m_env.getLocalPlayer(); assert(player != NULL); // Store formspec in LocalPlayer *pkt >> player->formspec_prepend; } void Client::handleCommand_CSMRestrictionFlags(NetworkPacket *pkt) { *pkt >> m_csm_restriction_flags >> m_csm_restriction_noderange; // Restrictions were received -> load mods if it's enabled // Note: this should be moved after mods receptions from server instead loadMods(); } void Client::handleCommand_PlayerSpeed(NetworkPacket *pkt) { v3f added_vel; *pkt >> added_vel; LocalPlayer *player = m_env.getLocalPlayer(); assert(player != NULL); player->addVelocity(added_vel); } void Client::handleCommand_MediaPush(NetworkPacket *pkt) { std::string raw_hash, filename, filedata; u32 token; bool cached; *pkt >> raw_hash >> filename >> cached; if (m_proto_ver >= 40) *pkt >> token; else filedata = pkt->readLongString(); if (raw_hash.size() != 20 || filename.empty() || (m_proto_ver < 40 && filedata.empty()) || !string_allowed(filename, TEXTURENAME_ALLOWED_CHARS)) { throw PacketError("Illegal filename, data or hash"); } verbosestream << "Server pushes media file \"" << filename << "\" "; if (filedata.empty()) verbosestream << "to be fetched "; else verbosestream << "with " << filedata.size() << " bytes "; verbosestream << "(cached=" << cached << ")" << std::endl; if (m_media_pushed_files.count(filename) != 0) { // Ignore (but acknowledge). Previously this was for sync purposes, // but even in new versions media cannot be replaced at runtime. if (m_proto_ver >= 40) sendHaveMedia({ token }); return; } if (!filedata.empty()) { // LEGACY CODEPATH // Compute and check checksum of data std::string computed_hash; { SHA1 ctx; ctx.addBytes(filedata.c_str(), filedata.size()); unsigned char *buf = ctx.getDigest(); computed_hash.assign((char*) buf, 20); free(buf); } if (raw_hash != computed_hash) { verbosestream << "Hash of file data mismatches, ignoring." << std::endl; return; } // Actually load media loadMedia(filedata, filename, true); m_media_pushed_files.insert(filename); // Cache file for the next time when this client joins the same server if (cached) clientMediaUpdateCache(raw_hash, filedata); return; } m_media_pushed_files.insert(filename); // create a downloader for this file auto downloader(std::make_shared<SingleMediaDownloader>(cached)); m_pending_media_downloads.emplace_back(token, downloader); downloader->addFile(filename, raw_hash); for (const auto &baseurl : m_remote_media_servers) downloader->addRemoteServer(baseurl); downloader->step(this); } /* * Mod channels */ void Client::handleCommand_ModChannelMsg(NetworkPacket *pkt) { std::string channel_name, sender, channel_msg; *pkt >> channel_name >> sender >> channel_msg; verbosestream << "Mod channel message received from server " << pkt->getPeerId() << " on channel " << channel_name << ". sender: `" << sender << "`, message: " << channel_msg << std::endl; if (!m_modchannel_mgr->channelRegistered(channel_name)) { verbosestream << "Server sent us messages on unregistered channel " << channel_name << ", ignoring." << std::endl; return; } m_script->on_modchannel_message(channel_name, sender, channel_msg); } void Client::handleCommand_ModChannelSignal(NetworkPacket *pkt) { u8 signal_tmp; ModChannelSignal signal; std::string channel; *pkt >> signal_tmp >> channel; signal = (ModChannelSignal)signal_tmp; bool valid_signal = true; // @TODO: send Signal to Lua API switch (signal) { case MODCHANNEL_SIGNAL_JOIN_OK: m_modchannel_mgr->setChannelState(channel, MODCHANNEL_STATE_READ_WRITE); infostream << "Server ack our mod channel join on channel `" << channel << "`, joining." << std::endl; break; case MODCHANNEL_SIGNAL_JOIN_FAILURE: // Unable to join, remove channel m_modchannel_mgr->leaveChannel(channel, 0); infostream << "Server refused our mod channel join on channel `" << channel << "`" << std::endl; break; case MODCHANNEL_SIGNAL_LEAVE_OK: #ifndef NDEBUG infostream << "Server ack our mod channel leave on channel " << channel << "`, leaving." << std::endl; #endif break; case MODCHANNEL_SIGNAL_LEAVE_FAILURE: infostream << "Server refused our mod channel leave on channel `" << channel << "`" << std::endl; break; case MODCHANNEL_SIGNAL_CHANNEL_NOT_REGISTERED: #ifndef NDEBUG // Generally unused, but ensure we don't do an implementation error infostream << "Server tells us we sent a message on channel `" << channel << "` but we are not registered. Message was dropped." << std::endl; #endif break; case MODCHANNEL_SIGNAL_SET_STATE: { u8 state; *pkt >> state; if (state == MODCHANNEL_STATE_INIT || state >= MODCHANNEL_STATE_MAX) { infostream << "Received wrong channel state " << state << ", ignoring." << std::endl; return; } m_modchannel_mgr->setChannelState(channel, (ModChannelState) state); infostream << "Server sets mod channel `" << channel << "` in read-only mode." << std::endl; break; } default: #ifndef NDEBUG warningstream << "Received unhandled mod channel signal ID " << signal << ", ignoring." << std::endl; #endif valid_signal = false; break; } // If signal is valid, forward it to client side mods if (valid_signal) m_script->on_modchannel_signal(channel, signal); } void Client::handleCommand_MinimapModes(NetworkPacket *pkt) { u16 count; // modes u16 mode; // wanted current mode index after change *pkt >> count >> mode; if (m_minimap) m_minimap->clearModes(); for (size_t index = 0; index < count; index++) { u16 type; std::string label; u16 size; std::string texture; u16 scale; *pkt >> type >> label >> size >> texture >> scale; if (m_minimap) m_minimap->addMode(MinimapType(type), size, label, texture, scale); } if (m_minimap) m_minimap->setModeIndex(mode); }