aboutsummaryrefslogtreecommitdiff
path: root/doc/lua_api.txt
blob: 7d8fa149f9bb48d16c28ce3e8ef5f8b637a5e443 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
12
		while (httpfetch_async_get(m_httpfetch_caller, fetch_result)) {
			m_httpfetch_active--;
			fetched_something = true;

			// Is this a hashset (index.mth) or a media file?
			if (fetch_result.request_id < m_remotes.size())
				remoteHashSetReceived(fetch_result);
			else
				remoteMediaReceived(fetch_result, client);
		}

		if (fetched_something)
			startRemoteMediaTransfers();

		// Did all remote transfers end and no new ones can be started?
		// If so, request still missing files from the minetest server
		// (Or report that we have all files.)
		if (m_httpfetch_active == 0) {
			if (m_uncached_received_count < m_uncached_count) {
				infostream << "Client: Failed to remote-fetch "
					<< (m_uncached_count-m_uncached_received_count)
					<< " files. Requesting them"
					<< " the usual way." << std::endl;
			}
			startConventionalTransfers(client);
		}
	}
}

void ClientMediaDownloader::initialStep(Client *client)
{
	// Check media cache
	m_uncached_count = m_files.size();
	for (auto &file_it : m_files) {
		const std::string &name = file_it.first;
		FileStatus *filestatus = file_it.second;
		const std::string &sha1 = filestatus->sha1;

		if (tryLoadFromCache(name, sha1, client)) {
			filestatus->received = true;
			m_uncached_count--;
		}
	}

	assert(m_uncached_received_count == 0);

	// Create the media cache dir if we are likely to write to it
	if (m_uncached_count != 0)
		createCacheDirs();

	// If we found all files in the cache, report this fact to the server.
	// If the server reported no remote servers, immediately start
	// conventional transfers. Note: if cURL support is not compiled in,
	// m_remotes is always empty, so "!USE_CURL" is redundant but may
	// reduce the size of the compiled code
	if (!USE_CURL || m_uncached_count == 0 || m_remotes.empty()) {
		startConventionalTransfers(client);
	}
	else {
		// Otherwise start off by requesting each server's sha1 set

		// This is the first time we use httpfetch, so alloc a caller ID
		m_httpfetch_caller = httpfetch_caller_alloc();

		// Set the active fetch limit to curl_parallel_limit or 84,
		// whichever is greater. This gives us some leeway so that
		// inefficiencies in communicating with the httpfetch thread
		// don't slow down fetches too much. (We still want some limit
		// so that when the first remote server returns its hash set,
		// not all files are requested from that server immediately.)
		// One such inefficiency is that ClientMediaDownloader::step()
		// is only called a couple times per second, while httpfetch
		// might return responses much faster than that.
		// Note that httpfetch strictly enforces curl_parallel_limit
		// but at no inter-thread communication cost. This however
		// doesn't help with the aforementioned inefficiencies.
		// The signifance of 84 is that it is 2*6*9 in base 13.
		m_httpfetch_active_limit = g_settings->getS32("curl_parallel_limit");
		m_httpfetch_active_limit = MYMAX(m_httpfetch_active_limit, 84);

		// Write a list of hashes that we need. This will be POSTed
		// to the server using Content-Type: application/octet-stream
		std::string required_hash_set = serializeRequiredHashSet();

		// minor fixme: this loop ignores m_httpfetch_active_limit

		// another minor fixme, unlikely to matter in normal usage:
		// these index.mth fetches do (however) count against
		// m_httpfetch_active_limit when starting actual media file
		// requests, so if there are lots of remote servers that are
		// not responding, those will stall new media file transfers.

		for (u32 i = 0; i < m_remotes.size(); ++i) {
			assert(m_httpfetch_next_id == i);

			RemoteServerStatus *remote = m_remotes[i];
			actionstream << "Client: Contacting remote server \""
				<< remote->baseurl << "\"" << std::endl;

			HTTPFetchRequest fetch_request;
			fetch_request.url =
				remote->baseurl + MTHASHSET_FILE_NAME;
			fetch_request.caller = m_httpfetch_caller;
			fetch_request.request_id = m_httpfetch_next_id; // == i
			fetch_request.method = HTTP_POST;
			fetch_request.raw_data = required_hash_set;
			fetch_request.extra_headers.emplace_back(
				"Content-Type: application/octet-stream");

			// Encapsulate possible IPv6 plain address in []
			std::string addr = client->getAddressName();
			if (addr.find(':', 0) != std::string::npos)
				addr = '[' + addr + ']';
			fetch_request.extra_headers.emplace_back(
				std::string("Referer: minetest://") +
				addr + ":" +
				std::to_string(client->getServerAddress().getPort()));

			httpfetch_async(fetch_request);

			m_httpfetch_active++;
			m_httpfetch_next_id++;
			m_outstanding_hash_sets++;
		}
	}
}

void ClientMediaDownloader::remoteHashSetReceived(
		const HTTPFetchResult &fetch_result)
{
	u32 remote_id = fetch_result.request_id;
	assert(remote_id < m_remotes.size());
	RemoteServerStatus *remote = m_remotes[remote_id];

	m_outstanding_hash_sets--;

	if (fetch_result.succeeded) {
		try {
			// Server sent a list of file hashes that are
			// available on it,Minetest Lua Modding API Reference 0.4.4
==========================================
More information at http://c55.me/minetest/

Introduction
-------------
Content and functionality can be added to Minetest 0.4 by using Lua
scripting in run-time loaded mods.

A mod is a self-contained bunch of scripts, textures and other related
things that is loaded by and interfaces with Minetest.

Mods are contained and ran solely on the server side. Definitions and media
files are automatically transferred to the client.

If you see a deficiency in the API, feel free to attempt to add the
functionality in the engine and API. You can send such improvements as
source code patches to <celeron55@gmail.com>.

Programming in Lua
-------------------
If you have any difficulty in understanding this, please read:
  http://www.lua.org/pil/

Startup
--------
Mods are loaded during server startup from the mod load paths by running
the init.lua scripts in a shared environment.

Mod load path
-------------
Generic:
  $path_share/games/gameid/mods/
  $path_share/mods/gameid/
  $path_user/games/gameid/mods/
  $path_user/mods/gameid/ <-- User-installed mods
  $worldpath/worldmods/

In a run-in-place version (eg. the distributed windows version):
  minetest-0.4.x/games/gameid/mods/
  minetest-0.4.x/mods/gameid/ <-- User-installed mods
  minetest-0.4.x/worlds/worldname/worldmods/

On an installed version on linux:
  /usr/share/minetest/games/gameid/mods/
  ~/.minetest/mods/gameid/ <-- User-installed mods
  ~/.minetest/worlds/worldname/worldmods

Mod load path for world-specific games
--------------------------------------
It is possible to include a game in a world; in this case, no mods or
games are loaded or checked from anywhere else.

This is useful for eg. adventure worlds.

This happens if the following directory exists:
  $world/game/

Mods should be then be placed in:
  $world/game/mods/

Modpack support
----------------
Mods can be put in a subdirectory, if the parent directory, which otherwise
should be a mod, contains a file named modpack.txt. This file shall be
empty, except for lines starting with #, which are comments.

Mod directory structure
------------------------
mods
|-- modname
|   |-- depends.txt
|   |-- init.lua
|   |-- textures
|   |   |-- modname_stuff.png
|   |   `-- modname_something_else.png
|   |-- sounds
|   |-- media
|   `-- <custom data>
`-- another

modname:
  The location of this directory can be fetched by using
  minetest.get_modpath(modname)

depends.txt:
  List of mods that have to be loaded before loading this mod.
  A single line contains a single modname.

init.lua:
  The main Lua script. Running this script should register everything it
  wants to register. Subsequent execution depends on minetest calling the
  registered callbacks.

  minetest.setting_get(name) and minetest.setting_getbool(name) can be used
  to read custom or existing settings at load time, if necessary.

textures, sounds, media:
  Media files (textures, sounds, whatever) that will be transferred to the
  client and will be available for use by the mod.

Naming convention for registered textual names
----------------------------------------------
Registered names should generally be in this format:
  "modname:<whatever>" (<whatever> can have characters a-zA-Z0-9_)

This is to prevent conflicting names from corrupting maps and is
enforced by the mod loader.

Example: mod "experimental", ideal item/node/entity name "tnt":
         -> the name should be "experimental:tnt".

Enforcement can be overridden by prefixing the name with ":". This can
be used for overriding the registrations of some other mod.

Example: Any mod can redefine experimental:tnt by using the name
         ":experimental:tnt" when registering it.
(also that mod is required to have "experimental" as a dependency)

The ":" prefix can also be used for maintaining backwards compatibility.

Aliases
-------
Aliases can be added by using minetest.register_alias(name, convert_to)

This will make Minetest to convert things called name to things called
convert_to.

This can be used for maintaining backwards compatibility.

This can be also used for setting quick access names for things, eg. if
you have an item called epiclylongmodname:stuff, you could do
  minetest.register_alias("stuff", "epiclylongmodname:stuff")
and be able to use "/giveme stuff".

Textures
--------
Mods should generally prefix their textures with modname_, eg. given
the mod name "foomod", a texture could be called
  "foomod_foothing.png"

Textures are referred to by their complete name, or alternatively by
stripping out the file extension:
  eg. foomod_foothing.png
  eg. foomod_foothing

Sounds
-------
Only OGG files are supported.

For positional playing of sounds, only single-channel (mono) files are
supported. Otherwise OpenAL will play them non-positionally.

Mods should generally prefix their sounds with modname_, eg. given
the mod name "foomod", a sound could be called
  "foomod_foosound.ogg"

Sounds are referred to by their name with a dot, a single digit and the
file extension stripped out.  When a sound is played, the actual sound file
is chosen randomly from the matching sounds.

When playing the sound "foomod_foosound", the sound is chosen randomly
from the available ones of the following files:
  foomod_foosound.ogg
  foomod_foosound.0.ogg
  foomod_foosound.1.ogg
  ...
  foomod_foosound.9.ogg

Examples of sound parameter tables:
-- Play locationless on all clients
{
	gain = 1.0, -- default
}
-- Play locationless to a player
{
	to_player = name,
	gain = 1.0, -- default
}
-- Play in a location
{
	pos = {x=1,y=2,z=3},
	gain = 1.0, -- default
	max_hear_distance = 32, -- default
}
-- Play connected to an object, looped
{
    object = <an ObjectRef>,
    gain = 1.0, -- default
    max_hear_distance = 32, -- default
    loop = true, -- only sounds connected to objects can be looped
}

SimpleSoundSpec:
eg. ""
eg. "default_place_node"
eg. {}
eg. {name="default_place_node"}
eg. {name="default_place_node", gain=1.0}

Registered definitions of stuff
--------------------------------
Anything added using certain minetest.register_* functions get added to
the global minetest.registered_* tables.

minetest.register_entity(name, prototype table)
 -> minetest.registered_entities[name]

minetest.register_node(name, node definition)
 -> minetest.registered_items[name]
 -> minetest.registered_nodes[name]

minetest.register_tool(name, item definition)
 -> minetest.registered_items[name]

minetest.register_craftitem(name, item definition)
 -> minetest.registered_items[name]

Note that in some cases you will stumble upon things that are not contained
in these tables (eg. when a mod has been removed). Always check for
existence before trying to access the fields.

Example: If you want to check the drawtype of a node, you could do:

local function get_nodedef_field(nodename, fieldname)
    if not minetest.registered_nodes[nodename] then
        return nil
    end
    return minetest.registered_nodes[nodename][fieldname]
end
local drawtype = get_nodedef_field(nodename, "drawtype")

Example: minetest.get_item_group(name, group) has been implemented as:

function minetest.get_item_group(name, group)
	if not minetest.registered_items[name] or not
			minetest.registered_items[name].groups[group] then
		return 0
	end
	return minetest.registered_items[name].groups[group]
end

Nodes
------
Nodes are the bulk data of the world: cubes and other things that take the
space of a cube. Huge amounts of them are handled efficiently, but they
are quite static.

The definition of a node is stored and can be accessed by name in
  minetest.registered_nodes[node.name]
See "Registered definitions of stuff".

Nodes are passed by value between Lua and the engine.
They are represented by a table:
  {name="name", param1=num, param2=num}

param1 and param2 are 8 bit integers. The engine uses them for certain
automated functions. If you don't use these functions, you can use them to
store arbitrary values.

The functions of param1 and param2 are determined by certain fields in the
node definition:
param1 is reserved for the engine when paramtype != "none":
  paramtype = "light"
  ^ The value stores light with and without sun in it's
    upper and lower 4 bits.
param2 is reserved for the engine when any of these are used:
  liquidtype == "flowing"
  ^ The level and some flags of the liquid is stored in param2
  drawtype == "flowingliquid"
  ^ The drawn liquid level is read from param2
  drawtype == "torchlike"
  drawtype == "signlike"
  paramtype2 == "wallmounted"
  ^ The rotation of the node is stored in param2. You can make this value
    by using minetest.dir_to_wallmounted().
  paramtype2 == "facedir"
  ^ The rotation of the node is stored in param2. Furnaces and chests are
    rotated this way. Can be made by using minetest.dir_to_facedir().

Nodes can also contain extra data. See "Node Metadata".

Node drawtypes
---------------
There are a bunch of different looking node types. These are mostly just
copied from Minetest 0.3; more may be made in the future.

Look for examples in games/minimal or games/minetest_game.

- normal
- airlike
- liquid
- flowingliquid
- glasslike
- allfaces
- allfaces_optional
- torchlike
- signlike
- plantlike
- fencelike
- raillike
- nodebox -- See below. EXPERIMENTAL

Node boxes
-----------
Node selection boxes are defined using "node boxes"

The "nodebox" node drawtype allows defining visual of nodes consisting of
arbitrary number of boxes. It allows defining stuff like stairs. Only the
"fixed" box type is supported for these.
^ Please note that this is still experimental, and may be incompatibly
  changed in the future.

A nodebox is defined as any of:
{
    -- A normal cube; the default in most things
    type = "regular"
}
{
    -- A fixed box (facedir param2 is used, if applicable)
    type = "fixed",
    fixed = box OR {box1, box2, ...}
}
{
    -- A box like the selection box for torches
    -- (wallmounted param2 is used, if applicable)
    type = "wallmounted",
    wall_top = box,
    wall_bottom = box,
    wall_side = box
}

A box is defined as:
  {x1, y1, z1, x2, y2, z2}
A box of a regular node would look like:
  {-0.5, -0.5, -0.5, 0.5, 0.5, 0.5},

Representations of simple things
--------------------------------
Position/vector:
  {x=num, y=num, z=num}
Currently the API does not provide any helper functions for addition,
subtraction and whatever; you can define those that you need yourself.

pointed_thing:
  {type="nothing"}
  {type="node", under=pos, above=pos}
  {type="object", ref=ObjectRef}

Items
------
Node (register_node):
  A node from the world
Tool (register_tool):
  A tool/weapon that can dig and damage things according to tool_capabilities
Craftitem (register_craftitem):
  A miscellaneous item

Items and item stacks can exist in three formats:

Serialized; This is called stackstring or itemstring:
eg. 'default:dirt 5'
eg. 'default:pick_wood 21323'
eg. 'default:apple'

Table format:
eg. {name="default:dirt", count=5, wear=0, metadata=""} 
    ^ 5 dirt nodes
eg. {name="default:pick_wood", count=1, wear=21323, metadata=""}
    ^ a wooden pick about 1/3 weared out
eg. {name="default:apple", count=1, wear=0, metadata=""}
    ^ an apple.

ItemStack:
C++ native format with many helper methods. Useful for converting between
formats. See the Class reference section for details.

When an item must be passed to a function, it can usually be in any of
these formats.

Groups
-------
In a number of places, there is a group table. Groups define the
properties of a thing (item, node, armor of entity, capabilities of
tool) in such a way that the engine and other mods can can interact with
the thing without actually knowing what the thing is.

Usage:
- Groups are stored in a table, having the group names with keys and the
  group ratings as values. For example:
    groups = {crumbly=3, soil=1}
    ^ Default dirt (soil group actually currently not defined; TODO)
    groups = {crumbly=2, soil=1, level=2, outerspace=1}
    ^ A more special dirt-kind of thing
- Groups always have a rating associated with them. If there is no
  useful meaning for a rating for an enabled group, it shall be 1.
- When not defined, the rating of a group defaults to 0. Thus when you
  read groups, you must interpret nil and 0 as the same value, 0.

You can read the rating of a group for an item or a node by using
  minetest.get_item_group(itemname, groupname)

Groups of items
----------------
Groups of items can define what kind of an item it is (eg. wool).

Groups of nodes
----------------
In addition to the general item things, groups are used to define whether
a node is destroyable and how long it takes to destroy by a tool.

Groups of entities
-------------------
For entities, groups are, as of now, used only for calculating damage.

object.get_armor_groups() -> a group-rating table (eg. {fleshy=3})
object.set_armor_groups({level=2, fleshy=2, cracky=2})

Groups of tools
----------------
Groups in tools define which groups of nodes and entities they are
effective towards.

Groups in crafting recipes
---------------------------
An example: Make meat soup from any meat, any water and any bowl
{
    output = 'food:meat_soup_raw',
    recipe = {
        {'group:meat'},
        {'group:water'},
        {'group:bowl'},
    },
    -- preserve = {'group:bowl'}, -- Not implemented yet (TODO)
}
An another example: Make red wool from white wool and red dye
{
	type = 'shapeless',
    output = 'wool:red',
    recipe = {'wool:white', 'group:dye,basecolor_red'},
}

Special groups
---------------
- immortal: Disables the group damage system for an entity
- level: Can be used to give an additional sense of progression in the game.
  - A larger level will cause eg. a weapon of a lower level make much less
    damage, and get weared out much faster, or not be able to get drops
	from destroyed nodes.
  - 0 is something that is directly accessible at the start of gameplay
  - There is no upper limit
- dig_immediate: (player can always pick up node without tool wear)
  - 2: node is removed without tool wear after 0.5 seconds or so
       (rail, sign)
  - 3: node is removed without tool wear immediately (torch)
- disable_jump: Player (and possibly other things) cannot jump from node
- fall_damage_add_percent: damage speed = speed * (1 + value/100)
- bouncy: value is bounce speed in percent
- falling_node: if there is no walkable block under the node it will fall
- attached_node: if the node under it is not a walkable block the node will be
                  dropped as an item. If the node is wallmounted the
                  wallmounted direction is checked.

Known damage and digging time defining groups
----------------------------------------------
Valid ratings for these are 0, 1, 2 and 3, unless otherwise stated.
- crumbly: dirt, sand
- cracky: tough but crackable stuff like stone.
- snappy: something that can be cut using fine tools; eg. leaves, small
          plants, wire, sheets of metal
- choppy: something that can be cut using force; eg. trees, wooden planks
- fleshy: Living things like animals and the player. This could imply
          some blood effects when hitting.
- explody: Especially prone to explosions
- oddly_breakable_by_hand:
   Can be added to nodes that shouldn't logically be breakable by the
   hand but are. Somewhat similar to dig_immediate, but times are more
   like {[1]=3.50,[2]=2.00,[3]=0.70} and this does not override the
   speed of a tool if the tool can dig at a faster speed than this
   suggests for the hand.

Examples of custom groups
--------------------------
Item groups are often used for defining, well, //groups of items//.
- meat: any meat-kind of a thing (rating might define the size or healing
  ability or be irrelevant - it is not defined as of yet)
- eatable: anything that can be eaten. Rating might define HP gain in half
  hearts.
- flammable: can be set on fire. Rating might define the intensity of the
  fire, affecting eg. the speed of the spreading of an open fire.
- wool: any wool (any origin, any color)
- metal: any metal
- weapon: any weapon
- heavy: anything considerably heavy

Digging time calculation specifics
-----------------------------------
Groups such as **crumbly**, **cracky** and **snappy** are used for this
purpose. Rating is 1, 2 or 3. A higher rating for such a group implies
faster digging time.

The **level** group is used to limit the toughness of nodes a tool can dig
and to scale the digging times / damage to a greater extent.

^ PLEASE DO UNDERSTAND THIS, otherwise you cannot use the system to it's
  full potential.

Tools define their properties by a list of parameters for groups. They
cannot dig other groups; thus it is important to use a standard bunch of
groups to enable interaction with tools.

**Tools define:**
  * Full punch interval
  * Maximum drop level
  * For an arbitrary list of groups:
    * Uses (until the tool breaks)
    * Maximum level (usually 0, 1, 2 or 3)
    * Digging times

**Full punch interval**:
When used as a weapon, the tool will do full damage if this time is spent
between punches. If eg. half the time is spent, the tool will do half
damage.

**Maximum drop level**
Suggests the maximum level of node, when dug with the tool, that will drop
it's useful item. (eg. iron ore to drop a lump of iron).
- This is not automated; it is the responsibility of the node definition
  to implement this

**Uses**
Determines how many uses the tool has when it is used for digging a node,
of this group, of the maximum level. For lower leveled nodes, the use count
is multiplied by 3^leveldiff.
- uses=10, leveldiff=0 -> actual uses: 10
- uses=10, leveldiff=1 -> actual uses: 30
- uses=10, leveldiff=2 -> actual uses: 90

**Maximum level**
Tells what is the maximum level of a node of this group that the tool will
be able to dig.

**Digging times**
List of digging times for different ratings of the group, for nodes of the
maximum level.
  * For example, as a lua table, ''times={2=2.00, 3=0.70}''. This would
    result in the tool to be able to dig nodes that have a rating of 2 or 3
    for this group, and unable to dig the rating 1, which is the toughest.
    Unless there is a matching group that enables digging otherwise.
  * For entities, damage equals the amount of nodes dug in the time spent
    between hits, with a maximum time of ''full_punch_interval''.

Example definition of the capabilities of a tool
-------------------------------------------------
tool_capabilities = {
	full_punch_interval=1.5,
	max_drop_level=1,
	groupcaps={
		crumbly={maxlevel=2, uses=20, times={[1]=1.60, [2]=1.20, [3]=0.80}}
	}
}

This makes the tool be able to dig nodes that fullfill both of these:
- Have the **crumbly** group
- Have a **level** group less or equal to 2

Table of resulting digging times:
crumbly        0     1     2     3     4  <- level
     ->  0     -     -     -     -     -
         1  0.80  1.60  1.60     -     -
         2  0.60  1.20  1.20     -     -
         3  0.40  0.80  0.80     -     -

level diff:    2     1     0    -1    -2

Table of resulting tool uses:
     ->  0     -     -     -     -     -
         1   180    60    20     -     -
         2   180    60    20     -     -
         3   180    60    20     -     -

Notes:
- At crumbly=0, the node is not diggable.
- At crumbly=3, the level difference digging time divider kicks in and makes
  easy nodes to be quickly breakable.
- At level > 2, the node is not diggable, because it's level > maxlevel

Entity damage mechanism
------------------------
Damage calculation:
- Take the time spent after the last hit
- Limit time to full_punch_interval
- Take the damage groups and imagine a bunch of nodes that have them
- Damage in HP is the amount of nodes destroyed in this time.

Client predicts damage based on damage groups. Because of this, it is able to
give an immediate response when an entity is damaged or dies; the response is
pre-defined somehow (eg. by defining a sprite animation) (not implemented;
TODO).
- Currently a smoke puff will appear when an entity dies.

The group **immortal** completely disables normal damage.

Entities can define a special armor group, which is **punch_operable**. This
group disables the regular damage mechanism for players punching it by hand or
a non-tool item, so that it can do something else than take damage.

On the Lua side, every punch calls ''entity:on_punch(puncher,
time_from_last_punch, tool_capabilities, direction)''. This should never be
called directly, because damage is usually not handled by the entity itself.
  * ''puncher'' is the object performing the punch. Can be nil. Should never be
    accessed unless absolutely required, to encourage interoperability.
  * ''time_from_last_punch'' is time from last punch (by puncher) or nil.
  * ''tool_capabilities'' can be nil.
  * ''direction'' is a unit vector, pointing from the source of the punch to
    the punched object.

To punch an entity/object in Lua, call ''object:punch(puncher,
time_from_last_punch, tool_capabilities, direction)''.
  * Return value is tool wear.
  * Parameters are equal to the above callback.
  * If ''direction'' is nil and ''puncher'' is not nil, ''direction'' will be
    automatically filled in based on the location of ''puncher''.

Node Metadata
-------------
The instance of a node in the world normally only contains the three values
mentioned in "Nodes". However, it is possible to insert extra data into a
node. It is called "node metadata"; See "NodeMetaRef".

Metadata contains two things:
- A key-value store
- An inventory

Some of the values in the key-value store are handled specially:
- formspec: Defines a right-click inventory menu. See "Formspec".
- infotext: Text shown on the screen when the node is pointed at

Example stuff:

local meta = minetest.env:get_meta(pos)
meta:set_string("formspec",
        "invsize[8,9;]"..
        "list[context;main;0,0;8,4;]"..
        "list[current_player;main;0,5;8,4;]")
meta:set_string("infotext", "Chest");
local inv = meta:get_inventory()
inv:set_size("main", 8*4)
print(dump(meta:to_table()))
meta:from_table({
    inventory = {
        main = {[1] = "default:dirt", [2] = "", [3] = "", [4] = "", [5] = "", [6] = "", [7] = "", [8] = "", [9] = "", [10] = "", [11] = "", [12] = "", [13] = "", [14] = "default:cobble", [15] = "", [16] = "", [17] = "", [18] = "", [19] = "", [20] = "default:cobble", [21] = "", [22] = "", [23] = "", [24] = "", [25] = "", [26] = "", [27] = "", [28] = "", [29] = "", [30] = "", [31] = "", [32] = ""}
    },
    fields = {
        formspec = "invsize[8,9;]list[context;main;0,0;8,4;]list[current_player;main;0,5;8,4;]",
        infotext = "Chest"
    }
})

Formspec
--------
Formspec defines a menu. Currently not much else than inventories are
supported. It is a string, with a somewhat strange format.

Spaces and newlines can be inserted between the blocks, as is used in the
examples.

Examples:
- Chest:
    invsize[8,9;]
    list[context;main;0,0;8,4;]
    list[current_player;main;0,5;8,4;]
- Furnace:
    invsize[8,9;]
    list[context;fuel;2,3;1,1;]
    list[context;src;2,1;1,1;]
    list[context;dst;5,1;2,2;]
    list[current_player;main;0,5;8,4;]
- Minecraft-like player inventory
    invsize[8,7.5;]
    image[1,0.6;1,2;player.png]
    list[current_player;main;0,3.5;8,4;]
    list[current_player;craft;3,0;3,3;]
    list[current_player;craftpreview;7,1;1,1;]

Elements:

size[<W>,<H>]
^ Define the size of the menu in inventory slots
^ deprecated: invsize[<W>,<H>;]

list[<inventory location>;<list name>;<X>,<Y>;<W>,<H>;]
list[<inventory location>;<list name>;<X>,<Y>;<W>,<H>;<starting item index>]
^ Show an inventory list

image[<X>,<Y>;<W>,<H>;<texture name>]
^ Show an image
^ Position and size units are inventory slots

item_image[<X>,<Y>;<W>,<H>;<item name>]
^ Show an inventory image of registered item/node
^ Position and size units are inventory slots

background[<X>,<Y>;<W>,<H>;<texture name>]
^ Use a background. Inventory rectangles are not drawn then.
^ Position and size units are inventory slots
^ Example for formspec 8x4 in 16x resolution: image shall be sized 8*16px x 4*16px

field[<X>,<Y>;<W>,<H>;<name>;<label>;<default>]
^ Textual field; will be sent to server when a button is clicked
^ x and y position the field relative to the top left of the menu
^ w and h are the size of the field
^ fields are a set height, but will be vertically centred on h
^ Position and size units are inventory slots
^ name is the name of the field as returned in fields to on_receive_fields
^ label, if not blank, will be text printed on the top left above the field
^ default is the default value of the field
  ^ default may contain variable references such as '${text}' which
    will fill the value from the metadata value 'text'
	^ Note: no extra text or more than a single variable is supported ATM.

field[<name>;<label>;<default>]
^ as above but without position/size units
^ special field for creating simple forms, such as sign text input
^ must be used without a size[] element
^ a 'Proceed' button will be added automatically

textarea[<X>,<Y>;<W>,<H>;<name>;<label>;<default>]
^ same as fields above, but with multi-line input

label[<X>,<Y>;<label>]
^ x and y work as per field
^ label is the text on the label
^ Position and size units are inventory slots

button[<X>,<Y>;<W>,<H>;<name>;<label>]
^ Clickable button. When clicked, fields will be sent.
^ x, y and name work as per field
^ w and h are the size of the button
^ label is the text on the button
^ Position and size units are inventory slots

image_button[<X>,<Y>;<W>,<H>;<texture name>;<name>;<label>]
^ x, y, w, h, and name work as per button
^ image is the filename of an image
^ Position and size units are inventory slots

item_image_button[<X>,<Y>;<W>,<H>;<item name>;<name>;<label&
		const std::string &data, bool is_from_cache, Client *client)
{
	const char *cached_or_received = is_from_cache ? "cached" : "received";
	const char *cached_or_received_uc = is_from_cache ? "Cached" : "Received";
	std::string sha1_hex = hex_encode(sha1);

	// Compute actual checksum of data
	std::string data_sha1;
	{
		SHA1 data_sha1_calculator;
		data_sha1_calculator.addBytes(data.c_str(), data.size());
		unsigned char *data_tmpdigest = data_sha1_calculator.getDigest();
		data_sha1.assign((char*) data_tmpdigest, 20);
		free(data_tmpdigest);
	}

	// Check that received file matches announced checksum
	if (data_sha1 != sha1) {
		std::string data_sha1_hex = hex_encode(data_sha1);
		infostream << "Client: "
			<< cached_or_received_uc << " media file "
			<< sha1_hex << " \"" << name << "\" "
			<< "mismatches actual checksum " << data_sha1_hex
			<< std::endl;
		return false;
	}

	// Checksum is ok, try loading the file
	bool success = loadMedia(client, data, name);
	if (!success) {
		infostream << "Client: "
			<< "Failed to load " << cached_or_received << " media: "
			<< sha1_hex << " \"" << name << "\""
			<< std::endl;
		return false;
	}

	verbosestream << "Client: "
		<< "Loaded " << cached_or_received << " media: "
		<< sha1_hex << " \"" << name << "\""
		<< std::endl;

	// Update cache (unless we just loaded the file from the cache)
	if (!is_from_cache && m_write_to_cache)
		m_media_cache.update(sha1_hex, data);

	return true;
}

/*
	Minetest Hashset File Format

	All values are stored in big-endian byte order.
	[u32] signature: 'MTHS'
	[u16] version: 1
	For each hash in set:
		[u8*20] SHA1 hash

	Version changes:
	1 - Initial version
*/

std::string ClientMediaDownloader::serializeRequiredHashSet()
{
	std::ostringstream os(std::ios::binary);

	writeU32(os, MTHASHSET_FILE_SIGNATURE); // signature
	writeU16(os, 1);                        // version

	// Write list of hashes of files that have not been
	// received (found in cache) yet
	for (const auto &it : m_files) {
		if (!it.second->received) {
			FATAL_ERROR_IF(it.second->sha1.size() != 20, "Invalid SHA1 size");
			os << it.second->sha1;
		}
	}

	return os.str();
}

void ClientMediaDownloader::deSerializeHashSet
		throw SerializationError(
				"ClientMediaDownloader::deSerializeHashSet: "
				"invalid hash set file signature");
	}

	u16 version = readU16(&data_cstr[4]);
	if (version != 1) {
		throw SerializationError(
				"ClientMediaDownloader::deSerializeHashSet: "
				"unsupported hash set file version");
	}

	for (u32 pos = 6; pos < data.size(); pos += 20) {
		result.insert(data.substr(pos, 20));
	}
}

/*
	SingleMediaDownloader
*/

SingleMediaDownloader::SingleMediaDownloader(bool write_to_cache):
	m_httpfetch_caller(HTTPFETCH_DISCARD)
{
	m_write_to_cache = write_to_cache;
}

SingleMediaDownloader::~SingleMediaDownloader()
{
	if (m_httpfetch_caller != HTTPFETCH_DISCARD)
		httpfetch_caller_free(m_httpfetch_caller);
}

bool SingleMediaDownloader::loadMedia(Client *client, const std::string &data,
		const std::string &name)
{
	return client->loadMedia(data, name, true);
}

void SingleMediaDownloader::addFile(const std::string &name, const std::string &sha1)
{
	assert(m_stage == STAGE_INIT); // pre-condition

	assert(!name.empty());
	assert(sha1.size() == 20);

	FATAL_ERROR_IF(!m_file_name.empty(), "Cannot add a second file");
	m_file_name = name;
	m_file_sha1 = sha1;
}

void SingleMediaDownloader::addRemoteServer(const std::string &baseurl)
{
	assert(m_stage == STAGE_INIT); // pre-condition

	if (g_settings->getBool("enable_remote_media_server"))
		m_remotes.emplace_back(baseurl);
}

void SingleMediaDownloader::step(Client *client)
{
	if (m_stage == STAGE_INIT) {
		m_stage = STAGE_CACHE_CHECKED;
		initialStep(client);
	}

	// Remote media: check for completion of fetches
	if (m_httpfetch_caller != HTTPFETCH_DISCARD) {
		HTTPFetchResult fetch_result;
		while (httpfetch_async_get(m_httpfetch_caller, fetch_result)) {
			remoteMediaReceived(fetch_result, client);
		}
	}
}

bool SingleMediaDownloader::conventionalTransferDone(const std::string &name,
		const std::string &data, Client *client)
{
	if (name != m_file_name)
		return false;

	// Mark file as received unconditionally and try to load it
	m_stage = STAGE_DONE;
	checkAndLoad(name, m_file_sha1, data, false, client);
	return true;
}

void SingleMediaDownloader::initialStep(Client *client)
{
	if (tryLoadFromCache(m_file_name, m_file_sha1, client))
		m_stage = STAGE_DONE;
	if (isDone())
		return;

	createCacheDirs();

	// If the server reported no remote servers, immediately fall back to
	// conventional transfer.
	if (!USE_CURL || m_remotes.empty()) {
		startConventionalTransfer(client);
	} else {
		// Otherwise start by requesting the file from the first remote media server
		m_httpfetch_caller = httpfetch_caller_alloc();
		m_current_remote = 0;
		startRemoteMediaTransfer();
	}
}

void SingleMediaDownloader::remoteMediaReceived(
		const HTTPFetchResult &fetch_result, Client *client)
{
	sanity_check(!isDone());
	sanity_check(m_current_remote >= 0);

	// If fetch succeeded, try to load it
	if (fetch_result.succeeded) {
		bool success = checkAndLoad(m_file_name, m_file_sha1,
				fetch_result.data, false, client);
		if (success) {
			m_stage = STAGE_DONE;
			return;
		}
	}

	// Otherwise try the next remote server or fall back to conventional transfer
	m_current_remote++;
	if (m_current_remote >= (int)m_remotes.size()) {
		infostream << "Client: Failed to remote-fetch \"" << m_file_name
				<< "\". Requesting it the usual way." << std::endl;
		m_current_remote = -1;
		startConventionalTransfer(client);
	} else {
		startRemoteMediaTransfer();
	}
}

void SingleMediaDownloader::startRemoteMediaTransfer()
{
	std::string url = m_remotes.at(m_current_remote) + hex_encode(m_file_sha1);
	verbosestream << "Client: Requesting remote media file "
		<< "\"" << m_file_name << "\" " << "\"" << url << "\"" << std::endl;

	HTTPFetchRequest fetch_request;
	fetch_request.url = url;
	fetch_request.caller = m_httpfetch_caller;
	fetch_request.request_id = m_httpfetch_next_id;
	fetch_request.timeout = g_settings->getS32("curl_file_download_timeout");
	httpfetch_async(fetch_request);

	m_httpfetch_next_id++;
}

void SingleMediaDownloader::startConventionalTransfer(Client *client)
{
	std::vector<std::string> requests;
	requests.emplace_back(m_file_name);
	client->request_media(requests);
}
ely places on ground when the player places the item. Server will always update actual result to client in a short moment. on_place = func(itemstack, placer, pointed_thing), ^ Shall place item and return the leftover itemstack ^ default: minetest.item_place on_drop = func(itemstack, dropper, pos), ^ Shall drop item and return the leftover itemstack ^ default: minetest.item_drop on_use = func(itemstack, user, pointed_thing), ^ default: nil ^ Function must return either nil if no item shall be removed from inventory, or an itemstack to replace the original itemstack. eg. itemstack:take_item(); return itemstack ^ Otherwise, the function is free to do what it wants. ^ The default functions handle regular use cases. } Tile definition: - "image.png" - {name="image.png", animation={Tile Animation definition}} - {name="image.png", backface_culling=bool} ^ backface culling only supported in special tiles - deprecated still supported field names: - image -> name Tile animation definition: - {type="vertical_frames", aspect_w=16, aspect_h=16, length=3.0} Node definition (register_node) { <all fields allowed in item definitions>, drawtype = "normal", -- See "Node drawtypes" visual_scale = 1.0, tiles = {tile definition 1, def2, def3, def4, def5, def6}, ^ Textures of node; +Y, -Y, +X, -X, +Z, -Z (old field name: tile_images) ^ List can be shortened to needed length special_tiles = {tile definition 1, Tile definition 2}, ^ Special textures of node; used rarely (old field name: special_materials) ^ List can be shortened to needed length alpha = 255, post_effect_color = {a=0, r=0, g=0, b=0}, -- If player is inside node paramtype = "none", -- See "Nodes" paramtype2 = "none", -- See "Nodes" is_ground_content = false, -- Currently not used for anything sunlight_propagates = false, -- If true, sunlight will go infinitely through this walkable = true, -- If true, objects collide with node pointable = true, -- If true, can be pointed at diggable = true, -- If false, can never be dug climbable = false, -- If true, can be climbed on (ladder) buildable_to = false, -- If true, placed nodes can replace this node drop = "", -- alternatively drop = { max_items = ..., items = { ... } } liquidtype = "none", -- "none"/"source"/"flowing" liquid_alternative_flowing = "", -- Flowing version of source liquid liquid_alternative_source = "", -- Source version of flowing liquid liquid_viscosity = 0, -- Higher viscosity = slower flow (max. 7) liquid_renewable = true, -- Can new liquid source be created by placing two or more sources nearly? light_source = 0, -- Amount of light emitted by node damage_per_second = 0, -- If player is inside node, this damage is caused node_box = {type="regular"}, -- See "Node boxes" selection_box = {type="regular"}, -- See "Node boxes" legacy_facedir_simple = false, -- Support maps made in and before January 2012 legacy_wallmounted = false, -- Support maps made in and before January 2012 sounds = { footstep = <SimpleSoundSpec>, dig = <SimpleSoundSpec>, -- "__group" = group-based sound (default) dug = <SimpleSoundSpec>, }, on_construct = func(pos), ^ Node constructor; always called after adding node ^ Can set up metadata and stuff like that ^ default: nil on_destruct = func(pos), ^ Node destructor; always called before removing node ^ default: nil after_destruct = func(pos, oldnode), ^ Node destructor; always called after removing node ^ default: nil after_place_node = func(pos, placer, itemstack), ^ Called after constructing node when node was placed using minetest.item_place_node / minetest.env:place_node ^ If return true no item is taken from itemstack ^ default: nil after_dig_node = func(pos, oldnode, oldmetadata, digger), ^ oldmetadata is in table format ^ Called after destructing node when node was dug using minetest.node_dig / minetest.env:dig_node ^ default: nil can_dig = function(pos,player) ^ returns true if node can be dug, or false if not ^ default: nil on_punch = func(pos, node, puncher), ^ default: minetest.node_punch ^ By default: does nothing on_rightclick = func(pos, node, clicker, itemstack), ^ default: nil ^ if defined, itemstack will hold clicker's wielded item Shall return the leftover itemstack on_dig = func(pos, node, digger), ^ default: minetest.node_dig ^ By default: checks privileges, wears out tool and removes node on_timer = function(pos,elapsed), ^ default: nil ^ called by NodeTimers, see EnvRef and NodeTimerRef ^ elapsed is the total time passed since the timer was started ^ return true to run the timer for another cycle with the same timeout value on_receive_fields = func(pos, formname, fields, sender), ^ fields = {name1 = value1, name2 = value2, ...} ^ Called when an UI form (eg. sign text input) returns data ^ default: nil allow_metadata_inventory_move = func(pos, from_list, from_index, to_list, to_index, count, player), ^ Called when a player wants to move items inside the inventory ^ Return value: number of items allowed to move allow_metadata_inventory_put = func(pos, listname, index, stack, player), ^ Called when a player wants to put something into the inventory ^ Return value: number of items allowed to put ^ Return value: -1: Allow and don't modify item count in inventory allow_metadata_inventory_take = func(pos, listname, index, stack, player), ^ Called when a player wants to take something out of the inventory ^ Return value: number of items allowed to take ^ Return value: -1: Allow and don't modify item count in inventory on_metadata_inventory_move = func(pos, from_list, from_index, to_list, to_index, count, player), on_metadata_inventory_put = func(pos, listname, index, stack, player), on_metadata_inventory_take = func(pos, listname, index, stack, player), ^ Called after the actual action has happened, according to what was allowed. ^ No return value on_blast = func(pos, intensity), ^ intensity: 1.0 = mid range of regular TNT ^ If defined, called when an explosion touches the node, instead of removing the node } Recipe for register_craft: (shaped) { output = 'default:pick_stone', recipe = { {'default:cobble', 'default:cobble', 'default:cobble'}, {'', 'default:stick', ''}, {'', 'default:stick', ''}, -- Also groups; eg. 'group:crumbly' }, replacements = <optional list of item pairs, replace one input item with another item on crafting> } Recipe for register_craft (shapeless) { type = "shapeless", output = 'mushrooms:mushroom_stew', recipe = { "mushrooms:bowl", "mushrooms:mushroom_brown", "mushrooms:mushroom_red", }, replacements = <optional list of item pairs, replace one input item with another item on crafting> } Recipe for register_craft (tool repair) { type = "toolrepair", additional_wear = -0.02, } Recipe for register_craft (cooking) { type = "cooking", output = "default:glass", recipe = "default:sand", cooktime = 3, } Recipe for register_craft (furnace fuel) { type = "fuel", recipe = "default:leaves", burntime = 1, } Chatcommand definition (register_chatcommand) { params = "<name> <privilege>", -- short parameter description description = "Remove privilege from player", -- full description privs = {privs=true}, -- require the "privs" privilege to run func = function(name, param), -- called when command is run } Detached inventory callbacks { allow_move = func(inv, from_list, from_index, to_list, to_index, count, player), ^ Called when a player wants to move items inside the inventory ^ Return value: number of items allowed to move allow_put = func(inv, listname, index, stack, player), ^ Called when a player wants to put something into the inventory ^ Return value: number of items allowed to put ^ Return value: -1: Allow and don't modify item count in inventory allow_take = func(inv, listname, index, stack, player), ^ Called when a player wants to take something out of the inventory ^ Return value: number of items allowed to take ^ Return value: -1: Allow and don't modify item count in inventory on_move = func(inv, from_list, from_index, to_list, to_index, count, player), on_put = func(inv, listname, index, stack, player), on_take = func(inv, listname, index, stack, player), ^ Called after the actual action has happened, according to what was allowed. ^ No return value }