aboutsummaryrefslogtreecommitdiff
path: root/advtrains
diff options
context:
space:
mode:
Diffstat (limited to 'advtrains')
-rw-r--r--advtrains/advtrains.zipbin1488724 -> 0 bytes
-rw-r--r--advtrains/advtrains/api_doc.txt157
-rw-r--r--advtrains/advtrains/atc.lua312
-rw-r--r--advtrains/advtrains/couple.lua180
-rw-r--r--advtrains/advtrains/debugitems.lua28
-rw-r--r--advtrains/advtrains/depends.txt2
-rw-r--r--advtrains/advtrains/helpers.lua255
-rw-r--r--advtrains/advtrains/init.lua329
-rw-r--r--advtrains/advtrains/locale/de.txt50
-rw-r--r--advtrains/advtrains/misc_nodes.lua67
-rw-r--r--advtrains/advtrains/nodedb.lua285
-rw-r--r--advtrains/advtrains/settingtypes.txt3
-rw-r--r--advtrains/advtrains/signals.lua229
-rw-r--r--advtrains/advtrains/textures/advtrains_couple.pngbin265 -> 0 bytes
-rw-r--r--advtrains/advtrains/textures/advtrains_discouple.pngbin307 -> 0 bytes
-rw-r--r--advtrains/advtrains/trackdb_legacy.lua27
-rw-r--r--advtrains/advtrains/trackplacer.lua305
-rw-r--r--advtrains/advtrains/tracks.lua734
-rw-r--r--advtrains/advtrains/trainhud.lua125
-rw-r--r--advtrains/advtrains/trainlogic.lua977
-rw-r--r--advtrains/advtrains/wagons.lua900
-rw-r--r--advtrains/advtrains_itrainmap/depends.txt1
-rw-r--r--advtrains/advtrains_itrainmap/init.lua149
-rw-r--r--advtrains/advtrains_itrainmap/textures/itm_example.pngbin154460 -> 0 bytes
-rw-r--r--advtrains/advtrains_luaautomation/README.txt165
-rw-r--r--advtrains/advtrains_luaautomation/active_common.lua134
-rw-r--r--advtrains/advtrains_luaautomation/atc_rail.lua120
-rw-r--r--advtrains/advtrains_luaautomation/chatcmds.lua84
-rw-r--r--advtrains/advtrains_luaautomation/depends.txt2
-rw-r--r--advtrains/advtrains_luaautomation/environment.lua270
-rw-r--r--advtrains/advtrains_luaautomation/init.lua110
-rw-r--r--advtrains/advtrains_luaautomation/interrupt.lua46
-rw-r--r--advtrains/advtrains_luaautomation/operation_panel.lua23
-rw-r--r--advtrains/advtrains_luaautomation/p_display.lua0
-rw-r--r--advtrains/advtrains_luaautomation/passive.lua39
-rw-r--r--advtrains/advtrains_luaautomation/passive_api.txt23
-rw-r--r--advtrains/advtrains_luaautomation/pcnaming.lua74
-rw-r--r--advtrains/advtrains_luaautomation/textures/atlatc_oppanel.pngbin631 -> 0 bytes
-rw-r--r--advtrains/advtrains_luaautomation/textures/atlatc_pcnaming.pngbin329 -> 0 bytes
-rw-r--r--advtrains/advtrains_train_industrial/depends.txt2
-rw-r--r--advtrains/advtrains_train_industrial/init.lua84
-rw-r--r--advtrains/advtrains_train_industrial/locale/de.txt5
-rw-r--r--advtrains/advtrains_train_industrial/models/advtrains_engine_industrial.b3dbin143659 -> 0 bytes
-rw-r--r--advtrains/advtrains_train_industrial/models/advtrains_wagon_tank.b3dbin223975 -> 0 bytes
-rw-r--r--advtrains/advtrains_train_industrial/models/advtrains_wagon_wood.b3dbin193975 -> 0 bytes
-rw-r--r--advtrains/advtrains_train_industrial/textures/advtrains_engine_industrial.pngbin59019 -> 0 bytes
-rw-r--r--advtrains/advtrains_train_industrial/textures/advtrains_engine_industrial_inv.pngbin381 -> 0 bytes
-rw-r--r--advtrains/advtrains_train_industrial/textures/advtrains_wagon_tank.pngbin8975 -> 0 bytes
-rw-r--r--advtrains/advtrains_train_industrial/textures/advtrains_wagon_tank_inv.pngbin408 -> 0 bytes
-rw-r--r--advtrains/advtrains_train_industrial/textures/advtrains_wagon_wood.pngbin5974 -> 0 bytes
-rw-r--r--advtrains/advtrains_train_industrial/textures/advtrains_wagon_wood_inv.pngbin316 -> 0 bytes
-rw-r--r--advtrains/advtrains_train_japan/depends.txt2
-rw-r--r--advtrains/advtrains_train_japan/init.lua144
-rw-r--r--advtrains/advtrains_train_japan/locale/de.txt4
-rw-r--r--advtrains/advtrains_train_japan/models/advtrains_engine_japan.b3dbin437635 -> 0 bytes
-rw-r--r--advtrains/advtrains_train_japan/models/advtrains_wagon_japan.b3dbin554284 -> 0 bytes
-rw-r--r--advtrains/advtrains_train_japan/textures/advtrains_engine_japan.pngbin27935 -> 0 bytes
-rw-r--r--advtrains/advtrains_train_japan/textures/advtrains_engine_japan_inv.pngbin434 -> 0 bytes
-rw-r--r--advtrains/advtrains_train_japan/textures/advtrains_wagon_japan.pngbin54396 -> 0 bytes
-rw-r--r--advtrains/advtrains_train_japan/textures/advtrains_wagon_japan_inv.pngbin400 -> 0 bytes
-rw-r--r--advtrains/advtrains_train_steam/depends.txt2
-rw-r--r--advtrains/advtrains_train_steam/init.lua242
-rw-r--r--advtrains/advtrains_train_steam/locale/de.txt6
-rw-r--r--advtrains/advtrains_train_steam/models/advtrains_detailed_steam_engine.b3dbin468002 -> 0 bytes
-rw-r--r--advtrains/advtrains_train_steam/models/advtrains_engine_steam.b3dbin437126 -> 0 bytes
-rw-r--r--advtrains/advtrains_train_steam/models/advtrains_passenger_wagon.b3dbin341965 -> 0 bytes
-rw-r--r--advtrains/advtrains_train_steam/models/advtrains_wagon.b3dbin107352 -> 0 bytes
-rw-r--r--advtrains/advtrains_train_steam/textures/advtrains_detailed_engine_steam_inv.pngbin462 -> 0 bytes
-rw-r--r--advtrains/advtrains_train_steam/textures/advtrains_detailed_steam_engine.pngbin61988 -> 0 bytes
-rw-r--r--advtrains/advtrains_train_steam/textures/advtrains_engine_steam.pngbin31915 -> 0 bytes
-rw-r--r--advtrains/advtrains_train_steam/textures/advtrains_engine_steam_inv.pngbin469 -> 0 bytes
-rw-r--r--advtrains/advtrains_train_steam/textures/advtrains_wagon.pngbin42023 -> 0 bytes
-rw-r--r--advtrains/advtrains_train_steam/textures/advtrains_wagon_box.pngbin22503 -> 0 bytes
-rw-r--r--advtrains/advtrains_train_steam/textures/advtrains_wagon_box_inv.pngbin347 -> 0 bytes
-rw-r--r--advtrains/advtrains_train_steam/textures/advtrains_wagon_inv.pngbin709 -> 0 bytes
-rw-r--r--advtrains/advtrains_train_subway/depends.txt2
-rw-r--r--advtrains/advtrains_train_subway/init.lua90
-rw-r--r--advtrains/advtrains_train_subway/locale/de.txt2
-rw-r--r--advtrains/advtrains_train_subway/models/advtrains_subway_wagon.b3dbin460013 -> 0 bytes
-rw-r--r--advtrains/advtrains_train_subway/textures/advtrains_subway_wagon.pngbin3618 -> 0 bytes
-rw-r--r--advtrains/advtrains_train_subway/textures/advtrains_subway_wagon_inv.pngbin900 -> 0 bytes
-rw-r--r--advtrains/api_doc.txt222
-rw-r--r--advtrains/atc.lua384
-rw-r--r--advtrains/atc_command.txt83
-rwxr-xr-xadvtrains/copytool.lua241
-rw-r--r--advtrains/couple.lua551
-rw-r--r--advtrains/craft_items.lua (renamed from advtrains/advtrains/craft_items.lua)11
-rw-r--r--advtrains/crafting.lua (renamed from advtrains/advtrains/crafting.lua)69
-rw-r--r--advtrains/debugitems.lua139
-rw-r--r--advtrains/debugringbuffer.lua47
-rw-r--r--advtrains/description.txt (renamed from advtrains/advtrains/description.txt)4
-rw-r--r--advtrains/doc/advtrains_speed_lessp.3advtrains.md15
-rw-r--r--advtrains/doc/advtrains_speed_set_restriction.3advtrains.md18
-rw-r--r--advtrains/doc/signal_aspect.7advtrains.md24
-rw-r--r--advtrains/formspec.lua114
-rw-r--r--advtrains/helpers.lua637
-rw-r--r--advtrains/init.lua819
-rw-r--r--advtrains/license.txt142
-rw-r--r--advtrains/license_media.txt68
-rw-r--r--advtrains/locale/README.md70
-rw-r--r--advtrains/locale/advtrains.de.po920
-rw-r--r--advtrains/locale/advtrains.fr.po1020
-rw-r--r--advtrains/locale/advtrains.pot625
-rw-r--r--advtrains/locale/advtrains.zh_CN.po861
-rw-r--r--advtrains/locale/advtrains.zh_TW.po860
-rw-r--r--advtrains/log.lua17
-rw-r--r--advtrains/lzb.lua285
-rw-r--r--advtrains/manual.pdfbin801491 -> 0 bytes
-rw-r--r--advtrains/misc_nodes.lua126
-rw-r--r--advtrains/mod.conf7
-rw-r--r--advtrains/models/advtrains_across.obj (renamed from advtrains/advtrains/models/advtrains_across.obj)0
-rw-r--r--advtrains/models/advtrains_dtrack_bumper_st.b3d (renamed from advtrains/advtrains/models/advtrains_dtrack_bumper_st.b3d)bin32927 -> 32927 bytes
-rw-r--r--advtrains/models/advtrains_dtrack_bumper_st_30.b3d (renamed from advtrains/advtrains/models/advtrains_dtrack_bumper_st_30.b3d)bin48546 -> 48546 bytes
-rw-r--r--advtrains/models/advtrains_dtrack_bumper_st_45.b3d (renamed from advtrains/advtrains/models/advtrains_dtrack_bumper_st_45.b3d)bin32926 -> 32926 bytes
-rw-r--r--advtrains/models/advtrains_dtrack_bumper_st_60.b3d (renamed from advtrains/advtrains/models/advtrains_dtrack_bumper_st_60.b3d)bin48546 -> 48546 bytes
-rw-r--r--advtrains/models/advtrains_dtrack_cr.b3d (renamed from advtrains/advtrains/models/advtrains_dtrack_cr.b3d)bin28040 -> 28040 bytes
-rw-r--r--advtrains/models/advtrains_dtrack_cr_30.b3d (renamed from advtrains/advtrains/models/advtrains_dtrack_cr_30.b3d)bin28043 -> 28043 bytes
-rw-r--r--advtrains/models/advtrains_dtrack_cr_45.b3d (renamed from advtrains/advtrains/models/advtrains_dtrack_cr_45.b3d)bin34483 -> 34483 bytes
-rw-r--r--advtrains/models/advtrains_dtrack_cr_60.b3d (renamed from advtrains/advtrains/models/advtrains_dtrack_cr_60.b3d)bin34483 -> 34483 bytes
-rw-r--r--advtrains/models/advtrains_dtrack_st.b3d (renamed from advtrains/advtrains/models/advtrains_dtrack_st.b3d)bin10712 -> 10712 bytes
-rw-r--r--advtrains/models/advtrains_dtrack_st_30.b3d (renamed from advtrains/advtrains/models/advtrains_dtrack_st_30.b3d)bin20043 -> 20043 bytes
-rw-r--r--advtrains/models/advtrains_dtrack_st_45.b3d (renamed from advtrains/advtrains/models/advtrains_dtrack_st_45.b3d)bin12235 -> 12235 bytes
-rw-r--r--advtrains/models/advtrains_dtrack_st_60.b3d (renamed from advtrains/advtrains/models/advtrains_dtrack_st_60.b3d)bin20043 -> 20043 bytes
-rw-r--r--advtrains/models/advtrains_dtrack_swlcr.b3d (renamed from advtrains/advtrains/models/advtrains_dtrack_swlcr.b3d)bin36203 -> 36203 bytes
-rw-r--r--advtrains/models/advtrains_dtrack_swlcr_30.b3d (renamed from advtrains/advtrains/models/advtrains_dtrack_swlcr_30.b3d)bin39958 -> 39958 bytes
-rw-r--r--advtrains/models/advtrains_dtrack_swlcr_45.b3d (renamed from advtrains/advtrains/models/advtrains_dtrack_swlcr_45.b3d)bin41302 -> 41302 bytes
-rw-r--r--advtrains/models/advtrains_dtrack_swlcr_60.b3d (renamed from advtrains/advtrains/models/advtrains_dtrack_swlcr_60.b3d)bin46270 -> 46270 bytes
-rw-r--r--advtrains/models/advtrains_dtrack_swlst.b3d (renamed from advtrains/advtrains/models/advtrains_dtrack_swlst.b3d)bin36203 -> 36203 bytes
-rw-r--r--advtrains/models/advtrains_dtrack_swlst_30.b3d (renamed from advtrains/advtrains/models/advtrains_dtrack_swlst_30.b3d)bin39958 -> 39958 bytes
-rw-r--r--advtrains/models/advtrains_dtrack_swlst_45.b3d (renamed from advtrains/advtrains/models/advtrains_dtrack_swlst_45.b3d)bin41302 -> 41302 bytes
-rw-r--r--advtrains/models/advtrains_dtrack_swlst_60.b3d (renamed from advtrains/advtrains/models/advtrains_dtrack_swlst_60.b3d)bin46270 -> 46270 bytes
-rw-r--r--advtrains/models/advtrains_dtrack_swrcr.b3d (renamed from advtrains/advtrains/models/advtrains_dtrack_swrcr.b3d)bin36203 -> 36203 bytes
-rw-r--r--advtrains/models/advtrains_dtrack_swrcr_30.b3d (renamed from advtrains/advtrains/models/advtrains_dtrack_swrcr_30.b3d)bin46270 -> 46270 bytes
-rw-r--r--advtrains/models/advtrains_dtrack_swrcr_45.b3d (renamed from advtrains/advtrains/models/advtrains_dtrack_swrcr_45.b3d)bin41302 -> 41302 bytes
-rw-r--r--advtrains/models/advtrains_dtrack_swrcr_60.b3d (renamed from advtrains/advtrains/models/advtrains_dtrack_swrcr_60.b3d)bin39958 -> 39958 bytes
-rw-r--r--advtrains/models/advtrains_dtrack_swrst.b3d (renamed from advtrains/advtrains/models/advtrains_dtrack_swrst.b3d)bin36203 -> 36203 bytes
-rw-r--r--advtrains/models/advtrains_dtrack_swrst_30.b3d (renamed from advtrains/advtrains/models/advtrains_dtrack_swrst_30.b3d)bin46270 -> 46270 bytes
-rw-r--r--advtrains/models/advtrains_dtrack_swrst_45.b3d (renamed from advtrains/advtrains/models/advtrains_dtrack_swrst_45.b3d)bin41302 -> 41302 bytes
-rw-r--r--advtrains/models/advtrains_dtrack_swrst_60.b3d (renamed from advtrains/advtrains/models/advtrains_dtrack_swrst_60.b3d)bin39958 -> 39958 bytes
-rw-r--r--advtrains/models/advtrains_dtrack_vst1.obj (renamed from advtrains/advtrains/models/advtrains_dtrack_vst1.obj)0
-rw-r--r--advtrains/models/advtrains_dtrack_vst1_45.obj (renamed from advtrains/advtrains/models/advtrains_dtrack_vst1_45.obj)0
-rw-r--r--advtrains/models/advtrains_dtrack_vst2.obj (renamed from advtrains/advtrains/models/advtrains_dtrack_vst2.obj)0
-rw-r--r--advtrains/models/advtrains_dtrack_vst2_45.obj (renamed from advtrains/advtrains/models/advtrains_dtrack_vst2_45.obj)0
-rw-r--r--advtrains/models/advtrains_dtrack_vst31.obj (renamed from advtrains/advtrains/models/advtrains_dtrack_vst31.obj)0
-rw-r--r--advtrains/models/advtrains_dtrack_vst32.obj (renamed from advtrains/advtrains/models/advtrains_dtrack_vst32.obj)0
-rw-r--r--advtrains/models/advtrains_dtrack_vst33.obj (renamed from advtrains/advtrains/models/advtrains_dtrack_vst33.obj)0
-rw-r--r--advtrains/models/advtrains_modernwagon.b3d (renamed from advtrains/advtrains/models/advtrains_modernwagon.b3d)bin172028 -> 172028 bytes
-rw-r--r--advtrains/models/advtrains_platform_diag.b3dbin0 -> 1970 bytes
-rw-r--r--advtrains/models/advtrains_platform_diag_low.b3dbin0 -> 1982 bytes
-rw-r--r--advtrains/models/advtrains_retrosignal_off.b3d (renamed from advtrains/advtrains/models/advtrains_retrosignal_off.b3d)bin13093 -> 13093 bytes
-rw-r--r--advtrains/models/advtrains_retrosignal_off_30.b3d (renamed from advtrains/advtrains/models/advtrains_retrosignal_off_30.b3d)bin13093 -> 13093 bytes
-rw-r--r--advtrains/models/advtrains_retrosignal_off_45.b3d (renamed from advtrains/advtrains/models/advtrains_retrosignal_off_45.b3d)bin13093 -> 13093 bytes
-rw-r--r--advtrains/models/advtrains_retrosignal_off_60.b3d (renamed from advtrains/advtrains/models/advtrains_retrosignal_off_60.b3d)bin13093 -> 13093 bytes
-rw-r--r--advtrains/models/advtrains_retrosignal_on.b3d (renamed from advtrains/advtrains/models/advtrains_retrosignal_on.b3d)bin13093 -> 13093 bytes
-rw-r--r--advtrains/models/advtrains_retrosignal_on_30.b3d (renamed from advtrains/advtrains/models/advtrains_retrosignal_on_30.b3d)bin13093 -> 13093 bytes
-rw-r--r--advtrains/models/advtrains_retrosignal_on_45.b3d (renamed from advtrains/advtrains/models/advtrains_retrosignal_on_45.b3d)bin13093 -> 13093 bytes
-rw-r--r--advtrains/models/advtrains_retrosignal_on_60.b3d (renamed from advtrains/advtrains/models/advtrains_retrosignal_on_60.b3d)bin13093 -> 13093 bytes
-rw-r--r--advtrains/models/advtrains_signal.b3d (renamed from advtrains/advtrains/models/advtrains_signal.b3d)bin61544 -> 61544 bytes
-rw-r--r--advtrains/models/advtrains_signal_30.b3d (renamed from advtrains/advtrains/models/advtrains_signal_30.b3d)bin61544 -> 61544 bytes
-rw-r--r--advtrains/models/advtrains_signal_45.b3d (renamed from advtrains/advtrains/models/advtrains_signal_45.b3d)bin61544 -> 61544 bytes
-rw-r--r--advtrains/models/advtrains_signal_60.b3d (renamed from advtrains/advtrains/models/advtrains_signal_60.b3d)bin61544 -> 61544 bytes
-rw-r--r--advtrains/models/advtrains_signal_wall_l.b3d (renamed from advtrains/advtrains/models/advtrains_signal_wall_l.b3d)bin40514 -> 40514 bytes
-rw-r--r--advtrains/models/advtrains_signal_wall_r.b3d (renamed from advtrains/advtrains/models/advtrains_signal_wall_r.b3d)bin40514 -> 40514 bytes
-rw-r--r--advtrains/models/advtrains_signal_wall_t.b3d (renamed from advtrains/advtrains/models/advtrains_signal_wall_t.b3d)bin40514 -> 40514 bytes
-rw-r--r--advtrains/models/advtrains_track_cr.b3d (renamed from advtrains/advtrains/models/advtrains_track_cr.b3d)bin8023 -> 8023 bytes
-rw-r--r--advtrains/models/advtrains_track_st.b3d (renamed from advtrains/advtrains/models/advtrains_track_st.b3d)bin15831 -> 15831 bytes
-rw-r--r--advtrains/models/advtrains_track_st_45.b3d (renamed from advtrains/advtrains/models/advtrains_track_st_45.b3d)bin8935 -> 8935 bytes
-rw-r--r--advtrains/models/trackplane.b3d (renamed from advtrains/advtrains/models/trackplane.b3d)bin262 -> 262 bytes
-rw-r--r--advtrains/modpack.txt0
-rw-r--r--advtrains/nodedb.lua397
-rw-r--r--advtrains/occupation.lua236
-rw-r--r--advtrains/p_mesecon_iface.lua (renamed from advtrains/advtrains_luaautomation/p_mesecon_iface.lua)39
-rw-r--r--advtrains/passive.lua107
-rw-r--r--advtrains/path.lua489
-rw-r--r--advtrains/protection.lua199
-rw-r--r--advtrains/readme.txt25
-rw-r--r--advtrains/screenshot.pngbin445014 -> 0 bytes
-rw-r--r--advtrains/settingtypes.txt70
-rw-r--r--advtrains/signals.lua342
-rw-r--r--advtrains/sounds/advtrains_crossing_bell.oggbin0 -> 24656 bytes
-rw-r--r--advtrains/spec/speed_spec.lua70
-rw-r--r--advtrains/spec/texture_spec.lua19
-rw-r--r--advtrains/spec/wagons_spec.lua40
-rw-r--r--advtrains/speed.lua88
-rw-r--r--advtrains/texture.lua228
-rwxr-xr-x[-rw-r--r--]advtrains/textures/advtrains_across.png (renamed from advtrains/advtrains/textures/advtrains_across.png)bin302 -> 302 bytes
-rwxr-xr-x[-rw-r--r--]advtrains/textures/advtrains_across_anim.png (renamed from advtrains/advtrains/textures/advtrains_across_anim.png)bin524 -> 524 bytes
-rwxr-xr-x[-rw-r--r--]advtrains/textures/advtrains_boiler.png (renamed from advtrains/advtrains/textures/advtrains_boiler.png)bin413 -> 413 bytes
-rwxr-xr-x[-rw-r--r--]advtrains/textures/advtrains_chimney.png (renamed from advtrains/advtrains/textures/advtrains_chimney.png)bin309 -> 309 bytes
-rw-r--r--advtrains/textures/advtrains_copytool.pngbin0 -> 779 bytes
-rwxr-xr-xadvtrains/textures/advtrains_couple.pngbin0 -> 339 bytes
-rw-r--r--advtrains/textures/advtrains_cpl_lock.pngbin0 -> 209 bytes
-rw-r--r--advtrains/textures/advtrains_cpl_unlock.pngbin0 -> 213 bytes
-rwxr-xr-xadvtrains/textures/advtrains_discouple.pngbin0 -> 293 bytes
-rwxr-xr-x[-rw-r--r--]advtrains/textures/advtrains_driver_cab.png (renamed from advtrains/advtrains/textures/advtrains_driver_cab.png)bin352 -> 352 bytes
-rwxr-xr-x[-rw-r--r--]advtrains/textures/advtrains_dtrack_atc_placer.png (renamed from advtrains/advtrains/textures/advtrains_dtrack_atc_placer.png)bin1259 -> 1259 bytes
-rwxr-xr-x[-rw-r--r--]advtrains/textures/advtrains_dtrack_bumper_placer.png (renamed from advtrains/advtrains/textures/advtrains_dtrack_bumper_placer.png)bin2213 -> 2213 bytes
-rwxr-xr-x[-rw-r--r--]advtrains/textures/advtrains_dtrack_detector_placer.png (renamed from advtrains/advtrains/textures/advtrains_dtrack_detector_placer.png)bin1253 -> 1253 bytes
-rwxr-xr-xadvtrains/textures/advtrains_dtrack_load_placer.pngbin0 -> 1248 bytes
-rwxr-xr-x[-rw-r--r--]advtrains/textures/advtrains_dtrack_placer.png (renamed from advtrains/advtrains/textures/advtrains_dtrack_placer.png)bin1097 -> 1097 bytes
-rwxr-xr-x[-rw-r--r--]advtrains/textures/advtrains_dtrack_rail.png (renamed from advtrains/advtrains/textures/advtrains_dtrack_rail.png)bin4582 -> 4582 bytes
-rwxr-xr-x[-rw-r--r--]advtrains/textures/advtrains_dtrack_shared.png (renamed from advtrains/advtrains/textures/advtrains_dtrack_shared.png)bin7141 -> 7141 bytes
-rwxr-xr-x[-rw-r--r--]advtrains/textures/advtrains_dtrack_shared_atc.png (renamed from advtrains/advtrains/textures/advtrains_dtrack_shared_atc.png)bin7215 -> 7215 bytes
-rwxr-xr-x[-rw-r--r--]advtrains/textures/advtrains_dtrack_shared_detector_off.png (renamed from advtrains/advtrains/textures/advtrains_dtrack_shared_detector_off.png)bin7180 -> 7180 bytes
-rwxr-xr-x[-rw-r--r--]advtrains/textures/advtrains_dtrack_shared_detector_on.png (renamed from advtrains/advtrains/textures/advtrains_dtrack_shared_detector_on.png)bin7181 -> 7181 bytes
-rwxr-xr-xadvtrains/textures/advtrains_dtrack_shared_load.pngbin0 -> 7339 bytes
-rwxr-xr-xadvtrains/textures/advtrains_dtrack_shared_unload.pngbin0 -> 7338 bytes
-rwxr-xr-x[-rw-r--r--]advtrains/textures/advtrains_dtrack_slopeplacer.png (renamed from advtrains/advtrains/textures/advtrains_dtrack_slopeplacer.png)bin2415 -> 2415 bytes
-rwxr-xr-xadvtrains/textures/advtrains_dtrack_unload_placer.pngbin0 -> 1260 bytes
-rw-r--r--advtrains/textures/advtrains_hud_arrow.pngbin0 -> 91 bytes
-rw-r--r--advtrains/textures/advtrains_hud_atc.pngbin0 -> 528 bytes
-rw-r--r--advtrains/textures/advtrains_hud_bg.pngbin0 -> 67 bytes
-rw-r--r--advtrains/textures/advtrains_hud_lzb.pngbin0 -> 398 bytes
-rw-r--r--advtrains/textures/advtrains_hud_shunt.pngbin0 -> 476 bytes
-rwxr-xr-x[-rw-r--r--]advtrains/textures/advtrains_platform.png (renamed from advtrains/advtrains/textures/advtrains_platform.png)bin193 -> 193 bytes
-rw-r--r--advtrains/textures/advtrains_platform_diag.pngbin0 -> 93 bytes
-rwxr-xr-x[-rw-r--r--]advtrains/textures/advtrains_retrosignal.png (renamed from advtrains/advtrains/textures/advtrains_retrosignal.png)bin8496 -> 8496 bytes
-rwxr-xr-x[-rw-r--r--]advtrains/textures/advtrains_retrosignal_inv.png (renamed from advtrains/advtrains/textures/advtrains_retrosignal_inv.png)bin2242 -> 2242 bytes
-rwxr-xr-x[-rw-r--r--]advtrains/textures/advtrains_signal_inv.png (renamed from advtrains/advtrains/textures/advtrains_signal_inv.png)bin856 -> 856 bytes
-rwxr-xr-x[-rw-r--r--]advtrains/textures/advtrains_signal_off.png (renamed from advtrains/advtrains/textures/advtrains_signal_off.png)bin5882 -> 5882 bytes
-rwxr-xr-x[-rw-r--r--]advtrains/textures/advtrains_signal_on.png (renamed from advtrains/advtrains/textures/advtrains_signal_on.png)bin5884 -> 5884 bytes
-rwxr-xr-x[-rw-r--r--]advtrains/textures/advtrains_signal_wall_off.png (renamed from advtrains/advtrains/textures/advtrains_signal_wall_off.png)bin3056 -> 3056 bytes
-rwxr-xr-x[-rw-r--r--]advtrains/textures/advtrains_signal_wall_on.png (renamed from advtrains/advtrains/textures/advtrains_signal_wall_on.png)bin3043 -> 3043 bytes
-rwxr-xr-x[-rw-r--r--]advtrains/textures/advtrains_track_cr.png (renamed from advtrains/advtrains/textures/advtrains_track_cr.png)bin33370 -> 33370 bytes
-rwxr-xr-x[-rw-r--r--]advtrains/textures/advtrains_track_cr_45.png (renamed from advtrains/advtrains/textures/advtrains_track_cr_45.png)bin33938 -> 33938 bytes
-rwxr-xr-x[-rw-r--r--]advtrains/textures/advtrains_track_placer.png (renamed from advtrains/advtrains/textures/advtrains_track_placer.png)bin32349 -> 32349 bytes
-rwxr-xr-x[-rw-r--r--]advtrains/textures/advtrains_track_st.png (renamed from advtrains/advtrains/textures/advtrains_track_st.png)bin20405 -> 20405 bytes
-rwxr-xr-x[-rw-r--r--]advtrains/textures/advtrains_track_st_45.png (renamed from advtrains/advtrains/textures/advtrains_track_st_45.png)bin39977 -> 39977 bytes
-rwxr-xr-x[-rw-r--r--]advtrains/textures/advtrains_track_swlcr.png (renamed from advtrains/advtrains/textures/advtrains_track_swlcr.png)bin33378 -> 33378 bytes
-rwxr-xr-x[-rw-r--r--]advtrains/textures/advtrains_track_swlcr_45.png (renamed from advtrains/advtrains/textures/advtrains_track_swlcr_45.png)bin45772 -> 45772 bytes
-rwxr-xr-x[-rw-r--r--]advtrains/textures/advtrains_track_swlst.png (renamed from advtrains/advtrains/textures/advtrains_track_swlst.png)bin32321 -> 32321 bytes
-rwxr-xr-x[-rw-r--r--]advtrains/textures/advtrains_track_swlst_45.png (renamed from advtrains/advtrains/textures/advtrains_track_swlst_45.png)bin46408 -> 46408 bytes
-rwxr-xr-x[-rw-r--r--]advtrains/textures/advtrains_track_swrcr.png (renamed from advtrains/advtrains/textures/advtrains_track_swrcr.png)bin33670 -> 33670 bytes
-rwxr-xr-x[-rw-r--r--]advtrains/textures/advtrains_track_swrcr_45.png (renamed from advtrains/advtrains/textures/advtrains_track_swrcr_45.png)bin46865 -> 46865 bytes
-rwxr-xr-x[-rw-r--r--]advtrains/textures/advtrains_track_swrst.png (renamed from advtrains/advtrains/textures/advtrains_track_swrst.png)bin32654 -> 32654 bytes
-rwxr-xr-x[-rw-r--r--]advtrains/textures/advtrains_track_swrst_45.png (renamed from advtrains/advtrains/textures/advtrains_track_swrst_45.png)bin47636 -> 47636 bytes
-rwxr-xr-x[-rw-r--r--]advtrains/textures/advtrains_trackworker.png (renamed from advtrains/advtrains/textures/advtrains_trackworker.png)bin328 -> 328 bytes
-rw-r--r--advtrains/textures/advtrains_wagon_placeholder.pngbin0 -> 723 bytes
-rw-r--r--advtrains/textures/advtrains_wagon_prop_tool.pngbin0 -> 779 bytes
-rwxr-xr-x[-rw-r--r--]advtrains/textures/advtrains_wheel.png (renamed from advtrains/advtrains/textures/advtrains_wheel.png)bin582 -> 582 bytes
-rwxr-xr-x[-rw-r--r--]advtrains/textures/drwho_screwdriver.png (renamed from advtrains/advtrains/textures/drwho_screwdriver.png)bin328 -> 328 bytes
-rw-r--r--advtrains/track_reg_helper.lua751
-rw-r--r--advtrains/trackplacer.lua374
-rw-r--r--advtrains/tracks.lua275
-rw-r--r--advtrains/trainhud.lua322
-rw-r--r--advtrains/trainlogic.lua1363
-rw-r--r--advtrains/wagonprop_tool.lua47
-rw-r--r--advtrains/wagons.lua1607
248 files changed, 15094 insertions, 7163 deletions
diff --git a/advtrains/advtrains.zip b/advtrains/advtrains.zip
deleted file mode 100644
index a3dab82..0000000
--- a/advtrains/advtrains.zip
+++ /dev/null
Binary files differ
diff --git a/advtrains/advtrains/api_doc.txt b/advtrains/advtrains/api_doc.txt
deleted file mode 100644
index 20f285f..0000000
--- a/advtrains/advtrains/api_doc.txt
+++ /dev/null
@@ -1,157 +0,0 @@
-Advanced Trains [advtrains] API documentation
---------
-To use the API, mods must depend on 'advtrains'.
-All boolean values in definition tables default to 'false' and can be omitted.
-### Wagons
-Wagons are registered using the function
-
-advtrains.register_wagon(name, prototype, description, inventory_image)
-- 'name' is the internal name of the wagon. It is registered inside the 'advtrains:' namespace.
- Example: A wagon with name="engine_tgv" will be registered as "advtrains:engine_tgv".
-- 'prototype' is the lua entity prototype. The regular definition keys for luaentites apply. Additional required and optional properties see below. DO NOT define 'on_step', 'on_activate', 'on_punch', 'on_rightclick' and 'get_staticdata' since these will be overridden. Use 'custom_*' instead.
-- 'description' is the description of the inventory item that is used to place the wagon.
-- 'inventory_image' is the inventory image of said item.
-
-# Wagon prototype properties
-{
- ... all regular luaentity properties (mesh, textures, collisionbox a.s.o)...
- drives_on = {default=true},
- ^- used to define the tracktypes (see below) that wagon can drive on. The tracktype identifiers are given as keys, similar to privileges)
- max_speed = 10,
- ^- optional, default 10: defines the maximum speed this wagon can drive. The maximum speed of a train is determined by the wagon with the lowest max_speed value.
- seats = {
- ^- contains zero or more seat definitions. A seat is a place where a player can be attached when getting on a wagon.
- {
- name="Left front window",
- ^- display name of this seat
- attach_offset={x=0, y=10, z=0},
- ^- this value is passed to 'set_attach'
- view_offset={x=0, y=6, z=0},
- ^- player:set_eye_offset is called with this parameter.
- driving_ctrl_access=false,
- ^- If the seat is a driver stand, and players sitting here should get access to the train's driving control.
- group="default"
- ^- optional. Defines the seat group. See 'seat_groups' below
- },
- },
- seat_groups = {
- ^- optional. If defined, activates advanced seating behavior. See "seating behavior".
- default = {
- name = "Seats"
- ^- name of this seat group, to be shown in get-on menu.
- access_to = {"foo", "bar"}
- ^- List of seat groups you can access from this seat using the menu when sitting inside the train.
- require_doors_open = true
- ^- Only allow getting on and off if doors are open.
- }
- }
- assign_to_seat_group = {"default"},
- ^- optional, like seat_groups. When player right_clicks the wagon, player will be assigned to the first free seat group in the list.
-
- doors={
- ^- optional. If defined, defines door animation frames. Opposite door has to be closed during animation period.
- ^- Remember, advtrains can't handle doors on both sides opened simultaneously.
- open={
- [-1]={frames={x=0, y=20}, time=1}, -- open left doors
- [1]={frames={x=40, y=60}, time=1} -- open right doors
- },
- close={
- [-1]={frames={x=20, y=40}, time=1}, -- close left doors
- [1]={frames={x=60, y=80}, time=1} -- close right doors
- }
- },
- door_entry={ 1.5, -1.5 }
- ^- optional. If defined, defines the locations of the doors on the model as distance from the object center on the path.
- ^- Getting on by walking in then takes effect.
- ^- Positive values mean front, negative ones back. Resulting position is automatically shifted to the right side.
-
- wagon_span=2,
- ^- How far this wagon extends from its base position. Is the half of the wagon length.
- ^- Used to determine in which distance the other wagons have to be positioned. Will require tweaking.
- drops = {"default:steelblock 3"}
- ^- List of itemstrings what to drop when the wagon is destroyed
-
- has_inventory = false
- ^- If this wagon has an inventory. The inventory is saved with the wagon.
- ^- the following settings are ignored if not.
- inventory_list_sizes = {
- box=8*6,
- },
- ^- List of assignments of type list_name=size.
- ^- For every entry, an inventory list is created with the specified size.
- get_inventory_formspec = function(self, player_name)
- return "<a formspec>"
- end,
- ^- Function that should return the formspec to be displayed when <player> requests to open the wagon's inventory
- ^- Use "list[detached:advtrains_wgn_"..self.unique_id..";<list_name>;<X>,<Y>;<W>,<H>;<Start>]" to display a wagon's inventory list.
-
- custom_on_step = function(self, dtime) end
- ^- optional: Execute custom code on every step
- custom_on_activate = function(self, dtime_s) end
- ^- optional: Execute custom code on activate. Staticdata does not need to be saved and restored since all properties written in 'self' are preserved over unloads.
- update_animation = function(self, velocity) end
- ^- optional: Function that is called whenever the train's velocity changes or every 2 seconds. Used to call 'self.object:update_animation()' if needed.
-
-}
-
-# Notes on wagons
-
-- Every wagon has the field 'unique_id' which assigns each wagon a random id.
-- All properties written in the lua entity (self) are saved and restored automatically. Minetest's internal staticdata is only used to save the unique_id of the wagon, which serves as a key in an externally saved table.
-- Assuming Z Axis as the axis parallel to the tracks and Y Axis as the one pointing into the sky, wagon models should be dimensioned in a way that:
- - their origin is centered in X and Z direction
- - their origin lies 0.5 units above the bottom of the model
- - the overall extent in X and Y direction is <=3 units
-- wagon_span is then the distance between the model origin and the Z axis extent.
-
-# Seating behavior
-If the advanced seating behavior is active, clicking on a wagon will immediately get you on that wagon depending on the entries in assign_to_seat_group.
-If all seat groups are full, if the doors are closed or if you are not authorized to enter this seat group(e.g. driver stands), will show a warning.
-On a train, right-clicking the wagon will make you get off the train unless:
-- the doors are closed and it requires open doors.
-- you have access to a seat group specified in access_to (you may enter it and it's not full)
-- you are the owner and can access the wagon preferences
-In case there's no possibility, does nothing.
-In case there are multiple possibilities, will show a form.
-
-If you can't enter or leave a train because the doors are closed, holding the Sneak key while right-clicking bypasses the "doors have to be open" enforcement.
-
-### Tracks
-Most modders will be satisfied with the built-in tracks. If cog railways, maglev trains and mine trains are added, it is necessary to understand the definition of tracks. Although the tracks API is there, explaining it would require more effort than me creating the wanted definitions myself. Contact me if you need to register your own rails using my registration functions.
-
-However, it is still possible to register single rails by understanding the node properties of rails.
-minetest.register_node(nodename, {
- ... usual node definition ...
- groups = {
- advtrains_track_<tracktype>=1
- ^- this group tells that the node is a track
- not_blocking_trains=1,
- ^- this group tells that the node should not block trains although it's walkable.
- },
- connect1 = 0,
- connect2 = 8,
- ^- These values tell the direction (horizontal) the rail ends are pointing to. 0 means +Z, then rotation values increase clockwise. For a translation of directions to positions see helpers.lua.
- rely1=0,
- rely2=0,
- ^- the Y height of the rail end 1/2. A value of >=1 means that the rail end points to the next y layer at rely-1
- railheight=0,
- ^- the height value of this rail that is saved in the path. usually the median of rely1 and rely2.
-
- can_dig=function(pos)
- return not advtrains.get_train_at_pos(pos)
- end,
- after_dig_node=function(pos)
- advtrains.ndb.update(pos)
- end,
- after_place_node=function(pos)
- advtrains.ndb.update(pos)
- end,
- ^- the code in these 3 default minetest API functions is required for advtrains to work, however you can add your own code
-
- advtrains = {
- on_train_enter=function(pos, train_id) end
- ^- called when a train enters the rail
- on_train_leave=function(pos, train_id) end
- ^- called when a train leaves the rail
- }
-}) \ No newline at end of file
diff --git a/advtrains/advtrains/atc.lua b/advtrains/advtrains/atc.lua
deleted file mode 100644
index 5f1f64d..0000000
--- a/advtrains/advtrains/atc.lua
+++ /dev/null
@@ -1,312 +0,0 @@
---atc.lua
---registers and controls the ATC system
-
-local atc={}
--- ATC persistence table. advtrains.atc is created by init.lua when it loads the save file.
-atc.controllers = {}
-function atc.load_data(data)
- local temp = data and data.controllers or {}
- --transcode atc controller data to node hashes: table access times for numbers are far less than for strings
- for pts, data in pairs(temp) do
- if type(pts)=="number" then
- pts=minetest.pos_to_string(minetest.get_position_from_hash(pts))
- end
- atc.controllers[pts] = data
- end
-end
-function atc.save_data()
- return {controllers = atc.controllers}
-end
---contents: {command="...", arrowconn=0-15 where arrow points}
-
---general
-
-function atc.send_command(pos, par_tid)
- local pts=minetest.pos_to_string(pos)
- if atc.controllers[pts] then
- --atprint("Called send_command at "..pts)
- local train_id = par_tid or advtrains.detector.on_node[pts]
- if train_id then
- if advtrains.trains[train_id] then
- --atprint("send_command inside if: "..sid(train_id))
- atc.train_reset_command(train_id)
- local arrowconn=atc.controllers[pts].arrowconn
- local train=advtrains.trains[train_id]
- for index, ppos in pairs(train.path) do
- if vector.equals(advtrains.round_vector_floor_y(ppos), pos) then
- advtrains.trains[train_id].atc_arrow =
- vector.equals(
- advtrains.dirCoordSet(pos, arrowconn),
- advtrains.round_vector_floor_y(train.path[index+train.movedir])
- )
- advtrains.trains[train_id].atc_command=atc.controllers[pts].command
- atprint("Sending ATC Command: ", atc.controllers[pts].command)
- return true
- end
- end
- atwarn("ATC rail at", pos, ": Rail not on train's path! Can't determine arrow direction. Assuming +!")
- advtrains.trains[train_id].atc_arrow=true
- advtrains.trains[train_id].atc_command=atc.controllers[pts].command
- atprint("Sending ATC Command: ", atc.controllers[pts].command)
- else
- atwarn("ATC rail at", pos, ": Sending command failed: The train",train_id,"does not exist. This seems to be a bug.")
- end
- else
- atwarn("ATC rail at", pos, ": Sending command failed: There's no train at this position. This seems to be a bug.")
- end
- else
- atwarn("ATC rail at", pos, ": Sending command failed: Entry for controller not found.")
- atwarn("ATC rail at", pos, ": Please visit controller and click 'Save'")
- end
- return false
-end
-
-function atc.train_reset_command(train_id)
- advtrains.trains[train_id].atc_command=nil
- advtrains.trains[train_id].atc_delay=0
- advtrains.trains[train_id].atc_brake_target=nil
- advtrains.trains[train_id].atc_wait_finish=nil
- advtrains.trains[train_id].atc_arrow=nil
-end
-
---nodes
-local idxtrans={static=1, mesecon=2, digiline=3}
-local apn_func=function(pos, node)
- advtrains.ndb.update(pos, node)
- local meta=minetest.get_meta(pos)
- if meta then
- meta:set_string("infotext", attrans("ATC controller, unconfigured."))
- meta:set_string("formspec", atc.get_atc_controller_formspec(pos, meta))
- end
-end
-
-advtrains.register_tracks("default", {
- nodename_prefix="advtrains:dtrack_atc",
- texture_prefix="advtrains_dtrack_atc",
- models_prefix="advtrains_dtrack",
- models_suffix=".b3d",
- shared_texture="advtrains_dtrack_shared_atc.png",
- description=attrans("ATC controller"),
- formats={},
- get_additional_definiton = function(def, preset, suffix, rotation)
- return {
- after_place_node=apn_func,
- after_dig_node=function(pos)
- return advtrains.pcall(function()
- advtrains.invalidate_all_paths(pos)
- advtrains.ndb.clear(pos)
- local pts=minetest.pos_to_string(pos)
- atc.controllers[pts]=nil
- end)
- end,
- on_receive_fields = function(pos, formname, fields, player)
- return advtrains.pcall(function()
- if advtrains.is_protected(pos, player:get_player_name()) then
- minetest.record_protection_violation(pos, player:get_player_name())
- return
- end
- local meta=minetest.get_meta(pos)
- if meta then
- if not fields.save then
- --maybe only the dropdown changed
- if fields.mode then
- meta:set_string("mode", idxtrans[fields.mode])
- if fields.mode=="digiline" then
- meta:set_string("infotext", attrans("ATC controller, mode @1\nChannel: @2", fields.mode, meta:get_string("command")) )
- else
- meta:set_string("infotext", attrans("ATC controller, mode @1\nCommand: @2", fields.mode, meta:get_string("command")) )
- end
- meta:set_string("formspec", atc.get_atc_controller_formspec(pos, meta))
- end
- return
- end
- meta:set_string("mode", idxtrans[fields.mode])
- meta:set_string("command", fields.command)
- meta:set_string("command_on", fields.command_on)
- meta:set_string("channel", fields.channel)
- if fields.mode=="digiline" then
- meta:set_string("infotext", attrans("ATC controller, mode @1\nChannel: @2", fields.mode, meta:get_string("command")) )
- else
- meta:set_string("infotext", attrans("ATC controller, mode @1\nCommand: @2", fields.mode, meta:get_string("command")) )
- end
- meta:set_string("formspec", atc.get_atc_controller_formspec(pos, meta))
-
- local pts=minetest.pos_to_string(pos)
- local _, conn1=advtrains.get_rail_info_at(pos, advtrains.all_tracktypes)
- atc.controllers[pts]={command=fields.command, arrowconn=conn1}
- if advtrains.detector.on_node[pts] then
- atc.send_command(pos)
- end
- end
- end)
- end,
- advtrains = {
- on_train_enter = function(pos, train_id)
- atc.send_command(pos)
- end,
- },
- }
- end
-}, advtrains.trackpresets.t_30deg_straightonly)
-
-
-function atc.get_atc_controller_formspec(pos, meta)
- local mode=tonumber(meta:get_string("mode")) or 1
- local command=meta:get_string("command")
- local command_on=meta:get_string("command_on")
- local channel=meta:get_string("channel")
- local formspec="size[8,6]"..
- "dropdown[0,0;3;mode;static,mesecon,digiline;"..mode.."]"
- if mode<3 then
- formspec=formspec.."field[0.5,1.5;7,1;command;"..attrans("Command")..";"..minetest.formspec_escape(command).."]"
- if tonumber(mode)==2 then
- formspec=formspec.."field[0.5,3;7,1;command_on;"..attrans("Command (on)")..";"..minetest.formspec_escape(command_on).."]"
- end
- else
- formspec=formspec.."field[0.5,1.5;7,1;channel;"..attrans("Digiline channel")..";"..minetest.formspec_escape(channel).."]"
- end
- return formspec.."button_exit[0.5,4.5;7,1;save;"..attrans("Save").."]"
-end
-
---from trainlogic.lua train step
-local matchptn={
- ["SM"]=function(id, train)
- train.tarvelocity=train.max_speed
- return 2
- end,
- ["S([0-9]+)"]=function(id, train, match)
- train.tarvelocity=tonumber(match)
- return #match+1
- end,
- ["B([0-9]+)"]=function(id, train, match)
- if train.velocity>tonumber(match) then
- train.atc_brake_target=tonumber(match)
- if train.tarvelocity>train.atc_brake_target then
- train.tarvelocity=train.atc_brake_target
- end
- end
- return #match+1
- end,
- ["W"]=function(id, train)
- train.atc_wait_finish=true
- return 1
- end,
- ["D([0-9]+)"]=function(id, train, match)
- train.atc_delay=tonumber(match)
- return #match+1
- end,
- ["R"]=function(id, train)
- if train.velocity<=0 then
- train.movedir=train.movedir*-1
- train.atc_arrow = not train.atc_arrow
- else
- atwarn(sid(id), attrans("ATC Reverse command warning: didn't reverse train, train moving!"))
- end
- return 1
- end,
- ["O([LRC])"]=function(id, train, match)
- local tt={L=-1, R=1, C=0}
- local arr=train.atc_arrow and 1 or -1
- train.door_open = tt[match]*arr*train.movedir
- return 2
- end,
-}
-
-function atc.execute_atc_command(id, train)
- --strip whitespaces
- local command=string.match(train.atc_command, "^%s*(.*)$")
-
-
- if string.match(command, "^%s*$") then
- train.atc_command=nil
- return
- end
- --conditional statement?
- local is_cond, cond_applies, compare
- local cond, rest=string.match(command, "^I([%+%-])(.+)$")
- if cond then
- is_cond=true
- if cond=="+" then
- cond_applies=train.atc_arrow
- end
- if cond=="-" then
- cond_applies=not train.atc_arrow
- end
- else
- cond, compare, rest=string.match(command, "^I([<>]=?)([0-9]+)(.+)$")
- if cond and compare then
- is_cond=true
- if cond=="<" then
- cond_applies=train.velocity<tonumber(compare)
- end
- if cond==">" then
- cond_applies=train.velocity>tonumber(compare)
- end
- if cond=="<=" then
- cond_applies=train.velocity<=tonumber(compare)
- end
- if cond==">=" then
- cond_applies=train.velocity>=tonumber(compare)
- end
- end
- end
- if is_cond then
- atprint("Evaluating if statement: "..command)
- atprint("Cond: "..(cond or "nil"))
- atprint("Applies: "..(cond_applies and "true" or "false"))
- atprint("Rest: "..rest)
- --find end of conditional statement
- local nest, pos, elsepos=0, 1
- while nest>=0 do
- if pos>#rest then
- atwarn(sid(id), attrans("ATC command syntax error: I statement not closed: @1",command))
- atc.train_reset_command(id)
- return
- end
- local char=string.sub(rest, pos, pos)
- if char=="I" then
- nest=nest+1
- end
- if char==";" then
- nest=nest-1
- end
- if nest==0 and char=="E" then
- elsepos=pos+0
- end
- pos=pos+1
- end
- if not elsepos then elsepos=pos-1 end
- if cond_applies then
- command=string.sub(rest, 1, elsepos-1)..string.sub(rest, pos)
- else
- command=string.sub(rest, elsepos+1, pos-2)..string.sub(rest, pos)
- end
- atprint("Result: "..command)
- train.atc_command=command
- atc.execute_atc_command(id, train)
- return
- else
- for pattern, func in pairs(matchptn) do
- local match=string.match(command, "^"..pattern)
- if match then
- local patlen=func(id, train, match)
-
- atprint("Executing: "..string.sub(command, 1, patlen))
-
- train.atc_command=string.sub(command, patlen+1)
- if train.atc_delay<=0 and not train.atc_wait_finish then
- --continue (recursive, cmds shouldn't get too long, and it's a end-recursion.)
- atc.execute_atc_command(id, train)
- end
- return
- end
- end
- end
- atwarn(sid(id), attrans("ATC command parse error: Unknown command: @1", command))
- atc.train_reset_command(id)
-end
-
-
-
---move table to desired place
-advtrains.atc=atc
diff --git a/advtrains/advtrains/couple.lua b/advtrains/advtrains/couple.lua
deleted file mode 100644
index ac4dfce..0000000
--- a/advtrains/advtrains/couple.lua
+++ /dev/null
@@ -1,180 +0,0 @@
---couple.lua
---defines couple entities.
-
---advtrains:discouple
---set into existing trains to split them when punched.
---they are attached to the wagons.
---[[fields
-wagon
-
-wagons keep their couple entity minetest-internal id inside the field discouple_id. if it refers to nowhere, they will spawn a new one if player is near
-]]
-
-local couple_max_dist=3
-
-minetest.register_entity("advtrains:discouple", {
- visual="sprite",
- textures = {"advtrains_discouple.png"},
- collisionbox = {-0.5,-0.5,-0.5, 0.5,0.5,0.5},
- visual_size = {x=1, y=1},
- initial_sprite_basepos = {x=0, y=0},
-
- is_discouple=true,
- on_activate=function(self, staticdata)
- if staticdata=="DISCOUPLE" then
- --couple entities have no right to exist further...
- atprint("Discouple loaded from staticdata, destroying")
- self.object:remove()
- return
- end
- self.object:set_armor_groups({immortal=1})
- end,
- get_staticdata=function() return "DISCOUPLE" end,
- on_punch=function(self, player)
- return advtrains.pcall(function()
- --only if player owns at least one wagon next to this
- local own=player:get_player_name()
- if self.wagon.owner and self.wagon.owner==own and not self.wagon.lock_couples then
- local train=advtrains.trains[self.wagon.train_id]
- local nextwgn_id=train.trainparts[self.wagon.pos_in_trainparts-1]
- for aoi, le in pairs(minetest.luaentities) do
- if le and le.is_wagon then
- if le.unique_id==nextwgn_id then
- if le.owner and le.owner~=own then
- minetest.chat_send_player(own, attrans("You need to own at least one neighboring wagon to destroy this couple."))
- return
- end
- end
- end
- end
- atprint("Discouple punched. Splitting train", self.wagon.train_id)
- advtrains.split_train_at_wagon(self.wagon)--found in trainlogic.lua
- self.object:remove()
- elseif self.wagon.lock_couples then
- minetest.chat_send_player(own, "Couples of one of the wagons are locked, can't discouple!")
- else
- minetest.chat_send_player(own, attrans("You need to own at least one neighboring wagon to destroy this couple."))
- end
- end)
- end,
- on_step=function(self, dtime)
- return advtrains.pcall(function()
- local t=os.clock()
- if not self.wagon then
- self.object:remove()
- atprint("Discouple: no wagon, destroying")
- return
- end
- --getyaw seems to be a reliable method to check if an object is loaded...if it returns nil, it is not.
- if not self.wagon.object:getyaw() then
- atprint("Discouple: wagon no longer loaded, destroying")
- self.object:remove()
- return
- end
- local velocityvec=self.wagon.object:getvelocity()
- self.updatepct_timer=(self.updatepct_timer or 0)-dtime
- if not self.old_velocity_vector or not vector.equals(velocityvec, self.old_velocity_vector) or self.updatepct_timer<=0 then--only send update packet if something changed
- local flipsign=self.wagon.wagon_flipped and -1 or 1
- self.object:setpos(vector.add(self.wagon.object:getpos(), {y=0, x=-math.sin(self.wagon.object:getyaw())*self.wagon.wagon_span*flipsign, z=math.cos(self.wagon.object:getyaw())*self.wagon.wagon_span*flipsign}))
- self.object:setvelocity(velocityvec)
- self.updatepct_timer=2
- end
- atprintbm("discouple_step", t)
- end)
- end,
-})
-
---advtrains:couple
---when two trains overlap with their end-positions, this entity will be spawned and both trains set its id into appropiate fields for them to know when to free them again. The entity will destroy automatically when it recognizes that any of the trains left the common position.
---[[fields
-train_id_1
-train_id_2
-train1_is_backpos
-train2_is_backpos
-]]
-
-
-minetest.register_entity("advtrains:couple", {
- visual="sprite",
- textures = {"advtrains_couple.png"},
- collisionbox = {-0.5,-0.5,-0.5, 0.5,0.5,0.5},
- visual_size = {x=1, y=1},
- initial_sprite_basepos = {x=0, y=0},
-
- is_couple=true,
- on_activate=function(self, staticdata)
- return advtrains.pcall(function()
- if staticdata=="COUPLE" then
- --couple entities have no right to exist further...
- atprint("Couple loaded from staticdata, destroying")
- self.object:remove()
- return
- end
- end)
- end,
- get_staticdata=function(self) return "COUPLE" end,
- on_rightclick=function(self, clicker)
- return advtrains.pcall(function()
- if not self.train_id_1 or not self.train_id_2 then return end
-
- local id1, id2=self.train_id_1, self.train_id_2
- if self.train1_is_backpos and not self.train2_is_backpos then
- advtrains.do_connect_trains(id1, id2, clicker)
- --case 2 (second train is front)
- elseif self.train2_is_backpos and not self.train1_is_backpos then
- advtrains.do_connect_trains(id2, id1, clicker)
- --case 3
- elseif self.train1_is_backpos and self.train2_is_backpos then
- advtrains.invert_train(id2)
- advtrains.do_connect_trains(id1, id2, clicker)
- --case 4
- elseif not self.train1_is_backpos and not self.train2_is_backpos then
- advtrains.invert_train(id1)
- advtrains.do_connect_trains(id1, id2, clicker)
- end
- atprint("Coupled trains", id1, id2)
- self.object:remove()
- end)
- end,
- on_step=function(self, dtime)
- return advtrains.pcall(function()
- local t=os.clock()
- if not self.train_id_1 or not self.train_id_2 then atprint("Couple: train ids not set!") self.object:remove() return end
- local train1=advtrains.trains[self.train_id_1]
- local train2=advtrains.trains[self.train_id_2]
- if not train1 or not train2 then
- atprint("Couple: trains missing, destroying")
- self.object:remove()
- return
- end
- if not train1.path or not train2.path or not train1.index or not train2.index or not train1.end_index or not train2.end_index then
- atprint("Couple: paths or end_index missing. Might happen when paths got cleared")
- return
- end
-
- local tp1
- if not self.train1_is_backpos then
- tp1=advtrains.get_real_index_position(train1.path, train1.index)
- else
- tp1=advtrains.get_real_index_position(train1.path, train1.end_index)
- end
- local tp2
- if not self.train2_is_backpos then
- tp2=advtrains.get_real_index_position(train2.path, train2.index)
- else
- tp2=advtrains.get_real_index_position(train2.path, train2.end_index)
- end
- if not tp1 or not tp2 or not (vector.distance(tp1,tp2)<couple_max_dist) then
- atprint("Couple: train end positions too distanced, destroying")
- self.object:remove()
- return
- else
- local pos_median=advtrains.pos_median(tp1, tp2)
- if not vector.equals(pos_median, self.object:getpos()) then
- self.object:setpos(pos_median)
- end
- end
- atprintbm("couple step", t)
- end)
- end,
-})
diff --git a/advtrains/advtrains/debugitems.lua b/advtrains/advtrains/debugitems.lua
deleted file mode 100644
index dcc95d9..0000000
--- a/advtrains/advtrains/debugitems.lua
+++ /dev/null
@@ -1,28 +0,0 @@
-minetest.register_tool("advtrains:tunnelborer",
-{
- description = "tunnelborer",
- groups = {cracky=1}, -- key=name, value=rating; rating=1..3.
- inventory_image = "drwho_screwdriver.png",
- wield_image = "drwho_screwdriver.png",
- stack_max = 1,
- range = 7.0,
-
- on_place = function(itemstack, placer, pointed_thing)
-
- end,
- --[[
- ^ Shall place item and return the leftover itemstack
- ^ default: minetest.item_place ]]
- on_use = function(itemstack, user, pointed_thing)
- if pointed_thing.type=="node" then
- for x=-1,1 do
- for y=-1,1 do
- for z=-1,1 do
- minetest.remove_node(vector.add(pointed_thing.under, {x=x, y=y, z=z}))
- end
- end
- end
- end
- end,
-}
-)
diff --git a/advtrains/advtrains/depends.txt b/advtrains/advtrains/depends.txt
deleted file mode 100644
index 20aa884..0000000
--- a/advtrains/advtrains/depends.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-default
-mesecons? \ No newline at end of file
diff --git a/advtrains/advtrains/helpers.lua b/advtrains/advtrains/helpers.lua
deleted file mode 100644
index a2b9b16..0000000
--- a/advtrains/advtrains/helpers.lua
+++ /dev/null
@@ -1,255 +0,0 @@
---advtrains by orwell96, see readme.txt
-
-advtrains.dir_trans_tbl={
- [0]={x=0, z=1},
- [1]={x=1, z=2},
- [2]={x=1, z=1},
- [3]={x=2, z=1},
- [4]={x=1, z=0},
- [5]={x=2, z=-1},
- [6]={x=1, z=-1},
- [7]={x=1, z=-2},
- [8]={x=0, z=-1},
- [9]={x=-1, z=-2},
- [10]={x=-1, z=-1},
- [11]={x=-2, z=-1},
- [12]={x=-1, z=0},
- [13]={x=-2, z=1},
- [14]={x=-1, z=1},
- [15]={x=-1, z=2},
-}
-
-function advtrains.dirCoordSet(coord, dir)
- local x,z
- if advtrains.dir_trans_tbl[dir] then
- x,z=advtrains.dir_trans_tbl[dir].x, advtrains.dir_trans_tbl[dir].z
- else
- error("advtrains: in helpers.lua/dirCoordSet() given dir="..(dir or "nil"))
- end
- return {x=coord.x+x, y=coord.y, z=coord.z+z}
-end
-function advtrains.dirToCoord(dir)
- return advtrains.dirCoordSet({x=0, y=0, z=0}, dir)
-end
-
-function advtrains.maxN(list, expectstart)
- local n=expectstart or 0
- while list[n] do
- n=n+1
- end
- return n-1
-end
-
-function advtrains.minN(list, expectstart)
- local n=expectstart or 0
- while list[n] do
- n=n-1
- end
- return n+1
-end
-
---vertical_transmit:
---[[
-rely1, rely2 tell to which height the connections are pointed to. 1 means it will go up the next node
-
-]]
-
-function advtrains.conway(midreal, prev, drives_on)--in order prev,mid,return
- local mid=advtrains.round_vector_floor_y(midreal)
-
- local midnode_ok, middir1, middir2, midrely1, midrely2=advtrains.get_rail_info_at(mid, drives_on)
- if not midnode_ok then
- return nil
- end
-
- local next, chkdir, chkrely, y_offset
- y_offset=0
- --atprint(" in order mid1,mid2",middir1,middir2)
- --try if it is dir1
- local cor1=advtrains.dirCoordSet(mid, middir2)--<<<<
- if cor1.x==prev.x and cor1.z==prev.z then--this was previous
- next=advtrains.dirCoordSet(mid, middir1)
- if midrely1>=1 then
- next.y=next.y+1
- --atprint("found midrely1 to be >=1: next is now "..(next and minetest.pos_to_string(next) or "nil"))
- y_offset=1
- end
- chkdir=middir1
- chkrely=midrely1
- --atprint("dir2 applied next pos:",minetest.pos_to_string(next),"(chkdir is ",chkdir,")")
- end
- --dir2???
- local cor2=advtrains.dirCoordSet(mid, middir1)--<<<<
- if math.floor(cor2.x+0.5)==math.floor(prev.x+0.5) and math.floor(cor2.z+0.5)==math.floor(prev.z+0.5) then
- next=advtrains.dirCoordSet(mid, middir2)--dir2 wird überprüft, alles gut.
- if midrely2>=1 then
- next.y=next.y+1
- --atprint("found midrely2 to be >=1: next is now "..(next and minetest.pos_to_string(next) or "nil"))
- y_offset=1
- end
- chkdir=middir2
- chkrely=midrely2
- --atprint(" dir2 applied next pos:",minetest.pos_to_string(next),"(chkdir is ",chkdir,")")
- end
- --atprint("dir applied next pos: "..(next and minetest.pos_to_string(next) or "nil").."(chkdir is "..(chkdir or "nil")..", y-offset "..y_offset..")")
- --is there a next
- if not next then
- --atprint("in conway: no next rail(nil), returning!")
- return nil
- end
-
- local nextnode_ok, nextdir1, nextdir2, nextrely1, nextrely2, nextrailheight=advtrains.get_rail_info_at(advtrains.round_vector_floor_y(next), drives_on)
-
- --is it a rail?
- if(not nextnode_ok) then
- --atprint("in conway: next "..minetest.pos_to_string(next).." not a rail, trying one node below!")
- next.y=next.y-1
- y_offset=y_offset-1
-
- nextnode_ok, nextdir1, nextdir2, nextrely1, nextrely2, nextrailheight=advtrains.get_rail_info_at(advtrains.round_vector_floor_y(next), drives_on)
- if(not nextnode_ok) then
- --atprint("in conway: one below "..minetest.pos_to_string(next).." is not a rail either, returning!")
- return nil
- end
- end
-
- --is this next rail connecting to the mid?
- if not ( (((nextdir1+8)%16)==chkdir and nextrely1==chkrely-y_offset) or (((nextdir2+8)%16)==chkdir and nextrely2==chkrely-y_offset) ) then
- --atprint("in conway: next "..minetest.pos_to_string(next).." not connecting, trying one node below!")
- next.y=next.y-1
- y_offset=y_offset-1
-
- nextnode_ok, nextdir1, nextdir2, nextrely1, nextrely2, nextrailheight=advtrains.get_rail_info_at(advtrains.round_vector_floor_y(next), drives_on)
- if(not nextnode_ok) then
- --atprint("in conway: (at connecting if check again) one below "..minetest.pos_to_string(next).." is not a rail either, returning!")
- return nil
- end
- if not ( (((nextdir1+8)%16)==chkdir and nextrely1==chkrely) or (((nextdir2+8)%16)==chkdir and nextrely2==chkrely) ) then
- --atprint("in conway: one below "..minetest.pos_to_string(next).." rail not connecting, returning!")
- --atprint(" in order mid1,2,next1,2,chkdir "..middir1.." "..middir2.." "..nextdir1.." "..nextdir2.." "..chkdir)
- return nil
- end
- end
-
- --atprint("conway found rail.")
- return vector.add(advtrains.round_vector_floor_y(next), {x=0, y=nextrailheight, z=0}), chkdir
-end
---TODO use this
-function advtrains.oppd(dir)
- return ((dir+8)%16)
-end
-
-function advtrains.round_vector_floor_y(vec)
- return {x=math.floor(vec.x+0.5), y=math.floor(vec.y), z=math.floor(vec.z+0.5)}
-end
-
-function advtrains.yawToDirection(yaw, conn1, conn2)
- if not conn1 or not conn2 then
- error("given nil to yawToDirection: conn1="..(conn1 or "nil").." conn2="..(conn1 or "nil"))
- end
- local yaw1=math.pi*(conn1/4)
- local yaw2=math.pi*(conn2/4)
- if advtrains.minAngleDiffRad(yaw, yaw1)<advtrains.minAngleDiffRad(yaw, yaw2) then--change to > if weird behavior
- return conn2
- else
- return conn1
- end
-end
-
-function advtrains.minAngleDiffRad(r1, r2)
- local try1=r2-r1
- local try2=(r2+2*math.pi)-r1
- local try3=r2-(r1+2*math.pi)
- if math.min(math.abs(try1), math.abs(try2), math.abs(try3))==math.abs(try1) then
- return try1
- end
- if math.min(math.abs(try1), math.abs(try2), math.abs(try3))==math.abs(try2) then
- return try2
- end
- if math.min(math.abs(try1), math.abs(try2), math.abs(try3))==math.abs(try3) then
- return try3
- end
-end
-function advtrains.dumppath(path)
- if not path then atprint("dumppath: no path(nil)") return end
- local min=advtrains.minN(path)
- local max=advtrains.maxN(path)
- for i=min, max do atprint("["..i.."] "..(path[i] and minetest.pos_to_string(path[i]) or "nil")) end
-end
-
-function advtrains.merge_tables(a, ...)
- local new={}
- for _,t in ipairs({a,...}) do
- for k,v in pairs(t) do new[k]=v end
- end
- return new
-end
-function advtrains.yaw_from_3_positions(prev, curr, next)
- local pts=minetest.pos_to_string
- --atprint("p3 "..pts(prev)..pts(curr)..pts(next))
- local prev2curr=math.atan2((curr.x-prev.x), (prev.z-curr.z))
- local curr2next=math.atan2((next.x-curr.x), (curr.z-next.z))
- --atprint("y3 "..(prev2curr*360/(2*math.pi)).." "..(curr2next*360/(2*math.pi)))
- return prev2curr+(advtrains.minAngleDiffRad(prev2curr, curr2next)/2)
-end
-function advtrains.get_wagon_yaw(front, first, second, back, pct)
- local pts=minetest.pos_to_string
- --atprint("p "..pts(front)..pts(first)..pts(second)..pts(back))
- local y2=advtrains.yaw_from_3_positions(second, first, front)
- local y1=advtrains.yaw_from_3_positions(back, second, first)
- --atprint("y "..(y1*360/(2*math.pi)).." "..(y2*360/(2*math.pi)))
- return y1+advtrains.minAngleDiffRad(y1, y2)*pct
-end
-function advtrains.get_real_index_position(path, index)
- if not path or not index then return end
-
- local first_pos=path[math.floor(index)]
- local second_pos=path[math.floor(index)+1]
-
- if not first_pos or not second_pos then return nil end
-
- local factor=index-math.floor(index)
- local actual_pos={x=first_pos.x-(first_pos.x-second_pos.x)*factor, y=first_pos.y-(first_pos.y-second_pos.y)*factor, z=first_pos.z-(first_pos.z-second_pos.z)*factor,}
- return actual_pos
-end
-function advtrains.pos_median(pos1, pos2)
- return {x=pos1.x-(pos1.x-pos2.x)*0.5, y=pos1.y-(pos1.y-pos2.y)*0.5, z=pos1.z-(pos1.z-pos2.z)*0.5}
-end
-function advtrains.abs_ceil(i)
- return math.ceil(math.abs(i))*math.sign(i)
-end
-
-function advtrains.serialize_inventory(inv)
- local ser={}
- local liszts=inv:get_lists()
- for lisztname, liszt in pairs(liszts) do
- ser[lisztname]={}
- for idx, item in ipairs(liszt) do
- local istring=item:to_string()
- if istring~="" then
- ser[lisztname][idx]=istring
- end
- end
- end
- return minetest.serialize(ser)
-end
-function advtrains.deserialize_inventory(sers, inv)
- local ser=minetest.deserialize(sers)
- if ser then
- inv:set_lists(ser)
- return true
- end
- return false
-end
-
---is_protected wrapper that checks for protection_bypass privilege
-function advtrains.is_protected(pos, name)
- if not name then
- error("advtrains.is_protected() called without name parameter!")
- end
- if minetest.check_player_privs(name, {protection_bypass=true}) then
- --player can bypass protection
- return false
- end
- return minetest.is_protected(pos, name)
-end
diff --git a/advtrains/advtrains/init.lua b/advtrains/advtrains/init.lua
deleted file mode 100644
index 2bdf39c..0000000
--- a/advtrains/advtrains/init.lua
+++ /dev/null
@@ -1,329 +0,0 @@
--- Boilerplate to support localized strings if intllib mod is installed.
-if minetest.get_modpath("intllib") then
- attrans = intllib.Getter()
-else
- attrans = function(s,a,...)a={a,...}return s:gsub("@(%d+)",function(n)return a[tonumber(n)]end)end
-end
-
---advtrains
-
-advtrains = {trains={}, wagon_save={}, player_to_train_mapping={}}
-
---pcall
-local no_action=false
-function advtrains.pcall(fun)
- if no_action then return end
-
- local succ, return1, return2, return3, return4=xpcall(fun, function(err)
- atwarn("Lua Error occured: ", err)
- atwarn(debug.traceback())
- end)
- if not succ then
- atwarn("Restoring saved state in 1 second...")
- no_action=true
- --read last save state and continue, as if server was restarted
- for aoi, le in pairs(minetest.luaentities) do
- if le.is_wagon then
- le.object:remove()
- end
- end
- minetest.after(1, function()
- advtrains.load()
- atwarn("Reload successful!")
- advtrains.ndb.restore_all()
- end)
- else
- return return1, return2, return3, return4
- end
-end
-
-
-advtrains.modpath = minetest.get_modpath("advtrains")
-
-function advtrains.print_concat_table(a)
- local str=""
- local stra=""
- for i=1,10 do
- t=a[i]
- if t==nil then
- stra=stra.."nil "
- else
- str=str..stra
- stra=""
- if type(t)=="table" then
- if t.x and t.y and t.z then
- str=str..minetest.pos_to_string(t)
- else
- str=str..dump(t)
- end
- elseif type(t)=="boolean" then
- if t then
- str=str.."true"
- else
- str=str.."false"
- end
- else
- str=str..t
- end
- str=str.." "
- end
- end
- return str
-end
-atprint=function() end
-if minetest.setting_getbool("advtrains_debug") then
- atprint=function(t, ...)
- local context=advtrains.atprint_context_tid
- if not context then context="" end
- --if context~="4527" then return end
- local text=advtrains.print_concat_table({t, ...})
- minetest.log("action", "[advtrains]"..context..">"..text)
- minetest.chat_send_all("[advtrains]"..context..">"..text)
- end
-end
-atwarn=function(t, ...)
- local text=advtrains.print_concat_table({t, ...})
- minetest.log("warning", "[advtrains]"..text)
- minetest.chat_send_all("[advtrains] -!- "..text)
-end
-sid=function(id) return string.sub(id, -4) end
-
-dofile(advtrains.modpath.."/helpers.lua");
---dofile(advtrains.modpath.."/debugitems.lua");
-
-advtrains.meseconrules =
-{{x=0, y=0, z=-1},
- {x=1, y=0, z=0},
- {x=-1, y=0, z=0},
- {x=0, y=0, z=1},
- {x=1, y=1, z=0},
- {x=1, y=-1, z=0},
- {x=-1, y=1, z=0},
- {x=-1, y=-1, z=0},
- {x=0, y=1, z=1},
- {x=0, y=-1, z=1},
- {x=0, y=1, z=-1},
- {x=0, y=-1, z=-1},
- {x=0, y=-2, z=0}}
-
-dofile(advtrains.modpath.."/trainlogic.lua")
-dofile(advtrains.modpath.."/trainhud.lua")
-dofile(advtrains.modpath.."/trackplacer.lua")
-dofile(advtrains.modpath.."/tracks.lua")
-dofile(advtrains.modpath.."/atc.lua")
-dofile(advtrains.modpath.."/wagons.lua")
-
-dofile(advtrains.modpath.."/trackdb_legacy.lua")
-dofile(advtrains.modpath.."/nodedb.lua")
-dofile(advtrains.modpath.."/couple.lua")
-
-dofile(advtrains.modpath.."/signals.lua")
-dofile(advtrains.modpath.."/misc_nodes.lua")
-dofile(advtrains.modpath.."/crafting.lua")
-dofile(advtrains.modpath.."/craft_items.lua")
-
-
---load/save
-
-advtrains.fpath=minetest.get_worldpath().."/advtrains"
-
-function advtrains.avt_load()
- local file, err = io.open(advtrains.fpath, "r")
- if not file then
- minetest.log("error", " Failed to read advtrains save data from file "..advtrains.fpath..": "..(err or "Unknown Error"))
- else
- local tbl = minetest.deserialize(file:read("*a"))
- if type(tbl) == "table" then
- if tbl.version then
- --congrats, we have the new save format.
- advtrains.trains = tbl.trains
- advtrains.wagon_save = tbl.wagon_save
- advtrains.player_to_train_mapping = tbl.ptmap or {}
- advtrains.ndb.load_data(tbl.ndb)
- advtrains.atc.load_data(tbl.atc)
- else
- --oh no, its the old one...
- advtrains.trains=tbl
- --load ATC
- advtrains.fpath_atc=minetest.get_worldpath().."/advtrains_atc"
- local file, err = io.open(advtrains.fpath_atc, "r")
- if not file then
- local er=err or "Unknown Error"
- atprint("Failed loading advtrains atc save file "..er)
- else
- local tbl = minetest.deserialize(file:read("*a"))
- if type(tbl) == "table" then
- advtrains.atc.controllers=tbl.controllers
- end
- file:close()
- end
- --load wagon saves
- advtrains.fpath_ws=minetest.get_worldpath().."/advtrains_wagon_save"
- local file, err = io.open(advtrains.fpath_ws, "r")
- if not file then
- local er=err or "Unknown Error"
- atprint("Failed loading advtrains save file "..er)
- else
- local tbl = minetest.deserialize(file:read("*a"))
- if type(tbl) == "table" then
- advtrains.wagon_save=tbl
- end
- file:close()
- end
- end
- else
- minetest.log("error", " Failed to deserialize advtrains save data: Not a table!")
- end
- file:close()
- end
-end
-
-advtrains.avt_save = function()
- --atprint("saving")
- --No more invalidating.
- --Instead, remove path a.s.o from the saved table manually
-
- -- update wagon saves
- for _,wagon in pairs(minetest.luaentities) do
- if wagon.is_wagon and wagon.initialized then
- wagon:get_staticdata()
- end
- end
- --cross out userdata
- for w_id, data in pairs(advtrains.wagon_save) do
- data.name=nil
- data.object=nil
- if data.driver then
- data.driver_name=data.driver:get_player_name()
- data.driver=nil
- else
- data.driver_name=nil
- end
- if data.discouple then
- data.discouple.object:remove()
- data.discouple=nil
- end
- end
-
- local tmp_trains={}
- for id, train in pairs(advtrains.trains) do
- --first, deep_copy the train
- local v=advtrains.merge_tables(train)
- --then invalidate
- if v.index then
- v.restore_add_index=v.index-math.floor(v.index+0.5)
- end
- v.path=nil
- v.path_dist=nil
- v.index=nil
- v.end_index=nil
- v.min_index_on_track=nil
- v.max_index_on_track=nil
- v.path_extent_min=nil
- v.path_extent_max=nil
-
- v.detector_old_index=nil
- v.detector_old_end_index=nil
-
- --then save it
- tmp_trains[id]=v
- end
-
- --versions:
- -- 1 - Initial new save format.
- local save_tbl={
- trains = tmp_trains,
- wagon_save = advtrains.wagon_save,
- ptmap = advtrains.player_to_train_mapping,
- atc = advtrains.atc.save_data(),
- ndb = advtrains.ndb.save_data(),
- version = 1,
- }
- local datastr = minetest.serialize(save_tbl)
- if not datastr then
- minetest.log("error", " Failed to serialize advtrains save data!")
- return
- end
- local file, err = io.open(advtrains.fpath, "w")
- if err then
- minetest.log("error", " Failed to write advtrains save data to file "..advtrains.fpath..": "..(err or "Unknown Error"))
- return
- end
- file:write(datastr)
- file:close()
-end
-
---## MAIN LOOP ##--
---Calls all subsequent main tasks of both advtrains and atlatc
-local init_load=false
-local save_interval=20
-local save_timer=save_interval
-
-minetest.register_globalstep(function(dtime_mt)
- return advtrains.pcall(function()
- --call load once. see advtrains.load() comment
- if not init_load then
- advtrains.load()
- end
- --limit dtime: if trains move too far in one step, automation may cause stuck and wrongly braking trains
- local dtime=dtime_mt
- if dtime>0.2 then
- atprint("Limiting dtime to 0.2!")
- dtime=0.2
- end
-
- advtrains.mainloop_trainlogic(dtime)
- if advtrains_itm_mainloop then
- advtrains_itm_mainloop(dtime)
- end
- if atlatc then
- atlatc.mainloop_stepcode(dtime)
- atlatc.interrupt.mainloop(dtime)
- end
-
-
- --trigger a save when necessary
- save_timer=save_timer-dtime
- if save_timer<=0 then
- local t=os.clock()
- --save
- advtrains.save()
- save_timer=save_interval
- atprintbm("saving", t)
- end
- end)
-end)
-
---if something goes wrong in these functions, there is no help. no pcall here.
-
---## MAIN LOAD ROUTINE ##
--- Causes the loading of everything
--- first time called in main loop (after the init phase) because luaautomation has to initialize first.
-function advtrains.load()
- advtrains.avt_load() --loading advtrains. includes ndb at advtrains.ndb.load_data()
- if atlatc then
- atlatc.load() --includes interrupts
- end
- if advtrains_itm_init then
- advtrains_itm_init()
- end
- init_load=true
- no_action=false
- atprint("[load_all]Loaded advtrains save files")
-end
-
---## MAIN SAVE ROUTINE ##
--- Causes the saving of everything
-function advtrains.save()
- if not init_load then
- --wait... we haven't loaded yet?!
- atwarn("Instructed to save() but load() was never called!")
- return
- end
- advtrains.avt_save() --saving advtrains. includes ndb at advtrains.ndb.save_data()
- if atlatc then
- atlatc.save()
- end
- atprint("[save_all]Saved advtrains save files")
-end
-minetest.register_on_shutdown(advtrains.save)
diff --git a/advtrains/advtrains/locale/de.txt b/advtrains/advtrains/locale/de.txt
deleted file mode 100644
index fe770d8..0000000
--- a/advtrains/advtrains/locale/de.txt
+++ /dev/null
@@ -1,50 +0,0 @@
-This wagon is owned by @1, you can't destroy it. = Dieser Waggon gehört @1, du kannst ihn nicht abbauen.
-Warning: If you destroy this wagon, you only get some steel back! If you are sure, hold Sneak and left-click the wagon. = Warnung: Du erhältst nur etwas Stahl zurück. Wenn du sicher bist, dass du den Waggon zerstören willst, halte 'Schleichen' und klicke links.
-Show Inventory = Zeige Inventar
-Select seat: = Wähle einen Sitzplatz aus:
-ATC controller, unconfigured. = Zugbeeinflussungsschiene, nicht konfiguiert.
-ATC controller = Zugbeeinflussungsschiene
-ATC controller, mode @1\nChannel: @2 = Zugbeeinflussungsschiene in Betriebsart "@1"\nKanal: @2
-ATC controller, mode @1\nCommand: @2 = Zugbeeinflussungsschiene in Betriebsart "@1"\nBefehl: @2
-Command = Befehl
-Command (on) = Befehl (wenn ein)
-Digiline channel = Digiline-Kanal
-Save = Speichern
-ATC Reverse command warning: didn't reverse train, train moving! = Zugbeeinflussung - Warnung: Befehl 'R' nicht ausgeführt, Zug in Bewegung!
-ATC command syntax error: I statement not closed: @1 = Zugbeeinflussung - Syntaxfehler: I-Anweisung nicht geschlossen: @1
-ATC command parse error: Unknown command: @1 = Zugbeeinflussung - Fehler: Unbekannter Befehl: @1
-This position is protected! = Diese Position ist geschützt!
-You need to own at least one neighboring wagon to destroy this couple. = Du musst Besitzer eines angrenzenden Waggons sein, um hier abzukuppeln.
-@1 Platform (low) = Niedriger @1-Bahnsteig
-@1 Platform (high) = Hoher @1-Bahnsteig
-off = aus
-on = ein
-Lampless Signal (@1) = Mechanisches Signal (@1)
-Signal (@1) = Lichtsignal (@1)
-Track Worker Tool\n\nLeft-click: change rail type (straight/curve/switch)\nRight-click: rotate rail/bumper/signal/etc. = Schienenwerkzeug\n\nLinksklick: Schienentyp ändern, Rechtsklick: Objekt drehen.
-This node can't be rotated using the trackworker! = Kann diesen Block nicht mit dem Schienenwerkzeug drehen.
-This node can't be changed using the trackworker! = Kann diesen Block nicht mit dem Schienenwerkzeug bearbeiten.
-Can't place: not pointing at node = Kann nicht platzieren: Du zeigst nicht auf einen Block.
-Can't place: space occupied! = Kann nicht platzieren: Platz besetzt.
-Can't place: protected position! = Kann nicht platzieren: Position geschützt.
-Can't place: Not enough slope items left (@1 required) = Kann nicht platzieren: nicht genug Steigungsblöcke, es werden insgesamt @1 benötigt.
-Can't place: There's no slope of length @1 = Kann nicht platzieren: Keine Steigung der Länge @1 definiert.
-Can't place: no supporting node at upper end. = Kann nicht platzieren: kein unterstützender Block am Ende der Steigung.
-Deprecated Track = ausrangierte Schiene, nicht verwenden.
-Track = Schiene
-Bumper = Prellbock
-Detector Rail = Detektorschiene
-Speed: = Geschw.:
-Target: = Zielges.:
-@1 Slope = @1 Steigung
-Can't get on: wagon full or doors closed! = Kann nicht einsteigen: Waggon voll oder Türen geschlossen.
-Use Sneak+rightclick to bypass closed doors! = Nutze Sneak+Rechtsklick, um die Türnotöffnung zu aktivieren und trotzdem einzusteigen.
-Lock couples = Kupplungen sperren
-Save wagon properties = Waggon-Einstellungen speichern
-Doors are closed! Use Sneak+rightclick to ignore the closed doors and get off! = Türen sind geschlossen! Sneak+Rechtsklick, um die Türnotöffnung zu aktivieren und trotzdem auszusteigen.
-Wagon properties = Waggon-Einstellungen
-Get off = Aussteigen
-Get off (forced) = Aussteigen (erzwingen)
-(Doors closed) = (Türen geschlossen)
-Access to @1 = Zugang zu @1
-
diff --git a/advtrains/advtrains/misc_nodes.lua b/advtrains/advtrains/misc_nodes.lua
deleted file mode 100644
index 37f535d..0000000
--- a/advtrains/advtrains/misc_nodes.lua
+++ /dev/null
@@ -1,67 +0,0 @@
---all nodes that do not fit in any other category
-
-function advtrains.register_platform(preset)
- local ndef=minetest.registered_nodes[preset]
- if not ndef then
- minetest.log("warning", " register_platform couldn't find preset node "..preset)
- return
- end
- local btex=ndef.tiles
- if type(btex)=="table" then
- btex=btex[1]
- end
- local desc=ndef.description or ""
- local nodename=string.match(preset, ":(.+)$")
- minetest.register_node("advtrains:platform_low_"..nodename, {
- description = attrans("@1 Platform (low)", desc),
- tiles = {btex.."^advtrains_platform.png", btex, btex, btex, btex, btex},
- groups = {cracky = 1, not_blocking_trains = 1, platform=1},
- sounds = default.node_sound_stone_defaults(),
- drawtype = "nodebox",
- node_box = {
- type = "fixed",
- fixed = {
- {-0.5, -0.1, -0.1, 0.5, 0 , 0.5},
- {-0.5, -0.5, 0 , 0.5, -0.1, 0.5}
- },
- },
- paramtype2="facedir",
- paramtype = "light",
- sunlight_propagates = true,
- })
- minetest.register_node("advtrains:platform_high_"..nodename, {
- description = attrans("@1 Platform (high)", desc),
- tiles = {btex.."^advtrains_platform.png", btex, btex, btex, btex, btex},
- groups = {cracky = 1, not_blocking_trains = 1, platform=2},
- sounds = default.node_sound_stone_defaults(),
- drawtype = "nodebox",
- node_box = {
- type = "fixed",
- fixed = {
- {-0.5, 0.3, -0.1, 0.5, 0.5, 0.5},
- {-0.5, -0.5, 0 , 0.5, 0.3, 0.5}
- },
- },
- paramtype2="facedir",
- paramtype = "light",
- sunlight_propagates = true,
- })
- minetest.register_craft({
- type="shapeless",
- output = "advtrains:platform_high_"..nodename.." 4",
- recipe = {
- "dye:yellow", preset, preset
- },
- })
- minetest.register_craft({
- type="shapeless",
- output = "advtrains:platform_low_"..nodename.." 4",
- recipe = {
- "dye:yellow", preset
- },
- })
-end
-
-
-advtrains.register_platform("default:stonebrick")
-advtrains.register_platform("default:sandstonebrick")
diff --git a/advtrains/advtrains/nodedb.lua b/advtrains/advtrains/nodedb.lua
deleted file mode 100644
index 5a193bd..0000000
--- a/advtrains/advtrains/nodedb.lua
+++ /dev/null
@@ -1,285 +0,0 @@
---nodedb.lua
---database of all nodes that have 'save_in_nodedb' field set to true in node definition
-
-
---serialization format:
---(2byte z) (2byte y) (2byte x) (2byte contentid)
---contentid := (14bit nodeid, 2bit param2)
-
-local function int_to_bytes(i)
- local x=i+32768--clip to positive integers
- local cH = math.floor(x / 256) % 256;
- local cL = math.floor(x ) % 256;
- return(string.char(cH, cL));
-end
-local function bytes_to_int(bytes)
- local t={string.byte(bytes,1,-1)}
- local n =
- t[1] * 256 +
- t[2]
- return n-32768
-end
-local function l2b(x)
- return x%4
-end
-local function u14b(x)
- return math.floor(x/4)
-end
-local ndb={}
-
---local variables for performance
-local ndb_nodeids={}
-local ndb_nodes={}
-
-local function ndbget(x,y,z)
- local ny=ndb_nodes[y]
- if ny then
- local nx=ny[x]
- if nx then
- return nx[z]
- end
- end
- return nil
-end
-local function ndbset(x,y,z,v)
- if not ndb_nodes[y] then
- ndb_nodes[y]={}
- end
- if not ndb_nodes[y][x] then
- ndb_nodes[y][x]={}
- end
- ndb_nodes[y][x][z]=v
-end
-
-
---load
---nodeids get loaded by advtrains init.lua and passed here
-function ndb.load_data(data)
- ndb_nodeids = data and data.nodeids or {}
-end
-
-local path=minetest.get_worldpath().."/advtrains_ndb2"
-
-local file, err = io.open(path, "r")
-if not file then
- atprint("load ndb failed: ", err or "Unknown Error")
-else
- local cnt=0
- local hst_z=file:read(2)
- local hst_y=file:read(2)
- local hst_x=file:read(2)
- local cid=file:read(2)
- while hst_z and hst_y and hst_x and cid and #hst_z==2 and #hst_y==2 and #hst_x==2 and #cid==2 do
- ndbset(bytes_to_int(hst_x), bytes_to_int(hst_y), bytes_to_int(hst_z), bytes_to_int(cid))
- cnt=cnt+1
- hst_z=file:read(2)
- hst_y=file:read(2)
- hst_x=file:read(2)
- cid=file:read(2)
- end
- atprint("nodedb: read", cnt, "nodes.")
- file:close()
-end
-
---save
-function ndb.save_data()
- local file, err = io.open(path, "w")
- if not file then
- atprint("save ndb failed: ", err or "Unknown Error")
- else
- for y, ny in pairs(ndb_nodes) do
- for x, nx in pairs(ny) do
- for z, cid in pairs(nx) do
- file:write(int_to_bytes(z))
- file:write(int_to_bytes(y))
- file:write(int_to_bytes(x))
- file:write(int_to_bytes(cid))
- end
- end
- end
- file:close()
- end
- return {nodeids = ndb_nodeids}
-end
-
---function to get node. track database is not helpful here.
-function ndb.get_node_or_nil(pos)
- local node=minetest.get_node_or_nil(pos)
- if node then
- return node
- else
- --maybe we have the node in the database...
- local cid=ndbget(pos.x, pos.y, pos.z)
- if cid then
- local nodeid = ndb_nodeids[u14b(cid)]
- if nodeid then
- --atprint("ndb.get_node_or_nil",pos,"found node",nodeid,"cid",cid,"par2",l2b(cid))
- return {name=nodeid, param2 = l2b(cid)}
- end
- end
- end
- atprint("ndb.get_node_or_nil",pos,"not found")
-end
-function ndb.get_node(pos)
- local n=ndb.get_node_or_nil(pos)
- if not n then
- return {name="ignore", param2=0}
- end
- return n
-end
-
-function ndb.swap_node(pos, node)
- minetest.swap_node(pos, node)
- ndb.update(pos, node)
-end
-
-function ndb.update(pos, pnode)
- local node = pnode or minetest.get_node_or_nil(pos)
- if not node or node.name=="ignore" then return end
- if minetest.registered_nodes[node.name] and minetest.registered_nodes[node.name].groups.save_in_nodedb then
- local nid
- for tnid, nname in pairs(ndb_nodeids) do
- if nname==node.name then
- nid=tnid
- end
- end
- if not nid then
- nid=#ndb_nodeids+1
- ndb_nodeids[nid]=node.name
- end
- ndbset(pos.x, pos.y, pos.z, (nid * 4) + (l2b(node.param2 or 0)) )
- --atprint("nodedb: updating node", pos, "stored nid",nid,"assigned",ndb_nodeids[nid],"resulting cid",ndb_nodes[hash])
- else
- --at this position there is no longer a node that needs to be tracked.
- ndbset(pos.x, pos.y, pos.z, nil)
- end
-end
-
-function ndb.clear(pos)
- ndbset(pos.x, pos.y, pos.z, nil)
-end
-
-
---get_node with pseudoload. now we only need track data, so we can use the trackdb as second fallback
---nothing new will be saved inside the trackdb.
---returns:
---true, conn1, conn2, rely1, rely2, railheight in case everything's right.
---false if it's not a rail or the train does not drive on this rail, but it is loaded or
---nil if the node is neither loaded nor in trackdb
---the distraction between false and nil will be needed only in special cases.(train initpos)
-function advtrains.get_rail_info_at(pos, drives_on)
- local rdp=advtrains.round_vector_floor_y(pos)
-
- local node=ndb.get_node_or_nil(rdp)
-
- --still no node?
- --advtrains.trackdb is nil when there's no data available.
- if not node then
- if advtrains.trackdb then
- --try raildb (see trackdb_legacy.lua)
- local dbe=(advtrains.trackdb[rdp.y] and advtrains.trackdb[rdp.y][rdp.x] and advtrains.trackdb[rdp.y][rdp.x][rdp.z])
- if dbe then
- for tt,_ in pairs(drives_on) do
- if not dbe.tracktype or tt==dbe.tracktype then
- return true, dbe.conn1, dbe.conn2, dbe.rely1 or 0, dbe.rely2 or 0, dbe.railheight or 0
- end
- end
- end
- end
- return nil
- end
- local nodename=node.name
- if(not advtrains.is_track_and_drives_on(nodename, drives_on)) then
- return false
- end
- local conn1, conn2, rely1, rely2, railheight, tracktype=advtrains.get_track_connections(node.name, node.param2)
-
- return true, conn1, conn2, rely1, rely2, railheight
-end
-
-ndb.run_lbm = function(pos, nodep)
- return advtrains.pcall(function()
- local node=nodep
- if not node then
- node=minetest.get_node_or_nil(pos)
- if not node then
- --this is defintely not loaded
- return nil
- end
- end
- local cid=ndbget(pos.x, pos.y, pos.z)
- if cid then
- --if in database, detect changes and apply.
- local nodeid = ndb_nodeids[u14b(cid)]
- local param2 = l2b(cid)
- if not nodeid then
- --something went wrong
- atprint("nodedb: lbm nid not found", pos, "with nid", u14b(cid), "param2", param2, "cid is", cid)
- ndb.update(pos, node)
- else
- if (nodeid~=node.name or param2~=node.param2) then
- local ori_ndef=minetest.registered_nodes[node.name]
- if ori_ndef and ori_ndef.groups.save_in_nodedb then --check if this node has been worldedited, and don't replace then
- atprint("nodedb: lbm replaced", pos, "with nodeid", nodeid, "param2", param2, "cid is", cid)
- minetest.swap_node(pos, {name=nodeid, param2 = param2})
- local ndef=minetest.registered_nodes[nodeid]
- if ndef and ndef.on_updated_from_nodedb then
- ndef.on_updated_from_nodedb(pos, node)
- end
- return true
- else
- ndb.clear(pos)
- end
- end
- end
- else
- --if not in database, take it.
- atprint("nodedb: ", pos, "not in database")
- ndb.update(pos, node)
- end
- return false
- end)
- end
-
-
-minetest.register_abm({
- name = "advtrains:nodedb_on_load_update",
- nodenames = {"group:save_in_nodedb"},
- run_at_every_load = true,
- action = ndb.run_lbm,
- interval=10,
- chance=1,
- })
-
---used when restoring stuff after a crash
-ndb.restore_all = function()
- atwarn("Updating the map from the nodedb, this may take a while")
- local cnt=0
- for y, ny in pairs(ndb_nodes) do
- for x, nx in pairs(ny) do
- for z, _ in pairs(nx) do
- if ndb.run_lbm({x=x, y=y, z=z}) then
- cnt=cnt+1
- end
- end
- end
- end
- atwarn("Updated",cnt,"nodes")
-end
-
-minetest.register_on_dignode(function(pos, oldnode, digger)
- return advtrains.pcall(function()
- ndb.clear(pos)
- end)
-end)
-
-function ndb.get_nodes()
- return ndb_nodes
-end
-function ndb.get_nodeids()
- return ndb_nodeids
-end
-
-
-advtrains.ndb=ndb
-
diff --git a/advtrains/advtrains/settingtypes.txt b/advtrains/advtrains/settingtypes.txt
deleted file mode 100644
index 537451b..0000000
--- a/advtrains/advtrains/settingtypes.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-# Whether to print debug information on advtrains to chat and debug.txt
-# Ob Debuginformationen in die Chatkonsole und debug.txt ausgegeben werden sollen
-advtrains_debug (Print advtrains debug messages) bool false \ No newline at end of file
diff --git a/advtrains/advtrains/signals.lua b/advtrains/advtrains/signals.lua
deleted file mode 100644
index 77d0aef..0000000
--- a/advtrains/advtrains/signals.lua
+++ /dev/null
@@ -1,229 +0,0 @@
---advtrains by orwell96
---signals.lua
-
---this code /should/ work but does not.
-local mrules_wallsignal = advtrains.meseconrules
-
-for r,f in pairs({on={as="off", ls="green", als="red"}, off={as="on", ls="red", als="green"}}) do
-
- advtrains.trackplacer.register_tracktype("advtrains:retrosignal", "")
- advtrains.trackplacer.register_tracktype("advtrains:signal", "")
-
- for rotid, rotation in ipairs({"", "_30", "_45", "_60"}) do
- local crea=1
- if rotid==1 and r=="off" then crea=0 end
-
- minetest.register_node("advtrains:retrosignal_"..r..rotation, {
- drawtype = "mesh",
- paramtype="light",
- paramtype2="facedir",
- walkable = false,
- selection_box = {
- type = "fixed",
- fixed = {-1/4, -1/2, -1/4, 1/4, 2, 1/4},
- },
- mesh = "advtrains_retrosignal_"..r..rotation..".b3d",
- tiles = {"advtrains_retrosignal.png"},
- inventory_image="advtrains_retrosignal_inv.png",
- drop="advtrains:retrosignal_off",
- description=attrans("Lampless Signal (@1)", attrans(r..rotation)),
- on_rightclick=switchfunc,
- sunlight_propagates=true,
- groups = {
- cracky=3,
- not_blocking_trains=1,
- not_in_creative_inventory=crea,
- save_in_nodedb=1,
- },
- mesecons = {effector = {
- rules=advtrains.meseconrules,
- ["action_"..f.as] = function (pos, node)
- advtrains.ndb.swap_node(pos, {name = "advtrains:retrosignal_"..f.as..rotation, param2 = node.param2})
- end
- }},
- on_rightclick=function(pos, node, player)
- if minetest.check_player_privs(player:get_player_name(), {train_operator=true}) then
- advtrains.ndb.swap_node(pos, {name = "advtrains:retrosignal_"..f.as..rotation, param2 = node.param2})
- end
- end,
- })
- advtrains.trackplacer.add_worked("advtrains:retrosignal", r, rotation, nil)
- minetest.register_node("advtrains:signal_"..r..rotation, {
- drawtype = "mesh",
- paramtype="light",
- paramtype2="facedir",
- walkable = false,
- selection_box = {
- type = "fixed",
- fixed = {-1/4, -1/2, -1/4, 1/4, 2, 1/4},
- },
- mesh = "advtrains_signal"..rotation..".b3d",
- tiles = {"advtrains_signal_"..r..".png"},
- inventory_image="advtrains_signal_inv.png",
- drop="advtrains:signal_off",
- description=attrans("Signal (@1)", attrans(r..rotation)),
- on_rightclick=switchfunc,
- groups = {
- cracky=3,
- not_blocking_trains=1,
- not_in_creative_inventory=crea,
- save_in_nodedb=1,
- },
- light_source = 1,
- sunlight_propagates=true,
- mesecons = {effector = {
- rules=advtrains.meseconrules,
- ["action_"..f.as] = function (pos, node)
- advtrains.ndb.swap_node(pos, {name = "advtrains:signal_"..f.as..rotation, param2 = node.param2})
- end
- }},
- luaautomation = {
- getstate = f.ls,
- setstate = function(pos, node, newstate)
- if newstate == f.als then
- advtrains.ndb.swap_node(pos, {name = "advtrains:signal_"..f.as..rotation, param2 = node.param2})
- end
- end,
- },
- on_rightclick=function(pos, node, player)
- if minetest.check_player_privs(player:get_player_name(), {train_operator=true}) then
- advtrains.ndb.swap_node(pos, {name = "advtrains:signal_"..f.as..rotation, param2 = node.param2})
- end
- end,
- })
- advtrains.trackplacer.add_worked("advtrains:signal", r, rotation, nil)
- end
-
- local crea=1
- if r=="off" then crea=0 end
-
- --tunnel signals. no rotations.
- for loc, sbox in pairs({l={-1/2, -1/2, -1/4, 0, 1/2, 1/4}, r={0, -1/2, -1/4, 1/2, 1/2, 1/4}, t={-1/2, 0, -1/4, 1/2, 1/2, 1/4}}) do
- minetest.register_node("advtrains:signal_wall_"..loc.."_"..r, {
- drawtype = "mesh",
- paramtype="light",
- paramtype2="facedir",
- walkable = false,
- selection_box = {
- type = "fixed",
- fixed = sbox,
- },
- mesh = "advtrains_signal_wall_"..loc..".b3d",
- tiles = {"advtrains_signal_wall_"..r..".png"},
- drop="advtrains:signal_wall_"..loc.."_off",
- description=attrans("Wallmounted Signal ("..loc..")"),
- groups = {
- cracky=3,
- not_blocking_trains=1,
- not_in_creative_inventory=crea,
- save_in_nodedb=1,
- },
- light_source = 1,
- sunlight_propagates=true,
- mesecons = {effector = {
- rules = mrules_wallsignal,
- ["action_"..f.as] = function (pos, node)
- advtrains.ndb.swap_node(pos, {name = "advtrains:signal_wall_"..loc.."_"..f.as, param2 = node.param2})
- end
- }},
- luaautomation = {
- getstate = f.ls,
- setstate = function(pos, node, newstate)
- if newstate == f.als then
- advtrains.ndb.swap_node(pos, {name = "advtrains:signal_wall_"..loc.."_"..f.as, param2 = node.param2})
- end
- end,
- },
- on_rightclick=function(pos, node, player)
- if minetest.check_player_privs(player:get_player_name(), {train_operator=true}) then
- advtrains.ndb.swap_node(pos, {name = "advtrains:signal_wall_"..loc.."_"..f.as, param2 = node.param2})
- end
- end,
- })
- end
-end
-
--- level crossing
--- german version (Andrew's Cross)
-minetest.register_node("advtrains:across_off", {
- drawtype = "mesh",
- paramtype="light",
- paramtype2="facedir",
- walkable = false,
- selection_box = {
- type = "fixed",
- fixed = {-1/4, -1/2, -1/2, 1/4, 1.5, 0},
- },
- mesh = "advtrains_across.obj",
- tiles = {"advtrains_across.png"},
- drop="advtrains:across_off",
- description=attrans("Andrew's Cross"),
- groups = {
- cracky=3,
- not_blocking_trains=1,
- save_in_nodedb=1,
- not_in_creative_inventory=nil,
- },
- light_source = 1,
- sunlight_propagates=true,
- mesecons = {effector = {
- rules = advtrains.meseconrules,
- action_on = function (pos, node)
- advtrains.ndb.swap_node(pos, {name = "advtrains:across_on", param2 = node.param2})
- end
- }},
- luaautomation = {
- getstate = "off",
- setstate = function(pos, node, newstate)
- if newstate == "on" then
- advtrains.ndb.swap_node(pos, {name = "advtrains:across_on", param2 = node.param2})
- end
- end,
- },
- on_rightclick=function(pos, node, player)
- if minetest.check_player_privs(player:get_player_name(), {train_operator=true}) then
- advtrains.ndb.swap_node(pos, {name = "advtrains:across_on", param2 = node.param2})
- end
- end,
-})
-minetest.register_node("advtrains:across_on", {
- drawtype = "mesh",
- paramtype="light",
- paramtype2="facedir",
- walkable = false,
- selection_box = {
- type = "fixed",
- fixed = {-1/4, -1/2, -1/2, 1/4, 1.5, 0},
- },
- mesh = "advtrains_across.obj",
- tiles = {{name="advtrains_across_anim.png", animation={type="vertical_frames", aspect_w=64, aspect_h=64, length=1.0}}},
- drop="advtrains:across_off",
- description=attrans("Andrew's Cross (on) (you hacker you)"),
- groups = {
- cracky=3,
- not_blocking_trains=1,
- save_in_nodedb=1,
- not_in_creative_inventory=1,
- },
- light_source = 1,
- sunlight_propagates=true,
- mesecons = {effector = {
- rules = advtrains.meseconrules,
- action_off = function (pos, node)
- advtrains.ndb.swap_node(pos, {name = "advtrains:across_off", param2 = node.param2})
- end
- }},
- luaautomation = {
- getstate = "on",
- setstate = function(pos, node, newstate)
- if newstate == "off" then
- advtrains.ndb.swap_node(pos, {name = "advtrains:across_off", param2 = node.param2})
- end
- end,
- },
- on_rightclick=function(pos, node, player)
- if minetest.check_player_privs(player:get_player_name(), {train_operator=true}) then
- advtrains.ndb.swap_node(pos, {name = "advtrains:across_off", param2 = node.param2})
- end
- end,
-})
diff --git a/advtrains/advtrains/textures/advtrains_couple.png b/advtrains/advtrains/textures/advtrains_couple.png
deleted file mode 100644
index 9e997e4..0000000
--- a/advtrains/advtrains/textures/advtrains_couple.png
+++ /dev/null
Binary files differ
diff --git a/advtrains/advtrains/textures/advtrains_discouple.png b/advtrains/advtrains/textures/advtrains_discouple.png
deleted file mode 100644
index b27c4fb..0000000
--- a/advtrains/advtrains/textures/advtrains_discouple.png
+++ /dev/null
Binary files differ
diff --git a/advtrains/advtrains/trackdb_legacy.lua b/advtrains/advtrains/trackdb_legacy.lua
deleted file mode 100644
index 99349e8..0000000
--- a/advtrains/advtrains/trackdb_legacy.lua
+++ /dev/null
@@ -1,27 +0,0 @@
---trackdb_legacy.lua
---loads the (old) track database. the only use for this is to provide data for rails that haven't been written into the ndb database.
---nothing will be saved.
---if the user thinks that he has loaded every track in his world at least once, he can delete the track database.
-
---trackdb[[y][x][z]={conn1, conn2, rely1, rely2, railheight}
-
-
---trackdb keeps its own save file.
-advtrains.fpath_tdb=minetest.get_worldpath().."/advtrains_trackdb2"
-local file, err = io.open(advtrains.fpath_tdb, "r")
-if not file then
- atprint("Not loading a trackdb file.")
-else
- local tbl = minetest.deserialize(file:read("*a"))
- if type(tbl) == "table" then
- advtrains.trackdb=tbl
- atprint("Loaded trackdb file.")
- end
- file:close()
-end
-
-
-
-
-
-
diff --git a/advtrains/advtrains/trackplacer.lua b/advtrains/advtrains/trackplacer.lua
deleted file mode 100644
index 105b77e..0000000
--- a/advtrains/advtrains/trackplacer.lua
+++ /dev/null
@@ -1,305 +0,0 @@
---trackplacer.lua
---holds code for the track-placing system. the default 'track' item will be a craftitem that places rails as needed. this will neither place or change switches nor place vertical rails.
-
---all new trackplacer code
-local tp={
- tracks={}
-}
-
-function tp.register_tracktype(nnprefix, n_suffix)
- if tp.tracks[nnprefix] then return end--due to the separate registration of slopes and flats for the same nnpref, definition would be overridden here. just don't.
- tp.tracks[nnprefix]={
- default=n_suffix,
- single_conn={},
- double_conn={},
- --keys:conn1_conn2 (example:1_4)
- --values:{name=x, param2=x}
- twcycle={},
- twrotate={},--indexed by suffix, list, tells order of rotations
- modify={}
- }
-end
-function tp.add_double_conn(nnprefix, suffix, rotation, conns)
- local nodename=nnprefix.."_"..suffix..rotation
- for i=0,3 do
- tp.tracks[nnprefix].double_conn[((conns.conn1+4*i)%16).."_"..((conns.conn2+4*i)%16)]={name=nodename, param2=i}
- tp.tracks[nnprefix].double_conn[((conns.conn2+4*i)%16).."_"..((conns.conn1+4*i)%16)]={name=nodename, param2=i}
- end
- tp.tracks[nnprefix].modify[nodename]=true
-end
-function tp.add_single_conn(nnprefix, suffix, rotation, conns)
- local nodename=nnprefix.."_"..suffix..rotation
- for i=0,3 do
- tp.tracks[nnprefix].single_conn[((conns.conn1+4*i)%16)]={name=nodename, param2=i}
- tp.tracks[nnprefix].single_conn[((conns.conn2+4*i)%16)]={name=nodename, param2=i}
- end
- tp.tracks[nnprefix].modify[nodename]=true
-end
-
-function tp.add_worked(nnprefix, suffix, rotation, cycle_follows)
- tp.tracks[nnprefix].twcycle[suffix]=cycle_follows
- if not tp.tracks[nnprefix].twrotate[suffix] then tp.tracks[nnprefix].twrotate[suffix]={} end
- table.insert(tp.tracks[nnprefix].twrotate[suffix], rotation)
-end
-
-
---[[
- rewrite algorithm.
- selection criteria: these will never be changed or even selected:
- - tracks being already connected on both sides
- - tracks that are already connected on one side but are not bendable to the desired position
- the following situations can occur:
- 1. there are two more than two rails around
- 1.1 there is one or more subset(s) that can be directly connected
- -> choose the first possibility
- 2.2 not
- -> choose the first one and orient straight
- 2. there's exactly 1 rail around
- -> choose and orient straight
- 3. there's no rail around
- -> set straight
-]]
-function tp.find_already_connected(pos)--TODO vertical calculations(check node below)
- local function istrackandbc(pos, conn)
- local cnode=minetest.get_node(advtrains.dirCoordSet(pos, conn))
- local bconn=(conn+8)%16
- if advtrains.is_track_and_drives_on(cnode.name, advtrains.all_tracktypes) then
- local cconn1, cconn2=advtrains.get_track_connections(cnode.name, cnode.param2)
- return cconn1==bconn or cconn2==bconn
- end
- return false
- end
- local dnode=minetest.get_node(pos)
- local dconn1, dconn2=advtrains.get_track_connections(dnode.name, dnode.param2)
- local t={[true]="true", [false]="false"}
- if istrackandbc(pos, dconn1) and istrackandbc(pos, dconn2) then return dconn1, dconn2
- elseif istrackandbc(pos, dconn1) then return dconn1
- elseif istrackandbc(pos, dconn2) then return dconn2
- end
- return nil
-end
-function tp.rail_and_can_be_bent(originpos, conn, nnpref)
- local pos=advtrains.dirCoordSet(originpos, conn)
- local newdir=(conn+8)%16
- local node=minetest.get_node(pos)
- local tr=tp.tracks[nnpref]
- if not advtrains.is_track_and_drives_on(node.name, advtrains.all_tracktypes) then
- return false
- end
- --rail at other end?
- local adj1, adj2=tp.find_already_connected(pos)
- if adj1 and adj2 then
- return false--dont destroy existing track
- elseif adj1 and not adj2 then
- if tr.double_conn[adj1.."_"..newdir] then
- return true--if exists, connect new rail and old end
- end
- return false
- else
- if tr.single_conn[newdir] then--just rotate old rail to right orientation
- return true
- end
- return false
- end
-end
-function tp.bend_rail(originpos, conn, nnpref)
- local pos=advtrains.dirCoordSet(originpos, conn)
- local newdir=(conn+8)%16
- local node=minetest.get_node(pos)
- local tr=tp.tracks[nnpref]
- --is rail already connected? no need to bend.
- local conn1, conn2=advtrains.get_track_connections(node.name, node.param2)
- if newdir==conn1 or newdir==conn2 then
- return
- end
- --rail at other end?
- local adj1, adj2=tp.find_already_connected(pos)
- if adj1 and adj2 then
- return false--dont destroy existing track
- elseif adj1 and not adj2 then
- if tr.double_conn[adj1.."_"..newdir] then
- advtrains.ndb.swap_node(pos, tr.double_conn[adj1.."_"..newdir])
- return true--if exists, connect new rail and old end
- end
- return false
- else
- if tr.single_conn[newdir] then--just rotate old rail to right orientation
- advtrains.ndb.swap_node(pos, tr.single_conn[newdir])
- return true
- end
- return false
- end
-end
-function tp.placetrack(pos, nnpref, placer, itemstack, pointed_thing)
- --1. find all rails that are likely to be connected
- local tr=tp.tracks[nnpref]
- local p_rails={}
- for i=0,15 do
- if tp.rail_and_can_be_bent(pos, i, nnpref) then
- p_rails[#p_rails+1]=i
- end
- end
- if #p_rails==0 then
- minetest.set_node(pos, {name=nnpref.."_"..tr.default})
- if minetest.registered_nodes[nnpref.."_"..tr.default] and minetest.registered_nodes[nnpref.."_"..tr.default].after_place_node then
- minetest.registered_nodes[nnpref.."_"..tr.default].after_place_node(pos, placer, itemstack, pointed_thing)
- end
- elseif #p_rails==1 then
- tp.bend_rail(pos, p_rails[1], nnpref)
- advtrains.ndb.swap_node(pos, tr.single_conn[p_rails[1]])
- local nname=tr.single_conn[p_rails[1]].name
- if minetest.registered_nodes[nname] and minetest.registered_nodes[nname].after_place_node then
- minetest.registered_nodes[nname].after_place_node(pos, placer, itemstack, pointed_thing)
- end
- else
- --iterate subsets
- for k1, conn1 in ipairs(p_rails) do
- for k2, conn2 in ipairs(p_rails) do
- if k1~=k2 then
- if (tr.double_conn[conn1.."_"..conn2]) then
- tp.bend_rail(pos, conn1, nnpref)
- tp.bend_rail(pos, conn2, nnpref)
- advtrains.ndb.swap_node(pos, tr.double_conn[conn1.."_"..conn2])
- local nname=tr.double_conn[conn1.."_"..conn2].name
- if minetest.registered_nodes[nname] and minetest.registered_nodes[nname].after_place_node then
- minetest.registered_nodes[nname].after_place_node(pos, placer, itemstack, pointed_thing)
- end
- return
- end
- end
- end
- end
- --not found
- tp.bend_rail(pos, p_rails[1], nnpref)
- advtrains.ndb.swap_node(pos, tr.single_conn[p_rails[1]])
- local nname=tr.single_conn[p_rails[1]].name
- if minetest.registered_nodes[nname] and minetest.registered_nodes[nname].after_place_node then
- minetest.registered_nodes[nname].after_place_node(pos, placer, itemstack, pointed_thing)
- end
- end
-end
-
-
-function tp.register_track_placer(nnprefix, imgprefix, dispname)
- minetest.register_craftitem(nnprefix.."_placer",{
- description = dispname,
- inventory_image = imgprefix.."_placer.png",
- wield_image = imgprefix.."_placer.png",
- groups={},
- on_place = function(itemstack, placer, pointed_thing)
- return advtrains.pcall(function()
- local name = placer:get_player_name()
- if not name then
- return itemstack
- end
- if pointed_thing.type=="node" then
- local pos=pointed_thing.above
- local upos=vector.subtract(pointed_thing.above, {x=0, y=1, z=0})
- if advtrains.is_protected(pos,name) then
- minetest.record_protection_violation(pos, name)
- return itemstack
- end
- if minetest.registered_nodes[minetest.get_node(pos).name] and minetest.registered_nodes[minetest.get_node(pos).name].buildable_to
- and minetest.registered_nodes[minetest.get_node(upos).name] and minetest.registered_nodes[minetest.get_node(upos).name].walkable then
- tp.placetrack(pos, nnprefix, placer, itemstack, pointed_thing)
- if not minetest.setting_getbool("creative_mode") then
- itemstack:take_item()
- end
- end
- end
- return itemstack
- end)
- end,
- })
-end
-
-
-
-minetest.register_craftitem("advtrains:trackworker",{
- description = attrans("Track Worker Tool\n\nLeft-click: change rail type (straight/curve/switch)\nRight-click: rotate rail/bumper/signal/etc."),
- groups = {cracky=1}, -- key=name, value=rating; rating=1..3.
- inventory_image = "advtrains_trackworker.png",
- wield_image = "advtrains_trackworker.png",
- stack_max = 1,
- on_place = function(itemstack, placer, pointed_thing)
- return advtrains.pcall(function()
- local name = placer:get_player_name()
- if not name then
- return
- end
- if pointed_thing.type=="node" then
- local pos=pointed_thing.under
- if advtrains.is_protected(pos, name) then
- minetest.record_protection_violation(pos, name)
- return
- end
- local node=minetest.get_node(pos)
-
- --if not advtrains.is_track_and_drives_on(minetest.get_node(pos).name, advtrains.all_tracktypes) then return end
- if advtrains.get_train_at_pos(pos) then return end
-
- local nnprefix, suffix, rotation=string.match(node.name, "^(.+)_([^_]+)(_[^_]+)$")
- --atprint(node.name.."\npattern recognizes:"..nodeprefix.." / "..railtype.." / "..rotation)
- if not tp.tracks[nnprefix] or not tp.tracks[nnprefix].twrotate[suffix] then
- nnprefix, suffix=string.match(node.name, "^(.+)_([^_]+)$")
- rotation = ""
- if not tp.tracks[nnprefix] or not tp.tracks[nnprefix].twrotate[suffix] then
- minetest.chat_send_player(placer:get_player_name(), attrans("This node can't be rotated using the trackworker!"))
- return
- end
- end
- local modext=tp.tracks[nnprefix].twrotate[suffix]
-
- if rotation==modext[#modext] then --increase param2
- advtrains.ndb.swap_node(pos, {name=nnprefix.."_"..suffix..modext[1], param2=(node.param2+1)%4})
- return
- else
- local modpos
- for k,v in pairs(modext) do if v==rotation then modpos=k end end
- if not modpos then
- minetest.chat_send_player(placer:get_player_name(), attrans("This node can't be rotated using the trackworker!"))
- return
- end
- advtrains.ndb.swap_node(pos, {name=nnprefix.."_"..suffix..modext[modpos+1], param2=node.param2})
- end
- end
- end)
- end,
- on_use=function(itemstack, user, pointed_thing)
- return advtrains.pcall(function()
- local name = user:get_player_name()
- if not name then
- return
- end
- if pointed_thing.type=="node" then
- local pos=pointed_thing.under
- local node=minetest.get_node(pos)
- if advtrains.is_protected(pos, name) then
- minetest.record_protection_violation(pos, name)
- return
- end
-
- --if not advtrains.is_track_and_drives_on(minetest.get_node(pos).name, advtrains.all_tracktypes) then return end
- if advtrains.get_train_at_pos(pos) then return end
- local nnprefix, suffix, rotation=string.match(node.name, "^(.+)_([^_]+)(_[^_]+)$")
- --atprint(node.name.."\npattern recognizes:"..nodeprefix.." / "..railtype.." / "..rotation)
- if not tp.tracks[nnprefix] or not tp.tracks[nnprefix].twcycle[suffix] then
- nnprefix, suffix=string.match(node.name, "^(.+)_([^_]+)$")
- rotation = ""
- if not tp.tracks[nnprefix] or not tp.tracks[nnprefix].twcycle[suffix] then
- minetest.chat_send_player(user:get_player_name(), attrans("This node can't be changed using the trackworker!"))
- return
- end
- end
- local nextsuffix=tp.tracks[nnprefix].twcycle[suffix]
- advtrains.ndb.swap_node(pos, {name=nnprefix.."_"..nextsuffix..rotation, param2=node.param2})
-
- else
- atprint(name, dump(tp.tracks))
- end
- end)
- end,
-})
-
---putting into right place
-advtrains.trackplacer=tp
diff --git a/advtrains/advtrains/tracks.lua b/advtrains/advtrains/tracks.lua
deleted file mode 100644
index b390c6a..0000000
--- a/advtrains/advtrains/tracks.lua
+++ /dev/null
@@ -1,734 +0,0 @@
---advtrains by orwell96, see readme.txt
-
---dev-time settings:
---EDIT HERE
---If the old non-model rails on straight tracks should be replaced by the new...
---false: no
---true: yes
-advtrains.register_replacement_lbms=false
-
---[[TracksDefinition
-nodename_prefix
-texture_prefix
-description
-common={}
-straight={}
-straight45={}
-curve={}
-curve45={}
-lswitchst={}
-lswitchst45={}
-rswitchst={}
-rswitchst45={}
-lswitchcr={}
-lswitchcr45={}
-rswitchcr={}
-rswitchcr45={}
-vert1={
- --you'll probably want to override mesh here
-}
-vert2={
- --you'll probably want to override mesh here
-}
-]]--
-advtrains.all_tracktypes={}
-
---definition preparation
-local function conns(c1, c2, r1, r2, rh, rots) return {conn1=c1, conn2=c2, rely1=r1, rely2=r2, railheight=rh} end
-
-local ap={}
-ap.t_30deg_flat={
- regstep=1,
- variant={
- st=conns(0,8),
- cr=conns(0,7),
- swlst=conns(0,8),
- swlcr=conns(0,7),
- swrst=conns(0,8),
- swrcr=conns(0,9),
- },
- description={
- st="straight",
- cr="curve",
- swlst="left switch (straight)",
- swlcr="left switch (curve)",
- swrst="right switch (straight)",
- swrcr="right switch (curve)",
- },
- switch={
- swlst="swlcr",
- swlcr="swlst",
- swrst="swrcr",
- swrcr="swrst",
- },
- switchmc={
- swlst="on",
- swlcr="off",
- swrst="on",
- swrcr="off",
- },
- switchst={
- swlst="st",
- swlcr="cr",
- swrst="st",
- swrcr="cr",
- },
- regtp=true,
- trackplacer={
- st=true,
- cr=true,
- },
- tpsingle={
- st=true,
- },
- tpdefault="st",
- trackworker={
- ["swrcr"]="st",
- ["swrst"]="st",
- ["st"]="cr",
- ["cr"]="swlst",
- ["swlcr"]="swrcr",
- ["swlst"]="swrst",
- },
- rotation={"", "_30", "_45", "_60"},
- slopenodes={},
- increativeinv={},
-}
-ap.t_30deg_slope={
- regstep=1,
- variant={
- vst1=conns(8,0,0,0.5,0.25),
- vst2=conns(8,0,0.5,1,0.75),
- vst31=conns(8,0,0,0.33,0.16),
- vst32=conns(8,0,0.33,0.66,0.5),
- vst33=conns(8,0,0.66,1,0.83),
- },
- description={
- vst1="steep uphill 1/2",
- vst2="steep uphill 2/2",
- vst31="uphill 1/3",
- vst32="uphill 2/3",
- vst33="uphill 3/3",
- },
- switch={},
- switchmc={},
- switchst={},
- regsp=true,
- slopenodes={
- vst1=true, vst2=true,
- vst31=true, vst32=true, vst33=true,
- },
- slopeplacer={
- [2]={"vst1", "vst2"},
- [3]={"vst31", "vst32", "vst33"},
- max=3,--highest entry
- },
- slopeplacer_45={
- [2]={"vst1_45", "vst2_45"},
- max=2,
- },
- rotation={"", "_30", "_45", "_60"},
- trackworker={},
- increativeinv={},
-}
-ap.t_30deg_straightonly={
- regstep=1,
- variant={
- st=conns(0,8),
- },
- description={
- st="straight",
- },
- switch={
- },
- switchmc={
- },
- regtp=true,
- trackplacer={
- },
- tpsingle={
- },
- tpdefault="st",
- trackworker={
- ["st"]="st",
- },
- slopenodes={},
- rotation={"", "_30", "_45", "_60"},
- increativeinv={st},
-}
-ap.t_30deg_straightonly_noplacer={
- regstep=1,
- variant={
- st=conns(0,8),
- },
- description={
- st="straight",
- },
- switch={
- },
- switchmc={
- },
- regtp=false,
- trackplacer={
- },
- tpsingle={
- },
- tpdefault="st",
- trackworker={
- ["st"]="st",
- },
- slopenodes={},
- rotation={"", "_30", "_45", "_60"},
- increativeinv={st},
-}
-ap.t_45deg={
- regstep=2,
- variant={
- st=conns(0,8),
- cr=conns(0,6),
- swlst=conns(0,8),
- swlcr=conns(0,6),
- swrst=conns(0,8),
- swrcr=conns(0,10),
- vst1=conns(8,0,0,0.5,0.25),
- vst2=conns(8,0,0.5,1,0.75),
- },
- description={
- st="straight",
- cr="curve",
- swlst="left switch (straight)",
- swlcr="left switch (curve)",
- swrst="right switch (straight)",
- swrcr="right switch (curve)",
- vst1="vertical lower node",
- vst2="vertical upper node",
- },
- switch={
- swlst="swlcr",
- swlcr="swlst",
- swrst="swrcr",
- swrcr="swrst",
- },
- switchmc={
- swlst="on",
- swlcr="off",
- swrst="on",
- swrcr="off",
- },
- switchst={
- swlst="st",
- swlcr="cr",
- swrst="st",
- swrcr="cr",
- },
- regtp=true,
- trackplacer={
- st=true,
- cr=true,
- },
- tpsingle={
- st=true,
- },
- tpdefault="st",
- trackworker={
- ["swrcr"]="st",
- ["swrst"]="st",
- ["st"]="cr",
- ["cr"]="swlst",
- ["swlcr"]="swrcr",
- ["swlst"]="swrst",
- },
- slopenodes={},
- rotation={"", "_45"},
- increativeinv={vst1=true, vst2=true}
-}
-advtrains.trackpresets = ap
-
---definition format: ([] optional)
---[[{
- nodename_prefix
- texture_prefix
- [shared_texture]
- models_prefix
- models_suffix (with dot)
- [shared_model]
- formats={
- st,cr,swlst,swlcr,swrst,swrcr,vst1,vst2
- (each a table with indices 0-3, for if to register a rail with this 'rotation' table entry. nil is assumed as 'all', set {} to not register at all)
- }
- common={} change something on common rail appearance
-}]]
-function advtrains.register_tracks(tracktype, def, preset)
- local function make_switchfunc(suffix_target, mesecon_state, is_state)
- local rcswitchfunc=function(pos, node, player)
- if minetest.check_player_privs(player:get_player_name(), {train_operator=true}) then
- advtrains.ndb.swap_node(pos, {name=def.nodename_prefix.."_"..suffix_target, param2=node.param2})
- advtrains.invalidate_all_paths(pos)
- end
- end
- local switchfunc=function(pos, node, newstate)
- if newstate~=is_state then
- advtrains.ndb.swap_node(pos, {name=def.nodename_prefix.."_"..suffix_target, param2=node.param2})
- advtrains.invalidate_all_paths(pos)
- end
- end
- local mesec
- if mesecon_state then -- if mesecons is not wanted, do not.
- mesec = {effector = {
- ["action_"..mesecon_state] = switchfunc,
- rules=advtrains.meseconrules
- }}
- end
- return rcswitchfunc, mesec,
- {
- getstate = is_state,
- setstate = switchfunc,
- }
- end
- local function make_overdef(suffix, rotation, conns, rcswitchfunc, mesecontbl, luaautomation, in_creative_inv, drop_slope)
- local img_suffix=suffix..rotation
- return {
- mesh = def.shared_model or (def.models_prefix.."_"..img_suffix..def.models_suffix),
- tiles = {def.shared_texture or (def.texture_prefix.."_"..img_suffix..".png"), def.second_texture},
- --inventory_image = def.texture_prefix.."_"..img_suffix..".png",
- --wield_image = def.texture_prefix.."_"..img_suffix..".png",
- description=def.description.."("..preset.description[suffix]..rotation..")",
- connect1=conns.conn1,
- connect2=conns.conn2,
- rely1=conns.rely1 or 0,
- rely2=conns.rely2 or 0,
- railheight=conns.railheight or 0,
-
- on_rightclick=rcswitchfunc,
- groups = {
- attached_node=1,
- ["advtrains_track_"..tracktype]=1,
- save_in_nodedb=1,
- dig_immediate=2,
- not_in_creative_inventory=(not in_creative_inv and 1 or nil),
- not_blocking_trains=1,
- },
- mesecons=mesecontbl,
- luaautomation=luaautomation,
- drop = increativeinv and def.nodename_prefix.."_"..suffix..rotation or (drop_slope and def.nodename_prefix.."_slopeplacer" or def.nodename_prefix.."_placer"),
- }
- end
- local function cycle_conns(conns, rotid)
- local add=(rotid-1)*preset.regstep
- return {
- conn1=(conns.conn1+add)%16,
- conn2=(conns.conn2+add)%16,
- rely1=conns.rely1 or 0,
- rely2=conns.rely2 or 0,
- railheight=conns.railheight or 0,
- }
- end
- local common_def=advtrains.merge_tables({
- description = def.description,
- drawtype = "mesh",
- paramtype="light",
- paramtype2="facedir",
- walkable = false,
- selection_box = {
- type = "fixed",
- fixed = {-1/2, -1/2, -1/2, 1/2, -1/2+1/16, 1/2},
- },
- rely1=0,
- rely2=0,
- railheight=0,
- drop=def.nodename_prefix.."_placer",
- can_dig=function(pos)
- return not advtrains.get_train_at_pos(pos)
- end,
- after_dig_node=function(pos)
- advtrains.ndb.update(pos)
- end,
- after_place_node=function(pos)
- advtrains.ndb.update(pos)
- end,
- }, def.common or {})
- --make trackplacer base def
- advtrains.trackplacer.register_tracktype(def.nodename_prefix, preset.tpdefault)
- if preset.regtp then
- advtrains.trackplacer.register_track_placer(def.nodename_prefix, def.texture_prefix, def.description)
- end
- if preset.regsp then
- advtrains.slope.register_placer(def, preset)
- end
- for suffix, conns in pairs(preset.variant) do
- for rotid, rotation in ipairs(preset.rotation) do
- if not def.formats[suffix] or def.formats[suffix][rotid] then
- local rcswitchfunc, mesecontbl, luaautomation
- if preset.switch[suffix] then
- rcswitchfunc, mesecontbl, luaautomation=make_switchfunc(preset.switch[suffix]..rotation, preset.switchmc[suffix], preset.switchst[suffix])
- end
- local adef={}
- if def.get_additional_definiton then
- adef=def.get_additional_definiton(def, preset, suffix, rotation)
- end
-
- minetest.register_node(def.nodename_prefix.."_"..suffix..rotation, advtrains.merge_tables(
- common_def,
- make_overdef(
- suffix, rotation,
- cycle_conns(conns, rotid),
- rcswitchfunc, mesecontbl, luaautomation, preset.increativeinv[suffix], preset.slopenodes[suffix]
- ),
- adef
- )
- )
- --trackplacer
- if preset.regtp then
- if preset.trackplacer[suffix] then
- advtrains.trackplacer.add_double_conn(def.nodename_prefix, suffix, rotation, cycle_conns(conns, rotid))
- end
- if preset.tpsingle[suffix] then
- advtrains.trackplacer.add_single_conn(def.nodename_prefix, suffix, rotation, cycle_conns(conns, rotid))
- end
- end
- advtrains.trackplacer.add_worked(def.nodename_prefix, suffix, rotation, preset.trackworker[suffix])
- end
- end
- end
- advtrains.all_tracktypes[tracktype]=true
-end
-
-
-function advtrains.is_track_and_drives_on(nodename, drives_on_p)
- if not minetest.registered_nodes[nodename] then
- return false
- end
- local nodedef=minetest.registered_nodes[nodename]
- for k,v in pairs(drives_on_p) do
- if nodedef.groups["advtrains_track_"..k] then
- return true
- end
- end
- return false
-end
-
-function advtrains.get_track_connections(name, param2)
- local nodedef=minetest.registered_nodes[name]
- if not nodedef then atprint(" get_track_connections couldn't find nodedef for nodename "..(name or "nil")) return 0, 8, 0, 0, 0 end
- local noderot=param2
- if not param2 then noderot=0 end
- if noderot > 3 then atprint(" get_track_connections: rail has invaild param2 of "..noderot) noderot=0 end
-
- local tracktype
- for k,_ in pairs(nodedef.groups) do
- local tt=string.match(k, "^advtrains_track_(.+)$")
- if tt then
- tracktype=tt
- end
- end
- return (nodedef.connect1 + 4 * noderot)%16, (nodedef.connect2 + 4 * noderot)%16, nodedef.rely1 or 0, nodedef.rely2 or 0, nodedef.railheight or 0, tracktype
-end
-
---detector code
---holds a table with nodes on which trains are on.
-
-advtrains.detector = {}
-advtrains.detector.on_node = {}
-
-function advtrains.detector.enter_node(pos, train_id)
- local ppos=advtrains.round_vector_floor_y(pos)
- local pts=minetest.pos_to_string(ppos)
- advtrains.detector.on_node[pts]=train_id
- advtrains.detector.call_enter_callback(ppos, train_id)
-end
-function advtrains.detector.leave_node(pos, train_id)
- local ppos=advtrains.round_vector_floor_y(pos)
- advtrains.detector.call_leave_callback(ppos, train_id)
-end
-function advtrains.detector.stay_node(pos, train_id)
- local ppos=advtrains.round_vector_floor_y(pos)
- local pts=minetest.pos_to_string(ppos)
- advtrains.detector.on_node[pts]=train_id
-end
-
-
-
-function advtrains.detector.call_enter_callback(pos, train_id)
- --atprint("instructed to call enter calback")
-
- local node = advtrains.ndb.get_node(pos) --this spares the check if node is nil, it has a name in any case
- local mregnode=minetest.registered_nodes[node.name]
- if mregnode and mregnode.advtrains and mregnode.advtrains.on_train_enter then
- mregnode.advtrains.on_train_enter(pos, train_id)
- end
-end
-function advtrains.detector.call_leave_callback(pos, train_id)
- --atprint("instructed to call leave calback")
-
- local node = advtrains.ndb.get_node(pos) --this spares the check if node is nil, it has a name in any case
- local mregnode=minetest.registered_nodes[node.name]
- if mregnode and mregnode.advtrains and mregnode.advtrains.on_train_leave then
- mregnode.advtrains.on_train_leave(pos, train_id)
- end
-end
-
--- slope placer. Defined in register_tracks.
---crafted with rail and gravel
-local sl={}
-function sl.register_placer(def, preset)
- minetest.register_craftitem(def.nodename_prefix.."_slopeplacer",{
- description = attrans("@1 Slope", def.description),
- inventory_image = def.texture_prefix.."_slopeplacer.png",
- wield_image = def.texture_prefix.."_slopeplacer.png",
- groups={},
- on_place = sl.create_slopeplacer_on_place(def, preset)
- })
-end
---(itemstack, placer, pointed_thing)
-function sl.create_slopeplacer_on_place(def, preset)
- return function(istack, player, pt)
- if not pt.type=="node" then
- minetest.chat_send_player(player:get_player_name(), attrans("Can't place: not pointing at node"))
- return istack
- end
- local pos=pt.above
- if not pos then
- minetest.chat_send_player(player:get_player_name(), attrans("Can't place: not pointing at node"))
- return istack
- end
- local node=minetest.get_node(pos)
- if not minetest.registered_nodes[node.name] or not minetest.registered_nodes[node.name].buildable_to then
- minetest.chat_send_player(player:get_player_name(), attrans("Can't place: space occupied!"))
- return istack
- end
- if advtrains.is_protected(pos, player:get_player_name()) then
- minetest.record_protection_violation(pos, player:get_player_name())
- return istack
- end
- --determine player orientation (only horizontal component)
- --get_look_horizontal may not be available
- local yaw=player.get_look_horizontal and player:get_look_horizontal() or (player:get_look_yaw() - math.pi/2)
-
- --rounding unit vectors is a nice way for selecting 1 of 8 directions since sin(30°) is 0.5.
- dirvec={x=math.floor(math.sin(-yaw)+0.5), y=0, z=math.floor(math.cos(-yaw)+0.5)}
- --translate to direction to look up inside the preset table
- local param2, rot45=({
- [-1]={
- [-1]=2,
- [0]=3,
- [1]=3,
- },
- [0]={
- [-1]=2,
- [1]=0,
- },
- [1]={
- [-1]=1,
- [0]=1,
- [1]=0,
- },
- })[dirvec.x][dirvec.z], dirvec.x~=0 and dirvec.z~=0
- local lookup=preset.slopeplacer
- if rot45 then lookup=preset.slopeplacer_45 end
-
- --go unitvector forward and look how far the next node is
- local step=1
- while step<=lookup.max do
- local node=minetest.get_node(vector.add(pos, dirvec))
- --next node solid?
- if not minetest.registered_nodes[node.name] or not minetest.registered_nodes[node.name].buildable_to or advtrains.is_protected(pos, player:get_player_name()) then
- --do slopes of this distance exist?
- if lookup[step] then
- if minetest.setting_getbool("creative_mode") or istack:get_count()>=step then
- --start placing
- local placenodes=lookup[step]
- while step>0 do
- minetest.set_node(pos, {name=def.nodename_prefix.."_"..placenodes[step], param2=param2})
- if not minetest.setting_getbool("creative_mode") then
- istack:take_item()
- end
- step=step-1
- pos=vector.subtract(pos, dirvec)
- end
- else
- minetest.chat_send_player(player:get_player_name(), attrans("Can't place: Not enough slope items left (@1 required)", step))
- end
- else
- minetest.chat_send_player(player:get_player_name(), attrans("Can't place: There's no slope of length @1",step))
- end
- return istack
- end
- step=step+1
- pos=vector.add(pos, dirvec)
- end
- minetest.chat_send_player(player:get_player_name(), attrans("Can't place: no supporting node at upper end."))
- return itemstack
- end
-end
-
-advtrains.slope=sl
-
---END code, BEGIN definition
---definition format: ([] optional)
---[[{
- nodename_prefix
- texture_prefix
- [shared_texture]
- models_prefix
- models_suffix (with dot)
- [shared_model]
- formats={
- st,cr,swlst,swlcr,swrst,swrcr,vst1,vst2
- (each a table with indices 0-3, for if to register a rail with this 'rotation' table entry. nil is assumed as 'all', set {} to not register at all)
- }
- common={} change something on common rail appearance
-}]]
-
-advtrains.register_tracks("regular", {
- nodename_prefix="advtrains:track",
- texture_prefix="advtrains_track",
- shared_model="trackplane.b3d",
- description=attrans("Deprecated Track"),
- formats={vst1={}, vst2={}},
-}, ap.t_45deg)
-
---flat
-advtrains.register_tracks("default", {
- nodename_prefix="advtrains:dtrack",
- texture_prefix="advtrains_dtrack",
- models_prefix="advtrains_dtrack",
- models_suffix=".b3d",
- shared_texture="advtrains_dtrack_shared.png",
- description=attrans("Track"),
- formats={},
-}, ap.t_30deg_flat)
---slopes
-advtrains.register_tracks("default", {
- nodename_prefix="advtrains:dtrack",
- texture_prefix="advtrains_dtrack",
- models_prefix="advtrains_dtrack",
- models_suffix=".obj",
- shared_texture="advtrains_dtrack_shared.png",
- second_texture="default_gravel.png",
- description=attrans("Track"),
- formats={vst1={true, false, true}, vst2={true, false, true}, vst31={true}, vst32={true}, vst33={true}},
-}, ap.t_30deg_slope)
-
---bumpers
-advtrains.register_tracks("default", {
- nodename_prefix="advtrains:dtrack_bumper",
- texture_prefix="advtrains_dtrack_bumper",
- models_prefix="advtrains_dtrack_bumper",
- models_suffix=".b3d",
- shared_texture="advtrains_dtrack_rail.png",
- --bumpers still use the old texture until the models are redone.
- description=attrans("Bumper"),
- formats={},
-}, ap.t_30deg_straightonly)
---legacy bumpers
-for _,rot in ipairs({"", "_30", "_45", "_60"}) do
- minetest.register_alias("advtrains:dtrack_bumper"..rot, "advtrains:dtrack_bumper_st"..rot)
-end
-
-if mesecon then
- advtrains.register_tracks("default", {
- nodename_prefix="advtrains:dtrack_detector_off",
- texture_prefix="advtrains_dtrack_detector",
- models_prefix="advtrains_dtrack",
- models_suffix=".b3d",
- shared_texture="advtrains_dtrack_shared_detector_off.png",
- description=attrans("Detector Rail"),
- formats={},
- get_additional_definiton = function(def, preset, suffix, rotation)
- return {
- mesecons = {
- receptor = {
- state = mesecon.state.off,
- rules = advtrains.meseconrules
- }
- },
- advtrains = {
- on_train_enter=function(pos, train_id)
- advtrains.ndb.swap_node(pos, {name="advtrains:dtrack_detector_on".."_"..suffix..rotation, param2=minetest.get_node(pos).param2})
- mesecon.receptor_on(pos, advtrains.meseconrules)
- end
- }
- }
- end
- }, ap.t_30deg_straightonly)
- advtrains.register_tracks("default", {
- nodename_prefix="advtrains:dtrack_detector_on",
- texture_prefix="advtrains_dtrack",
- models_prefix="advtrains_dtrack",
- models_suffix=".b3d",
- shared_texture="advtrains_dtrack_shared_detector_on.png",
- description="Detector(on)(you hacker you)",
- formats={},
- get_additional_definiton = function(def, preset, suffix, rotation)
- return {
- mesecons = {
- receptor = {
- state = mesecon.state.on,
- rules = advtrains.meseconrules
- }
- },
- advtrains = {
- on_train_leave=function(pos, train_id)
- advtrains.ndb.swap_node(pos, {name="advtrains:dtrack_detector_off".."_"..suffix..rotation, param2=minetest.get_node(pos).param2})
- mesecon.receptor_off(pos, advtrains.meseconrules)
- end
- }
- }
- end
- }, ap.t_30deg_straightonly_noplacer)
-end
---TODO legacy
---I know lbms are better for this purpose
-for name,rep in pairs({swl_st="swlst", swr_st="swrst", swl_cr="swlcr", swr_cr="swrcr", }) do
- minetest.register_abm({
- -- In the following two fields, also group:groupname will work.
- nodenames = {"advtrains:track_"..name},
- interval = 1.0, -- Operation interval in seconds
- chance = 1, -- Chance of trigger per-node per-interval is 1.0 / this
- action = function(pos, node, active_object_count, active_object_count_wider) minetest.set_node(pos, {name="advtrains:track_"..rep, param2=node.param2}) end,
- })
- minetest.register_abm({
- -- In the following two fields, also group:groupname will work.
- nodenames = {"advtrains:track_"..name.."_45"},
- interval = 1.0, -- Operation interval in seconds
- chance = 1, -- Chance of trigger per-node per-interval is 1.0 / this
- action = function(pos, node, active_object_count, active_object_count_wider) minetest.set_node(pos, {name="advtrains:track_"..rep.."_45", param2=node.param2}) end,
- })
-end
-
-if advtrains.register_replacement_lbms then
-minetest.register_lbm({
- name = "advtrains:ramp_replacement_1",
--- In the following two fields, also group:groupname will work.
- nodenames = {"advtrains:track_vert1"},
- action = function(pos, node, active_object_count, active_object_count_wider) minetest.set_node(pos, {name="advtrains:dtrack_vst1", param2=(node.param2+2)%4}) end,
-})
-minetest.register_lbm({
- name = "advtrains:ramp_replacement_1",
--- -- In the following two fields, also group:groupname will work.
- nodenames = {"advtrains:track_vert2"},
- action = function(pos, node, active_object_count, active_object_count_wider) minetest.set_node(pos, {name="advtrains:dtrack_vst2", param2=(node.param2+2)%4}) end,
-})
- minetest.register_abm({
- name = "advtrains:st_rep_1",
- -- In the following two fields, also group:groupname will work.
- nodenames = {"advtrains:track_st"},
- interval=1,
- chance=1,
- action = function(pos, node, active_object_count, active_object_count_wider) minetest.set_node(pos, {name="advtrains:dtrack_st", param2=node.param2}) end,
- })
- minetest.register_lbm({
- name = "advtrains:st_rep_1",
- -- -- In the following two fields, also group:groupname will work.
- nodenames = {"advtrains:track_st_45"},
- action = function(pos, node, active_object_count, active_object_count_wider) minetest.set_node(pos, {name="advtrains:dtrack_st_45", param2=node.param2}) end,
- })
-end
-
-
-
-
-
-
-
-
diff --git a/advtrains/advtrains/trainhud.lua b/advtrains/advtrains/trainhud.lua
deleted file mode 100644
index 967acfc..0000000
--- a/advtrains/advtrains/trainhud.lua
+++ /dev/null
@@ -1,125 +0,0 @@
---trainhud.lua: holds all the code for train controlling
-
-advtrains.hud = {}
-
-minetest.register_on_leaveplayer(function(player)
-advtrains.hud[player:get_player_name()] = nil
-end)
-
-local mletter={[1]="F", [-1]="R", [0]="N"}
-local doorstr={[-1]="|<>| >|<", [0]=">|< >|<", [1]=">|< |<>|"}
-
-function advtrains.on_control_change(pc, train, flip)
- if pc.sneak then
- if pc.up then
- train.tarvelocity = train.max_speed or 10
- end
- if pc.down then
- train.tarvelocity = 0
- end
- if pc.left then
- train.tarvelocity = 4
- end
- if pc.right then
- train.tarvelocity = 8
- end
- if pc.jump then
- train.brake = true
- --0: released, 1: brake and pressed, 2: released and brake, 3: pressed and brake
- if not train.brake_hold_state or train.brake_hold_state==0 then
- train.brake_hold_state = 1
- elseif train.brake_hold_state==2 then
- train.brake_hold_state = 3
- end
- elseif train.brake_hold_state==1 then
- train.brake_hold_state = 2
- elseif train.brake_hold_state==3 then
- train.brake = false
- train.brake_hold_state = 0
- end
- --shift+use:see wagons.lua
- else
- if pc.up then
- train.tarvelocity = train.tarvelocity + 1
- end
- if pc.down then
- if train.velocity>0 then
- train.tarvelocity = math.max(train.tarvelocity - 1, 0)
- else
- train.movedir = -train.movedir
- end
- end
- if pc.left then
- if train.door_open ~= 0 then
- train.door_open = 0
- else
- train.door_open = -train.movedir
- end
- end
- if pc.right then
- if train.door_open ~= 0 then
- train.door_open = 0
- else
- train.door_open = train.movedir
- end
- end
- if train.brake_hold_state~=2 then
- train.brake = false
- end
- if pc.jump then
- train.brake = true
- end
- if pc.aux1 then
- --horn
- end
- end
-end
-function advtrains.update_driver_hud(pname, train, flip)
- local inside=train.text_inside or ""
- advtrains.set_trainhud(pname, inside.."\n"..advtrains.hud_train_format(train, flip))
-end
-function advtrains.clear_driver_hud(pname)
- advtrains.set_trainhud(pname, "")
-end
-
-function advtrains.set_trainhud(name, text)
- local hud = advtrains.hud[name]
- local player=minetest.get_player_by_name(name)
- if not player then
- return
- end
- if not hud then
- hud = {}
- advtrains.hud[name] = hud
- hud.id = player:hud_add({
- hud_elem_type = "text",
- name = "ADVTRAINS",
- number = 0xFFFFFF,
- position = {x=0.5, y=0.7},
- offset = {x=0, y=0},
- text = text,
- scale = {x=200, y=60},
- alignment = {x=0, y=0},
- })
- hud.oldText=text
- return
- elseif hud.oldText ~= text then
- player:hud_change(hud.id, "text", text)
- hud.oldText=text
- end
-end
-function advtrains.hud_train_format(train, flip)
- local fct=flip and -1 or 1
- if not train then return "" end
-
- local max=train.max_speed or 10
- local vel=advtrains.abs_ceil(train.velocity)
- local tvel=advtrains.abs_ceil(train.tarvelocity)
- local topLine, firstLine, secondLine
-
- topLine=" ["..mletter[fct*train.movedir].."] "..doorstr[(train.door_open or 0) * train.movedir].." "..(train.brake and "="..( train.brake_hold_state==2 and "^" or "" ).."B=" or "")
- firstLine=attrans("Speed:").." |"..string.rep("+", vel)..string.rep("_", max-vel)..">"
- secondLine=attrans("Target:").." |"..string.rep("+", tvel)..string.rep("_", max-tvel)..">"
-
- return topLine.."\n"..firstLine.."\n"..secondLine
-end
diff --git a/advtrains/advtrains/trainlogic.lua b/advtrains/advtrains/trainlogic.lua
deleted file mode 100644
index 1b862c9..0000000
--- a/advtrains/advtrains/trainlogic.lua
+++ /dev/null
@@ -1,977 +0,0 @@
---trainlogic.lua
---controls train entities stuff about connecting/disconnecting/colliding trains and other things
-
-
-local benchmark=false
-local bm={}
-local bmlt=0
-local bmsteps=0
-local bmstepint=200
-atprintbm=function(action, ta)
- if not benchmark then return end
- local t=(os.clock()-ta)*1000
- if not bm[action] then
- bm[action]=t
- else
- bm[action]=bm[action]+t
- end
- bmlt=bmlt+t
-end
-function endstep()
- if not benchmark then return end
- bmsteps=bmsteps-1
- if bmsteps<=0 then
- bmsteps=bmstepint
- for key, value in pairs(bm) do
- minetest.chat_send_all(key.." "..(value/bmstepint).." ms avg.")
- end
- minetest.chat_send_all("Total time consumed by all advtrains actions per step: "..(bmlt/bmstepint).." ms avg.")
- bm={}
- bmlt=0
- end
-end
-
-advtrains.train_accel_force=2--per second and divided by number of wagons
-advtrains.train_brake_force=3--per second, not divided by number of wagons
-advtrains.train_roll_force=0.5--per second, not divided by number of wagons, acceleration when rolling without brake
-advtrains.train_emerg_force=10--for emergency brakes(when going off track)
-
-
-advtrains.mainloop_trainlogic=function(dtime)
- --build a table of all players indexed by pts. used by damage and door system.
- advtrains.playersbypts={}
- for _, player in pairs(minetest.get_connected_players()) do
- if not advtrains.player_to_train_mapping[player:get_player_name()] then
- --players in train are not subject to damage
- local ptspos=minetest.pos_to_string(vector.round(player:getpos()))
- advtrains.playersbypts[ptspos]=player
- end
- end
- --regular train step
- -- do in two steps:
- -- a: predict path and add all nodes to the advtrains.detector.on_node table
- -- b: check for collisions based on these data
- -- (and more)
- local t=os.clock()
- advtrains.detector.on_node={}
- for k,v in pairs(advtrains.trains) do
- advtrains.atprint_context_tid=sid(k)
- advtrains.train_step_a(k, v, dtime)
- end
- for k,v in pairs(advtrains.trains) do
- advtrains.atprint_context_tid=sid(k)
- advtrains.train_step_b(k, v, dtime)
- end
-
- advtrains.atprint_context_tid=nil
-
- atprintbm("trainsteps", t)
- endstep()
-end
-
-minetest.register_on_joinplayer(function(player)
- return advtrains.pcall(function()
- local pname=player:get_player_name()
- local id=advtrains.player_to_train_mapping[pname]
- if id then
- local train=advtrains.trains[id]
- if not train then advtrains.player_to_train_mapping[pname]=nil return end
- --set the player to the train position.
- --minetest will emerge the area and load the objects, which then will call reattach_all().
- --because player is in mapping, it will not be subject to dying.
- player:setpos(train.last_pos_prev)
- --independent of this, cause all wagons of the train which are loaded to reattach their players
- --needed because already loaded wagons won't call reattach_all()
- for _,wagon in pairs(minetest.luaentities) do
- if wagon.is_wagon and wagon.initialized and wagon.train_id==id then
- wagon:reattach_all()
- end
- end
- end
- end)
-end)
-
-minetest.register_on_dieplayer(function(player)
- return advtrains.pcall(function()
- local pname=player:get_player_name()
- local id=advtrains.player_to_train_mapping[pname]
- if id then
- local train=advtrains.trains[id]
- if not train then advtrains.player_to_train_mapping[pname]=nil return end
- for _,wagon in pairs(minetest.luaentities) do
- if wagon.is_wagon and wagon.initialized and wagon.train_id==id then
- --when player dies, detach him from the train
- --call get_off_plr on every wagon since we don't know which one he's on.
- wagon:get_off_plr(pname)
- end
- end
- end
- end)
-end)
---[[
-train step structure:
-
-
-- legacy stuff
-- preparing the initial path and creating index
-- setting node coverage old indices
-- handle velocity influences:
- - off-track
- - atc
- - player controls
- - environment collision
-- update index = move
-- create path
-- update node coverage
-- do less important stuff such as checking trainpartload or removing
-
--- break --
-- handle train collisions
-
-]]
-
-function advtrains.train_step_a(id, train, dtime)
- --- 1. LEGACY STUFF ---
- if not train.drives_on or not train.max_speed then
- advtrains.update_trainpart_properties(id)
- end
- --TODO check for all vars to be present
- if not train.velocity then
- train.velocity=0
- end
- if not train.movedir or (train.movedir~=1 and train.movedir~=-1) then
- train.movedir=1
- end
- --- 2. prepare initial path and index if needed ---
- if not train.index then train.index=0 end
- if not train.path then
- if not train.last_pos then
- --no chance to recover
- atprint("train hasn't saved last-pos, removing train.")
- advtrains.trains[id]=nil
- return false
- end
-
- local node_ok=advtrains.get_rail_info_at(advtrains.round_vector_floor_y(train.last_pos), train.drives_on)
-
- if node_ok==nil then
- --block not loaded, do nothing
- atprint("last_pos", advtrains.round_vector_floor_y(train.last_pos), "not loaded and not in ndb, waiting")
- return nil
- elseif node_ok==false then
- atprint("no track here, (fail) removing train.")
- advtrains.trains[id]=nil
- return false
- end
-
- if not train.last_pos_prev then
- --no chance to recover
- atprint("train hasn't saved last-pos_prev, removing train.")
- advtrains.trains[id]=nil
- return false
- end
-
- local prevnode_ok=advtrains.get_rail_info_at(advtrains.round_vector_floor_y(train.last_pos_prev), train.drives_on)
-
- if prevnode_ok==nil then
- --block not loaded, do nothing
- atprint("last_pos_prev", advtrains.round_vector_floor_y(train.last_pos_prev), "not loaded and not in ndb, waiting")
- return nil
- elseif prevnode_ok==false then
- atprint("no track at prev, (fail) removing train.")
- advtrains.trains[id]=nil
- return false
- end
-
- train.index=(train.restore_add_index or 0)+(train.savedpos_off_track_index_offset or 0)
- --restore_add_index is set by save() to prevent trains hopping to next round index. should be between -0.5 and 0.5
- --savedpos_off_track_index_offset is set if train went off track. see below.
- train.path={}
- train.path_dist={}
- train.path[0]=train.last_pos
- train.path[-1]=train.last_pos_prev
- train.path_dist[-1]=vector.distance(train.last_pos, train.last_pos_prev)
- train.path_extent_min=-1
- train.path_extent_max=0
- --[[
- Bugfix for trains randomly ignoring ATC rails:
- - Paths have been invalidated. 1 gets executed and ensures an initial path
- - 2a sets train end index. The problem is that path_dist is not known for the whole path, so train end index will be nearly trainlen
- - Since the detector indices are also unknown, they get set to the new (wrong) train_end_index. Enter_node calls are not executed for the nodes that lie in between real end_index and trainlen.
- - The next step, mistake is recognized, train leaves some positions. From there, everything works again.
- To overcome this, we will generate the full required path here so that path_dist is available for get_train_end_index().
- ]]
- advtrains.pathpredict(id, train)
- end
-
- --- 2a. set train.end_index which is required in different places, IF IT IS NOT SET YET by STMT afterwards. ---
- --- table entry to avoid triple recalculation ---
- if not train.end_index then
- train.end_index=advtrains.get_train_end_index(train)
- end
-
- --- 2b. set node coverage old indices ---
-
- train.detector_old_index = math.floor(train.index)
- train.detector_old_end_index = math.floor(train.end_index)
-
- --- 3. handle velocity influences ---
- local train_moves=(train.velocity~=0)
-
- if train.recently_collided_with_env then
- train.tarvelocity=0
- if not train_moves then
- train.recently_collided_with_env=false--reset status when stopped
- end
- end
- if train.locomotives_in_train==0 then
- train.tarvelocity=0
- end
-
- --- 3a. this can be useful for debugs/warnings and is used for check_trainpartload ---
- local t_info, train_pos=sid(id), train.path[math.floor(train.index)]
- if train_pos then
- t_info=t_info.." @"..minetest.pos_to_string(train_pos)
- end
-
- --apply off-track handling:
- local front_off_track=train.max_index_on_track and train.index>train.max_index_on_track
- local back_off_track=train.min_index_on_track and train.end_index<train.min_index_on_track
- local pprint
-
- if front_off_track and back_off_track then--allow movement in both directions
- if train.tarvelocity>1 then
- train.tarvelocity=1
- atwarn("Train",t_info,"is off track at both ends. Clipping velocity to 1")
- pprint=true
- end
- elseif front_off_track then--allow movement only backward
- if train.movedir==1 and train.tarvelocity>0 then
- train.tarvelocity=0
- atwarn("Train",t_info,"is off track. Trying to drive further out. Velocity clipped to 0")
- pprint=true
- end
- if train.movedir==-1 and train.tarvelocity>1 then
- train.tarvelocity=1
- atwarn("Train",t_info,"is off track. Velocity clipped to 1")
- pprint=true
- end
- elseif back_off_track then--allow movement only forward
- if train.movedir==-1 and train.tarvelocity>0 then
- train.tarvelocity=0
- atwarn("Train",t_info,"is off track. Trying to drive further out. Velocity clipped to 0")
- pprint=true
- end
- if train.movedir==1 and train.tarvelocity>1 then
- train.tarvelocity=1
- atwarn("Train",t_info,"is off track. Velocity clipped to 1")
- pprint=true
- end
- end
- if pprint then
- atprint("max_iot", train.max_index_on_track, "min_iot", train.min_index_on_track, "<> index", train.index, "end_index", train.end_index)
- end
-
- --interpret ATC command
- if train.atc_brake_target and train.atc_brake_target>=train.velocity then
- train.atc_brake_target=nil
- end
- if train.atc_wait_finish then
- if not train.atc_brake_target and train.velocity==train.tarvelocity then
- train.atc_wait_finish=nil
- end
- end
- if train.atc_command then
- if train.atc_delay<=0 and not train.atc_wait_finish then
- advtrains.atc.execute_atc_command(id, train)
- else
- train.atc_delay=train.atc_delay-dtime
- end
- end
-
- --make brake adjust the tarvelocity if necessary
- if train.brake and (math.ceil(train.velocity)-1)<train.tarvelocity then
- train.tarvelocity=math.max((math.ceil(train.velocity)-1), 0)
- end
-
- --- 3a. actually calculate new velocity ---
- if train.velocity~=train.tarvelocity then
- local applydiff=0
- local mass=#train.trainparts
- local diff=train.tarvelocity-train.velocity
- if diff>0 then--accelerating, force will be brought on only by locomotives.
- --atprint("accelerating with default force")
- applydiff=(math.min((advtrains.train_accel_force*train.locomotives_in_train*dtime)/mass, math.abs(diff)))
- else--decelerating
- if front_off_track or back_off_track or train.recently_collided_with_env then --every wagon has a brake, so not divided by mass.
- --atprint("braking with emergency force")
- applydiff= -(math.min((advtrains.train_emerg_force*dtime), math.abs(diff)))
- elseif train.brake or (train.atc_brake_target and train.atc_brake_target<train.velocity) then
- --atprint("braking with default force")
- --no math.min, because it can grow beyond tarvelocity, see up there
- --dont worry, it will never fall below zero.
- applydiff= -((advtrains.train_brake_force*dtime))
- else
- --atprint("roll")
- applydiff= -(math.min((advtrains.train_roll_force*dtime), math.abs(diff)))
- end
- end
- train.last_accel=(applydiff*train.movedir)
- train.velocity=math.min(math.max( train.velocity+applydiff , 0), train.max_speed or 10)
- else
- train.last_accel=0
- end
-
- --- 4. move train ---
-
- train.index=train.index and train.index+(((train.velocity*train.movedir)/(train.path_dist[math.floor(train.index)] or 1))*dtime) or 0
-
- --- 4a. update train.end_index to the new position ---
- train.end_index=advtrains.get_train_end_index(train)
-
- --- 5. extend path as necessary ---
- --why this is an extra function, see under 3.
- advtrains.pathpredict(id, train, true)
-
- --- 5a. make pos/yaw available for possible recover calls ---
- if train.max_index_on_track<train.index then --whoops, train went too far. the saved position will be the last one that lies on a track, and savedpos_off_track_index_offset will hold how far to go from here
- train.savedpos_off_track_index_offset=train.index-train.max_index_on_track
- train.last_pos=train.path[train.max_index_on_track]
- train.last_pos_prev=train.path[train.max_index_on_track-1]
- atprint("train is off-track (front), last positions kept at", train.last_pos, "/", train.last_pos_prev)
- elseif train.min_index_on_track+1>train.index then --whoops, train went even more far. same behavior
- train.savedpos_off_track_index_offset=train.index-train.min_index_on_track
- train.last_pos=train.path[train.min_index_on_track+1]
- train.last_pos_prev=train.path[train.min_index_on_track]
- atprint("train is off-track (back), last positions kept at", train.last_pos, "/", train.last_pos_prev)
- else --regular case
- train.savedpos_off_track_index_offset=nil
- train.last_pos=train.path[math.floor(train.index+0.5)]
- train.last_pos_prev=train.path[math.floor(train.index-0.5)]
- end
-
- --- 5b. Remove path items that are no longer used ---
- -- Necessary since path items are no longer invalidated in save steps
- local path_pregen_keep=20
- local offtrack_keep=4
- local gen_front_keep= path_pregen_keep
- local gen_back_keep= - train.trainlen - path_pregen_keep
-
- local delete_min=math.min(train.max_index_on_track - offtrack_keep, math.floor(train.index)+gen_back_keep)
- local delete_max=math.max(train.min_index_on_track + offtrack_keep, math.floor(train.index)+gen_front_keep)
-
- if train.path_extent_min<delete_min then
- atprint(sid(id),"clearing path min ",train.path_extent_min," to ",delete_min)
- for i=train.path_extent_min,delete_min-1 do
- train.path[i]=nil
- train.path_dist[i]=nil
- end
- train.path_extent_min=delete_min
- train.min_index_on_track=math.max(train.min_index_on_track, delete_min)
- end
- if train.path_extent_max>delete_max then
- atprint(sid(id),"clearing path max ",train.path_extent_max," to ",delete_max)
- train.path_dist[delete_max]=nil
- for i=delete_max+1,train.path_extent_max do
- train.path[i]=nil
- train.path_dist[i]=nil
- end
- train.path_extent_max=delete_max
- train.max_index_on_track=math.min(train.max_index_on_track, delete_max)
- end
-
- --- 6. update node coverage ---
-
- -- when paths get cleared, the old indices set above will be up-to-date and represent the state in which the last run of this code was made
- local ifo, ifn, ibo, ibn = train.detector_old_index, math.floor(train.index), train.detector_old_end_index, math.floor(train.end_index)
-
- local path=train.path
-
- if train.enter_node_all then
- --field set by create_new_train_at.
- --ensures that new train calls enter_node on all nodes
- for i=ibn, ifn do
- if path[i] then
- advtrains.detector.enter_node(path[i], id)
- end
- end
- train.enter_node_all=nil
- else
- for i=ibn, ifn do
- if path[i] then
- advtrains.detector.stay_node(path[i], id)
- end
- end
-
- if ifn>ifo then
- for i=ifo+1, ifn do
- if path[i] then
- local pts=minetest.pos_to_string(path[i])
- if advtrains.detector.on_node[pts] and advtrains.detector.on_node[pts]~=id then
- --if another train has signed up for this position first, it won't be recognized in train_step_b. So do collision here.
- advtrains.collide_and_spawn_couple(id, path[i], advtrains.detector.on_node[pts], false)
- end
- advtrains.detector.enter_node(path[i], id)
- end
- end
- elseif ifn<ifo then
- for i=ifn+1, ifo do
- if path[i] then
- advtrains.detector.leave_node(path[i], id)
- end
- end
- end
- if ibn<ibo then
- for i=ibn, ibo-1 do
- if path[i] then
- local pts=minetest.pos_to_string(path[i])
- if advtrains.detector.on_node[pts] and advtrains.detector.on_node[pts]~=id then
- --if another train has signed up for this position first, it won't be recognized in train_step_b. So do collision here.
- advtrains.collide_and_spawn_couple(id, path[i], advtrains.detector.on_node[pts], false)
- end
- advtrains.detector.enter_node(path[i], id)
- end
- end
- elseif ibn>ibo then
- for i=ibo, ibn-1 do
- if path[i] then
- advtrains.detector.leave_node(path[i], id)
- end
- end
- end
- end
-
- --- 7. do less important stuff ---
- --check for any trainpart entities if they have been unloaded. do this only if train is near a player, to not spawn entities into unloaded areas
-
- train.check_trainpartload=(train.check_trainpartload or 0)-dtime
- local node_range=(math.max((minetest.setting_get("active_block_range") or 0),1)*16)
- if train.check_trainpartload<=0 then
- local ori_pos=train_pos --see 3a.
- --atprint("[train "..id.."] at "..minetest.pos_to_string(vector.round(ori_pos)))
-
- local should_check=false
- for _,p in ipairs(minetest.get_connected_players()) do
- should_check=should_check or ((vector.distance(ori_pos, p:getpos())<node_range))
- end
- if should_check then
- advtrains.update_trainpart_properties(id)
- end
- train.check_trainpartload=2
- end
- --remove?
- if #train.trainparts==0 then
- atprint("[train "..sid(id).."] has empty trainparts, removing.")
- advtrains.detector.leave_node(path[train.detector_old_index], id)
- advtrains.trains[id]=nil
- return
- end
-end
-
---about regular: Used by 1. to ensure path gets generated far enough, since end index is not known at this time.
-function advtrains.pathpredict(id, train, regular)
- --TODO duplicate code under 5b.
- local path_pregen=10
-
- local gen_front= path_pregen
- local gen_back= - train.trainlen - path_pregen
- if regular then
- gen_front=math.max(train.index, train.detector_old_index) + path_pregen
- gen_back=math.min(train.end_index, train.detector_old_end_index) - path_pregen
- end
-
- local maxn=train.path_extent_max or 0
- while maxn < gen_front do--pregenerate
- atprint("maxn conway for ",maxn,train.path[maxn],maxn-1,train.path[maxn-1])
- local conway=advtrains.conway(train.path[maxn], train.path[maxn-1], train.drives_on)
- if conway then
- train.path[maxn+1]=conway
- train.max_index_on_track=maxn
- else
- --do as if nothing has happened and preceed with path
- --but do not update max_index_on_track
- atprint("over-generating path max to index ",(maxn+1)," (position ",train.path[maxn]," )")
- train.path[maxn+1]=vector.add(train.path[maxn], vector.subtract(train.path[maxn], train.path[maxn-1]))
- end
- train.path_dist[maxn]=vector.distance(train.path[maxn+1], train.path[maxn])
- maxn=maxn+1
- end
- train.path_extent_max=maxn
-
- local minn=train.path_extent_min or -1
- while minn > gen_back do
- atprint("minn conway for ",minn,train.path[minn],minn+1,train.path[minn+1])
- local conway=advtrains.conway(train.path[minn], train.path[minn+1], train.drives_on)
- if conway then
- train.path[minn-1]=conway
- train.min_index_on_track=minn
- else
- --do as if nothing has happened and preceed with path
- --but do not update min_index_on_track
- atprint("over-generating path min to index ",(minn-1)," (position ",train.path[minn]," )")
- train.path[minn-1]=vector.add(train.path[minn], vector.subtract(train.path[minn], train.path[minn+1]))
- end
- train.path_dist[minn-1]=vector.distance(train.path[minn], train.path[minn-1])
- minn=minn-1
- end
- train.path_extent_min=minn
- if not train.min_index_on_track then train.min_index_on_track=-1 end
- if not train.max_index_on_track then train.max_index_on_track=0 end
-end
-
-
-function advtrains.train_step_b(id, train, dtime)
-
- --hacky fix: if train_step_a returned in phase 2, end_index may not be set.
- --just return
- if not train.end_index then
- return
- end
-
- --- 8. check for collisions with other trains and damage players ---
-
- local train_moves=(train.velocity~=0)
-
- if train_moves then
- local collpos
- local coll_grace=1
- if train.movedir==1 then
- collpos=advtrains.get_real_index_position(train.path, train.index-coll_grace)
- else
- collpos=advtrains.get_real_index_position(train.path, train.end_index+coll_grace)
- end
- if collpos then
- local rcollpos=advtrains.round_vector_floor_y(collpos)
- for x=-1,1 do
- for z=-1,1 do
- local testpos=vector.add(rcollpos, {x=x, y=0, z=z})
- --- 8a Check collision ---
- local testpts=minetest.pos_to_string(testpos)
- if advtrains.detector.on_node[testpts] and advtrains.detector.on_node[testpts]~=id then
- --collides
- advtrains.collide_and_spawn_couple(id, testpos, advtrains.detector.on_node[testpts], train.movedir==-1)
- end
- --- 8b damage players ---
- if not minetest.setting_getbool("creative_mode") then
- local player=advtrains.playersbypts[testpts]
- if player and train.velocity>3 then
- --instantly kill player
- --drop inventory contents first, to not to spawn bones
- local player_inv=player:get_inventory()
- for i=1,player_inv:get_size("main") do
- minetest.add_item(testpos, player_inv:get_stack("main", i))
- end
- for i=1,player_inv:get_size("craft") do
- minetest.add_item(testpos, player_inv:get_stack("craft", i))
- end
- -- empty lists main and craft
- player_inv:set_list("main", {})
- player_inv:set_list("craft", {})
- player:set_hp(0)
- end
- end
- end
- end
- end
- end
-end
-
---returns new id
-function advtrains.create_new_train_at(pos, pos_prev)
- local newtrain_id=os.time()..os.clock()
- while advtrains.trains[newtrain_id] do newtrain_id=os.time()..os.clock() end--ensure uniqueness(will be unneccessary)
-
- advtrains.trains[newtrain_id]={}
- advtrains.trains[newtrain_id].last_pos=pos
- advtrains.trains[newtrain_id].last_pos_prev=pos_prev
- advtrains.trains[newtrain_id].tarvelocity=0
- advtrains.trains[newtrain_id].velocity=0
- advtrains.trains[newtrain_id].trainparts={}
-
- advtrains.trains[newtrain_id].enter_node_all=true
-
- return newtrain_id
-end
-
-
-function advtrains.get_train_end_index(train)
- return advtrains.get_real_path_index(train, train.trainlen or 2)--this function can be found inside wagons.lua since it's more related to wagons. we just set trainlen as pos_in_train
-end
-
-function advtrains.add_wagon_to_train(wagon, train_id, index)
- local train=advtrains.trains[train_id]
- if index then
- table.insert(train.trainparts, index, wagon.unique_id)
- else
- table.insert(train.trainparts, wagon.unique_id)
- end
- --this is not the usual case!!!
- --we may set initialized because the wagon has no chance to step()
- wagon.initialized=true
- --TODO is this art or can we throw it away?
- advtrains.update_trainpart_properties(train_id)
-end
-function advtrains.update_trainpart_properties(train_id, invert_flipstate)
- local train=advtrains.trains[train_id]
- train.drives_on=advtrains.all_tracktypes
- train.max_speed=20
- local rel_pos=0
- local count_l=0
- for i, w_id in ipairs(train.trainparts) do
- local wagon=nil
- for aoid,iwagon in pairs(minetest.luaentities) do
- if iwagon.is_wagon and iwagon.unique_id==w_id then
- if wagon then
- --duplicate
- atprint("update_trainpart_properties: Removing duplicate wagon with id="..aoid)
- iwagon.object:remove()
- else
- wagon=iwagon
- end
- end
- end
- if not wagon then
- if advtrains.wagon_save[w_id] then
- --spawn a new and initialize it with the properties from wagon_save
- wagon=minetest.add_entity(train.last_pos, advtrains.wagon_save[w_id].entity_name):get_luaentity()
- if not wagon then
- minetest.chat_send_all("[advtrains] Warning: Wagon "..advtrains.wagon_save[w_id].entity_name.." does not exist. Make sure all required modules are loaded!")
- else
- wagon:init_from_wagon_save(w_id)
- end
- end
- end
- if wagon then
- rel_pos=rel_pos+wagon.wagon_span
- wagon.train_id=train_id
- wagon.pos_in_train=rel_pos
- wagon.pos_in_trainparts=i
- wagon.old_velocity_vector=nil
- if wagon.is_locomotive then
- count_l=count_l+1
- end
- if invert_flipstate then
- wagon.wagon_flipped = not wagon.wagon_flipped
- end
- rel_pos=rel_pos+wagon.wagon_span
-
- if wagon.drives_on then
- for k,_ in pairs(train.drives_on) do
- if not wagon.drives_on[k] then
- train.drives_on[k]=nil
- end
- end
- end
- train.max_speed=math.min(train.max_speed, wagon.max_speed)
- if i==1 then
- train.couple_lock_front=wagon.lock_couples
- end
- if i==#train.trainparts then
- train.couple_lock_back=wagon.lock_couples
- end
-
- else
- atprint(w_id.." not loaded and no save available")
- --what the hell...
- table.remove(train.trainparts, pit)
- end
- end
- train.trainlen=rel_pos
- train.locomotives_in_train=count_l
-end
-
-function advtrains.split_train_at_wagon(wagon)
- --get train
- local train=advtrains.trains[wagon.train_id]
- if not train.path then return end
-
- local real_pos_in_train=advtrains.get_real_path_index(train, wagon.pos_in_train)
- local pos_for_new_train=train.path[math.floor(real_pos_in_train+wagon.wagon_span)]
- local pos_for_new_train_prev=train.path[math.floor(real_pos_in_train-1+wagon.wagon_span)]
-
- --before doing anything, check if both are rails. else do not allow
- if not pos_for_new_train then
- atprint("split_train: pos_for_new_train not set")
- return false
- end
- local node_ok=advtrains.get_rail_info_at(advtrains.round_vector_floor_y(pos_for_new_train), train.drives_on)
- if not node_ok then
- atprint("split_train: pos_for_new_train ",advtrains.round_vector_floor_y(pos_for_new_train_prev)," not loaded or is not a rail")
- return false
- end
-
- if not train.last_pos_prev then
- atprint("split_train: pos_for_new_train_prev not set")
- return false
- end
-
- local prevnode_ok=advtrains.get_rail_info_at(advtrains.round_vector_floor_y(pos_for_new_train), train.drives_on)
- if not prevnode_ok then
- atprint("split_train: pos_for_new_train_prev ", advtrains.round_vector_floor_y(pos_for_new_train_prev), " not loaded or is not a rail")
- return false
- end
-
- --create subtrain
- local newtrain_id=advtrains.create_new_train_at(pos_for_new_train, pos_for_new_train_prev)
- local newtrain=advtrains.trains[newtrain_id]
- --insert all wagons to new train
- for k,v in ipairs(train.trainparts) do
- if k>=wagon.pos_in_trainparts then
- table.insert(newtrain.trainparts, v)
- train.trainparts[k]=nil
- end
- end
- --update train parts
- advtrains.update_trainpart_properties(wagon.train_id)--atm it still is the desierd id.
- advtrains.update_trainpart_properties(newtrain_id)
- train.tarvelocity=0
- newtrain.velocity=train.velocity
- newtrain.tarvelocity=0
- newtrain.enter_node_all=true
-end
-
---there are 4 cases:
---1/2. F<->R F<->R regular, put second train behind first
---->frontpos of first train will match backpos of second
---3. F<->R R<->F flip one of these trains, take the other as new train
---->backpos's will match
---4. R<->F F<->R flip one of these trains and take it as new parent
---->frontpos's will match
-
---true when trains are facing each other. needed on colliding.
--- check done by iterating paths and checking their direction
---returns nil when not on the same track at all OR when required path items are not generated. this distinction may not always be needed.
-function advtrains.trains_facing(train1, train2)
- local sr_pos=train1.path[math.floor(train1.index)]
- local sr_pos_p=train1.path[math.floor(train1.index)-1]
-
- for i=advtrains.minN(train2.path), advtrains.maxN(train2.path) do
- if vector.equals(sr_pos, train2.path[i]) then
- if train2.path[i+1] and vector.equals(sr_pos_p, train2.path[i+1]) then return true end
- if train2.path[i-1] and vector.equals(sr_pos_p, train2.path[i-1]) then return false end
- return nil
- end
- end
- return nil
-end
-
-function advtrains.collide_and_spawn_couple(id1, pos, id2, t1_is_backpos)
- atprint("COLLISION: "..sid(id1).." and "..sid(id2).." at ",pos,", t1_is_backpos="..(t1_is_backpos and "true" or "false"))
- --TODO:
- local train1=advtrains.trains[id1]
-
- -- do collision
- train1.recently_collided_with_env=true
- train1.velocity=0.5*train1.velocity
- train1.movedir=train1.movedir*-1
- train1.tarvelocity=0
-
- local train2=advtrains.trains[id2]
-
- if not train1 or not train2 then return end
-
- local found
- for i=advtrains.minN(train1.path), advtrains.maxN(train1.path) do
- if vector.equals(train1.path[i], pos) then
- found=true
- end
- end
- if not found then
- atprint("Err: pos not in path. Not spawning a couple")
- return
- end
-
- local frontpos2=train2.path[math.floor(train2.detector_old_index)]
- local backpos2=train2.path[math.floor(train2.detector_old_end_index)]
- local t2_is_backpos
- atprint("End positions: ",frontpos2,backpos2)
-
- t2_is_backpos = vector.distance(backpos2, pos) < vector.distance(frontpos2, pos)
-
- atprint("t2_is_backpos="..(t2_is_backpos and "true" or "false"))
-
- local t1_has_couple
- if t1_is_backpos then
- t1_has_couple=train1.couple_eid_back
- else
- t1_has_couple=train1.couple_eid_front
- end
- local t2_has_couple
- if t2_is_backpos then
- t2_has_couple=train2.couple_eid_back
- else
- t2_has_couple=train2.couple_eid_front
- end
-
- if t1_has_couple then
- if minetest.object_refs[t1_has_couple] then minetest.object_refs[t1_has_couple]:remove() end
- end
- if t2_has_couple then
- if minetest.object_refs[t2_has_couple] then minetest.object_refs[t2_has_couple]:remove() end
- end
- local obj=minetest.add_entity(pos, "advtrains:couple")
- if not obj then atprint("failed creating object") return end
- local le=obj:get_luaentity()
- le.train_id_1=id1
- le.train_id_2=id2
- le.train1_is_backpos=t1_is_backpos
- le.train2_is_backpos=t2_is_backpos
- --find in object_refs
- local p_aoi
- for aoi, compare in pairs(minetest.object_refs) do
- if compare==obj then
- if t1_is_backpos then
- train1.couple_eid_back=aoi
- else
- train1.couple_eid_front=aoi
- end
- if t2_is_backpos then
- train2.couple_eid_back=aoi
- else
- train2.couple_eid_front=aoi
- end
- p_aoi=aoi
- end
- end
- atprint("Couple spawned (ActiveObjectID ",p_aoi,")")
-end
---order of trains may be irrelevant in some cases. check opposite cases. TODO does this work?
---pos1 and pos2 are just needed to form a median.
-
-
-function advtrains.do_connect_trains(first_id, second_id, player)
- local first, second=advtrains.trains[first_id], advtrains.trains[second_id]
-
- if not first or not second or not first.index or not second.index or not first.end_index or not second.end_index then
- return false
- end
-
- if first.couple_lock_back or second.couple_lock_front then
- -- trains are ordered correctly!
- if player then
- minetest.chat_send_player(player:get_player_name(), "Can't couple: couples locked!")
- end
- return
- end
-
- local first_wagoncnt=#first.trainparts
- local second_wagoncnt=#second.trainparts
-
- for _,v in ipairs(second.trainparts) do
- table.insert(first.trainparts, v)
- end
- --kick it like physics (with mass being #wagons)
- local new_velocity=((first.velocity*first_wagoncnt)+(second.velocity*second_wagoncnt))/(first_wagoncnt+second_wagoncnt)
- advtrains.trains[second_id]=nil
- advtrains.update_trainpart_properties(first_id)
- advtrains.trains[first_id].velocity=new_velocity
- advtrains.trains[first_id].tarvelocity=0
- return true
-end
-
-function advtrains.invert_train(train_id)
- local train=advtrains.trains[train_id]
-
- local old_path=train.path
- local old_path_dist=train.path_dist
- train.path={}
- train.path_dist={}
- train.index, train.end_index= -train.end_index, -train.index
- train.path_extent_min, train.path_extent_max = -train.path_extent_max, -train.path_extent_min
- train.min_index_on_track, train.max_index_on_track = -train.max_index_on_track, -train.min_index_on_track
- train.detector_old_index, train.detector_old_end_index = -train.detector_old_end_index, -train.detector_old_index
-
- train.velocity=-train.velocity
- train.tarvelocity=-train.tarvelocity
- for k,v in pairs(old_path) do
- train.path[-k]=v
- train.path_dist[-k-1]=old_path_dist[k]
- end
- local old_trainparts=train.trainparts
- train.trainparts={}
- for k,v in ipairs(old_trainparts) do
- table.insert(train.trainparts, 1, v)--notice insertion at first place
- end
- advtrains.update_trainpart_properties(train_id, true)
-end
-
-function advtrains.get_train_at_pos(pos)
- local ph=minetest.pos_to_string(advtrains.round_vector_floor_y(pos))
- return advtrains.detector.on_node[ph]
-end
-
-function advtrains.invalidate_all_paths(pos)
- --if a position is given, only invalidate inside a radius to save performance
- local inv_radius=50
- atprint("invalidating all paths")
- for k,v in pairs(advtrains.trains) do
- local exec=true
- if pos and v.path and v.index and v.end_index then
- --start and end pos of the train
- local cmp1=v.path[math.floor(v.index)]
- local cmp2=v.path[math.floor(v.end_index)]
- if vector.distance(pos, cmp1)>inv_radius and vector.distance(pos, cmp2)>inv_radius then
- exec=false
- end
- end
- if exec then
- --TODO duplicate code in init.lua avt_save()!
- if v.index then
- v.restore_add_index=v.index-math.floor(v.index+0.5)
- end
- v.path=nil
- v.path_dist=nil
- v.index=nil
- v.end_index=nil
- v.min_index_on_track=nil
- v.max_index_on_track=nil
- v.path_extent_min=nil
- v.path_extent_max=nil
-
- v.detector_old_index=nil
- v.detector_old_end_index=nil
- end
- end
-end
-
---not blocking trains group
-function advtrains.train_collides(node)
- if node and minetest.registered_nodes[node.name] and minetest.registered_nodes[node.name].walkable then
- if not minetest.registered_nodes[node.name].groups.not_blocking_trains then
- return true
- end
- end
- return false
-end
-
-local nonblocknodes={
- "default:fence_wood",
- "default:fence_acacia_wood",
- "default:fence_aspen_wood",
- "default:fence_pine_wood",
- "default:fence_junglewood",
- "default:torch",
-
- "default:sign_wall",
- "signs:sign_wall",
- "signs:sign_wall_blue",
- "signs:sign_wall_brown",
- "signs:sign_wall_orange",
- "signs:sign_wall_green",
- "signs:sign_yard",
- "signs:sign_wall_white_black",
- "signs:sign_wall_red",
- "signs:sign_wall_white_red",
- "signs:sign_wall_yellow",
- "signs:sign_post",
- "signs:sign_hanging",
-
-
-}
-minetest.after(0, function()
- for _,name in ipairs(nonblocknodes) do
- if minetest.registered_nodes[name] then
- minetest.registered_nodes[name].groups.not_blocking_trains=1
- end
- end
-end)
diff --git a/advtrains/advtrains/wagons.lua b/advtrains/advtrains/wagons.lua
deleted file mode 100644
index 3325879..0000000
--- a/advtrains/advtrains/wagons.lua
+++ /dev/null
@@ -1,900 +0,0 @@
---atan2 counts angles clockwise, minetest does counterclockwise
-
-minetest.register_privilege("train_place", {
- description = "Player can place trains on tracks not owned by player",
- give_to_singleplayer= false,
-});
-minetest.register_privilege("train_remove", {
- description = "Player can remove trains not owned by player",
- give_to_singleplayer= false,
-});
-minetest.register_privilege("train_operator", {
- description = "Player may operate trains and switch signals. Given by default. Revoke to prevent players from griefing automated subway systems.",
- give_to_singleplayer= true,
- default= true,
-});
-
-local wagon={
- collisionbox = {-0.5,-0.5,-0.5, 0.5,0.5,0.5},
- --physical = true,
- visual = "mesh",
- mesh = "wagon.b3d",
- visual_size = {x=3, y=3},
- textures = {"black.png"},
- is_wagon=true,
- wagon_span=1,--how many index units of space does this wagon consume
- has_inventory=false,
-}
-
-
-function wagon:train()
- return advtrains.trains[self.train_id]
-end
-
---[[about 'initalized':
- when initialized is false, the entity hasn't got any data yet and should wait for these to be set before doing anything
- when loading an existing object (with staticdata), it will be set
- when instanciating a new object via add_entity, it is not set at the time on_activate is called.
- then, wagon:initialize() will be called
-
- wagon will save only uid in staticdata, no serialized table
-]]
-function wagon:on_activate(sd_uid, dtime_s)
- if sd_uid~="" then
- --destroy when loaded from static block.
- self.object:remove()
- return
- end
- self.object:set_armor_groups({immortal=1})
- self.entity_name=self.name
-end
-
-function wagon:get_staticdata()
- return advtrains.pcall(function()
- if not self:ensure_init() then return end
- atprint("[wagon "..((self.unique_id and self.unique_id~="" and self.unique_id) or "no-id").."]: saving to wagon_save")
- --serialize inventory, if it has one
- if self.has_inventory then
- local inv=minetest.get_inventory({type="detached", name="advtrains_wgn_"..self.unique_id})
- self.ser_inv=advtrains.serialize_inventory(inv)
- end
- --save to table before being unloaded
- advtrains.wagon_save[self.unique_id]=advtrains.merge_tables(self)
- advtrains.wagon_save[self.unique_id].entity_name=self.name
- advtrains.wagon_save[self.unique_id].name=nil
- advtrains.wagon_save[self.unique_id].object=nil
- return self.unique_id
- end)
-end
---returns: uid of wagon
-function wagon:init_new_instance(train_id, properties)
- self.unique_id=os.time()..os.clock()
- self.train_id=train_id
- for k,v in pairs(properties) do
- if k~="name" and k~="object" then
- self[k]=v
- end
- end
- self:init_shared()
- self.initialized=true
- atprint("init_new_instance "..self.unique_id.." ("..self.train_id..")")
- return self.unique_id
-end
-function wagon:init_from_wagon_save(uid)
- if not advtrains.wagon_save[uid] then
- self.object:remove()
- return
- end
- self.unique_id=uid
- for k,v in pairs(advtrains.wagon_save[uid]) do
- if k~="name" and k~="object" then
- self[k]=v
- end
- end
- if not self.train_id or not self:train() then
- self.object:remove()
- return
- end
- self:init_shared()
- self.initialized=true
- minetest.after(0.2, function() self:reattach_all() end)
- atprint("init_from_wagon_save "..self.unique_id.." ("..self.train_id..")")
-end
-function wagon:init_shared()
- if self.has_inventory then
- local uid_noptr=self.unique_id..""
- --to be used later
- local inv=minetest.create_detached_inventory("advtrains_wgn_"..self.unique_id, {
- allow_move = function(inv, from_list, from_index, to_list, to_index, count, player)
- return count
- end,
- allow_put = function(inv, listname, index, stack, player)
- return stack:get_count()
- end,
- allow_take = function(inv, listname, index, stack, player)
- return stack:get_count()
- end
- })
- if self.ser_inv then
- advtrains.deserialize_inventory(self.ser_inv, inv)
- end
- if self.inventory_list_sizes then
- for lst, siz in pairs(self.inventory_list_sizes) do
- inv:set_size(lst, siz)
- end
- end
- end
- if self.doors then
- self.door_anim_timer=0
- self.door_state=0
- end
- if self.custom_on_activate then
- self:custom_on_activate(dtime_s)
- end
-end
-function wagon:ensure_init()
- if self.initialized then
- if self.noninitticks then self.noninitticks=nil end
- return true
- end
- if not self.noninitticks then self.noninitticks=0 end
- self.noninitticks=self.noninitticks+1
- if self.noninitticks>20 then
- self.object:remove()
- else
- self.object:setvelocity({x=0,y=0,z=0})
- end
- return false
-end
-
--- Remove the wagon
-function wagon:on_punch(puncher, time_from_last_punch, tool_capabilities, direction)
- return advtrains.pcall(function()
- if not self:ensure_init() then return end
- if not puncher or not puncher:is_player() then
- return
- end
- if self.owner and puncher:get_player_name()~=self.owner and (not minetest.check_player_privs(puncher, {train_remove = true })) then
- minetest.chat_send_player(puncher:get_player_name(), attrans("This wagon is owned by @1, you can't destroy it.", self.owner));
- return
- end
-
- if minetest.setting_getbool("creative_mode") then
- if not self:destroy() then return end
-
- local inv = puncher:get_inventory()
- if not inv:contains_item("main", self.name) then
- inv:add_item("main", self.name)
- end
- else
- local pc=puncher:get_player_control()
- if not pc.sneak then
- minetest.chat_send_player(puncher:get_player_name(), attrans("Warning: If you destroy this wagon, you only get some steel back! If you are sure, hold Sneak and left-click the wagon."))
- return
- end
-
- if not self:destroy() then return end
-
- local inv = puncher:get_inventory()
- for _,item in ipairs(self.drops or {self.name}) do
- inv:add_item("main", item)
- end
- end
- end)
-end
-function wagon:destroy()
- --some rules:
- -- you get only some items back
- -- single left-click shows warning
- -- shift leftclick destroys
- -- not when a driver is inside
-
- for _,_ in pairs(self.seatp) do
- return
- end
-
- if self.custom_may_destroy then
- if not self.custom_may_destroy(self, puncher, time_from_last_punch, tool_capabilities, direction) then
- return
- end
- end
- if self.custom_on_destroy then
- self.custom_on_destroy(self, puncher, time_from_last_punch, tool_capabilities, direction)
- end
-
- atprint("[wagon "..((self.unique_id and self.unique_id~="" and self.unique_id) or "no-id").."]: destroying")
-
- self.object:remove()
-
- table.remove(self:train().trainparts, self.pos_in_trainparts)
- advtrains.update_trainpart_properties(self.train_id)
- advtrains.wagon_save[self.unique_id]=nil
- if self.discouple then self.discouple.object:remove() end--will have no effect on unloaded objects
- return true
-end
-
-
-function wagon:on_step(dtime)
- return advtrains.pcall(function()
- if not self:ensure_init() then return end
-
- local t=os.clock()
- local pos = self.object:getpos()
-
- if not pos then
- atprint("["..self.unique_id.."][fatal] missing position (object:getpos() returned nil)")
- return
- end
-
- self.entity_name=self.name
-
- --is my train still here
- if not self.train_id or not self:train() then
- atprint("[wagon "..self.unique_id.."] missing train_id, destroying")
- self.object:remove()
- return
- end
- if not self.seatp then
- self.seatp={}
- end
- if not self.seatpc then
- self.seatpc={}
- end
-
- --Legacy: remove infotext since it does not work this way anyways
- self.infotext=nil
-
- --custom on_step function
- if self.custom_on_step then
- self:custom_on_step(self, dtime)
- end
-
- --driver control
- for seatno, seat in ipairs(self.seats) do
- local driver=self.seatp[seatno] and minetest.get_player_by_name(self.seatp[seatno])
- local has_driverstand=seat.driving_ctrl_access and self.seatp[seatno] and minetest.check_player_privs(self.seatp[seatno], {train_operator=true})
- if has_driverstand and driver then
- advtrains.update_driver_hud(driver:get_player_name(), self:train(), self.wagon_flipped)
- elseif driver then
- --only show the inside text
- local inside=self:train().text_inside or ""
- advtrains.set_trainhud(driver:get_player_name(), inside)
- end
- if driver and driver:get_player_control_bits()~=self.seatpc[seatno] then
- local pc=driver:get_player_control()
- self.seatpc[seatno]=driver:get_player_control_bits()
-
- if has_driverstand then
- --regular driver stand controls
- advtrains.on_control_change(pc, self:train(), self.wagon_flipped)
- else
- -- If on a passenger seat and doors are open, get off when W or D pressed.
- local pass = self.seatp[seatno] and minetest.get_player_by_name(self.seatp[seatno])
- if pass and self:train().door_open~=0 then
- local pc=pass:get_player_control()
- if pc.up or pc.down then
- self:get_off(seatno)
- end
- end
- end
- if pc.aux1 and pc.sneak then
- self:get_off(seatno)
- end
- end
- end
-
- --check infotext
- local outside=self:train().text_outside or ""
- if self.object:get_properties().infotext~=outside then
- self.object:set_properties({infotext=outside})
- end
-
- local gp=self:train()
- local fct=self.wagon_flipped and -1 or 1
- --door animation
- if self.doors then
- if (self.door_anim_timer or 0)<=0 then
- local dstate = (gp.door_open or 0) * fct
- if dstate ~= self.door_state then
- local at
- --meaning of the train.door_open field:
- -- -1: left doors (rel. to train orientation)
- -- 0: closed
- -- 1: right doors
- --this code produces the following behavior:
- -- if changed from 0 to +-1, play open anim. if changed from +-1 to 0, play close.
- -- if changed from +-1 to -+1, first close and set 0, then it will detect state change again and run open.
- if self.door_state == 0 then
- at=self.doors.open[dstate]
- self.object:set_animation(at.frames, at.speed or 15, at.blend or 0, false)
- self.door_state = dstate
- else
- at=self.doors.close[self.door_state or 1]--in case it has not been set yet
- self.object:set_animation(at.frames, at.speed or 15, at.blend or 0, false)
- self.door_state = 0
- end
- self.door_anim_timer = at.time
- end
- else
- self.door_anim_timer = (self.door_anim_timer or 0) - dtime
- end
- end
-
- --DisCouple
- if self.pos_in_trainparts and self.pos_in_trainparts>1 then
- if gp.velocity==0 and not self.lock_couples then
- if not self.discouple or not self.discouple.object:getyaw() then
- local object=minetest.add_entity(pos, "advtrains:discouple")
- if object then
- local le=object:get_luaentity()
- le.wagon=self
- --box is hidden when attached, so unuseful.
- --object:set_attach(self.object, "", {x=0, y=0, z=self.wagon_span*10}, {x=0, y=0, z=0})
- self.discouple=le
- else
- atprint("Couldn't spawn DisCouple")
- end
- end
- else
- if self.discouple and self.discouple.object:getyaw() then
- self.discouple.object:remove()
- end
- end
- end
- --for path to be available. if not, skip step
- if not gp.path then
- self.object:setvelocity({x=0, y=0, z=0})
- return
- end
- if not self.pos_in_train then
- --why ever. but better continue next step...
- advtrains.update_trainpart_properties(self.train_id)
- return
- end
-
- local index=advtrains.get_real_path_index(self:train(), self.pos_in_train)
- --atprint("trainindex "..gp.index.." wagonindex "..index)
-
- --automatic get_on
- --needs to know index and path
- if self.door_entry and gp.door_open and gp.door_open~=0 and gp.velocity==0 then
- --using the mapping created by the trainlogic globalstep
- for i, ino in ipairs(self.door_entry) do
- --fct is the flipstate flag from door animation above
- local aci = index + ino*fct
- local ix1=gp.path[math.floor(aci)]
- local ix2=gp.path[math.floor(aci+1)]
- -- the two wanted positions are ix1 and ix2 + (2nd-1st rotated by 90deg)
- -- (x z) rotated by 90deg is (-z x) (http://stackoverflow.com/a/4780141)
- local add = { x = (ix2.z-ix1.z)*gp.door_open, y = 0, z = (ix1.x-ix2.x)*gp.door_open }
- local pts1=vector.round(vector.add(ix1, add))
- local pts2=vector.round(vector.add(ix2, add))
- if minetest.get_item_group(minetest.get_node(pts1).name, "platform")>0 then
- local ckpts={
- pts1,
- pts2,
- vector.add(pts1, {x=0, y=1, z=0}),
- vector.add(pts2, {x=0, y=1, z=0}),
- }
- for _,ckpos in ipairs(ckpts) do
- local cpp=minetest.pos_to_string(ckpos)
- if advtrains.playersbypts[cpp] then
- self:on_rightclick(advtrains.playersbypts[cpp])
- end
- end
- end
- end
- end
-
- --position recalculation
- local first_pos=gp.path[math.floor(index)]
- local second_pos=gp.path[math.floor(index)+1]
- if not first_pos or not second_pos then
- --atprint(" object "..self.unique_id.." path end reached!")
- self.object:setvelocity({x=0,y=0,z=0})
- return
- end
-
- --checking for environment collisions(a 3x3 cube around the center)
- if not gp.recently_collided_with_env then
- local collides=false
- for x=-1,1 do
- for y=0,2 do
- for z=-1,1 do
- local node=minetest.get_node_or_nil(vector.add(first_pos, {x=x, y=y, z=z}))
- if (advtrains.train_collides(node)) then
- collides=true
- end
- end
- end
- end
- if collides then
- if self.collision_count and self.collision_count>10 then
- --enable collision mercy to get trains stuck in walls out of walls
- --actually do nothing except limiting the velocity to 1
- gp.velocity=math.min(gp.velocity, 1)
- gp.tarvelocity=math.min(gp.tarvelocity, 1)
- else
- gp.recently_collided_with_env=true
- gp.velocity=2*gp.velocity
- gp.movedir=-gp.movedir
- gp.tarvelocity=0
- self.collision_count=(self.collision_count or 0)+1
- end
- else
- self.collision_count=nil
- end
- end
-
- --FIX: use index of the wagon, not of the train.
- local velocity=(gp.velocity*gp.movedir)/(gp.path_dist[math.floor(index)] or 1)
- local acceleration=(gp.last_accel or 0)/(gp.path_dist[math.floor(index)] or 1)
- local factor=index-math.floor(index)
- local actual_pos={x=first_pos.x-(first_pos.x-second_pos.x)*factor, y=first_pos.y-(first_pos.y-second_pos.y)*factor, z=first_pos.z-(first_pos.z-second_pos.z)*factor,}
- local velocityvec={x=(first_pos.x-second_pos.x)*velocity*-1, z=(first_pos.z-second_pos.z)*velocity*-1, y=(first_pos.y-second_pos.y)*velocity*-1}
- local accelerationvec={x=(first_pos.x-second_pos.x)*acceleration*-1, z=(first_pos.z-second_pos.z)*acceleration*-1, y=(first_pos.y-second_pos.y)*acceleration*-1}
-
- --some additional positions to determine orientation
- local aposfwd=gp.path[math.floor(index+2)]
- local aposbwd=gp.path[math.floor(index-1)]
-
- local yaw
- if aposfwd and aposbwd then
- yaw=advtrains.get_wagon_yaw(aposfwd, second_pos, first_pos, aposbwd, factor)+math.pi--TODO remove when cleaning up
- else
- yaw=math.atan2((first_pos.x-second_pos.x), (second_pos.z-first_pos.z))
- end
- if self.wagon_flipped then
- yaw=yaw+math.pi
- end
-
- self.updatepct_timer=(self.updatepct_timer or 0)-dtime
- if not self.old_velocity_vector
- or not vector.equals(velocityvec, self.old_velocity_vector)
- or not self.old_acceleration_vector
- or not vector.equals(accelerationvec, self.old_acceleration_vector)
- or self.old_yaw~=yaw
- or self.updatepct_timer<=0 then--only send update packet if something changed
- self.object:setpos(actual_pos)
- self.object:setvelocity(velocityvec)
- self.object:setacceleration(accelerationvec)
- self.object:setyaw(yaw)
- self.updatepct_timer=2
- if self.update_animation then
- self:update_animation(gp.velocity)
- end
- end
-
-
- self.old_velocity_vector=velocityvec
- self.old_acceleration_vector=accelerationvec
- self.old_yaw=yaw
- atprintbm("wagon step", t)
- end)
-end
-
-function advtrains.get_real_path_index(train, pit)
- local pos_in_train_left=pit
- local index=train.index
- if pos_in_train_left>(index-math.floor(index))*(train.path_dist[math.floor(index)] or 1) then
- pos_in_train_left=pos_in_train_left - (index-math.floor(index))*(train.path_dist[math.floor(index)] or 1)
- index=math.floor(index)
- while pos_in_train_left>(train.path_dist[index-1] or 1) do
- pos_in_train_left=pos_in_train_left - (train.path_dist[index-1] or 1)
- index=index-1
- end
- index=index-(pos_in_train_left/(train.path_dist[index-1] or 1))
- else
- index=index-(pos_in_train_left/(train.path_dist[math.floor(index-1)] or 1))
- end
- return index
-end
-
-function wagon:on_rightclick(clicker)
- return advtrains.pcall(function()
- if not self:ensure_init() then return end
- if not clicker or not clicker:is_player() then
- return
- end
- if clicker:get_player_control().aux1 then
- --advtrains.dumppath(self:train().path)
- --minetest.chat_send_all("at index "..(self:train().index or "nil"))
- --advtrains.invert_train(self.train_id)
- atprint(dump(self))
- return
- end
- local pname=clicker:get_player_name()
- local no=self:get_seatno(pname)
- if no then
- if self.seat_groups then
- local poss={}
- local sgr=self.seats[no].group
- for _,access in ipairs(self.seat_groups[sgr].access_to) do
- if self:check_seat_group_access(pname, access) then
- poss[#poss+1]={name=self.seat_groups[access].name, key="sgr_"..access}
- end
- end
- if self.has_inventory and self.get_inventory_formspec then
- poss[#poss+1]={name=attrans("Show Inventory"), key="inv"}
- end
- if self.owner==pname then
- poss[#poss+1]={name=attrans("Wagon properties"), key="prop"}
- end
- if not self.seat_groups[sgr].require_doors_open or self:train().door_open~=0 then
- poss[#poss+1]={name=attrans("Get off"), key="off"}
- else
- if clicker:get_player_control().sneak then
- poss[#poss+1]={name=attrans("Get off (forced)"), key="off"}
- else
- poss[#poss+1]={name=attrans("(Doors closed)"), key="dcwarn"}
- end
- end
- if #poss==0 then
- --can't do anything.
- elseif #poss==1 then
- self:seating_from_key_helper(pname, {[poss[1].key]=true}, no)
- else
- local form = "size[5,"..1+(#poss).."]"
- for pos,ent in ipairs(poss) do
- form = form .. "button_exit[0.5,"..(pos-0.5)..";4,1;"..ent.key..";"..ent.name.."]"
- end
- minetest.show_formspec(pname, "advtrains_seating_"..self.unique_id, form)
- end
- else
- self:get_off(no)
- end
- else
- --do not attach if already on a train
- if advtrains.player_to_train_mapping[pname] then return end
- if self.seat_groups then
- if #self.seats==0 then
- if self.has_inventory and self.get_inventory_formspec then
- minetest.show_formspec(pname, "advtrains_inv_"..self.unique_id, self:get_inventory_formspec(pname))
- end
- return
- end
-
- local doors_open = self:train().door_open~=0 or clicker:get_player_control().sneak
- for _,sgr in ipairs(self.assign_to_seat_group) do
- if self:check_seat_group_access(pname, sgr) then
- for seatid, seatdef in ipairs(self.seats) do
- if seatdef.group==sgr and not self.seatp[seatid] and (not self.seat_groups[sgr].require_doors_open or doors_open) then
- self:get_on(clicker, seatid)
- return
- end
- end
- end
- end
- minetest.chat_send_player(pname, attrans("Can't get on: wagon full or doors closed!"))
- minetest.chat_send_player(pname, attrans("Use Sneak+rightclick to bypass closed doors!"))
- else
- self:show_get_on_form(pname)
- end
- end
- end)
-end
-
-function wagon:get_on(clicker, seatno)
- if not self.seatp then self.seatp={}end
- if not self.seatpc then self.seatpc={}end--player controls in driver stands
-
- if not self.seats[seatno] then return end
- local oldno=self:get_seatno(clicker:get_player_name())
- if oldno then
- atprint("get_on: clearing oldno",seatno)
- advtrains.player_to_train_mapping[clicker:get_player_name()]=nil
- advtrains.clear_driver_hud(clicker:get_player_name())
- self.seatp[oldno]=nil
- end
- if self.seatp[seatno] and self.seatp[seatno]~=clicker:get_player_name() then
- atprint("get_on: throwing off",self.seatp[seatno],"from seat",seatno)
- self:get_off(seatno)
- end
- atprint("get_on: attaching",clicker:get_player_name())
- self.seatp[seatno] = clicker:get_player_name()
- self.seatpc[seatno] = clicker:get_player_control_bits()
- advtrains.player_to_train_mapping[clicker:get_player_name()]=self.train_id
- clicker:set_attach(self.object, "", self.seats[seatno].attach_offset, {x=0,y=0,z=0})
- clicker:set_eye_offset(self.seats[seatno].view_offset, self.seats[seatno].view_offset)
-end
-function wagon:get_off_plr(pname)
- local no=self:get_seatno(pname)
- if no then
- self:get_off(no)
- end
-end
-function wagon:get_seatno(pname)
- for no, cont in pairs(self.seatp) do
- if cont==pname then
- return no
- end
- end
- return nil
-end
-function wagon:get_off(seatno)
- if not self.seatp[seatno] then return end
- local pname = self.seatp[seatno]
- local clicker = minetest.get_player_by_name(pname)
- advtrains.player_to_train_mapping[pname]=nil
- advtrains.clear_driver_hud(pname)
- self.seatp[seatno]=nil
- self.seatpc[seatno]=nil
- if clicker then
- atprint("get_off: detaching",clicker:get_player_name())
- clicker:set_detach()
- clicker:set_eye_offset({x=0,y=0,z=0}, {x=0,y=0,z=0})
- local gp=self:train()
- --code as in step - automatic get on
- if self.door_entry and gp.door_open and gp.door_open~=0 and gp.velocity==0 and gp.index and gp.path then
- local index=advtrains.get_real_path_index(gp, self.pos_in_train)
- --using the mapping created by the trainlogic globalstep
- for i, ino in ipairs(self.door_entry) do
- local aci = index + ino*(self.wagon_flipped and -1 or 1)
- local ix1=gp.path[math.floor(aci)]
- local ix2=gp.path[math.floor(aci+1)]
- -- the two wanted positions are ix1 and ix2 + (2nd-1st rotated by 90deg)
- -- (x z) rotated by 90deg is (-z x) (http://stackoverflow.com/a/4780141)
- -- multiplied by 2 here, to place off on platform, y of add is 1.
- local add = { x = (ix2.z-ix1.z)*gp.door_open, y = 0, z = (ix1.x-ix2.x)*gp.door_open}
- local oadd = { x = (ix2.z-ix1.z)*gp.door_open*2, y = 1, z = (ix1.x-ix2.x)*gp.door_open*2}
- local platpos=vector.round(vector.add(ix1, add))
- local offpos=vector.round(vector.add(ix1, oadd))
- atprint("platpos:", platpos, "offpos:", offpos)
- if minetest.get_item_group(minetest.get_node(platpos).name, "platform")>0 then
- minetest.after(0.2, function() clicker:setpos(offpos) end)
- return
- end
- end
- else--if not door_entry, or paths missing, fall back to old method
- local objpos=advtrains.round_vector_floor_y(self.object:getpos())
- local yaw=self.object:getyaw()
- local isx=(yaw < math.pi/4) or (yaw > 3*math.pi/4 and yaw < 5*math.pi/4) or (yaw > 7*math.pi/4)
- --abuse helper function
- for _,r in ipairs({-1, 1}) do
- local p=vector.add({x=isx and r or 0, y=0, z=not isx and r or 0}, objpos)
- local offp=vector.add({x=isx and r*2 or 0, y=1, z=not isx and r*2 or 0}, objpos)
- if minetest.get_item_group(minetest.get_node(p).name, "platform")>0 then
- minetest.after(0.2, function() clicker:setpos(offp) end)
- return
- end
- end
- end
- end
-end
-function wagon:show_get_on_form(pname)
- if not self.initialized then return end
- if #self.seats==0 then
- if self.has_inventory and self.get_inventory_formspec then
- minetest.show_formspec(pname, "advtrains_inv_"..self.unique_id, self:get_inventory_formspec(pname))
- end
- return
- end
- local form, comma="size[5,8]label[0.5,0.5;"..attrans("Select seat:").."]textlist[0.5,1;4,6;seat;", ""
- for seatno, seattbl in ipairs(self.seats) do
- local addtext, colorcode="", ""
- if self.seatp and self.seatp[seatno] then
- colorcode="#FF0000"
- addtext=" ("..self.seatp[seatno]..")"
- end
- form=form..comma..colorcode..seattbl.name..addtext
- comma=","
- end
- form=form..";0,false]"
- if self.has_inventory and self.get_inventory_formspec then
- form=form.."button_exit[1,7;3,1;inv;"..attrans("Show Inventory").."]"
- end
- minetest.show_formspec(pname, "advtrains_geton_"..self.unique_id, form)
-end
-function wagon:show_wagon_properties(pname)
- local numsgr=0
- if self.seat_groups then
- numsgr=#self.seat_groups
- end
- if not self.seat_access then
- self.seat_access={}
- end
- --[[
- fields: seat access: empty: everyone
- checkbox: lock couples
- button: save
- ]]
- local form="size[5,"..(numsgr*1.5+7).."]"
- local at=0
- if self.seat_groups then
- for sgr,sgrdef in pairs(self.seat_groups) do
- local text = attrans("Access to @1",sgrdef.name)
- form=form.."field[0.5,"..(0.5+at*1.5)..";4,1;sgr_"..sgr..";"..text..";"..(self.seat_access[sgr] or "").."]"
- at=at+1
- end
- end
- form=form.."checkbox[0,"..(at*1.5)..";lock_couples;"..attrans("Lock couples")..";"..(self.lock_couples and "true" or "false").."]"
- if self:train() then --just in case
- form=form.."field[0.5,"..(1.5+at*1.5)..";4,1;text_outside;"..attrans("Text displayed outside on train")..";"..(self:train().text_outside or "").."]"
- form=form.."field[0.5,"..(2.5+at*1.5)..";4,1;text_inside;"..attrans("Text displayed inside train")..";"..(self:train().text_inside or "").."]"
- end
- form=form.."button_exit[0.5,"..(3+at*1.5)..";4,1;save;"..attrans("Save wagon properties").."]"
- minetest.show_formspec(pname, "advtrains_prop_"..self.unique_id, form)
-end
-minetest.register_on_player_receive_fields(function(player, formname, fields)
- return advtrains.pcall(function()
- local uid=string.match(formname, "^advtrains_geton_(.+)$")
- if uid then
- for _,wagon in pairs(minetest.luaentities) do
- if wagon.is_wagon and wagon.initialized and wagon.unique_id==uid then
- if fields.inv then
- if wagon.has_inventory and wagon.get_inventory_formspec then
- minetest.show_formspec(player:get_player_name(), "advtrains_inv_"..uid, wagon:get_inventory_formspec(player:get_player_name()))
- end
- elseif fields.seat then
- local val=minetest.explode_textlist_event(fields.seat)
- if val and val.type~="INV" and not wagon.seatp[player:get_player_name()] then
- --get on
- wagon:get_on(player, val.index)
- --will work with the new close_formspec functionality. close exactly this formspec.
- minetest.show_formspec(player:get_player_name(), formname, "")
- end
- end
- end
- end
- end
- uid=string.match(formname, "^advtrains_seating_(.+)$")
- if uid then
- for _,wagon in pairs(minetest.luaentities) do
- if wagon.is_wagon and wagon.initialized and wagon.unique_id==uid then
- local pname=player:get_player_name()
- local no=wagon:get_seatno(pname)
- if no then
- if wagon.seat_groups then
- wagon:seating_from_key_helper(pname, fields, no)
- end
- end
- end
- end
- end
- uid=string.match(formname, "^advtrains_prop_(.+)$")
- if uid then
- for _,wagon in pairs(minetest.luaentities) do
- if wagon.is_wagon and wagon.initialized and wagon.unique_id==uid then
- local pname=player:get_player_name()
- if pname~=wagon.owner then
- return true
- end
- if fields.save or not fields.quit then
- for sgr,sgrdef in pairs(wagon.seat_groups) do
- if fields["sgr_"..sgr] then
- local fcont = fields["sgr_"..sgr]
- wagon.seat_access[sgr] = fcont~="" and fcont or nil
- end
- end
- if fields.lock_couples then
- wagon.lock_couples = fields.lock_couples == "true"
- end
- if fields.text_outside then
- if fields.text_outside~="" then
- wagon:train().text_outside=fields.text_outside
- else
- wagon:train().text_outside=nil
- end
- end
- if fields.text_inside then
- if fields.text_inside~="" then
- wagon:train().text_inside=fields.text_inside
- else
- wagon:train().text_inside=nil
- end
- end
-
- end
- end
- end
- end
- end)
-end)
-function wagon:seating_from_key_helper(pname, fields, no)
- local sgr=self.seats[no].group
- for _,access in ipairs(self.seat_groups[sgr].access_to) do
- if fields["sgr_"..access] and self:check_seat_group_access(pname, access) then
- for seatid, seatdef in ipairs(self.seats) do
- if seatdef.group==access and not self.seatp[seatid] then
- self:get_on(minetest.get_player_by_name(pname), seatid)
- return
- end
- end
- end
- end
- if fields.inv and self.has_inventory and self.get_inventory_formspec then
- minetest.show_formspec(player:get_player_name(), "advtrains_inv_"..self.unique_id, wagon:get_inventory_formspec(player:get_player_name()))
- end
- if fields.prop and self.owner==pname then
- self:show_wagon_properties(pname)
- end
- if fields.dcwarn then
- minetest.chat_send_player(pname, attrans("Doors are closed! Use Sneak+rightclick to ignore the closed doors and get off!"))
- end
- if fields.off then
- self:get_off(no)
- end
-end
-function wagon:check_seat_group_access(pname, sgr)
- if not self.seat_access then
- return true
- end
- local sae=self.seat_access[sgr]
- if not sae or sae=="" then
- return true
- end
- for name in string.gmatch(sae, "%S+") do
- if name==pname then
- return true
- end
- end
- return false
-end
-function wagon:reattach_all()
- if not self.seatp then self.seatp={} end
- for seatno, pname in pairs(self.seatp) do
- local p=minetest.get_player_by_name(pname)
- if p then
- self:get_on(p ,seatno)
- end
- end
-end
-
-function advtrains.register_wagon(sysname, prototype, desc, inv_img)
- setmetatable(prototype, {__index=wagon})
- minetest.register_entity(":advtrains:"..sysname,prototype)
-
- minetest.register_craftitem(":advtrains:"..sysname, {
- description = desc,
- inventory_image = inv_img,
- wield_image = inv_img,
- stack_max = 1,
-
- on_place = function(itemstack, placer, pointed_thing)
- return advtrains.pcall(function()
- if not pointed_thing.type == "node" then
- return
- end
-
-
- local node=minetest.get_node_or_nil(pointed_thing.under)
- if not node then atprint("[advtrains]Ignore at placer position") return itemstack end
- local nodename=node.name
- if(not advtrains.is_track_and_drives_on(nodename, prototype.drives_on)) then
- atprint("no track here, not placing.")
- return itemstack
- end
- if not minetest.check_player_privs(placer, {train_place = true }) and minetest.is_protected(pointed_thing.under, placer:get_player_name()) then
- minetest.record_protection_violation(pointed_thing.under, placer:get_player_name())
- return
- end
- local conn1=advtrains.get_track_connections(node.name, node.param2)
- local id=advtrains.create_new_train_at(pointed_thing.under, advtrains.dirCoordSet(pointed_thing.under, conn1))
-
- local ob=minetest.add_entity(pointed_thing.under, "advtrains:"..sysname)
- if not ob then
- atprint("couldn't add_entity, aborting")
- end
- local le=ob:get_luaentity()
-
- le.owner=placer:get_player_name()
-
- local wagon_uid=le:init_new_instance(id, {})
-
- advtrains.add_wagon_to_train(le, id)
- if not minetest.setting_getbool("creative_mode") then
- itemstack:take_item()
- end
- return itemstack
-
- end)
- end,
- })
-end
-
---[[
- wagons can define update_animation(self, velocity) if they have a speed-dependent animation
- this function will be called when the velocity vector changes or every 2 seconds.
-]]
-
-
diff --git a/advtrains/advtrains_itrainmap/depends.txt b/advtrains/advtrains_itrainmap/depends.txt
deleted file mode 100644
index 6f00bf6..0000000
--- a/advtrains/advtrains_itrainmap/depends.txt
+++ /dev/null
@@ -1 +0,0 @@
-advtrains \ No newline at end of file
diff --git a/advtrains/advtrains_itrainmap/init.lua b/advtrains/advtrains_itrainmap/init.lua
deleted file mode 100644
index 756f1da..0000000
--- a/advtrains/advtrains_itrainmap/init.lua
+++ /dev/null
@@ -1,149 +0,0 @@
-
-
-local map_def={
- example = {
- p1x=168,
- p1z=530,
- p2x=780,
- p2z=1016,
- background="itm_example.png",
- },
-}
-
-local itm_cache={}
-local itm_pdata={}
-local itm_conf_mindia=0.1
-
-minetest.register_privilege("itm", { description = "Allows to display train map", give_to_singleplayer = true, default = false })
-
-local function create_map_form_with_bg(d)
- local minx, minz, maxx, maxz = math.min(d.p1x, d.p2x), math.min(d.p1z, d.p2z), math.max(d.p1x, d.p2x), math.max(d.p1z, d.p2z)
- local form_x, form_z=10,10
- local edge_x, edge_z = form_x/(maxx-minx), form_z/(maxz-minz)
- local len_x, len_z=math.max(edge_x, itm_conf_mindia), math.max(edge_z, itm_conf_mindia)
- local form="size["..(form_x+edge_x)..","..(form_z+edge_z).."] background[0,0;0,0;"..d.background..";true] "
- local lbl={}
-
- for pts, tid in pairs(advtrains.detector.on_node) do
- local pos=minetest.string_to_pos(pts)
- form=form.."box["..(edge_x*(pos.x-minx))..","..(form_z-(edge_z*(pos.z-minz)))..";"..len_x..","..len_z..";red]"
- lbl[sid(tid)]=pos
- end
-
- for t_id, xz in pairs(lbl) do
- form=form.."label["..(edge_x*(xz.x-minx))..","..(form_x-(edge_z*(xz.z-minz)))..";"..t_id.."]"
- end
- return form
-end
-
-local function create_map_form(d)
- if d.background then
- return create_map_form_with_bg(d)
- end
-
- local minx, minz, maxx, maxz = math.min(d.p1x, d.p2x), math.min(d.p1z, d.p2z), math.max(d.p1x, d.p2x), math.max(d.p1z, d.p2z)
- local form_x, form_z=10,10
- local edge_x, edge_z = form_x/(maxx-minx), form_z/(maxz-minz)
- local len_x, len_z=math.max(edge_x, itm_conf_mindia), math.max(edge_z, itm_conf_mindia)
- local form="size["..(form_x+edge_x)..","..(form_z+edge_z).."]"
- local lbl={}
-
- for x,itx in pairs(itm_cache) do
- if x>=minx and x<=maxx then
- for z,y in pairs(itx) do
- if z>=minz and z<=maxz then
- local adn=advtrains.detector.on_node[minetest.pos_to_string({x=x, y=y, z=z})]
- local color="gray"
- if adn then
- color="red"
- lbl[sid(adn)]={x=x, z=z}
- end
- form=form.."box["..(edge_x*(x-minx))..","..(form_z-(edge_z*(z-minz)))..";"..len_x..","..len_z..";"..color.."]"
- end
- end
- end
- end
- for t_id, xz in pairs(lbl) do
- form=form.."label["..(edge_x*(xz.x-minx))..","..(form_x-(edge_z*(xz.z-minz)))..";"..t_id.."]"
- end
- return form
-end
-
-local function cache_ndb()
- itm_cache={}
- local ndb_nodes=advtrains.ndb.get_nodes()
- for y, xzt in pairs(ndb_nodes) do
- for x, zt in pairs(xzt) do
- for z, _ in pairs(zt) do
- if not itm_cache[x] then
- itm_cache[x]={}
- end
- itm_cache[x][z]=y
- end
- end
- end
-end
-
-minetest.register_chatcommand("itm", {
- params="[x1 z1 x2 z2] or [mdef]",
- description="Display advtrains train map of given area.\nFirst form:[x1 z1 x2 z2] - specify area directly.\nSecond form:[mdef] - Use a predefined map background(see init.lua)\nThird form: No parameters - use WorldEdit position markers.",
- privs={itm=true},
- func = function(name, param)
- local mdef=string.match(param, "^(%S+)$")
- if mdef then
- local d=map_def[mdef]
- if not d then
- return false, "Map definiton not found: "..mdef
- end
- itm_pdata[name]=map_def[mdef]
- minetest.show_formspec(name, "itrainmap", create_map_form(d))
- return true, "Showing train map: "..mdef
- end
- local x1, z1, x2, z2=string.match(param, "^(%S+) (%S+) (%S+) (%S+)$")
- if not (x1 and z1 and x2 and z2) then
- if worldedit then
- local wep1, wep2=worldedit.pos1[name], worldedit.pos2[name]
- if wep1 and wep2 then
- x1, z1, x2, z2=wep1.x, wep1.z, wep2.x, wep2.z
- end
- end
- end
- if not (x1 and z1 and x2 and z2) then
- return false, "Invalid parameters and no WE positions set"
- end
- local d={p1x=x1, p1z=z1, p2x=x2, p2z=z2}
- itm_pdata[name]=d
- minetest.show_formspec(name, "itrainmap", create_map_form(d))
- return true, "Showing ("..x1..","..z1..")-("..x2..","..z2..")"
- end,
-})
-minetest.register_chatcommand("itm_cache_ndb", {
- params="",
- description="Cache advtrains node database again. Run when tracks changed.",
- privs={itm=true},
- func = function(name, param)
- cache_ndb()
- return true, "Done caching node database."
- end,
-})
-
-local timer=0
-function advtrains_itm_mainloop(dtime)
- timer=timer-math.min(dtime, 0.1)
- if timer<=0 then
- for pname,d in pairs(itm_pdata) do
- minetest.show_formspec(pname, "itrainmap", create_map_form(d))
- end
- timer=2
- end
-end
-minetest.register_on_player_receive_fields(function(player, formname, fields)
- if formname=="itrainmap" and fields.quit then
- itm_pdata[player:get_player_name()]=nil
- end
-end)
-
-function advtrains_itm_init()
- --automatically run itm_cache_ndb
- minetest.after(2, cache_ndb)
-end
diff --git a/advtrains/advtrains_itrainmap/textures/itm_example.png b/advtrains/advtrains_itrainmap/textures/itm_example.png
deleted file mode 100644
index caf084a..0000000
--- a/advtrains/advtrains_itrainmap/textures/itm_example.png
+++ /dev/null
Binary files differ
diff --git a/advtrains/advtrains_luaautomation/README.txt b/advtrains/advtrains_luaautomation/README.txt
deleted file mode 100644
index f2219bf..0000000
--- a/advtrains/advtrains_luaautomation/README.txt
+++ /dev/null
@@ -1,165 +0,0 @@
-
-#### Advtrains - Lua Automation features
-
-This mod offers components that run LUA code and interface with each other through a global environment. It makes complex automated railway systems possible.
-
-### atlatc
-The mod is sometimes abbreviated as 'atlatc'. This stands for AdvTrainsLuaATC. This short name has been chosen for user convenience, since the name of this mod ('advtrains_luaautomation') is very long.
-
-### Privilege
-To perform any operations using this mod (except executing operation panels), players need the "atlatc" privilege.
-This privilege should never be granted to anyone except trusted administrators. Even though the LUA environment is sandboxed, it is still possible to DoS the server by coding infinite loops or requesting expotentially growing interrupts.
-
-### Active and passive
-Active components are these who have LUA code running in them. They are triggered on specific events. Passive components are dumb, they only have a state and can be set to another state, they can't perform actions themselves.
-
-### Environments
-
-Each active component is assigned to an environment. This is where all data are held. Components in different environments can't inferface with each other.
-This system allows multiple independent automation systems to run simultaneously without polluting each other's environment.
-
-/env_create <env_name>
-Create environment with the given name. To be able to do anything, you first need to create an environment. Choose the name wisely, you can't change it afterwards.
-
-/env_setup <env_name>
-Invoke the form to edit the environment's initialization code. For more information, see the section on active components. You can also delete an environment from here.
-
-### Active components
-
-The code of every active component is run on specific events which are explained soon. When run, every variable written that is not local and is no function or userdata is saved over code re-runs and over server restarts. Additionally, the following global variables are defined:
-
-# event
-The variable 'event' contains a table with information on the current event. How this table can look is explained below.
-
-# S
-The variable 'S' contains a table which is shared between all components of the environment. Its contents are persistent over server restarts. May not contain functions, every other value is allowed.
-Example:
-Component 1: S.stuff="foo"
-Component 2: print(S.stuff)
--> foo
-
-# F
-The variable 'F' also contains a table which is shared between all components of the environment. Its contents are discarded on server shutdown or when the init code gets re-run. Every data type is allowed, even functions.
-The purpose of this table is not to save data, but to provide static value and function definitions. The table should be populated by the init code.
-
-# Standard Lua functions
-The following standard Lua libraries are available:
-string, math, table, os
-The following standard Lua functions are available:
-assert, error, ipairs, pairs, next, select, tonumber, tostring, type, unpack
-
-Every attempt to overwrite any of the predefined values results in an error.
-
-# LuaAutomation-specific global functions
-
-POS(x,y,z)
-Shorthand function to create a position vector {x=?, y=?, z=?} with less characters
-
-getstate(pos)
-Get the state of the passive component at position 'pos'. See section on passive components for more info.
-pos can be either a position vector (created by POS()) or a string, the name of this passive component.
-
-setstate(pos, newstate)
-Set the state of the passive component at position 'pos'.
-pos can be either a position vector (created by POS()) or a string, the name of this passive component.
-
-interrupt(time, message)
-Cause LuaAutomation to trigger an 'int' event on this component after the given time in seconds with the specified 'message' field. 'message' can be of any Lua data type.
-Not available in init code!
-
-interrupt_pos(pos, message)
-Immediately trigger an 'ext_int' event on the active component at position pos. 'message' is like in interrupt().
-USE WITH CARE, or better don't use! Incorrect use can result in expotential growth of interrupts.
-
-## Components and events
-
-The event table is a table of the following format:
-{
- type = "<type>",
- <type> = true,
- ... additional content ...
-}
-You can check for the event type by either using
-if event.type == "wanted" then ...do stuff... end
-or
-if event.wanted then ...do stuff... end
-(if 'wanted' is the event type to check for)
-
-# Init code
-The initialization code is not a component as such, but rather a part of the whole environment. It can (and should) be used to make definitions that other components can refer to.
-Examples:
-A function to define behavior for trains in subway stations:
-function F.station()
- if event.train then atc_send("B0WOL") end
- if event.int and event.message="depart" then atc_send("OCD1SM") end
-end
-
-The init code is run whenever the F table needs to be refilled with data. This is the case on server startup and whenever the init code is changed and you choose to run it.
-Functions are run in the environment of the currently active node, regardless of where they were defined. So, the 'event' table always reflects the state of the calling node.
-
-The 'event' table of the init code is always {type="init", init=true}.
-
-# ATC rails
-The Lua-controlled ATC rails are the only components that can actually interface with trains. The following event types are generated:
-
-{type="train", train=true, id="<train_id>"}
-This event is fired when a train enters the rail. The field 'id' is the unique train ID, which is a long string (generated by concatenating os.time() and os.clock() at creation time). The Itrainmap mod displays the last 4 digits of this ID.
-
-{type="int", int=true, message=<message>}
-Fired when an interrupt set by the 'interrupt' function runs out. 'message' is the message passed to the interrupt function.
-{type="ext_int", ext_int=true, message=<message>}
-Fired when another node called 'interrupt_pos' on this position. 'message' is the message passed to the interrupt_pos function.
-
-In addition to the default environment functions, the following functions are available:
-
-atc_send(<atc_command>)
- Sends the specified ATC command to the train and returns true. If there is no train, returns false and does nothing.
-atc_reset()
- Resets the train's current ATC command. If there is no train, returns false and does nothing.
-atc_arrow
- Boolean, true when the train is driving in the direction of the arrows of the ATC rail. Nil if there is no train.
-atc_id
- Train ID of the train currently passing the controller. Nil if there's no train.
-atc_speed
- Speed of the train, or nil if there is no train.
-atc_set_text_outside(text)
- Set text shown on the outside of the train. Pass nil to show no text.
-atc_set_text_inside(text)
- Set text shown to train passengers. Pass nil to show no text.
-
-# Operator panel
-This simple node executes its actions when punched. It can be used to change a switch and update the corresponding signals or similar applications.
-
-The event fired is {type="punch", punch=true} by default. In case of an interrupt, the events are similar to the ones of the ATC rail.
-
-### Passive components
-
-All passive components can be interfaced with the setstate and getstate functions(see above).
-Below, each apperance is mapped to the "state" of that node.
-
-## Signals
-The light signals are interfaceable, the analog signals are not.
-"green" - Signal shows green light
-"red" - Signal shows red light
-
-## Switches
-All default rail switches are interfaceable, independent of orientation.
-"cr" - The switch is set in the direction that is not straight.
-"st" - The switch is set in the direction that is straight.
-
-## Mesecon Switch
-The Mesecon switch can be switched using LuaAutomation. Note that this is not possible on levers, only the full-node 'Switch' block.
-"on" - the switch is switched on
-"off" - the switch is switched off
-
-##Andrew's Cross
-"on" - it blinks
-"off" - it does not blink
-
-### Passive component naming
-You can assign names to passive components using the Passive Component Naming tool.
-Once you set a name for any component, you can reference it by that name in the getstate() and setstate() functions, like this:
-(Imagine a signal that you have named "Stn_P1_out" at position (1,2,3) )
-setstate("Stn_P1_out", "green") instead of setstate(POS(1,2,3), "green")
-This way, you don't need to memorize positions.
-
diff --git a/advtrains/advtrains_luaautomation/active_common.lua b/advtrains/advtrains_luaautomation/active_common.lua
deleted file mode 100644
index 8c910c6..0000000
--- a/advtrains/advtrains_luaautomation/active_common.lua
+++ /dev/null
@@ -1,134 +0,0 @@
-
-
-local ac = {nodes={}}
-
-function ac.load(data)
- if data then
- ac.nodes=data.nodes
- end
-end
-function ac.save()
- return {nodes = ac.nodes}
-end
-
-function ac.after_place_node(pos, player)
- advtrains.ndb.update(pos)
- local meta=minetest.get_meta(pos)
- meta:set_string("formspec", ac.getform(pos, meta))
- meta:set_string("infotext", "LuaAutomation component, unconfigured.")
- local ph=minetest.pos_to_string(pos)
- --just get first available key!
- for en,_ in pairs(atlatc.envs) do
- ac.nodes[ph]={env=en}
- return
- end
-end
-function ac.getform(pos, meta_p)
- local meta = meta_p or minetest.get_meta(pos)
- local envs_asvalues={}
-
- local ph=minetest.pos_to_string(pos)
- local nodetbl = ac.nodes[ph]
- local env, code, err = nil, "", ""
- if nodetbl then
- code=nodetbl.code or ""
- err=nodetbl.err or ""
- env=nodetbl.env or ""
- end
- local sel = 1
- for n,_ in pairs(atlatc.envs) do
- envs_asvalues[#envs_asvalues+1]=n
- if n==env then
- sel=#envs_asvalues
- end
- end
- local form = "size[10,10]dropdown[0,0;3;env;"..table.concat(envs_asvalues, ",")..";"..sel.."]"
- .."button[4,0;2,1;save;Save]button[7,0;2,1;cle;Clear local env] textarea[0.2,1;10,10;code;Code;"..minetest.formspec_escape(code).."]"
- .."label[0,9.8;"..err.."]"
- return form
-end
-
-function ac.after_dig_node(pos, node, player)
- advtrains.invalidate_all_paths(pos)
- advtrains.ndb.clear(pos)
- local ph=minetest.pos_to_string(pos)
- ac.nodes[ph]=nil
-end
-
-function ac.on_receive_fields(pos, formname, fields, player)
- if not minetest.check_player_privs(player:get_player_name(), {atlatc=true}) then
- minetest.chat_send_player(player:get_player_name(), "Missing privilege: atlatc - Operation cancelled!")
- return
- end
-
- local meta=minetest.get_meta(pos)
- local ph=minetest.pos_to_string(pos)
- local nodetbl = ac.nodes[ph] or {}
- --if fields.quit then return end
- if fields.env then
- nodetbl.env=fields.env
- end
- if fields.code then
- nodetbl.code=fields.code
- end
- if fields.save then
- nodetbl.err=nil
- end
- if fields.cle then
- nodetbl.data={}
- end
-
- ac.nodes[ph]=nodetbl
-
- meta:set_string("formspec", ac.getform(pos, meta))
- if nodetbl.env then
- meta:set_string("infotext", "LuaAutomation component, assigned to environment '"..nodetbl.env.."'")
- else
- meta:set_string("infotext", "LuaAutomation component, invalid enviroment set!")
- end
-end
-
-function ac.run_in_env(pos, evtdata, customfct_p)
- local ph=minetest.pos_to_string(pos)
- local nodetbl = ac.nodes[ph]
- if not nodetbl then
- atwarn("LuaAutomation component at",ph,": Data not in memory! Please visit component and click 'Save'!")
- return
- end
-
- local meta
- if minetest.get_node_or_nil(pos) then
- meta=minetest.get_meta(pos)
- end
-
- if not nodetbl.env or not atlatc.envs[nodetbl.env] then
- atwarn("LuaAutomation component at",ph,": Not an existing environment: "..(nodetbl.env or "<nil>"))
- return false
- end
- if not nodetbl.code or nodetbl.code=="" then
- atwarn("LuaAutomation component at",ph,": No code to run! (insert -- to suppress warning)")
- return false
- end
-
- local customfct=customfct_p or {}
- customfct.interrupt=function(t, imesg)
- atlatc.interrupt.add(t, pos, {type="int", int=true, message=imesg})
- end
-
- local datain=nodetbl.data or {}
- local succ, dataout = atlatc.envs[nodetbl.env]:execute_code(datain, nodetbl.code, evtdata, customfct)
- if succ then
- atlatc.active.nodes[ph].data=atlatc.remove_invalid_data(dataout)
- else
- atlatc.active.nodes[ph].err=dataout
- atwarn("LuaAutomation ATC interface rail at",ph,": LUA Error:",dataout)
- if meta then
- meta:set_string("infotext", "LuaAutomation ATC interface rail, ERROR:"..dataout)
- end
- end
- if meta then
- meta:set_string("formspec", ac.getform(pos, meta))
- end
-end
-
-atlatc.active=ac
diff --git a/advtrains/advtrains_luaautomation/atc_rail.lua b/advtrains/advtrains_luaautomation/atc_rail.lua
deleted file mode 100644
index ab84986..0000000
--- a/advtrains/advtrains_luaautomation/atc_rail.lua
+++ /dev/null
@@ -1,120 +0,0 @@
--- atc_rail.lua
--- registers and handles the ATC rail. Active component.
--- This is the only component that can interface with trains, so train interface goes here too.
-
---Using subtable
-local r={}
-
-function r.fire_event(pos, evtdata)
-
- local ph=minetest.pos_to_string(pos)
- local railtbl = atlatc.active.nodes[ph]
-
- if not railtbl then
- atwarn("LuaAutomation ATC interface rail at",ph,": Data not in memory! Please visit position and click 'Save'!")
- return
- end
-
-
- local arrowconn = railtbl.arrowconn
-
- --prepare ingame API for ATC. Regenerate each time since pos needs to be known
- --If no train, then return false.
- local train_id=advtrains.detector.on_node[ph]
- local train, atc_arrow, tvel
- if train_id then train=advtrains.trains[train_id] end
- if train then
- if not train.path then
- --we happened to get in between an invalidation step
- --delay
- atlatc.interrupt.add(0,pos,evtdata)
- return
- end
- for index, ppos in pairs(train.path) do
- if vector.equals(advtrains.round_vector_floor_y(ppos), pos) then
- atc_arrow =
- vector.equals(
- advtrains.dirCoordSet(pos, arrowconn),
- advtrains.round_vector_floor_y(train.path[index+train.movedir])
- )
- end
- end
- if atc_arrow==nil then
- atwarn("LuaAutomation ATC rail at", pos, ": Rail not on train's path! Can't determine arrow direction. Assuming +!")
- atc_arrow=true
- end
- tvel=train.velocity
- end
- local customfct={
- atc_send = function(cmd)
- if not train_id then return false end
- assertt(cmd, "string")
- advtrains.atc.train_reset_command(train_id)
- train.atc_command=cmd
- train.atc_arrow=atc_arrow
- return true
- end,
- atc_reset = function(cmd)
- if not train_id then return false end
- assertt(cmd, "string")
- advtrains.atc.train_reset_command(train_id)
- return true
- end,
- atc_arrow = atc_arrow,
- atc_id = train_id,
- atc_speed = tvel,
- atc_set_text_outside = function(text)
- if not train_id then return false end
- if text then assertt(text, "string") end
- advtrains.trains[train_id].text_outside=text
- return true
- end,
- atc_set_text_inside = function(text)
- if not train_id then return false end
- if text then assertt(text, "string") end
- advtrains.trains[train_id].text_inside=text
- return true
- end,
- }
-
- atlatc.active.run_in_env(pos, evtdata, customfct)
-
-end
-
-advtrains.register_tracks("default", {
- nodename_prefix="advtrains_luaautomation:dtrack",
- texture_prefix="advtrains_dtrack_atc",
- models_prefix="advtrains_dtrack",
- models_suffix=".b3d",
- shared_texture="advtrains_dtrack_shared_atc.png",
- description=atltrans("LuaAutomation ATC Rail"),
- formats={},
- get_additional_definiton = function(def, preset, suffix, rotation)
- return {
- after_place_node = atlatc.active.after_place_node,
- after_dig_node = atlatc.active.after_dig_node,
-
- on_receive_fields = function(pos, ...)
- atlatc.active.on_receive_fields(pos, ...)
-
- --set arrowconn (for ATC)
- local ph=minetest.pos_to_string(pos)
- local _, conn1=advtrains.get_rail_info_at(pos, advtrains.all_tracktypes)
- atlatc.active.nodes[ph].arrowconn=conn1
- end,
-
- advtrains = {
- on_train_enter = function(pos, train_id)
- --do async. Event is fired in train steps
- atlatc.interrupt.add(0, pos, {type="train", train=true, id=train_id})
- end,
- },
- luaautomation = {
- fire_event=r.fire_event
- }
- }
- end
-}, advtrains.trackpresets.t_30deg_straightonly)
-
-
-atlatc.rail = r
diff --git a/advtrains/advtrains_luaautomation/chatcmds.lua b/advtrains/advtrains_luaautomation/chatcmds.lua
deleted file mode 100644
index 2d0c69d..0000000
--- a/advtrains/advtrains_luaautomation/chatcmds.lua
+++ /dev/null
@@ -1,84 +0,0 @@
---chatcmds.lua
---Registers commands to modify the init and step code for LuaAutomation
-
---position helper.
---punching a node will result in that position being saved and inserted into a text field on the top of init form.
-local punchpos={}
-
-minetest.register_on_punchnode(function(pos, node, player, pointed_thing)
- local pname=player:get_player_name()
- punchpos[pname]=pos
-end)
-
-local function get_init_form(env, pname)
- local err = env.init_err or ""
- local code = env.init_code or ""
- local ppos=punchpos[pname]
- local pp=""
- if ppos then
- pp="POS"..minetest.pos_to_string(ppos)
- end
- local form = "size[10,10]button[0,0;2,1;run;Run InitCode]button[2,0;2,1;cls;Clear S]"
- .."button[4,0;2,1;save;Save] button[6,0;2,1;del;Delete Env.] field[8.1,0.5;2,1;punchpos;Last punched position;"..pp.."]"
- .."textarea[0.2,1;10,10;code;Environment initialization code;"..minetest.formspec_escape(code).."]"
- .."label[0,9.8;"..err.."]"
- return form
-end
-
-core.register_chatcommand("env_setup", {
- params = "<environment name>",
- description = "Set up and modify AdvTrains LuaAutomation environment",
- privs = {atlatc=true},
- func = function(name, param)
- local env=atlatc.envs[param]
- if not env then return false,"Invalid environment name!" end
- minetest.show_formspec(name, "atlatc_envsetup_"..param, get_init_form(env, name))
- return true
- end,
-})
-
-core.register_chatcommand("env_create", {
- params = "<environment name>",
- description = "Create an AdvTrains LuaAutomation environment",
- privs = {atlatc=true},
- func = function(name, param)
- if not param or param=="" then return false, "Name required!" end
- if atlatc.envs[param] then return false, "Environment already exists!" end
- atlatc.envs[param] = atlatc.env_new(param)
- return true, "Created environment '"..param.."'. Use '/env_setup "..param.."' to define global initialization code, or start building LuaATC components!"
- end,
-})
-
-
-minetest.register_on_player_receive_fields(function(player, formname, fields)
-
- local pname=player:get_player_name()
- if not minetest.check_player_privs(pname, {atlatc=true}) then return end
-
- local envname=string.match(formname, "^atlatc_delconfirm_(.+)$")
- if envname and fields.sure=="YES" then
- atlatc.envs[envname]=nil
- minetest.chat_send_player(pname, "Environment deleted!")
- return
- end
-
- envname=string.match(formname, "^atlatc_envsetup_(.+)$")
- if not envname then return end
-
- local env=atlatc.envs[envname]
- if not env then return end
-
- if fields.del then
- minetest.show_formspec(pname, "atlatc_delconfirm_"..envname, "field[sure;"..minetest.formspec_escape("SURE TO DELETE ENVIRONMENT "..envname.."? Type YES (all uppercase) to continue or just quit form to cancel.")..";]")
- return
- end
-
- env.init_err=nil
- if fields.code then
- env.init_code=fields.code
- end
- if fields.run then
- env:run_initcode()
- minetest.show_formspec(pname, formname, get_init_form(env, pname))
- end
-end)
diff --git a/advtrains/advtrains_luaautomation/depends.txt b/advtrains/advtrains_luaautomation/depends.txt
deleted file mode 100644
index 602cf47..0000000
--- a/advtrains/advtrains_luaautomation/depends.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-advtrains
-mesecons_switch? \ No newline at end of file
diff --git a/advtrains/advtrains_luaautomation/environment.lua b/advtrains/advtrains_luaautomation/environment.lua
deleted file mode 100644
index ec1f7cb..0000000
--- a/advtrains/advtrains_luaautomation/environment.lua
+++ /dev/null
@@ -1,270 +0,0 @@
--------------
--- lua sandboxed environment
-
--- function to cross out functions and userdata.
--- modified from dump()
-function atlatc.remove_invalid_data(o, nested)
- if o==nil then return nil end
- local valid_dt={["nil"]=true, boolean=true, number=true, string=true}
- if type(o) ~= "table" then
- --check valid data type
- if not valid_dt[type(o)] then
- return nil
- end
- return o
- end
- -- Contains table -> true/nil of currently nested tables
- nested = nested or {}
- if nested[o] then
- return nil
- end
- nested[o] = true
- for k, v in pairs(o) do
- v = atlatc.remove_invalid_data(v, nested)
- end
- nested[o] = nil
- return o
-end
-
-
-local env_proto={
- load = function(self, envname, data)
- self.name=envname
- self.sdata=data.sdata and atlatc.remove_invalid_data(data.sdata) or {}
- self.fdata={}
- self.init_code=data.init_code or ""
- self.step_code=data.step_code or ""
- end,
- save = function(self)
- -- throw any function values out of the sdata table
- self.sdata = atlatc.remove_invalid_data(self.sdata)
- return {sdata = self.sdata, init_code=self.init_code, step_code=self.step_code}
- end,
-}
-
---Environment
---Code modified from mesecons_luacontroller (credit goes to Jeija and mesecons contributors)
-
-local safe_globals = {
- "assert", "error", "ipairs", "next", "pairs", "select",
- "tonumber", "tostring", "type", "unpack", "_VERSION"
-}
-
---print is actually minetest.chat_send_all()
---using advtrains.print_concat_table because it's cool
-local function safe_print(t, ...)
- local str=advtrains.print_concat_table({t, ...})
- minetest.log("action", "[atlatc] "..str)
- minetest.chat_send_all(str)
-end
-
-local function safe_date()
- return(os.date("*t",os.time()))
-end
-
--- string.rep(str, n) with a high value for n can be used to DoS
--- the server. Therefore, limit max. length of generated string.
-local function safe_string_rep(str, n)
- if #str * n > 2000 then
- debug.sethook() -- Clear hook
- error("string.rep: string length overflow", 2)
- end
-
- return string.rep(str, n)
-end
-
--- string.find with a pattern can be used to DoS the server.
--- Therefore, limit string.find to patternless matching.
--- Note: Disabled security since there are enough security leaks and this would be unneccessary anyway to DoS the server
-local function safe_string_find(...)
- --if (select(4, ...)) ~= true then
- -- debug.sethook() -- Clear hook
- -- error("string.find: 'plain' (fourth parameter) must always be true for security reasons.")
- --end
-
- return string.find(...)
-end
-
-local mp=minetest.get_modpath("advtrains_luaautomation")
-local p_api_getstate, p_api_setstate = dofile(mp.."/passive.lua")
-
-local static_env = {
- --core LUA functions
- print = safe_print,
- string = {
- byte = string.byte,
- char = string.char,
- format = string.format,
- len = string.len,
- lower = string.lower,
- upper = string.upper,
- rep = safe_string_rep,
- reverse = string.reverse,
- sub = string.sub,
- find = safe_string_find,
- },
- math = {
- abs = math.abs,
- acos = math.acos,
- asin = math.asin,
- atan = math.atan,
- atan2 = math.atan2,
- ceil = math.ceil,
- cos = math.cos,
- cosh = math.cosh,
- deg = math.deg,
- exp = math.exp,
- floor = math.floor,
- fmod = math.fmod,
- frexp = math.frexp,
- huge = math.huge,
- ldexp = math.ldexp,
- log = math.log,
- log10 = math.log10,
- max = math.max,
- min = math.min,
- modf = math.modf,
- pi = math.pi,
- pow = math.pow,
- rad = math.rad,
- random = math.random,
- sin = math.sin,
- sinh = math.sinh,
- sqrt = math.sqrt,
- tan = math.tan,
- tanh = math.tanh,
- },
- table = {
- concat = table.concat,
- insert = table.insert,
- maxn = table.maxn,
- remove = table.remove,
- sort = table.sort,
- },
- os = {
- clock = os.clock,
- difftime = os.difftime,
- time = os.time,
- date = safe_date,
- },
- POS = function(x,y,z) return {x=x, y=y, z=z} end,
- getstate = p_api_getstate,
- setstate = p_api_setstate,
- --interrupts are handled per node, position unknown.
- --however external interrupts can be set here.
- interrupt_pos = function(pos, imesg)
- if not type(pos)=="table" or not pos.x or not pos.y or not pos.z then
- debug.sethook()
- error("Invalid position supplied to interrupt_pos")
- end
- atlatc.interrupt.add(0, pos, {type="ext_int", ext_int=true, message=imesg})
- end,
-}
-
-for _, name in pairs(safe_globals) do
- static_env[name] = _G[name]
-end
-
-
---The environment all code calls get is a table that has set static_env as metatable.
---In general, every variable is local to a single code chunk, but kept persistent over code re-runs. Data is also saved, but functions and userdata and circular references are removed
---Init code and step code's environments are not saved
--- S - Table that can contain any save data global to the environment. Will be saved statically. Can't contain functions or userdata or circular references.
--- F - Table global to the environment, can contain volatile data that is deleted when server quits.
--- The init code should populate this table with functions and other definitions.
-
-local proxy_env={}
---proxy_env gets a new metatable in every run, but is the shared environment of all functions ever defined.
-
--- returns: true, fenv if successful; nil, error if error
-function env_proto:execute_code(localenv, code, evtdata, customfct)
- local metatbl ={
- __index = function(t, i)
- if i=="S" then
- return self.sdata
- elseif i=="F" then
- return self.fdata
- elseif i=="event" then
- return evtdata
- elseif customfct and customfct[i] then
- return customfct[i]
- elseif localenv and localenv[i] then
- return localenv[i]
- end
- return static_env[i]
- end,
- __newindex = function(t, i, v)
- if i=="S" or i=="F" or i=="event" or (customfct and customfct[i]) or static_env[i] then
- debug.sethook()
- error("Trying to overwrite environment contents")
- end
- localenv[i]=v
- end,
- }
- setmetatable(proxy_env, metatbl)
- local fun, err=loadstring(code)
- if not fun then
- return false, err
- end
-
- setfenv(fun, proxy_env)
- local succ, data = pcall(fun)
- if succ then
- data=localenv
- end
- return succ, data
-end
-
-function env_proto:run_initcode()
- if self.init_code and self.init_code~="" then
- self.fdata = {}
- atprint("[atlatc]Running initialization code for environment '"..self.name.."'")
- local succ, err = self:execute_code({}, self.init_code, {type="init", init=true})
- if not succ then
- atwarn("[atlatc]Executing InitCode for '"..self.name.."' failed:"..err)
- self.init_err=err
- end
- end
-end
-function env_proto:run_stepcode()
- if self.step_code and self.step_code~="" then
- local succ, err = self:execute_code({}, self.step_code, nil, {})
- if not succ then
- --TODO
- end
- end
-end
-
---- class interface
-
-function atlatc.env_new(name)
- local newenv={
- name=name,
- init_code="",
- step_code="",
- sdata={}
- }
- setmetatable(newenv, {__index=env_proto})
- return newenv
-end
-function atlatc.env_load(name, data)
- local newenv={}
- setmetatable(newenv, {__index=env_proto})
- newenv:load(name, data)
- return newenv
-end
-
-function atlatc.run_initcode()
- for envname, env in pairs(atlatc.envs) do
- env:run_initcode()
- end
-end
-function atlatc.run_stepcode()
- for envname, env in pairs(atlatc.envs) do
- env:run_stepcode()
- end
-end
-
-
-
-
diff --git a/advtrains/advtrains_luaautomation/init.lua b/advtrains/advtrains_luaautomation/init.lua
deleted file mode 100644
index 0257aef..0000000
--- a/advtrains/advtrains_luaautomation/init.lua
+++ /dev/null
@@ -1,110 +0,0 @@
--- advtrains_luaautomation/init.lua
--- Lua automation features for advtrains
--- Uses global table 'atlatc' (AdvTrains_LuaATC)
-
--- Boilerplate to support localized strings if intllib mod is installed.
-if minetest.get_modpath("intllib") then
- atltrans = intllib.Getter()
-else
- atltrans = function(s,a,...)a={a,...}return s:gsub("@(%d+)",function(n)return a[tonumber(n)]end)end
-end
-
---Privilege
---Only trusted players should be enabled to build stuff which can break the server.
-
-atlatc = { envs = {}}
-
-minetest.register_privilege("atlatc", { description = "Player can place and modify LUA ATC components. Grant with care! Allows to execute bad LUA code.", give_to_singleplayer = false, default= false })
-
---assertt helper. error if a variable is not of a type
-function assertt(var, typ)
- if type(var)~=typ then
- error("Assertion failed, variable has to be of type "..typ)
- end
-end
-
-local mp=minetest.get_modpath("advtrains_luaautomation")
-if not mp then
- error("Mod name error: Mod folder is not named 'advtrains_luaautomation'!")
-end
-dofile(mp.."/environment.lua")
-dofile(mp.."/interrupt.lua")
-dofile(mp.."/active_common.lua")
-dofile(mp.."/atc_rail.lua")
-dofile(mp.."/operation_panel.lua")
-dofile(mp.."/pcnaming.lua")
-if mesecon then
- dofile(mp.."/p_mesecon_iface.lua")
-end
-dofile(mp.."/chatcmds.lua")
-
-
-local filename=minetest.get_worldpath().."/advtrains_luaautomation"
-
-function atlatc.load()
- local file, err = io.open(filename, "r")
- if not file then
- minetest.log("error", " Failed to read advtrains_luaautomation save data from file "..filename..": "..(err or "Unknown Error"))
- else
- atprint("luaautomation reading file:",filename)
- local tbl = minetest.deserialize(file:read("*a"))
- if type(tbl) == "table" then
- if tbl.version==1 then
- for envname, data in pairs(tbl.envs) do
- atlatc.envs[envname]=atlatc.env_load(envname, data)
- end
- atlatc.active.load(tbl.active)
- atlatc.interrupt.load(tbl.interrupt)
- atlatc.pcnaming.load(tbl.pcnaming)
- end
- else
- minetest.log("error", " Failed to read advtrains_luaautomation save data from file "..filename..": Not a table!")
- end
- file:close()
- end
- -- run init code of all environments
- atlatc.run_initcode()
-end
-
-
-atlatc.save = function()
- --versions:
- -- 1 - Initial save format.
-
- local envdata={}
- for envname, env in pairs(atlatc.envs) do
- envdata[envname]=env:save()
- end
- local save_tbl={
- version = 1,
- envs=envdata,
- active = atlatc.active.save(),
- interrupt = atlatc.interrupt.save(),
- pcnaming = atlatc.pcnaming.save(),
- }
-
- local datastr = minetest.serialize(save_tbl)
- if not datastr then
- minetest.log("error", " Failed to save advtrains_luaautomation save data to file "..filename..": Can't serialize!")
- return
- end
- local file, err = io.open(filename, "w")
- if err then
- minetest.log("error", " Failed to save advtrains_luaautomation save data to file "..filename..": "..(err or "Unknown Error"))
- return
- end
- file:write(datastr)
- file:close()
-end
-
-
--- globalstep for step code
-local timer, step_int=0, 2
-
-function atlatc.mainloop_stepcode(dtime)
- timer=timer+dtime
- if timer>step_int then
- timer=0
- atlatc.run_stepcode()
- end
-end
diff --git a/advtrains/advtrains_luaautomation/interrupt.lua b/advtrains/advtrains_luaautomation/interrupt.lua
deleted file mode 100644
index 718b8c7..0000000
--- a/advtrains/advtrains_luaautomation/interrupt.lua
+++ /dev/null
@@ -1,46 +0,0 @@
--- interrupt.lua
--- implements interrupt queue
-
---to be saved: pos and evtdata
-local iq={}
-local queue={}
-local timer=0
-local run=false
-
-function iq.load(data)
- local d=data or {}
- queue = d.queue or {}
- timer = d.timer or 0
-end
-function iq.save()
- return {queue = queue, timer=timer}
-end
-
-function iq.add(t, pos, evtdata)
- queue[#queue+1]={t=t+timer, p=pos, e=evtdata}
- run=true
-end
-
-function iq.mainloop(dtime)
- timer=timer + math.min(dtime, 0.2)
- for i=1,#queue do
- local qe=queue[i]
- if not qe then
- table.remove(queue, i)
- i=i-1
- elseif timer>qe.t then
- local pos, evtdata=queue[i].p, queue[i].e
- local node=advtrains.ndb.get_node(pos)
- local ndef=minetest.registered_nodes[node.name]
- if ndef and ndef.luaautomation and ndef.luaautomation.fire_event then
- ndef.luaautomation.fire_event(pos, evtdata)
- end
- table.remove(queue, i)
- i=i-1
- end
- end
-end
-
-
-
-atlatc.interrupt=iq
diff --git a/advtrains/advtrains_luaautomation/operation_panel.lua b/advtrains/advtrains_luaautomation/operation_panel.lua
deleted file mode 100644
index 1d585f7..0000000
--- a/advtrains/advtrains_luaautomation/operation_panel.lua
+++ /dev/null
@@ -1,23 +0,0 @@
-
-local function on_punch(pos, player)
- atlatc.interrupt.add(0, pos, {type="punch", punch=true})
-end
-
-
-minetest.register_node("advtrains_luaautomation:oppanel", {
- drawtype = "normal",
- tiles={"atlatc_oppanel.png"},
- description = "LuaAutomation operation panel",
- groups = {
- choppy = 1,
- save_in_nodedb=1,
- },
- after_place_node = atlatc.active.after_place_node,
- after_dig_node = atlatc.active.after_dig_node,
- on_receive_fields = atlatc.active.on_receive_fields,
- on_punch = on_punch,
- luaautomation = {
- fire_event=atlatc.active.run_in_env
- }
-
-})
diff --git a/advtrains/advtrains_luaautomation/p_display.lua b/advtrains/advtrains_luaautomation/p_display.lua
deleted file mode 100644
index e69de29..0000000
--- a/advtrains/advtrains_luaautomation/p_display.lua
+++ /dev/null
diff --git a/advtrains/advtrains_luaautomation/passive.lua b/advtrains/advtrains_luaautomation/passive.lua
deleted file mode 100644
index 774df8a..0000000
--- a/advtrains/advtrains_luaautomation/passive.lua
+++ /dev/null
@@ -1,39 +0,0 @@
--- passive.lua
--- API to passive components, as described in passive_api.txt
-
-local function getstate(parpos)
- local pos=atlatc.pcnaming.resolve_pos(parpos)
- if type(pos)~="table" or (not pos.x or not pos.y or not pos.z) then
- debug.sethook()
- error("Invalid position supplied to getstate")
- end
- local node=advtrains.ndb.get_node(pos)
- local ndef=minetest.registered_nodes[node.name]
- if ndef and ndef.luaautomation and ndef.luaautomation.getstate then
- local st=ndef.luaautomation.getstate
- if type(st)=="function" then
- return st(pos, node)
- else
- return st
- end
- end
- return nil
-end
-
-local function setstate(parpos, newstate)
- local pos=atlatc.pcnaming.resolve_pos(parpos)
- if type(pos)~="table" or (not pos.x or not pos.y or not pos.z) then
- debug.sethook()
- error("Invalid position supplied to setstate")
- end
- local node=advtrains.ndb.get_node(pos)
- local ndef=minetest.registered_nodes[node.name]
- if ndef and ndef.luaautomation and ndef.luaautomation.setstate then
- local st=ndef.luaautomation.setstate
- st(pos, node, newstate)
- end
-end
-
--- gets called from environment.lua
--- return the values here to keep them local
-return getstate, setstate
diff --git a/advtrains/advtrains_luaautomation/passive_api.txt b/advtrains/advtrains_luaautomation/passive_api.txt
deleted file mode 100644
index a735208..0000000
--- a/advtrains/advtrains_luaautomation/passive_api.txt
+++ /dev/null
@@ -1,23 +0,0 @@
-Lua Automation - Passive Component API
-
-Passive components are nodes that do not have code running in them. However, active components can query these and request actions from them. Examples:
-Switches
-Signals
-Displays
-Mesecon Transmitter
-
-All passive components have a table called 'luaautomation' in their node definition and have the group 'save_in_nodedb' set, so they work in unloaded chunks.
-Example for a switch:
-luaautomation = {
- getstate = function(pos, node)
- return "st"
- end,
- -- OR
- getstate = "st",
-
- setstate = function(pos, node, newstate)
- if newstate=="cr" then
- advtrains.ndb.swap_node(pos, <corresponding switch alt>)
- end
- end
-} \ No newline at end of file
diff --git a/advtrains/advtrains_luaautomation/pcnaming.lua b/advtrains/advtrains_luaautomation/pcnaming.lua
deleted file mode 100644
index 56ed2d6..0000000
--- a/advtrains/advtrains_luaautomation/pcnaming.lua
+++ /dev/null
@@ -1,74 +0,0 @@
---pcnaming.lua
---a.k.a Passive component naming
---Allows to assign names to passive components, so they can be called like:
---setstate("iamasignal", "green")
-atlatc.pcnaming={name_map={}}
-function atlatc.pcnaming.load(stuff)
- if type(stuff)=="table" then
- atlatc.pcnaming.name_map=stuff
- end
-end
-function atlatc.pcnaming.save()
- return atlatc.pcnaming.name_map
-end
-
-function atlatc.pcnaming.resolve_pos(posorname)
- if type(posorname)=="table" then return posorname end
- return atlatc.pcnaming.name_map[posorname]
-end
-
-minetest.register_craftitem("advtrains_luaautomation:pcnaming",{
- description = attrans("Passive Component Naming Tool\n\nRight-click to name a passive component."),
- groups = {cracky=1}, -- key=name, value=rating; rating=1..3.
- inventory_image = "atlatc_pcnaming.png",
- wield_image = "atlatc_pcnaming.png",
- stack_max = 1,
- on_place = function(itemstack, placer, pointed_thing)
- local pname = placer:get_player_name()
- if not pname then
- return
- end
- if not minetest.check_player_privs(pname, {atlatc=true}) then
- minetest.chat_send_player(pname, "Missing privilege: atlatc")
- return
- end
- if pointed_thing.type=="node" then
- local pos=pointed_thing.under
- if advtrains.is_protected(pos, pname) then
- minetest.record_protection_violation(pos, pname)
- return
- end
- local node=minetest.get_node(pos)
- local ndef=minetest.registered_nodes[node.name]
- if ndef then
- if ndef.luaautomation then
- --look if this one already has a name
- local pn=""
- for name, npos in pairs(atlatc.pcnaming.name_map) do
- if vector.equals(npos, pos) then
- pn=name
- end
- end
- minetest.show_formspec(pname, "atlatc_naming_"..minetest.pos_to_string(pos), "field[pn;Set name of component (empty to clear);"..pn.."]")
- end
- end
- end
- end,
-})
-minetest.register_on_player_receive_fields(function(player, formname, fields)
- local pts=string.match(formname, "^atlatc_naming_(.+)")
- if pts then
- local pos=minetest.string_to_pos(pts)
- if fields.pn then
- --first remove all occurences
- for name, npos in pairs(atlatc.pcnaming.name_map) do
- if vector.equals(npos, pos) then
- atlatc.pcnaming.name_map[name]=nil
- end
- end
- if fields.pn~="" then
- atlatc.pcnaming.name_map[fields.pn]=pos
- end
- end
- end
-end)
diff --git a/advtrains/advtrains_luaautomation/textures/atlatc_oppanel.png b/advtrains/advtrains_luaautomation/textures/atlatc_oppanel.png
deleted file mode 100644
index 96eb30e..0000000
--- a/advtrains/advtrains_luaautomation/textures/atlatc_oppanel.png
+++ /dev/null
Binary files differ
diff --git a/advtrains/advtrains_luaautomation/textures/atlatc_pcnaming.png b/advtrains/advtrains_luaautomation/textures/atlatc_pcnaming.png
deleted file mode 100644
index 3fccdfc..0000000
--- a/advtrains/advtrains_luaautomation/textures/atlatc_pcnaming.png
+++ /dev/null
Binary files differ
diff --git a/advtrains/advtrains_train_industrial/depends.txt b/advtrains/advtrains_train_industrial/depends.txt
deleted file mode 100644
index 1fb6665..0000000
--- a/advtrains/advtrains_train_industrial/depends.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-advtrains
-intllib? \ No newline at end of file
diff --git a/advtrains/advtrains_train_industrial/init.lua b/advtrains/advtrains_train_industrial/init.lua
deleted file mode 100644
index 2eed2b1..0000000
--- a/advtrains/advtrains_train_industrial/init.lua
+++ /dev/null
@@ -1,84 +0,0 @@
--- Boilerplate to support localized strings if intllib mod is installed.
-local S
-if minetest.get_modpath("intllib") then
- S = intllib.Getter()
-else
- S = function(s,a,...)a={a,...}return s:gsub("@(%d+)",function(n)return a[tonumber(n)]end)end
-end
-
-advtrains.register_wagon("engine_industrial", {
- mesh="advtrains_engine_industrial.b3d",
- textures = {"advtrains_engine_industrial.png"},
- drives_on={default=true},
- max_speed=20,
- seats = {
- {
- name=S("Driver Stand (left)"),
- attach_offset={x=-5, y=10, z=-10},
- view_offset={x=0, y=10, z=0},
- driving_ctrl_access=true,
- group = "dstand",
- },
- {
- name=S("Driver Stand (right)"),
- attach_offset={x=5, y=10, z=-10},
- view_offset={x=0, y=10, z=0},
- driving_ctrl_access=true,
- group = "dstand",
- },
- },
- seat_groups = {
- dstand={
- name = "Driver Stand",
- access_to = {},
- },
- },
- assign_to_seat_group = {"dstand"},
- visual_size = {x=1, y=1},
- wagon_span=2.6,
- is_locomotive=true,
- collisionbox = {-1.0,-0.5,-1.0, 1.0,2.5,1.0},
- drops={"default:steelblock 4"},
-}, S("Industrial Train Engine"), "advtrains_engine_industrial_inv.png")
-advtrains.register_wagon("wagon_tank", {
- mesh="advtrains_wagon_tank.b3d",
- textures = {"advtrains_wagon_tank.png"},
- seats = {},
- drives_on={default=true},
- max_speed=20,
- visual_size = {x=1, y=1},
- wagon_span=2.2,
- collisionbox = {-1.0,-0.5,-1.0, 1.0,2.5,1.0},
- drops={"default:steelblock 4"},
- has_inventory = true,
- get_inventory_formspec = function(self)
- return "size[8,11]"..
- "list[detached:advtrains_wgn_"..self.unique_id..";box;0,0;8,6;]"..
- "list[current_player;main;0,7;8,4;]"..
- "listring[]"
- end,
- inventory_list_sizes = {
- box=8*6,
- },
-}, S("Industrial tank wagon"), "advtrains_wagon_tank_inv.png")
-advtrains.register_wagon("wagon_wood", {
- mesh="advtrains_wagon_wood.b3d",
- textures = {"advtrains_wagon_wood.png"},
- seats = {},
- drives_on={default=true},
- max_speed=20,
- visual_size = {x=1, y=1},
- wagon_span=1.8,
- collisionbox = {-1.0,-0.5,-1.0, 1.0,2.5,1.0},
- drops={"default:steelblock 4"},
- has_inventory = true,
- get_inventory_formspec = function(self)
- return "size[8,11]"..
- "list[detached:advtrains_wgn_"..self.unique_id..";box;0,0;8,6;]"..
- "list[current_player;main;0,7;8,4;]"..
- "listring[]"
- end,
- inventory_list_sizes = {
- box=8*6,
- },
-}, S("Industrial wood wagon"), "advtrains_wagon_wood_inv.png")
diff --git a/advtrains/advtrains_train_industrial/locale/de.txt b/advtrains/advtrains_train_industrial/locale/de.txt
deleted file mode 100644
index a45ca27..0000000
--- a/advtrains/advtrains_train_industrial/locale/de.txt
+++ /dev/null
@@ -1,5 +0,0 @@
-Driver Stand (left) = Führerstand Links
-Driver Stand (right) = Führerstand Rechts
-Industrial Train Engine = Industrielle Lokomotive
-Industrial tank wagon = Tankwaggon
-Industrial wood wagon = Holztransportwaggon \ No newline at end of file
diff --git a/advtrains/advtrains_train_industrial/models/advtrains_engine_industrial.b3d b/advtrains/advtrains_train_industrial/models/advtrains_engine_industrial.b3d
deleted file mode 100644
index f1ea485..0000000
--- a/advtrains/advtrains_train_industrial/models/advtrains_engine_industrial.b3d
+++ /dev/null
Binary files differ
diff --git a/advtrains/advtrains_train_industrial/models/advtrains_wagon_tank.b3d b/advtrains/advtrains_train_industrial/models/advtrains_wagon_tank.b3d
deleted file mode 100644
index af2604b..0000000
--- a/advtrains/advtrains_train_industrial/models/advtrains_wagon_tank.b3d
+++ /dev/null
Binary files differ
diff --git a/advtrains/advtrains_train_industrial/models/advtrains_wagon_wood.b3d b/advtrains/advtrains_train_industrial/models/advtrains_wagon_wood.b3d
deleted file mode 100644
index 0e7fb4b..0000000
--- a/advtrains/advtrains_train_industrial/models/advtrains_wagon_wood.b3d
+++ /dev/null
Binary files differ
diff --git a/advtrains/advtrains_train_industrial/textures/advtrains_engine_industrial.png b/advtrains/advtrains_train_industrial/textures/advtrains_engine_industrial.png
deleted file mode 100644
index 38a872f..0000000
--- a/advtrains/advtrains_train_industrial/textures/advtrains_engine_industrial.png
+++ /dev/null
Binary files differ
diff --git a/advtrains/advtrains_train_industrial/textures/advtrains_engine_industrial_inv.png b/advtrains/advtrains_train_industrial/textures/advtrains_engine_industrial_inv.png
deleted file mode 100644
index be4e80f..0000000
--- a/advtrains/advtrains_train_industrial/textures/advtrains_engine_industrial_inv.png
+++ /dev/null
Binary files differ
diff --git a/advtrains/advtrains_train_industrial/textures/advtrains_wagon_tank.png b/advtrains/advtrains_train_industrial/textures/advtrains_wagon_tank.png
deleted file mode 100644
index 79b1316..0000000
--- a/advtrains/advtrains_train_industrial/textures/advtrains_wagon_tank.png
+++ /dev/null
Binary files differ
diff --git a/advtrains/advtrains_train_industrial/textures/advtrains_wagon_tank_inv.png b/advtrains/advtrains_train_industrial/textures/advtrains_wagon_tank_inv.png
deleted file mode 100644
index 03401be..0000000
--- a/advtrains/advtrains_train_industrial/textures/advtrains_wagon_tank_inv.png
+++ /dev/null
Binary files differ
diff --git a/advtrains/advtrains_train_industrial/textures/advtrains_wagon_wood.png b/advtrains/advtrains_train_industrial/textures/advtrains_wagon_wood.png
deleted file mode 100644
index acc6f72..0000000
--- a/advtrains/advtrains_train_industrial/textures/advtrains_wagon_wood.png
+++ /dev/null
Binary files differ
diff --git a/advtrains/advtrains_train_industrial/textures/advtrains_wagon_wood_inv.png b/advtrains/advtrains_train_industrial/textures/advtrains_wagon_wood_inv.png
deleted file mode 100644
index 87109dd..0000000
--- a/advtrains/advtrains_train_industrial/textures/advtrains_wagon_wood_inv.png
+++ /dev/null
Binary files differ
diff --git a/advtrains/advtrains_train_japan/depends.txt b/advtrains/advtrains_train_japan/depends.txt
deleted file mode 100644
index 1fb6665..0000000
--- a/advtrains/advtrains_train_japan/depends.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-advtrains
-intllib? \ No newline at end of file
diff --git a/advtrains/advtrains_train_japan/init.lua b/advtrains/advtrains_train_japan/init.lua
deleted file mode 100644
index 8816db3..0000000
--- a/advtrains/advtrains_train_japan/init.lua
+++ /dev/null
@@ -1,144 +0,0 @@
-local S
-if minetest.get_modpath("intllib") then
- S = intllib.Getter()
-else
- S = function(s,a,...)a={a,...}return s:gsub("@(%d+)",function(n)return a[tonumber(n)]end)end
-end
-
-advtrains.register_wagon("engine_japan", {
- mesh="advtrains_engine_japan.b3d",
- textures = {"advtrains_engine_japan.png"},
- drives_on={default=true},
- max_speed=20,
- seats = {
- {
- name=S("Driver stand"),
- attach_offset={x=0, y=8, z=13},
- view_offset={x=0, y=0, z=0},
- driving_ctrl_access=true,
- group="dstand",
- },
- {
- name="1",
- attach_offset={x=-4, y=8, z=0},
- view_offset={x=0, y=0, z=0},
- group="pass",
- },
- {
- name="2",
- attach_offset={x=4, y=8, z=0},
- view_offset={x=0, y=0, z=0},
- group="pass",
- },
- {
- name="3",
- attach_offset={x=-4, y=8, z=-8},
- view_offset={x=0, y=0, z=0},
- group="pass",
- },
- {
- name="4",
- attach_offset={x=4, y=8, z=-8},
- view_offset={x=0, y=0, z=0},
- group="pass",
- },
- },
- seat_groups = {
- dstand={
- name = "Driver Stand",
- access_to = {"pass"},
- require_doors_open=true,
- },
- pass={
- name = "Passenger area",
- access_to = {"dstand"},
- require_doors_open=true,
- },
- },
- assign_to_seat_group = {"dstand", "pass"},
- doors={
- open={
- [-1]={frames={x=0, y=20}, time=1},
- [1]={frames={x=40, y=60}, time=1}
- },
- close={
- [-1]={frames={x=20, y=40}, time=1},
- [1]={frames={x=60, y=80}, time=1}
- }
- },
- door_entry={-1},
- visual_size = {x=1, y=1},
- wagon_span=2.5,
- is_locomotive=true,
- collisionbox = {-1.0,-0.5,-1.0, 1.0,2.5,1.0},
- drops={"default:steelblock 4"},
-}, S("Japanese Train Engine"), "advtrains_engine_japan_inv.png")
-
-advtrains.register_wagon("wagon_japan", {
- mesh="advtrains_wagon_japan.b3d",
- textures = {"advtrains_wagon_japan.png"},
- drives_on={default=true},
- max_speed=20,
- seats = {
- {
- name="1",
- attach_offset={x=-4, y=8, z=8},
- view_offset={x=0, y=0, z=0},
- group="pass",
- },
- {
- name="2",
- attach_offset={x=4, y=8, z=8},
- view_offset={x=0, y=0, z=0},
- group="pass",
- },
- {
- name="1a",
- attach_offset={x=-4, y=8, z=0},
- view_offset={x=0, y=0, z=0},
- group="pass",
- },
- {
- name="2a",
- attach_offset={x=4, y=8, z=0},
- view_offset={x=0, y=0, z=0},
- group="pass",
- },
- {
- name="3",
- attach_offset={x=-4, y=8, z=-8},
- view_offset={x=0, y=0, z=0},
- group="pass",
- },
- {
- name="4",
- attach_offset={x=4, y=8, z=-8},
- view_offset={x=0, y=0, z=0},
- group="pass",
- },
- },
- seat_groups = {
- pass={
- name = "Passenger area",
- access_to = {},
- require_doors_open=true,
- },
- },
- assign_to_seat_group = {"pass"},
- doors={
- open={
- [-1]={frames={x=0, y=20}, time=1},
- [1]={frames={x=40, y=60}, time=1}
- },
- close={
- [-1]={frames={x=20, y=40}, time=1},
- [1]={frames={x=60, y=80}, time=1}
- }
- },
- door_entry={-1, 1},
- visual_size = {x=1, y=1},
- wagon_span=2.3,
- collisionbox = {-1.0,-0.5,-1.0, 1.0,2.5,1.0},
- drops={"default:steelblock 4"},
-}, S("Japanese Train Wagon"), "advtrains_wagon_japan_inv.png")
-
diff --git a/advtrains/advtrains_train_japan/locale/de.txt b/advtrains/advtrains_train_japan/locale/de.txt
deleted file mode 100644
index 63d7a97..0000000
--- a/advtrains/advtrains_train_japan/locale/de.txt
+++ /dev/null
@@ -1,4 +0,0 @@
-Driver Stand = Führerstand
-Japanese Train Engine = Japanische Personenzug-Lokomotive
-Default Seat = Standardsitzplatz
-Japanese Train Wagon = Japanischer Personenzug-Passagierwaggon \ No newline at end of file
diff --git a/advtrains/advtrains_train_japan/models/advtrains_engine_japan.b3d b/advtrains/advtrains_train_japan/models/advtrains_engine_japan.b3d
deleted file mode 100644
index 218d965..0000000
--- a/advtrains/advtrains_train_japan/models/advtrains_engine_japan.b3d
+++ /dev/null
Binary files differ
diff --git a/advtrains/advtrains_train_japan/models/advtrains_wagon_japan.b3d b/advtrains/advtrains_train_japan/models/advtrains_wagon_japan.b3d
deleted file mode 100644
index e6263dd..0000000
--- a/advtrains/advtrains_train_japan/models/advtrains_wagon_japan.b3d
+++ /dev/null
Binary files differ
diff --git a/advtrains/advtrains_train_japan/textures/advtrains_engine_japan.png b/advtrains/advtrains_train_japan/textures/advtrains_engine_japan.png
deleted file mode 100644
index 2bc5fb8..0000000
--- a/advtrains/advtrains_train_japan/textures/advtrains_engine_japan.png
+++ /dev/null
Binary files differ
diff --git a/advtrains/advtrains_train_japan/textures/advtrains_engine_japan_inv.png b/advtrains/advtrains_train_japan/textures/advtrains_engine_japan_inv.png
deleted file mode 100644
index 6af0636..0000000
--- a/advtrains/advtrains_train_japan/textures/advtrains_engine_japan_inv.png
+++ /dev/null
Binary files differ
diff --git a/advtrains/advtrains_train_japan/textures/advtrains_wagon_japan.png b/advtrains/advtrains_train_japan/textures/advtrains_wagon_japan.png
deleted file mode 100644
index c9cddc8..0000000
--- a/advtrains/advtrains_train_japan/textures/advtrains_wagon_japan.png
+++ /dev/null
Binary files differ
diff --git a/advtrains/advtrains_train_japan/textures/advtrains_wagon_japan_inv.png b/advtrains/advtrains_train_japan/textures/advtrains_wagon_japan_inv.png
deleted file mode 100644
index 3e6357c..0000000
--- a/advtrains/advtrains_train_japan/textures/advtrains_wagon_japan_inv.png
+++ /dev/null
Binary files differ
diff --git a/advtrains/advtrains_train_steam/depends.txt b/advtrains/advtrains_train_steam/depends.txt
deleted file mode 100644
index 1fb6665..0000000
--- a/advtrains/advtrains_train_steam/depends.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-advtrains
-intllib? \ No newline at end of file
diff --git a/advtrains/advtrains_train_steam/init.lua b/advtrains/advtrains_train_steam/init.lua
deleted file mode 100644
index 16a71f7..0000000
--- a/advtrains/advtrains_train_steam/init.lua
+++ /dev/null
@@ -1,242 +0,0 @@
-local S
-if minetest.get_modpath("intllib") then
- S = intllib.Getter()
-else
- S = function(s,a,...)a={a,...}return s:gsub("@(%d+)",function(n)return a[tonumber(n)]end)end
-end
-
-advtrains.register_wagon("newlocomotive", {
- mesh="advtrains_engine_steam.b3d",
- textures = {"advtrains_engine_steam.png"},
- is_locomotive=true,
- drives_on={default=true},
- max_speed=10,
- seats = {
- {
- name=S("Driver Stand (left)"),
- attach_offset={x=-5, y=10, z=-10},
- view_offset={x=0, y=6, z=0},
- driving_ctrl_access=true,
- group = "dstand",
- },
- {
- name=S("Driver Stand (right)"),
- attach_offset={x=5, y=10, z=-10},
- view_offset={x=0, y=6, z=0},
- driving_ctrl_access=true,
- group = "dstand",
- },
- },
- seat_groups = {
- dstand={
- name = "Driver Stand",
- access_to = {},
- },
- },
- assign_to_seat_group = {"dstand"},
- visual_size = {x=1, y=1},
- wagon_span=1.85,
- collisionbox = {-1.0,-0.5,-1.0, 1.0,2.5,1.0},
- update_animation=function(self, velocity)
- if self.old_anim_velocity~=advtrains.abs_ceil(velocity) then
- self.object:set_animation({x=1,y=80}, advtrains.abs_ceil(velocity)*15, 0, true)
- self.old_anim_velocity=advtrains.abs_ceil(velocity)
- end
- end,
- custom_on_activate = function(self, staticdata_table, dtime_s)
- minetest.add_particlespawner({
- amount = 10,
- time = 0,
- -- ^ If time is 0 has infinite lifespan and spawns the amount on a per-second base
- minpos = {x=0, y=2, z=1.2},
- maxpos = {x=0, y=2, z=1.2},
- minvel = {x=-0.2, y=1.8, z=-0.2},
- maxvel = {x=0.2, y=2, z=0.2},
- minacc = {x=0, y=-0.1, z=0},
- maxacc = {x=0, y=-0.3, z=0},
- minexptime = 2,
- maxexptime = 4,
- minsize = 1,
- maxsize = 5,
- -- ^ The particle's properties are random values in between the bounds:
- -- ^ minpos/maxpos, minvel/maxvel (velocity), minacc/maxacc (acceleration),
- -- ^ minsize/maxsize, minexptime/maxexptime (expirationtime)
- collisiondetection = true,
- -- ^ collisiondetection: if true uses collision detection
- vertical = false,
- -- ^ vertical: if true faces player using y axis only
- texture = "smoke_puff.png",
- -- ^ Uses texture (string)
- attached = self.object,
- })
- end,
- drops={"default:steelblock 4"},
-}, S("Steam Engine"), "advtrains_engine_steam_inv.png")
-
-advtrains.register_wagon("detailed_steam_engine", {
- mesh="advtrains_detailed_steam_engine.b3d",
- textures = {"advtrains_detailed_steam_engine.png"},
- is_locomotive=true,
- drives_on={default=true},
- max_speed=10,
- seats = {
- {
- name=S("Driver Stand (left)"),
- attach_offset={x=-5, y=10, z=-10},
- view_offset={x=0, y=6, z=0},
- driving_ctrl_access=true,
- group = "dstand",
- },
- {
- name=S("Driver Stand (right)"),
- attach_offset={x=5, y=10, z=-10},
- view_offset={x=0, y=6, z=0},
- driving_ctrl_access=true,
- group = "dstand",
- },
- },
- seat_groups = {
- dstand={
- name = "Driver Stand",
- access_to = {},
- },
- },
- assign_to_seat_group = {"dstand"},
- visual_size = {x=1, y=1},
- wagon_span=2.05,
- collisionbox = {-1.0,-0.5,-1.0, 1.0,2.5,1.0},
- update_animation=function(self, velocity)
- if self.old_anim_velocity~=advtrains.abs_ceil(velocity) then
- self.object:set_animation({x=1,y=80}, advtrains.abs_ceil(velocity)*15, 0, true)
- self.old_anim_velocity=advtrains.abs_ceil(velocity)
- end
- end,
- custom_on_activate = function(self, staticdata_table, dtime_s)
- minetest.add_particlespawner({
- amount = 10,
- time = 0,
- -- ^ If time is 0 has infinite lifespan and spawns the amount on a per-second base
- minpos = {x=0, y=2.3, z=1.45},
- maxpos = {x=0, y=2.3, z=1.4},
- minvel = {x=-0.2, y=1.8, z=-0.2},
- maxvel = {x=0.2, y=2, z=0.2},
- minacc = {x=0, y=-0.1, z=0},
- maxacc = {x=0, y=-0.3, z=0},
- minexptime = 2,
- maxexptime = 4,
- minsize = 1,
- maxsize = 5,
- -- ^ The particle's properties are random values in between the bounds:
- -- ^ minpos/maxpos, minvel/maxvel (velocity), minacc/maxacc (acceleration),
- -- ^ minsize/maxsize, minexptime/maxexptime (expirationtime)
- collisiondetection = true,
- -- ^ collisiondetection: if true uses collision detection
- vertical = false,
- -- ^ vertical: if true faces player using y axis only
- texture = "smoke_puff.png",
- -- ^ Uses texture (string)
- attached = self.object,
- })
- end,
- drops={"default:steelblock 4"},
-}, S("Detailed Steam Engine"), "advtrains_detailed_engine_steam_inv.png")
-
-advtrains.register_wagon("wagon_default", {
- mesh="advtrains_passenger_wagon.b3d",
- textures = {"advtrains_wagon.png"},
- drives_on={default=true},
- max_speed=10,
- seats = {
- {
- name="1",
- attach_offset={x=-4, y=8, z=8},
- view_offset={x=0, y=0, z=0},
- group="pass",
- },
- {
- name="2",
- attach_offset={x=4, y=8, z=8},
- view_offset={x=0, y=0, z=0},
- group="pass",
- },
- {
- name="3",
- attach_offset={x=-4, y=8, z=-8},
- view_offset={x=0, y=0, z=0},
- group="pass",
- },
- {
- name="4",
- attach_offset={x=4, y=8, z=-8},
- view_offset={x=0, y=0, z=0},
- group="pass",
- },
- },
- seat_groups = {
- pass={
- name = "Passenger area",
- access_to = {},
- },
- },
- assign_to_seat_group = {"pass"},
- visual_size = {x=1, y=1},
- wagon_span=3.1,
- collisionbox = {-1.0,-0.5,-1.0, 1.0,2.5,1.0},
- drops={"default:steelblock 4"},
-}, S("Passenger Wagon"), "advtrains_wagon_inv.png")
-advtrains.register_wagon("wagon_box", {
- mesh="advtrains_wagon.b3d",
- textures = {"advtrains_wagon_box.png"},
- drives_on={default=true},
- max_speed=10,
- seats = {},
- visual_size = {x=1, y=1},
- wagon_span=1.8,
- collisionbox = {-1.0,-0.5,-1.0, 1.0,2.5,1.0},
- drops={"default:steelblock 4"},
- has_inventory = true,
- get_inventory_formspec = function(self)
- return "size[8,11]"..
- "list[detached:advtrains_wgn_"..self.unique_id..";box;0,0;8,6;]"..
- "list[current_player;main;0,7;8,4;]"..
- "listring[]"
- end,
- inventory_list_sizes = {
- box=8*6,
- },
-}, S("Box Wagon"), "advtrains_wagon_box_inv.png")
-
-minetest.register_craft({
- output = 'advtrains:newlocomotive',
- recipe = {
- {'', '', 'advtrains:chimney'},
- {'advtrains:driver_cab', 'dye:black', 'advtrains:boiler'},
- {'advtrains:wheel', 'advtrains:wheel', 'advtrains:wheel'},
- },
-})
-
-minetest.register_craft({
- output = 'advtrains:detailed_steam_engine',
- recipe = {
- {'', '', 'advtrains:chimney'},
- {'advtrains:driver_cab', 'dye:green', 'advtrains:boiler'},
- {'advtrains:wheel', 'advtrains:wheel', 'advtrains:wheel'},
- },
-})
-
-minetest.register_craft({
- output = 'advtrains:wagon_default',
- recipe = {
- {'default:steelblock', 'default:steelblock', 'default:steelblock'},
- {'default:glass', 'dye:dark_green', 'default:glass'},
- {'advtrains:wheel', 'advtrains:wheel', 'advtrains:wheel'},
- },
-})
-minetest.register_craft({
- output = 'advtrains:wagon_box',
- recipe = {
- {'group:wood', 'group:wood', 'group:wood'},
- {'group:wood', 'default:chest', 'group:wood'},
- {'advtrains:wheel', '', 'advtrains:wheel'},
- },
-})
diff --git a/advtrains/advtrains_train_steam/locale/de.txt b/advtrains/advtrains_train_steam/locale/de.txt
deleted file mode 100644
index ac06e20..0000000
--- a/advtrains/advtrains_train_steam/locale/de.txt
+++ /dev/null
@@ -1,6 +0,0 @@
-Driver Stand (left) = Führerstand Links
-Driver Stand (right) = Führerstand Rechts
-Steam Engine = Dampflokomotive
-Detailed Steam Engine = detaillierte Dampflokomotive
-Passenger Wagon = Passagierwaggon
-Box wagon = Güterwaggon \ No newline at end of file
diff --git a/advtrains/advtrains_train_steam/models/advtrains_detailed_steam_engine.b3d b/advtrains/advtrains_train_steam/models/advtrains_detailed_steam_engine.b3d
deleted file mode 100644
index 7418d8a..0000000
--- a/advtrains/advtrains_train_steam/models/advtrains_detailed_steam_engine.b3d
+++ /dev/null
Binary files differ
diff --git a/advtrains/advtrains_train_steam/models/advtrains_engine_steam.b3d b/advtrains/advtrains_train_steam/models/advtrains_engine_steam.b3d
deleted file mode 100644
index 6a92f57..0000000
--- a/advtrains/advtrains_train_steam/models/advtrains_engine_steam.b3d
+++ /dev/null
Binary files differ
diff --git a/advtrains/advtrains_train_steam/models/advtrains_passenger_wagon.b3d b/advtrains/advtrains_train_steam/models/advtrains_passenger_wagon.b3d
deleted file mode 100644
index bb057f8..0000000
--- a/advtrains/advtrains_train_steam/models/advtrains_passenger_wagon.b3d
+++ /dev/null
Binary files differ
diff --git a/advtrains/advtrains_train_steam/models/advtrains_wagon.b3d b/advtrains/advtrains_train_steam/models/advtrains_wagon.b3d
deleted file mode 100644
index 5c8214c..0000000
--- a/advtrains/advtrains_train_steam/models/advtrains_wagon.b3d
+++ /dev/null
Binary files differ
diff --git a/advtrains/advtrains_train_steam/textures/advtrains_detailed_engine_steam_inv.png b/advtrains/advtrains_train_steam/textures/advtrains_detailed_engine_steam_inv.png
deleted file mode 100644
index 51adb5a..0000000
--- a/advtrains/advtrains_train_steam/textures/advtrains_detailed_engine_steam_inv.png
+++ /dev/null
Binary files differ
diff --git a/advtrains/advtrains_train_steam/textures/advtrains_detailed_steam_engine.png b/advtrains/advtrains_train_steam/textures/advtrains_detailed_steam_engine.png
deleted file mode 100644
index eab4dc8..0000000
--- a/advtrains/advtrains_train_steam/textures/advtrains_detailed_steam_engine.png
+++ /dev/null
Binary files differ
diff --git a/advtrains/advtrains_train_steam/textures/advtrains_engine_steam.png b/advtrains/advtrains_train_steam/textures/advtrains_engine_steam.png
deleted file mode 100644
index 4b27e77..0000000
--- a/advtrains/advtrains_train_steam/textures/advtrains_engine_steam.png
+++ /dev/null
Binary files differ
diff --git a/advtrains/advtrains_train_steam/textures/advtrains_engine_steam_inv.png b/advtrains/advtrains_train_steam/textures/advtrains_engine_steam_inv.png
deleted file mode 100644
index 8d3fafb..0000000
--- a/advtrains/advtrains_train_steam/textures/advtrains_engine_steam_inv.png
+++ /dev/null
Binary files differ
diff --git a/advtrains/advtrains_train_steam/textures/advtrains_wagon.png b/advtrains/advtrains_train_steam/textures/advtrains_wagon.png
deleted file mode 100644
index c850518..0000000
--- a/advtrains/advtrains_train_steam/textures/advtrains_wagon.png
+++ /dev/null
Binary files differ
diff --git a/advtrains/advtrains_train_steam/textures/advtrains_wagon_box.png b/advtrains/advtrains_train_steam/textures/advtrains_wagon_box.png
deleted file mode 100644
index 8bfbe06..0000000
--- a/advtrains/advtrains_train_steam/textures/advtrains_wagon_box.png
+++ /dev/null
Binary files differ
diff --git a/advtrains/advtrains_train_steam/textures/advtrains_wagon_box_inv.png b/advtrains/advtrains_train_steam/textures/advtrains_wagon_box_inv.png
deleted file mode 100644
index 480f245..0000000
--- a/advtrains/advtrains_train_steam/textures/advtrains_wagon_box_inv.png
+++ /dev/null
Binary files differ
diff --git a/advtrains/advtrains_train_steam/textures/advtrains_wagon_inv.png b/advtrains/advtrains_train_steam/textures/advtrains_wagon_inv.png
deleted file mode 100644
index 0b72ac3..0000000
--- a/advtrains/advtrains_train_steam/textures/advtrains_wagon_inv.png
+++ /dev/null
Binary files differ
diff --git a/advtrains/advtrains_train_subway/depends.txt b/advtrains/advtrains_train_subway/depends.txt
deleted file mode 100644
index 1fb6665..0000000
--- a/advtrains/advtrains_train_subway/depends.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-advtrains
-intllib? \ No newline at end of file
diff --git a/advtrains/advtrains_train_subway/init.lua b/advtrains/advtrains_train_subway/init.lua
deleted file mode 100644
index 8864e92..0000000
--- a/advtrains/advtrains_train_subway/init.lua
+++ /dev/null
@@ -1,90 +0,0 @@
-local S
-if minetest.get_modpath("intllib") then
- S = intllib.Getter()
-else
- S = function(s,a,...)a={a,...}return s:gsub("@(%d+)",function(n)return a[tonumber(n)]end)end
-end
-
-advtrains.register_wagon("subway_wagon", {
- mesh="advtrains_subway_wagon.b3d",
- textures = {"advtrains_subway_wagon.png"},
- drives_on={default=true},
- max_speed=15,
- seats = {
- {
- name="Driver stand",
- attach_offset={x=0, y=10, z=0},
- view_offset={x=0, y=0, z=0},
- driving_ctrl_access=true,
- group="dstand",
- },
- {
- name="1",
- attach_offset={x=-4, y=8, z=8},
- view_offset={x=0, y=0, z=0},
- group="pass",
- },
- {
- name="2",
- attach_offset={x=4, y=8, z=8},
- view_offset={x=0, y=0, z=0},
- group="pass",
- },
- {
- name="3",
- attach_offset={x=-4, y=8, z=-8},
- view_offset={x=0, y=0, z=0},
- group="pass",
- },
- {
- name="4",
- attach_offset={x=4, y=8, z=-8},
- view_offset={x=0, y=0, z=0},
- group="pass",
- },
- },
- seat_groups = {
- dstand={
- name = "Driver Stand",
- access_to = {"pass"},
- require_doors_open=true,
- },
- pass={
- name = "Passenger area",
- access_to = {"dstand"},
- require_doors_open=true,
- },
- },
- assign_to_seat_group = {"pass","dstand"},
- doors={
- open={
- [-1]={frames={x=0, y=20}, time=1},
- [1]={frames={x=40, y=60}, time=1}
- },
- close={
- [-1]={frames={x=20, y=40}, time=1},
- [1]={frames={x=60, y=80}, time=1}
- }
- },
- door_entry={-1, 1},
- visual_size = {x=1, y=1},
- wagon_span=2,
- --collisionbox = {-1.0,-0.5,-1.8, 1.0,2.5,1.8},
- collisionbox = {-1.0,-0.5,-1.0, 1.0,2.5,1.0},
- is_locomotive=true,
- drops={"default:steelblock 4"},
- --custom_on_activate = function(self, dtime_s)
- -- atprint("subway custom_on_activate")
- -- self.object:set_animation({x=1,y=80}, 15, 0, true)
- --end,
-}, S("Subway Passenger Wagon"), "advtrains_subway_wagon_inv.png")
-
---wagons
-minetest.register_craft({
- output = 'advtrains:subway_wagon',
- recipe = {
- {'default:steelblock', 'default:steelblock', 'default:steelblock'},
- {'default:steelblock', 'dye:yellow', 'default:steelblock'},
- {'default:steelblock', 'default:steelblock', 'default:steelblock'},
- },
-})
diff --git a/advtrains/advtrains_train_subway/locale/de.txt b/advtrains/advtrains_train_subway/locale/de.txt
deleted file mode 100644
index 4aceebd..0000000
--- a/advtrains/advtrains_train_subway/locale/de.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-Default Seat (driver stand) = Standardsitzplatz (Führerstand)
-Subway Passenger Wagon = U-Bahn-Waggon \ No newline at end of file
diff --git a/advtrains/advtrains_train_subway/models/advtrains_subway_wagon.b3d b/advtrains/advtrains_train_subway/models/advtrains_subway_wagon.b3d
deleted file mode 100644
index cbd0f8e..0000000
--- a/advtrains/advtrains_train_subway/models/advtrains_subway_wagon.b3d
+++ /dev/null
Binary files differ
diff --git a/advtrains/advtrains_train_subway/textures/advtrains_subway_wagon.png b/advtrains/advtrains_train_subway/textures/advtrains_subway_wagon.png
deleted file mode 100644
index 079d797..0000000
--- a/advtrains/advtrains_train_subway/textures/advtrains_subway_wagon.png
+++ /dev/null
Binary files differ
diff --git a/advtrains/advtrains_train_subway/textures/advtrains_subway_wagon_inv.png b/advtrains/advtrains_train_subway/textures/advtrains_subway_wagon_inv.png
deleted file mode 100644
index 1d0e809..0000000
--- a/advtrains/advtrains_train_subway/textures/advtrains_subway_wagon_inv.png
+++ /dev/null
Binary files differ
diff --git a/advtrains/api_doc.txt b/advtrains/api_doc.txt
new file mode 100644
index 0000000..a1eea92
--- /dev/null
+++ b/advtrains/api_doc.txt
@@ -0,0 +1,222 @@
+Advanced Trains [advtrains] API documentation
+--------
+To use the API, mods must depend on 'advtrains'.
+All boolean values in definition tables default to 'false' and can be omitted.
+### Wagons
+Wagons are registered using the function
+
+advtrains.register_wagon(name, prototype, description, inventory_image)
+- 'name' is the internal name of the wagon. It should follow the mod naming convention, however, this is not enforced.
+ For compatibility reasons, if a mod name is omitted, the wagon will be registered in the advtrains: namespace.
+ Example: A wagon with name="engine_tgv" will be registered as "advtrains:engine_tgv".
+ !IMPORTANT! You must not append a ":" at the start of the name, even if you want to bypass the mod naming convention check. This is because internally the register_wagon function
+ appends a ":" automatically.
+- 'prototype' is the lua entity prototype. The regular definition keys for luaentites apply. Additional required and optional properties see below. DO NOT define 'on_step', 'on_activate', 'on_punch', 'on_rightclick' and 'get_staticdata' since these will be overridden. Use 'custom_*' instead.
+- 'description' is the description of the inventory item that is used to place the wagon.
+- 'inventory_image' is the inventory image of said item.
+
+# Wagon prototype properties
+{
+ ... all regular luaentity properties (mesh, textures, collisionbox a.s.o)...
+ max_speed = 10,
+ ^- optional, default 10: defines the maximum speed this wagon can drive. The maximum speed of a train is determined by the wagon with the lowest max_speed value.
+ seats = {
+ ^- contains zero or more seat definitions. A seat is a place where a player can be attached when getting on a wagon.
+ {
+ name="Left front window",
+ ^- display name of this seat
+ attach_offset={x=0, y=10, z=0},
+ ^- this value is passed to 'set_attach'
+ view_offset={x=0, y=6, z=0},
+ ^- player:set_eye_offset is called with this parameter.
+ group="default"
+ ^- optional. Defines the seat group. See 'seat_groups' below
+ -!- Note: driving_ctrl_access field has moved to seat group definition,
+ -!- but is still partwise supported here. If you don't use seat groups yet,
+ -!- you really should change NOW!
+ },
+ },
+ seat_groups = {
+ ^- If defined, activates advanced seating behavior. See "seating behavior".
+ default = {
+ name = "Seats"
+ ^- name of this seat group, to be shown in get-on menu.
+ access_to = {"foo", "bar"}
+ ^- List of seat groups you can access from this seat using the menu when sitting inside the train.
+ require_doors_open = true
+ ^- Only allow getting on and off if doors are open.
+ driving_ctrl_access=false,
+ ^- If the seat is a driver stand, and players sitting here should get access to the train's driving control.
+ }
+ }
+ assign_to_seat_group = {"default"},
+ ^- optional, like seat_groups. When player right_clicks the wagon, player will be assigned to the first free seat group in the list.
+
+ doors={
+ ^- optional. If defined, defines door animation frames. Opposite door has to be closed during animation period.
+ ^- Remember, advtrains can't handle doors on both sides opened simultaneously.
+ open={
+ [-1]={frames={x=0, y=20}, time=1}, -- open left doors
+ [1]={frames={x=40, y=60}, time=1} -- open right doors
+ sound = <simpleSoundSpec>
+ ^- The sound file of the doors opening. If none is specified, nothing is played.
+ },
+ close={
+ [-1]={frames={x=20, y=40}, time=1}, -- close left doors
+ [1]={frames={x=60, y=80}, time=1} -- close right doors
+ sound = <simpleSoundSpec>
+ ^- The sound file of the doors closing. If none is specified, nothing is played.
+ }
+ },
+ door_entry={ 1.5, -1.5 }
+ ^- optional. If defined, defines the locations of the doors on the model as distance from the object center on the path.
+ ^- Getting on by walking in then takes effect.
+ ^- Positive values mean front, negative ones back. Resulting position is automatically shifted to the right side.
+ door_operation_time = 2
+ ^- Time in seconds specifying how long opening/closing the doors takes. The maximum of this value is used
+ ^- by the stop rail (and possibly ATC) to wait for closing the doors before departure. Default is 1 second.
+
+ coupler_types_front = {scharfenberg=true},
+ coupler_types_back = {chain=true},
+ ^- Defines the available coupler types on this wagon on the front and back side. Wagon will only couple to wagons that have a matching coupler. (this property does not have any visual impact)
+ ^- Default: not given (nil) - causes the wagon to couple to any other wagon regardless of coupler type.
+ ^- Empty table ({}): This wagon does not couple to any other wagon (e.g. for Linetrack vehicles)
+ ^- Register coupler types using ''advtrains.register_coupler_type(type, name)''. advtrains defines the default types "chain" (Buffer and Chain) and "scharfenberg" (Scharfenberg coupler).
+
+ wagon_span=2,
+ ^- How far this wagon extends from its base position. Is the half of the wagon length.
+ ^- Used to determine in which distance the other wagons have to be positioned. Will require tweaking.
+ wheel_positions = {1.5, -1.5},
+ ^- Optional: if defined, the wagon will be placed so that these 2 wheel positions are on the track
+ ^- This parameter is recommended for long wagons (wagon_span >= 2).
+ ^- The position is a distance relative to the center of the wagon.
+ ^- Must have exactly 2 entries, corresponding to the front (1) and rear (2) wheel of the wagon object. 1st must be greater than 2nd.
+ ^- If not provided, the simple 1-position positioning logic will be used (wagon is positioned with the center on the track)
+
+ extent_h = 1,
+ ^- Determines the collision box extent in x/z direction. Defaults to 1 (=3x3)
+ ^- The actual bounding box size is (extent_h*2)+1, so 0 means 1x1, 1 means 3x3 and 2 means 5x5
+ extent_v = 2,
+ ^- Determines the collision box extent in y direction. Defaults to 2 (=3).
+ ^- The actual bounding box size is extent_v+1, so 0 means 1, 1 means 2, 2 means 3 a.s.o.
+ horn_sound = <simpleSoundSpec>,
+ ^- The sound file of the horn. If none is specified, this wagon can't sound a horn. The specified sound file will be looped.
+
+ drops = {"default:steelblock 3"}
+ ^- List of itemstrings what to drop when the wagon is destroyed
+
+ has_inventory = false
+ ^- If this wagon has an inventory. The inventory is saved with the wagon.
+ ^- the following settings are ignored if not.
+ inventory_list_sizes = {
+ box=8*6,
+ },
+ ^- List of assignments of type list_name=size.
+ ^- For every entry, an inventory list is created with the specified size.
+ get_inventory_formspec = function(self, player_name, inventory_name)
+ return "<a formspec>"
+ end,
+ ^- Function that should return the formspec to be displayed when <player> requests to open the wagon's inventory.
+ ^- advtrains.standard_inventory_formspec can be used for ordinary wagons with inventories to show
+ ^- both the inventory grid and a 'Wagon properties' button.
+ ^- Use "list["..inventory_name..";<list_name>;<X>,<Y>;<W>,<H>;<Start>]" to display a wagon's inventory list.
+
+ custom_on_step = function(self, dtime) end
+ ^- optional: Execute custom code on every step
+ custom_on_activate = function(self, dtime_s) end
+ ^- optional: Execute custom code on activate. Staticdata does not need to be saved and restored since all properties written in 'self' are preserved over unloads.
+ custom_on_velocity_change = function(self, velocity, old_velocity) end
+ ^- optional: Function that is called whenever the train's velocity changes or every 2 seconds. Used to call 'self.object:update_animation()' if needed.
+ ^- for compatibility reasons the name 'update_animation' for this function is still supported.
+
+ custom_copy_from_wagon_to_clipboard() = function(wagon) end
+ ^- optional: This is only used by the copy/paste tool to allow wagons that have custom data (such as livery information) to have their data be included in the copy operation.
+ ^- This function must also be defined if paste_to_wagon_from_clipboard() is defined, otherwise neither function will be called.
+ ^- The wagon parameter is a value from the advtrains.wagons[] table representing an exising wagon in the train being copied by the copy/paste tool.
+ ^- This function should return a Lua value (a bool, string, integer or table as needed) that will be passed to the paste_to_wagon_from_clipboard() during the paste operation.
+ paste_to_wagon_from_clipboard() = function(wagon, custom_info)
+ ^- optional: This is only used by the copy/paste tool to allow wagons that have custom data, such as livery information, to have their data be included in the paste operation.
+ ^- This function must also be defined if custom_copy_from_wagon_to_clipboard() is defined, otherwise neither function will be called.
+ ^- The wagon parameter is a value from the advtrains.wagons[] table representing the new wagon that is being created by the copy/paste tool.
+ ^- The custom_info parameter is the value that was returned by the custom_copy_from_wagon_to_clipboard() for the wagon during the copy operation.
+ ^- This function does not need to return a value.
+ ^- Note: advtrains does nothing with custom_info other than pass it to paste_to_wagon_from_clipboard(). It can contain any data that is needed. Mod authors should be aware,
+ ^- however, that although unlikely, players can delete their wagons in between the copy and paste operations and so should avoid passing and using references to the source
+ ^- wagon via custom_info. Improper handling of this situation will lead to a crash during the the paste operation. To be safe, custom_info should always contain a copy of the
+ ^- needed data from the source wagon.
+}
+
+# Notes on wagons
+
+- Every wagon has the field 'id' which assigns each wagon a random id.
+- Properties written in the Lua Entity (self) are discarded when the wagon entity is unloaded. At the moment there is no way to store data inside a wagon persistently.
+- Assuming Z Axis as the axis parallel to the tracks and Y Axis as the one pointing into the sky, wagon models should be dimensioned in a way that:
+ - their origin is centered in X and Z direction
+ - their origin lies 0.5 units above the bottom of the model
+ - the overall extent in X and Y direction is <=3 units
+- wagon_span is then the distance between the model origin and the Z axis extent.
+
+# Seating behavior
+If the advanced seating behavior is active, clicking on a wagon will immediately get you on that wagon depending on the entries in assign_to_seat_group.
+If all seat groups are full, if the doors are closed or if you are not authorized to enter this seat group(e.g. driver stands), will show a warning.
+On a train, right-clicking the wagon will make you get off the train unless:
+- the doors are closed and it requires open doors.
+- you have access to a seat group specified in access_to (you may enter it and it's not full)
+- you are the owner and can access the wagon preferences
+In case there's no possibility, does nothing.
+In case there are multiple possibilities, will show a form.
+
+If you can't enter or leave a train because the doors are closed, holding the Sneak key while right-clicking bypasses the "doors have to be open" enforcement.
+
+### Tracks
+Most modders will be satisfied with the built-in tracks. If cog railways, maglev trains and mine trains are added, it is necessary to understand the definition of tracks. Although the tracks API is there, explaining it would require more effort than me creating the wanted definitions myself. Contact me if you need to register your own rails using my registration functions.
+
+However, it is still possible to register single rails by understanding the node properties of rails.
+minetest.register_node(nodename, {
+ ... usual node definition ...
+ groups = {
+ advtrains_track = 1,
+ advtrains_track_<tracktype>=1
+ ^- these groups tell that the node is a track
+ not_blocking_trains=1,
+ ^- this group tells that the node should not block trains although it's walkable.
+ },
+
+ at_rail_y = 0,
+ ^- Height of this rail node (the y position of a wagon that stands centered on this rail)
+ at_conns = {
+ [1] = { c=0..15, y=0..1 },
+ [2] = { c=0..15, y=0..1 },
+ ( [3] = { c=0..15, y=0..1 }, )
+ ( [4] = { c=0..15, y=0..1 }, )
+ }
+ ^- Connections of this rail. There can be up to 4 connections.
+ 2 connections are a normal rail, 3 connections a turnout (1->2 and 2/3->1) and 4 connections a crossing (1<>2 and 3<>4)
+ c is the direction of the connection (0-16) and y is the height of the connection (rail will only connect when this matches)
+
+ can_dig=function(pos)
+ return not advtrains.get_train_at_pos(pos)
+ end,
+ after_dig_node=function(pos)
+ advtrains.ndb.update(pos)
+ end,
+ after_place_node=function(pos)
+ advtrains.ndb.update(pos)
+ end,
+ ^- the code in these 3 default minetest API functions is required for advtrains to work, however you can add your own code
+
+ advtrains = {
+ on_train_enter=function(pos, train_id, train, index) end
+ ^- called when a train enters the rail
+ on_train_leave=function(pos, train_id, train, index) end
+ ^- called when a train leaves the rail
+
+ -- The following function is only in effect when interlocking is enabled:
+ on_train_approach = function(pos, train_id, train, index, has_entered, lzbdata)
+ ^- called when a train is approaching this position, called exactly once for every path recalculation (which can happen at any time)
+ ^- This is called so that if the train would start braking now, it would come to halt about(wide approx) 5 nodes before the rail.
+ ^- has_entered: when true, the train is already standing on this node with its front tip, and the enter callback has already been called.
+ Possibly, some actions need not to be taken in this case. Only set if it's the very first node the train is standing on.
+ ^- lzbdata should be ignored and nothing should be assigned to it
+ }
+})
diff --git a/advtrains/atc.lua b/advtrains/atc.lua
new file mode 100644
index 0000000..e14e5c1
--- /dev/null
+++ b/advtrains/atc.lua
@@ -0,0 +1,384 @@
+--atc.lua
+--registers and controls the ATC system
+
+-- Get current translator
+local S = advtrains.translate
+
+local atc={}
+
+local eval_conditional
+
+-- ATC persistence table. advtrains.atc is created by init.lua when it loads the save file.
+atc.controllers = {}
+function atc.load_data(data)
+ local temp = data and data.controllers or {}
+ --transcode atc controller data to node hashes: table access times for numbers are far less than for strings
+ for pts, data in pairs(temp) do
+ if type(pts)=="number" then
+ pts=minetest.pos_to_string(minetest.get_position_from_hash(pts))
+ end
+ atc.controllers[pts] = data
+ end
+end
+function atc.save_data()
+ return {controllers = atc.controllers}
+end
+--contents: {command="...", arrowconn=0-15 where arrow points}
+
+--general
+function atc.train_set_command(train, command, arrow)
+ atc.train_reset_command(train, true)
+ train.atc_delay = 0
+ train.atc_arrow = arrow
+ train.atc_command = command
+end
+
+function atc.send_command(pos, par_tid)
+ local pts=minetest.pos_to_string(pos)
+ if atc.controllers[pts] then
+ --atprint("Called send_command at "..pts)
+ local train_id = par_tid or advtrains.get_train_at_pos(pos)
+ if train_id then
+ if advtrains.trains[train_id] then
+ --atprint("send_command inside if: "..sid(train_id))
+ if atc.controllers[pts].arrowconn then
+ atlog("ATC controller at",pts,": This controller had an arrowconn of", atc.controllers[pts].arrowconn, "set. Since this field is now deprecated, it was removed.")
+ atc.controllers[pts].arrowconn = nil
+ end
+
+ local train = advtrains.trains[train_id]
+ local index = advtrains.path_lookup(train, pos)
+
+ local iconnid = 1
+ if index then
+ iconnid = train.path_cn[index]
+ else
+ atwarn("ATC rail at", pos, ": Rail not on train's path! Can't determine arrow direction. Assuming +!")
+ end
+
+ local command = atc.controllers[pts].command
+ command = eval_conditional(command, iconnid==1, train.velocity)
+ if not command then command="" end
+ command=string.match(command, "^%s*(.*)$")
+
+ if command == "" then
+ atprint("Sending ATC Command to", train_id, ": Not modifying, conditional evaluated empty.")
+ return true
+ end
+
+ atc.train_set_command(train, command, iconnid==1)
+ atprint("Sending ATC Command to", train_id, ":", command, "iconnid=",iconnid)
+ return true
+
+ else
+ atwarn("ATC rail at", pos, ": Sending command failed: The train",train_id,"does not exist. This seems to be a bug.")
+ end
+ else
+ atwarn("ATC rail at", pos, ": Sending command failed: There's no train at this position. This seems to be a bug.")
+ -- huch
+ --local train = advtrains.trains[train_id_temp_debug]
+ --atlog("Train speed is",train.velocity,", have moved",train.dist_moved_this_step,", lever",train.lever)
+ --advtrains.path_print(train, atlog)
+ -- TODO track again when ATC bugs occur...
+
+ end
+ else
+ atwarn("ATC rail at", pos, ": Sending command failed: Entry for controller not found.")
+ atwarn("ATC rail at", pos, ": Please visit controller and click 'Save'")
+ end
+ return false
+end
+
+-- Resets any ATC commands the train is currently executing, including the target speed (tarvelocity) it is instructed to hold
+-- if keep_tarvel is set, does not clear the tarvelocity
+function atc.train_reset_command(train, keep_tarvel)
+ train.atc_command=nil
+ train.atc_delay=nil
+ train.atc_brake_target=nil
+ train.atc_wait_finish=nil
+ train.atc_wait_autocouple=nil
+ train.atc_wait_signal=nil
+ train.atc_arrow=nil
+ if not keep_tarvel then
+ train.tarvelocity=nil
+ end
+end
+
+--nodes
+local idxtrans={static=1, mesecon=2, digiline=3}
+local apn_func=function(pos)
+ -- FIX for long-persisting ndb bug: there's no node in parameter 2 of this function!
+ local meta=minetest.get_meta(pos)
+ if meta then
+ meta:set_string("infotext", S("Unconfigured ATC controller"))
+ meta:set_string("formspec", atc.get_atc_controller_formspec(pos, meta))
+ end
+end
+
+advtrains.atc_function = function(def, preset, suffix, rotation)
+ return {
+ after_place_node=apn_func,
+ after_dig_node=function(pos)
+ advtrains.invalidate_all_paths(pos)
+ advtrains.ndb.clear(pos)
+ local pts=minetest.pos_to_string(pos)
+ atc.controllers[pts]=nil
+ end,
+ on_receive_fields = function(pos, formname, fields, player)
+ if advtrains.is_protected(pos, player:get_player_name()) then
+ minetest.record_protection_violation(pos, player:get_player_name())
+ return
+ end
+ local meta=minetest.get_meta(pos)
+ if meta then
+ if not fields.save then
+ return
+ end
+ --meta:set_string("mode", idxtrans[fields.mode])
+ meta:set_string("command", fields.command)
+ --meta:set_string("command_on", fields.command_on)
+ meta:set_string("channel", fields.channel)
+
+ meta:set_string("infotext", S("ATC controller, Command: @1", meta:get_string("command")) )
+
+ meta:set_string("formspec", atc.get_atc_controller_formspec(pos, meta))
+
+ local pts=minetest.pos_to_string(pos)
+ local _, conns=advtrains.get_rail_info_at(pos, advtrains.all_tracktypes)
+ atc.controllers[pts]={command=fields.command}
+ if #advtrains.occ.get_trains_at(pos) > 0 then
+ atc.send_command(pos)
+ end
+ end
+ end,
+ advtrains = {
+ on_train_enter = function(pos, train_id)
+ atc.send_command(pos, train_id)
+ end,
+ },
+ }
+end
+
+function atc.get_atc_controller_formspec(pos, meta)
+ local mode=tonumber(meta:get_string("mode")) or 1
+ local command=meta:get_string("command")
+ local command_on=meta:get_string("command_on")
+ local channel=meta:get_string("channel")
+ local formspec="size[8,6]"
+ -- "dropdown[0,0;3;mode;static,mesecon,digiline;"..mode.."]"
+ if mode<3 then
+ formspec=formspec
+ .."style[command;font=mono]"
+ .."field[0.8,1.5;7,1;command;"..S("Command")..";"..minetest.formspec_escape(command).."]"
+ else
+ formspec=formspec.."field[0.8,1.5;7,1;channel;"..S("Digiline channel")..";"..minetest.formspec_escape(channel).."]"
+ end
+ return formspec.."button_exit[0.5,4.5;7,1;save;"..S("Save").."]"
+end
+
+--from trainlogic.lua train step
+local matchptn={
+ ["SM"]=function(id, train)
+ train.tarvelocity=train.max_speed
+ return 2
+ end,
+ ["S([0-9]+)"]=function(id, train, match)
+ train.tarvelocity=tonumber(match)
+ return #match+1
+ end,
+ ["B([0-9]+)"]=function(id, train, match)
+ local btar = tonumber(match)
+ if train.velocity>btar then
+ train.atc_brake_target=btar
+ if not train.tarvelocity or train.tarvelocity>btar then
+ train.tarvelocity=btar
+ end
+ else
+ -- independent of brake target, must make sure that tarvelocity is not greater than it
+ if train.tarvelocity and train.tarvelocity>btar then
+ train.tarvelocity=btar
+ end
+ end
+ return #match+1
+ end,
+ ["BB"]=function(id, train)
+ train.atc_brake_target = -1
+ train.tarvelocity = 0
+ return 2
+ end,
+ ["W"]=function(id, train)
+ train.atc_wait_finish=true
+ return 1
+ end,
+ ["D([0-9]+)"]=function(id, train, match)
+ train.atc_delay=tonumber(match)
+ return #match+1
+ end,
+ ["R"]=function(id, train)
+ if train.velocity<=0 then
+ advtrains.invert_train(id)
+ advtrains.train_ensure_init(id, train)
+ -- no one minds if this failed... this shouldn't even be called without train being initialized...
+ else
+ atwarn(sid(id), S("ATC Reverse command warning: didn't reverse train, train moving."))
+ end
+ return 1
+ end,
+ ["O([LRC])"]=function(id, train, match)
+ local tt={L=-1, R=1, C=0}
+ local arr=train.atc_arrow and 1 or -1
+ train.door_open = tt[match]*arr
+ return 2
+ end,
+ ["K"] = function(id, train)
+ if train.door_open == 0 then
+ atwarn(sid(id), S("ATC Kick command warning: doors are closed."))
+ return 1
+ end
+ if train.velocity > 0 then
+ atwarn(sid(id), S("ATC Kick command warning: train moving."))
+ return 1
+ end
+ local tp = train.trainparts
+ for i=1,#tp do
+ local data = advtrains.wagons[tp[i]]
+ local obj = advtrains.wagon_objects[tp[i]]
+ if data and obj then
+ local ent = obj:get_luaentity()
+ if ent then
+ for seatno,seat in pairs(ent.seats) do
+ if data.seatp[seatno] and not ent:is_driver_stand(seat) then
+ ent:get_off(seatno)
+ end
+ end
+ end
+ end
+ end
+ return 1
+ end,
+ ["A([01])"]=function(id, train, match)
+ if not advtrains.interlocking then return 2 end
+ advtrains.interlocking.ars_set_disable(train, match=="0")
+ return 2
+ end,
+ ["Cpl"]=function(id, train)
+ train.atc_wait_autocouple=true
+ return 3
+ end,
+ ["G"]=function(id, train)
+ train.atc_wait_signal=true
+ return 1
+ end,
+}
+
+eval_conditional = function(command, arrow, speed)
+ --conditional statement?
+ local is_cond, cond_applies, compare
+ local cond, rest=string.match(command, "^I([%+%-])(.+)$")
+ if cond then
+ is_cond=true
+ if cond=="+" then
+ cond_applies=arrow
+ end
+ if cond=="-" then
+ cond_applies=not arrow
+ end
+ else
+ cond, compare, rest=string.match(command, "^I([<>]=?)([0-9]+)(.+)$")
+ if cond and compare then
+ is_cond=true
+ if cond=="<" then
+ cond_applies=speed<tonumber(compare)
+ end
+ if cond==">" then
+ cond_applies=speed>tonumber(compare)
+ end
+ if cond=="<=" then
+ cond_applies=speed<=tonumber(compare)
+ end
+ if cond==">=" then
+ cond_applies=speed>=tonumber(compare)
+ end
+ end
+ end
+ if is_cond then
+ atprint("Evaluating if statement: "..command)
+ atprint("Cond: "..(cond or "nil"))
+ atprint("Applies: "..(cond_applies and "true" or "false"))
+ atprint("Rest: "..rest)
+ --find end of conditional statement
+ local nest, pos, elsepos=0, 1
+ while nest>=0 do
+ if pos>#rest then
+ atwarn(sid(id), S("ATC command syntax error: I statement not closed: @1",command))
+ return ""
+ end
+ local char=string.sub(rest, pos, pos)
+ if char=="I" then
+ nest=nest+1
+ end
+ if char==";" then
+ nest=nest-1
+ end
+ if nest==0 and char=="E" then
+ elsepos=pos+0
+ end
+ pos=pos+1
+ end
+ if not elsepos then elsepos=pos-1 end
+ if cond_applies then
+ command=string.sub(rest, 1, elsepos-1)..string.sub(rest, pos)
+ else
+ command=string.sub(rest, elsepos+1, pos-2)..string.sub(rest, pos)
+ end
+ atprint("Result: "..command)
+ end
+ return command
+end
+
+function atc.execute_atc_command(id, train)
+ --strip whitespaces
+ local command=string.match(train.atc_command, "^%s*(.*)$")
+
+
+ if string.match(command, "^%s*$") then
+ train.atc_command=nil
+ return
+ end
+
+ train.atc_command = eval_conditional(command, train.atc_arrow, train.velocity)
+
+ if not train.atc_command then return end
+ command=string.match(train.atc_command, "^%s*(.*)$")
+
+ if string.match(command, "^%s*$") then
+ train.atc_command=nil
+ return
+ end
+
+ for pattern, func in pairs(matchptn) do
+ local match=string.match(command, "^"..pattern)
+ if match then
+ local patlen=func(id, train, match)
+ --atdebug("Executing: "..string.sub(command, 1, patlen))
+ --atdebug("Train ATC State: tvel=",train.tarvelocity,"brktar=",train.atc_brake_target,"delay=",train.atc_delay,"wfinish=",train.atc_wait_finish,"wacpl=",train.atc_wait_autocouple)
+
+ train.atc_command=string.sub(command, patlen+1)
+ if train.atc_delay<=0
+ and not train.atc_wait_finish
+ and not train.atc_wait_autocouple
+ and not train.atc_wait_signal then
+ --continue (recursive, cmds shouldn't get too long, and it's a end-recursion.)
+ atc.execute_atc_command(id, train)
+ end
+ return
+ end
+ end
+ atwarn(sid(id), S("ATC command parse error: Unknown command: @1", command))
+ atc.train_reset_command(train, true)
+end
+
+
+
+--move table to desired place
+advtrains.atc=atc
diff --git a/advtrains/atc_command.txt b/advtrains/atc_command.txt
deleted file mode 100644
index 3df60c8..0000000
--- a/advtrains/atc_command.txt
+++ /dev/null
@@ -1,83 +0,0 @@
-ATC Command Syntax
-
-A train runs the current ATC command once it receives it, including delayed instructions. If the train receives a new command, the current command is discarded.
-Spaces can be inserted into commands as needed and are ignored.
-
-# simple commands:
-
-S<[0-9]+ speed or 'M'>
-Set target speed of train to <speed>. Accelerates if slower, rolls if faster. 'M' means maximum speed.
-Execution of command continues immediately.
-
-B<[0-9]+ speed>
-Brake until speed is reached. If faster, apply brakes, if slower, do nothing.
-Execution of command continues immediately.
-
-Examples:
-SM : accelerate to maximum speed
-S0 : roll to stand
-B0 : brake to stand
-S0B3 or B3S0: brake to 3, then roll to stand.
-
-W
-Wait until S and/or B commands reached the desired speed before continuing execution.
-
-D<[0-9]+ time>
-Delay: Wait for time seconds before continuing execution.
-
-R
-Reverse: change movement direction of train. ONLY WORKS WHEN TRAIN STANDS, else no-op.
-Use B0WR to definitely change direction.
-
-Examples:
-B0 W R D10 SM
-Subway train stopping in dead end station and returning in opposite direction
-
-OL
-Open left doors
-OR
-Open right doors
-OC
-Close Doors
-All door commands are relative to the arrow direction, so if a train drives to opposite arrow direction, L will open its right doors from driver perspective.
-Execution continues immediately, there is no way to wait for all doors to be opened/closed.
-
-Example:
-B0 W OL D10 OC D1 SM
-Subway train: stop in station and open doors, depart after 10 seconds.
-
-# conditional statements:
-
-I<condition><code>;
-Execute code only if condition applies
-I<condition><code1>E<code2>;
-Execute code1 only if condition applies, else execute code2
-
-Conditions:
-+ / -
-Tests the train's movement direction against the arrow on the ATC rail: M+ is true when train drives in direction of arrow.
-
-[</>/<=/>=][speed]
-Test if train's speed is greater or smaller than the given value
-
-Examples:
-I- B0 W R ; S8
-If the train drives in the 'wrong' direction, stop and reverse; independently accelerate to speed 8 afterwards.
-
-I<8 S8 ;
-If the train is slower than 8, accelerate to 8.
-
-# ATC controller operation modes
-static: Only give 1 static command.
-
-mesecon: Give 2 different commands depending on if the controller is mesecon-powered or not
-digiline: Don't give any commands by itself. When a train passes, a digiline message in the form of "[+/-][speed]" is sent on the set channel (where +/- means the same as with conditions). Any digiline message sent to the controller will be interpreted as ATC command and sent to the train.
-** the latter two are not yet implemented.
-
-# Persistence
-ATC controllers that are configured as 'static' or 'mesecon' are persistent over mapblock unloads and will even command the train when the mapblock is unloaded. This is not possible with digilines since these do not work in unloaded mapchunks.
-
-# LUA ATC controller (in development)
-The LUA ATC Controller will operate by using LUA code. All operations shown above will have a function equivalent. Additionally all LUA ATC controllers share an environment and setting signal and switch status will be possible to allow for complicated railway systems/fully automated subways a.s.o.
-Also planned:
-- digicompute add-on to allow computer access to the ATC environment (railway maps... ... ... ... ...)
diff --git a/advtrains/copytool.lua b/advtrains/copytool.lua
new file mode 100755
index 0000000..7e12045
--- /dev/null
+++ b/advtrains/copytool.lua
@@ -0,0 +1,241 @@
+--clipboard = {trainlen = number, [n] = {type = string, flipped = bool, properties = {}, bike_painter_livery = string, custom_info = <optional custom data>}
+
+-- Yaw is in radians. There are 2pi rad in a circle. North is the 0 point and the angle increases anticlockwise.
+-- 4.712389 = 1.5pi; sin(1.5pi) = -1
+-- 7.853981 = 2.5pi; sin(2.5pi) = 1
+
+-- Get current translator
+local S = advtrains.translate
+
+minetest.register_tool("advtrains:copytool", {
+ description = S("Train copy/paste tool\n\nLeft-click: copy train\nRight-click: paste train"),
+ inventory_image = "advtrains_copytool.png",
+ wield_image = "advtrains_copytool.png",
+ stack_max = 1,
+ -- Paste: Take the clipboard and the player yaw, and attempt to place a new train in the world.
+ -- The front of the train is used as the start of the new train and it proceeds backwards from
+ -- the direction of travel.
+ on_place = function(itemstack, placer, pointed_thing)
+ if ((not pointed_thing.type == "node") or (not placer.get_player_name)) then
+ return
+ end
+ local pname = placer:get_player_name()
+
+ local node=minetest.get_node_or_nil(pointed_thing.under)
+ if not node then atprint("[advtrains]Ignore at placer position") return itemstack end
+ local nodename=node.name
+ if(not advtrains.is_track(nodename)) then
+ atprint("no track here, not placing.")
+ return itemstack
+ end
+ if not minetest.check_player_privs(placer, {train_operator = true }) then
+ minetest.chat_send_player(pname, S("You do not have the @1 privilege.", "train_operator"))
+ return itemstack
+ end
+ if not minetest.check_player_privs(placer, {train_admin = true }) and minetest.is_protected(pointed_thing.under, placer:get_player_name()) then
+ return itemstack
+ end
+ local tconns=advtrains.get_track_connections(node.name, node.param2)
+ local yaw = placer:get_look_horizontal()
+ local plconnid = advtrains.yawToClosestConn(yaw, tconns)
+
+ local prevpos = advtrains.get_adjacent_rail(pointed_thing.under, tconns, plconnid, {default=true})
+ if not prevpos then
+ minetest.chat_send_player(pname, S("The track you are trying to place the wagon on is not long enough."))
+ return
+ end
+
+ local meta = itemstack:get_meta()
+ if not meta then
+ minetest.chat_send_player(pname, S("The clipboard couldn't access the metadata. Paste failed."))
+ return
+ end
+ local clipboard = meta:get_string("clipboard")
+ if (clipboard == "") then
+ minetest.chat_send_player(pname, S("The clipboard is empty."));
+ return
+ end
+ clipboard = minetest.deserialize(clipboard)
+ if (clipboard.wagons == nil) then
+ minetest.chat_send_player(pname, S("The clipboard is empty."));
+ return
+ end
+
+ local wagons = {}
+ local n = 1
+ for _, clip_data in pairs(clipboard.wagons) do
+ wagons[n] = advtrains.create_wagon(clip_data.type, pname)
+ local wagon = advtrains.wagons[wagons[n]]
+ wagon.wagon_flipped = clip_data.wagon_flipped
+
+ -- Paste relevant wagon properties
+ wagon.whitelist = clip_data.properties.whitelist
+ wagon.roadnumber = clip_data.properties.roadnumber
+ wagon.fc = clip_data.properties.fc
+ wagon.fcind = clip_data.properties.fcind
+
+ -- Paste bike painter livery information
+ if clip_data.bike_painter_livery then
+ wagon.livery = clip_data.bike_painter_livery
+ end
+
+ -- Paste any optional custom data
+ if clip_data.custom_info then
+ local wagon_proto = advtrains.wagon_prototypes[wagon.type or wagon.entity_name]
+ if wagon_proto and wagon_proto.custom_paste_to_wagon_from_clipboard then
+ wagon_proto.custom_paste_to_wagon_from_clipboard(wagon, clip_data.custom_info)
+ end
+ end
+
+ n = n + 1
+ end
+
+ local id=advtrains.create_new_train_at(pointed_thing.under, plconnid, 0, wagons)
+ local train = advtrains.trains[id]
+ train.off_track = train.end_index<train.path_trk_b
+ if (train.off_track) then
+ minetest.chat_send_player(pname, S("Back of train would end up off track, cancelling."))
+ advtrains.remove_train(id)
+ return
+ end
+ train.text_outside = clipboard.text_outside
+ train.text_inside = clipboard.text_inside
+ train.routingcode = clipboard.routingcode
+ train.line = clipboard.line
+
+ return
+ end,
+ -- Copy: Take the pointed-at train and put it on the clipboard
+ on_use = function(itemstack, user, pointed_thing)
+ if not user:get_player_name() then return end
+ if (pointed_thing.type ~= "object") then return end
+
+ local le = pointed_thing.ref:get_luaentity()
+ if (le == nil) then
+ minetest.chat_send_player(user:get_player_name(), S("No such lua entity."))
+ return
+ end
+
+ local wagon = advtrains.wagons[le.id]
+ if (not (le.id and advtrains.wagons[le.id])) then
+ minetest.chat_send_player(user:get_player_name(), S("No such wagon: @1.", le.id))
+ return
+ end
+
+ local train = advtrains.trains[wagon.train_id]
+ if (not train) then
+ minetest.chat_send_player(user:get_player_name(), S("No such train: @1.", wagon.train_id))
+ return
+ end
+
+ -- Record the train length. The paste operation should require this much free space.
+ local clipboard = {
+ trainlen = math.ceil(train.trainlen),
+ text_outside = train.text_outside,
+ text_inside = train.text_inside,
+ routingcode = train.routingcode,
+ line = train.line,
+ wagons = {}
+ }
+ local trainLength = math.ceil(train.trainlen)
+
+ local n = 1
+ for _, wagonid in pairs(train.trainparts) do
+ local wagon = advtrains.wagons[wagonid]
+ clipboard.wagons[n] = {
+ wagon_flipped = wagon.wagon_flipped,
+ properties = {
+ -- Copy relevant wagon properties
+ whitelist = wagon.whitelist,
+ roadnumber = wagon.roadnumber,
+ fc = wagon.fc,
+ fcind = wagon.fcind,
+ },
+ type = wagon.type
+ }
+
+ -- Copy bike painter livery information
+ if wagon.livery and type(wagon.livery) == "string" then
+ -- As a convenience for older wagon mods, copy the livery string that can be set
+ -- by some mods that support using the bike painter. Note that this will result in
+ -- incomplete or missing livery information being copied for some mods that use
+ -- additional fields for livery information. In general, all mods that support
+ -- customizing liveries should provide the necessary implementations of
+ -- custom_copy_from_wagon_to_clipboard() and custom_paste_to_wagon_from_clipboard()
+ -- in their wagon's prototype to support their liveries being properly copied with
+ -- this tool. It is beyond the scope of advtrains to support livery schemes defined
+ -- in other mods.
+
+ -- As with code that supports the bike painter elsewhere in advtrains, this code
+ -- should be considered temporary since it may be removed in the future.
+ clipboard.wagons[n].bike_painter_livery = wagon.livery
+ end
+
+ -- Copy any custom data (for liveries or other uses) if defined in the wagon's prototype
+ local wagon_proto = advtrains.wagon_prototypes[wagon.type or wagon.entity_name]
+ if wagon_proto and wagon_proto.custom_copy_from_wagon_to_clipboard and wagon_proto.custom_paste_to_wagon_from_clipboard then
+ -- Use wagon_proto.custom_copy_from_wagon_to_clipboard() and
+ -- wagon_proto.custom_paste_to_wagon_from_clipboard() if and only if both are
+ -- defined. They should always be defined in tandem for a wagon when custom liveries
+ -- or other mod specific data need to be copied by this tool. The content of
+ -- custom_info is not relevant to the copy tool. It is treated as a "black box".
+ clipboard.wagons[n].custom_info = wagon_proto.custom_copy_from_wagon_to_clipboard(wagon)
+ end
+
+ n = n + 1
+ end
+
+ local function flip_clipboard(wagon_clipboard)
+ local flipped = {}
+ local numWagons = #wagon_clipboard
+ for k, v in ipairs(wagon_clipboard) do
+ local otherSide = (numWagons-k)+1
+ flipped[otherSide] = v
+ local wagon = flipped[otherSide]
+ wagon.wagon_flipped = not wagon.wagon_flipped
+ end
+ return flipped
+ end
+
+ local function is_loco(wagon_id)
+ local wagon = advtrains.wagons[wagon_id]
+ if (not wagon) then return false end
+ local wagon_proto = advtrains.wagon_prototypes[wagon.type or wagon.entity_name]
+ if wagon_proto and wagon_proto.is_locomotive then
+ return true
+ end
+ return false
+ end
+
+ -- Decide on a new 'front of train' and possibly flip the train.
+ -- Locomotive on one end = loco-hauled, that end is front;
+ -- if (advtrains.wagons[train.trainparts[1]].is_locomotive) then -- do nothing, train is already in right order
+ local numWagons = #train.trainparts
+ local backLoco = train.trainparts[numWagons]
+ backLoco = is_loco(backLoco)
+ local frontLoco = train.trainparts[1]
+ frontLoco = is_loco(frontLoco)
+ if ((backLoco) and (not frontLoco)) then
+ clipboard.wagons = flip_clipboard(clipboard.wagons)
+ --minetest.chat_send_player(user:get_player_name(), "Flipped train: Loco-hauled")
+ end
+ -- locomotives on both ends = train is push-pull / multi-unit, has no front, do nothing
+ -- no locomotives on ends = rake of wagons, front is end closest to where player copied.
+ if ((not frontLoco) and (not backLoco)) then
+
+ if (wagon.pos_in_trainparts / numWagons > 0.5) then -- towards the end of the rain
+ clipboard.wagons = flip_clipboard(clipboard.wagons)
+ --minetest.chat_send_player(user:get_player_name(), "Flipped train: Rake")
+ end
+ end
+
+ local meta = itemstack:get_meta()
+ if not meta then
+ minetest.chat_send_player(pname, S("The clipboard couldn't access the metadata. Copy failed."))
+ return
+ end
+ meta:set_string("clipboard", minetest.serialize(clipboard))
+ minetest.chat_send_player(user:get_player_name(), S("Train copied."))
+ return itemstack
+ end
+})
diff --git a/advtrains/couple.lua b/advtrains/couple.lua
new file mode 100644
index 0000000..cb325a0
--- /dev/null
+++ b/advtrains/couple.lua
@@ -0,0 +1,551 @@
+--couple.lua
+--Handles coupling and discoupling of trains, and defines the coupling entities
+--Rework June 2021 - some functions from trainlogic.lua have been moved here
+
+-- COUPLING --
+-- During coupling rework, the behavior of coupling was changed to make automation easier. It is now as follows:
+-- Coupling is only ever initiated when a train is standing somewhere (not moving) and another train drives onto one of its ends
+-- with a speed greater than 0
+-- "stationary" train is the one standing there - in old code called "train2"
+-- "initiating" train is the one that approached it and bumped into it - typically an engine - in old code called "train1"
+-- When the initiating train has autocouple set, trains are immediately coupled
+-- When not, a couple entity is spawned and coupling commences on click
+-- Coupling MUST preserve the train ID of the initiating train, so it is done like this:
+ -- index of initiating train is set so that it matches the front pos of stationary train
+ -- remove stationary train
+ -- wagons of stationary train are inserted at the beginning of initiating train (considers direction of stat_train and inserts reverse if required)
+
+-- train.couple_* contain references to ObjectRefs of couple objects, which contain all relevant information
+-- These objectRefs will delete themselves once the couples no longer match (see below)
+
+-- Get current translator
+local S = advtrains.translate
+
+advtrains.coupler_types = {}
+
+function advtrains.register_coupler_type(code, name)
+ advtrains.coupler_types[code] = name
+end
+
+-- Register some default couplers
+advtrains.register_coupler_type("chain", S("Buffer and Chain Coupler"))
+advtrains.register_coupler_type("scharfenberg", S("Scharfenberg Coupler"))
+
+for _, name in pairs {"couple", "decouple"} do
+ local t = {}
+ local function reg(f)
+ table.insert(t, f)
+ end
+ local function cb(...)
+ for _, f in ipairs(t) do
+ f(...)
+ end
+ end
+ advtrains["te_registered_on_" .. name] = t
+ advtrains["te_register_on_" .. name] = reg
+ advtrains["te_run_callbacks_on_" .. name] = cb
+end
+
+local function create_couple_entity(pos, train1, t1_is_front, train2, t2_is_front)
+ local id1 = train1.id
+ local id2 = train2.id
+
+ -- delete previous couple entities
+ if t1_is_front then
+ if train1.cpl_front then train1.cpl_front:remove() end
+ else
+ if train1.cpl_back then train1.cpl_back:remove() end
+ end
+ if t2_is_front then
+ if train2.cpl_front then train2.cpl_front:remove() end
+ else
+ if train2.cpl_back then train2.cpl_back:remove() end
+ end
+
+ local obj=minetest.add_entity(pos, "advtrains:couple")
+ if not obj then error("Failed creating couple object!") return end
+ local le=obj:get_luaentity()
+ le.train_id_1=id1
+ le.t1_is_front=t1_is_front
+ le.train_id_2=id2
+ le.t2_is_front=t2_is_front
+ --atdebug("created couple between",train1.id,train2.id,t2_is_front)
+
+ if t1_is_front then
+ train1.cpl_front = obj
+ else
+ train2.cpl_back = obj
+ end
+ if t2_is_front then
+ train2.cpl_front = obj
+ else
+ train2.cpl_back = obj
+ end
+end
+
+-- Old static couple checking. Never used for autocouple, only used for standing trains if train did not approach
+local CPL_CHK_DST = -1
+local CPL_ZONE = 2
+function advtrains.train_check_couples(train)
+ --atdebug("rechecking couples")
+ if train.cpl_front then
+ if not train.cpl_front:get_yaw() then
+ -- objectref is no longer valid. reset.
+ train.cpl_front = nil
+ end
+ end
+ if not train.cpl_front then
+ -- recheck front couple
+ local pos = advtrains.path_get(train, atround(train.index) + CPL_CHK_DST)
+ if advtrains.is_node_loaded(pos) then -- if the position is loaded...
+ local front_trains = advtrains.occ.reverse_lookup_sel(pos, "in_train")
+ for tid, idx in pairs(front_trains) do
+ local other_train = advtrains.trains[tid]
+ if not advtrains.train_ensure_init(tid, other_train) then
+ atwarn("Train",tid,"is not initialized! Couldn't check couples!")
+ return
+ end
+ --atdebug(train.id,"front: ",idx,"on",tid,atround(other_train.index),atround(other_train.end_index))
+ if other_train.velocity == 0 then
+ if idx>=other_train.index and idx<=other_train.index + CPL_ZONE then
+ create_couple_entity(pos, train, true, other_train, true)
+ break
+ end
+ if idx<=other_train.end_index and idx>=other_train.end_index - CPL_ZONE then
+ create_couple_entity(pos, train, true, other_train, false)
+ break
+ end
+ end
+ end
+ end
+ end
+ if train.cpl_back then
+ if not train.cpl_back:get_yaw() then
+ -- objectref is no longer valid. reset.
+ train.cpl_back = nil
+ end
+ end
+ if not train.cpl_back then
+ -- recheck back couple
+ local pos = advtrains.path_get(train, atround(train.end_index) - CPL_CHK_DST)
+ if advtrains.is_node_loaded(pos) then -- if the position is loaded...
+ local back_trains = advtrains.occ.reverse_lookup_sel(pos, "in_train")
+ for tid, idx in pairs(back_trains) do
+ local other_train = advtrains.trains[tid]
+ if not advtrains.train_ensure_init(tid, other_train) then
+ atwarn("Train",tid,"is not initialized! Couldn't check couples!")
+ return
+ end
+ --atdebug(train.id,"back: ",idx,"on",tid,atround(other_train.index),atround(other_train.end_index))
+ if other_train.velocity == 0 then
+ if idx>=other_train.index and idx<=other_train.index + CPL_ZONE then
+ create_couple_entity(pos, train, false, other_train, true)
+ break
+ end
+ if idx<=other_train.end_index and idx>=other_train.end_index - CPL_ZONE then
+ create_couple_entity(pos, train, false, other_train, false)
+ break
+ end
+ end
+ end
+ end
+ end
+end
+
+-- Deletes couple entities from the train
+function advtrains.couple_invalidate(train)
+ if train.cpl_back then
+ train.cpl_back:remove()
+ train.cpl_back = nil
+ end
+ if train.cpl_front then
+ train.cpl_front:remove()
+ train.cpl_front = nil
+ end
+ train.couples_up_to_date = nil
+end
+
+-- Called from train_step_b() when the current train (init_train) just stopped at one of the end indices of another train (stat_train)
+-- Depending on autocouple, either couples immediately or spawns a couple entity
+function advtrains.couple_initiate_with(init_train, stat_train, stat_is_front)
+ --atdebug("Couple init autocouple=",init_train.autocouple,"atc_w_acpl=",init_train.atc_wait_autocouple)
+ if init_train.autocouple or init_train.atc_wait_autocouple then
+ local cplmatch, msg = advtrains.check_matching_coupler_types(init_train, true, stat_train, stat_is_front)
+ if cplmatch then
+ advtrains.couple_trains(init_train, false, stat_train, stat_is_front)
+ -- clear atc couple waiting blocker
+ init_train.atc_wait_autocouple = nil
+ return
+ end
+ end
+ -- get here if either autocouple is not on or couples dont match
+ local pos = advtrains.path_get_interpolated(init_train, init_train.index)
+ create_couple_entity(pos, init_train, true, stat_train, stat_is_front)
+ -- clear ATC command on collision
+ advtrains.atc.train_reset_command(init_train)
+
+end
+
+-- check if the player has permission for the first/last wagon of the train
+local function check_twagon_owner(train, b_first, pname)
+ local wtp = b_first and 1 or #train.trainparts
+ local wid = train.trainparts[wtp]
+ local wdata = advtrains.wagons[wid]
+ if wdata then
+ return advtrains.check_driving_couple_protection(pname, wdata.owner, wdata.whitelist)
+ end
+ return false
+end
+
+-- Perform coupling, but check if the player is authorized to couple
+function advtrains.safe_couple_trains(train1, t1_is_front, train2, t2_is_front, pname)
+
+ if pname and not minetest.check_player_privs(pname, "train_operator") then
+ minetest.chat_send_player(pname, S("You are not allowed to couple trains without the train_operator privilege."))
+ return false
+ end
+
+ local wck_t1, wck_t2
+ if pname then
+ wck_t1 = check_twagon_owner(train1, t1_is_front, pname)
+ wck_t2 = check_twagon_owner(train2, t2_is_front, pname)
+ end
+ if (wck_t1 or wck_t2) or not pname then
+
+ local cplmatch, msg = advtrains.check_matching_coupler_types(train1, t1_is_front, train2, t2_is_front)
+ if cplmatch then
+ advtrains.couple_trains(train1, not t1_is_front, train2, t2_is_front)
+ else
+ minetest.chat_send_player(pname, msg)
+ end
+ end
+end
+
+-- Actually performs the train coupling. Always retains train ID of train1
+function advtrains.couple_trains(init_train, invert_init_train, stat_train, stat_train_opposite)
+ --atdebug("Couple trains init=",init_train.id,"initinv=",invert_init_train,"stat=",stat_train.id,"statreverse=",stat_train_opposite)
+
+ if not advtrains.train_ensure_init(init_train.id, init_train) then
+ atwarn("Coupling: initiating train",init_train.id,"is not initialized! Operation aborted!")
+ return
+ end
+ if not advtrains.train_ensure_init(stat_train.id, stat_train) then
+ atwarn("Coupling: stationary train",stat_train.id,"is not initialized! Operation aborted!")
+ return
+ end
+
+ -- only used with the couple entity
+ if invert_init_train then
+ advtrains.invert_train(init_train.id)
+ end
+
+ local itp = init_train.trainparts
+ local init_wagoncnt = #itp
+ local stp = stat_train.trainparts
+ local stat_wagoncnt = #stp
+ local stat_trainlen = stat_train.trainlen -- save the train length of stat train, to be added to index
+
+ -- sanity check, prevent coupling if train would be longer than 20 after coupling
+ local tot_len = init_wagoncnt + stat_wagoncnt
+ if tot_len > advtrains.TRAIN_MAX_WAGONS then
+ atwarn(S("Cannot couple @1 and @2 - train would have length @3 which is above the limit of @4", stat_train.id, init_train.id, tot_len, advtrains.TRAIN_MAX_WAGONS))
+ return
+ end
+
+ advtrains.te_run_callbacks_on_couple(init_train, stat_train)
+
+ if stat_train_opposite then
+ -- insert wagons in inverse order and set their wagon_flipped state
+ for i=1,stat_wagoncnt do
+ table.insert(itp, 1, stp[i])
+ local wdata = advtrains.wagons[stp[i]]
+ if wdata then
+ wdata.wagon_flipped = not wdata.wagon_flipped
+ else
+ atwarn("While coupling, wagon",stp[i],"of stationary train",stat_train.id,"not found!")
+ end
+ end
+ else
+ --insert wagons in normal order
+ for i=stat_wagoncnt,1,-1 do
+ table.insert(itp, 1, stp[i])
+ end
+ end
+
+ -- TODO: migrate some of the properties from stat_train to init_train?
+
+ advtrains.remove_train(stat_train.id)
+
+ -- Set train index forward
+ init_train.index = advtrains.path_get_index_by_offset(init_train, init_train.index, stat_trainlen)
+
+ advtrains.update_trainpart_properties(init_train.id)
+ advtrains.update_train_start_and_end(init_train)
+
+ advtrains.couple_invalidate(init_train)
+ return true
+end
+
+-- Couple types matching check
+-- returns: true, nil if OK
+-- false, errmsg if there is an error
+function advtrains.check_matching_coupler_types(t1, t1_front, t2, t2_front)
+ -- 1. get wagons
+ local t1_wid
+ if t1_front then
+ t1_wid = t1.trainparts[1]
+ else
+ t1_wid = t1.trainparts[#t1.trainparts]
+ end
+ local t2_wid
+ if t2_front then
+ t2_wid = t2.trainparts[1]
+ else
+ t2_wid = t2.trainparts[#t2.trainparts]
+ end
+
+ --atdebug("CMCT: t1_wid",t1_wid,"t2_wid",t2_wid,"")
+
+ if not t1_wid or not t2_wid then
+ return false, "Unable to retrieve wagons from train"--note: no translation needed, case should not occur
+ end
+
+ local t1_wagon = advtrains.wagons[t1_wid]
+ local t2_wagon = advtrains.wagons[t2_wid]
+
+ if not t1_wagon or not t2_wagon then
+ return false, "At least one of wagons "..t1_wagon.." or "..t2_wagon.." does not exist"--note: no translation needed, case should not occur
+ end
+
+ -- these calls do not fail, they may return placeholder - doesn't matter
+ local _,t1_wpro = advtrains.get_wagon_prototype(t1_wagon)
+ local _,t2_wpro = advtrains.get_wagon_prototype(t2_wagon)
+
+ -- get correct couplers table (front/back)
+ local t1_cplt
+ if not t1_front == not t1_wagon.wagon_flipped then --fancy XOR
+ t1_cplt = t1_wpro.coupler_types_back
+ else
+ t1_cplt = t1_wpro.coupler_types_front
+ end
+ local t2_cplt
+ if not t2_front == not t2_wagon.wagon_flipped then --fancy XOR
+ t2_cplt = t2_wpro.coupler_types_back
+ else
+ t2_cplt = t2_wpro.coupler_types_front
+ end
+
+ --atdebug("CMCT: t1",t1_cplt,"t2",t2_cplt,"")
+
+ -- if at least one of the trains has no couplers table, it always couples (fallback behavior and mode for universal shunters)
+ if minetest.settings:get_bool("advtrains_universal_couplers", false) or not t1_cplt or not t2_cplt then
+ return true
+ end
+
+ -- have common coupler?
+ for typ,_ in pairs(t1_cplt) do
+ if t2_cplt[typ] then
+ --atdebug("CMCT: Matching type",typ)
+ return true
+ end
+ end
+ --no match, give user an info
+ local t1_cplhr, t2_cplhr = {},{}
+ for typ,_ in pairs(t1_cplt) do
+ table.insert(t1_cplhr, advtrains.coupler_types[typ] or typ)
+ end
+ if #t1_cplhr==0 then t1_cplhr[1]=S("<No coupler>") end
+ for typ,_ in pairs(t2_cplt) do
+ table.insert(t2_cplhr, advtrains.coupler_types[typ] or typ)
+ end
+ if #t2_cplhr==0 then t2_cplhr[1]=S("<No coupler>") end
+ return false, S("Can not couple: The couplers of the trains do not match (@1 and @2).", table.concat(t1_cplhr, ","), table.concat(t2_cplhr, ","))
+end
+
+-- DECOUPLING --
+function advtrains.split_train_at_fc(train, count_empty, length_limit)
+ -- splits train at first different current FC by convention,
+ -- locomotives have empty FC so are ignored
+ -- count_empty is used to split off locomotives
+ -- length_limit limits the length of the first train to length_limit wagons
+ local train_id = train.id
+ local fc = false
+ local ind = 0
+ for i = 1, #train.trainparts do
+ local w_id = train.trainparts[i]
+ local data = advtrains.wagons[w_id]
+ if length_limit and i > length_limit then
+ ind = i
+ break
+ end
+ if data then
+ local wfc = advtrains.get_cur_fc(data)
+ if wfc ~= "" or count_empty then
+ if fc then
+ if fc ~= wfc then
+ ind = i
+ break
+ end
+ else
+ fc = wfc
+ end
+ end
+ end
+ end
+ if ind > 0 then
+ return advtrains.split_train_at_index(train, ind), fc
+ end
+ if fc then
+ return nil, fc
+ end
+end
+
+function advtrains.train_step_fc(train)
+ for i=1,#train.trainparts do
+ local w_id = train.trainparts[i]
+ local data = advtrains.wagons[w_id]
+ if data then
+ advtrains.step_fc(data)
+ end
+ end
+end
+
+
+-- split_train_at_index() is in trainlogic.lua because it needs access to two local functions
+
+function advtrains.split_train_at_wagon(wagon_id)
+ --get train
+ local data = advtrains.wagons[wagon_id]
+ advtrains.split_train_at_index(advtrains.trains[data.train_id], data.pos_in_trainparts)
+end
+
+
+-- COUPLE ENTITIES --
+
+local couple_max_dist=3
+
+minetest.register_entity("advtrains:discouple", {
+ visual="sprite",
+ textures = {"advtrains_discouple.png"},
+ collisionbox = {-0.3,-0.3,-0.3, 0.3,0.3,0.3},
+ visual_size = {x=0.7, y=0.7},
+ initial_sprite_basepos = {x=0, y=0},
+
+ is_discouple=true,
+ static_save = false,
+ on_activate=function(self, staticdata)
+ if staticdata=="DISCOUPLE" then
+ --couple entities have no right to exist further...
+ atprint("Discouple loaded from staticdata, destroying")
+ self.object:remove()
+ return
+ end
+ self.object:set_armor_groups({immortal=1})
+ end,
+ get_staticdata=function() return "DISCOUPLE" end,
+ on_punch=function(self, player)
+ local pname = player:get_player_name()
+ if pname and pname~="" and self.wagon then
+ if advtrains.safe_decouple_wagon(self.wagon.id, pname) then
+ self.object:remove()
+ end
+ end
+ end,
+ on_step=function(self, dtime)
+ if not self.wagon then
+ self.object:remove()
+ return
+ end
+ --get_yaw seems to be a reliable method to check if an object is loaded...if it returns nil, it is not.
+ if not self.wagon.object:get_yaw() then
+ self.object:remove()
+ return
+ end
+ if not self.wagon:train() or self.wagon:train().velocity > 0 then
+ self.object:remove()
+ return
+ end
+ end,
+})
+
+-- advtrains:couple
+-- Couple entity
+
+minetest.register_entity("advtrains:couple", {
+ visual="sprite",
+ textures = {"advtrains_couple.png"},
+ collisionbox = {-0.3,-0.3,-0.3, 0.3,0.3,0.3},
+ visual_size = {x=0.7, y=0.7},
+ initial_sprite_basepos = {x=0, y=0},
+
+ is_couple=true,
+ static_save = false,
+ on_activate=function(self, staticdata)
+ if staticdata=="COUPLE" then
+ --couple entities have no right to exist further...
+ --atdebug("Couple loaded from staticdata, destroying")
+ self.object:remove()
+ return
+ end
+ self.object:set_armor_groups({immmortal=1})
+ end,
+ get_staticdata=function(self) return "COUPLE" end,
+ on_rightclick=function(self, clicker)
+ if not self.train_id_1 or not self.train_id_2 then return end
+
+ local pname=clicker
+ if type(clicker)~="string" then pname=clicker:get_player_name() end
+
+ local train1=advtrains.trains[self.train_id_1]
+ local train2=advtrains.trains[self.train_id_2]
+
+ advtrains.safe_couple_trains(train1, self.t1_is_front, train2, self.t2_is_front, pname)
+ self.object:remove()
+ end,
+ on_step=function(self, dtime)
+ if advtrains.wagon_outside_range(self.object:get_pos()) then
+ --atdebug("Couple Removing outside range")
+ self.object:remove()
+ return
+ end
+
+ if not self.train_id_1 or not self.train_id_2 then
+ --atdebug("Couple Removing ids missing")
+ self.object:remove()
+ return
+ end
+ local train1=advtrains.trains[self.train_id_1]
+ local train2=advtrains.trains[self.train_id_2]
+ if not train1 or not train2 then
+ --atdebug("Couple Removing trains missing")
+ self.object:remove()
+ return
+ end
+
+ if self.position_set and train1.velocity>0 or train2.velocity>0 then
+ --atdebug("Couple: train is moving, destroying")
+ self.object:remove()
+ return
+ end
+
+ if not self.position_set then
+ local tp1
+ if self.t1_is_front then
+ tp1=advtrains.path_get_interpolated(train1, train1.index)
+ else
+ tp1=advtrains.path_get_interpolated(train1, train1.end_index)
+ end
+ local tp2
+ if self.t2_is_front then
+ tp2=advtrains.path_get_interpolated(train2, train2.index)
+ else
+ tp2=advtrains.path_get_interpolated(train2, train2.end_index)
+ end
+ local pos_median=advtrains.pos_median(tp1, tp2)
+ if not vector.equals(pos_median, self.object:get_pos()) then
+ self.object:set_pos(pos_median)
+ end
+ self.position_set=true
+ end
+ end,
+})
diff --git a/advtrains/advtrains/craft_items.lua b/advtrains/craft_items.lua
index a4db385..6b1dcef 100644
--- a/advtrains/advtrains/craft_items.lua
+++ b/advtrains/craft_items.lua
@@ -1,23 +1,26 @@
+-- Get current translator
+local S = advtrains.translate
+
core.register_craftitem("advtrains:boiler", {
- description = "Boiler",
+ description = S("Boiler"),
inventory_image = "advtrains_boiler.png",
})
core.register_craftitem("advtrains:driver_cab", {
- description = "driver's cab",
+ description = S("Driver's cab"),
inventory_image = "advtrains_driver_cab.png",
})
core.register_craftitem("advtrains:wheel", {
- description = "Wheel",
+ description = S("Wheel"),
inventory_image = "advtrains_wheel.png",
})
core.register_craftitem("advtrains:chimney", {
- description = "Chimney",
+ description = S("Chimney"),
inventory_image = "advtrains_chimney.png",
})
diff --git a/advtrains/advtrains/crafting.lua b/advtrains/crafting.lua
index 72cd6da..9f80456 100644
--- a/advtrains/advtrains/crafting.lua
+++ b/advtrains/crafting.lua
@@ -2,57 +2,66 @@
--crafting.lua
--registers crafting recipes
---tracks
+--tracks: see advtrains_train_track
+--signals
minetest.register_craft({
- output = 'advtrains:dtrack_placer 50',
+ output = 'advtrains:retrosignal_off 2',
recipe = {
- {'default:steel_ingot', 'group:stick', 'default:steel_ingot'},
- {'default:steel_ingot', 'group:stick', 'default:steel_ingot'},
- {'default:steel_ingot', 'group:stick', 'default:steel_ingot'},
+ {'dye:red', 'default:steel_ingot', 'default:steel_ingot'},
+ {'', '', 'default:steel_ingot'},
+ {'', '', 'default:steel_ingot'},
},
})
minetest.register_craft({
- type = "shapeless",
- output = 'advtrains:dtrack_slopeplacer 2',
+ output = 'advtrains:signal_off 2',
recipe = {
- "advtrains:dtrack_placer",
- "advtrains:dtrack_placer",
- "default:gravel",
+ {'', 'dye:red', 'default:steel_ingot'},
+ {'', 'dye:dark_green', 'default:steel_ingot'},
+ {'', '', 'default:steel_ingot'},
},
})
-
+--Wallmounted Signal
minetest.register_craft({
- output = 'advtrains:dtrack_bumper_placer 2',
+ output = 'advtrains:signal_wall_l_off 2',
recipe = {
- {'default:wood', 'dye:red'},
- {'default:steel_ingot', 'default:steel_ingot'},
- {'advtrains:dtrack_placer', 'advtrains:dtrack_placer'},
+ {'default:steel_ingot', 'default:steel_ingot', 'dye:red'},
+ {'', 'default:steel_ingot', ''},
+ {'default:steel_ingot', 'default:steel_ingot', 'dye:dark_green'},
},
})
minetest.register_craft({
- type="shapeless",
- output = 'advtrains:dtrack_detector_off_placer',
+ output = 'advtrains:signal_wall_r_off 2',
recipe = {
- "advtrains:dtrack_placer",
- "mesecons:wire_00000000_off"
+ {'dye:red', 'default:steel_ingot', 'default:steel_ingot'},
+ {'', 'default:steel_ingot', ''},
+ {'dye:dark_green', 'default:steel_ingot', 'default:steel_ingot'},
},
})
---signals
minetest.register_craft({
- output = 'advtrains:retrosignal_off 2',
+ output = 'advtrains:signal_wall_t_off 2',
recipe = {
- {'dye:red', 'default:steel_ingot', 'default:steel_ingot'},
- {'', '', 'default:steel_ingot'},
- {'', '', 'default:steel_ingot'},
+ {'default:steel_ingot', '', 'default:steel_ingot'},
+ {'default:steel_ingot', 'default:steel_ingot', 'default:steel_ingot'},
+ {'dye:dark_green', '', 'dye:red'},
},
})
+
+
+--Wallmounted Signals can be converted into every orientation by shapeless crafting
minetest.register_craft({
- output = 'advtrains:signal_off 2',
- recipe = {
- {'', 'dye:red', 'default:steel_ingot'},
- {'', 'dye:dark_green', 'default:steel_ingot'},
- {'', '', 'default:steel_ingot'},
- },
+ output = 'advtrains:signal_wall_l_off',
+ type = "shapeless",
+ recipe = {'advtrains:signal_wall_r_off'},
+})
+minetest.register_craft({
+ output = 'advtrains:signal_wall_t_off',
+ type = "shapeless",
+ recipe = {'advtrains:signal_wall_l_off'},
+})
+minetest.register_craft({
+ output = 'advtrains:signal_wall_r_off',
+ type = "shapeless",
+ recipe = {'advtrains:signal_wall_t_off'},
})
--trackworker
diff --git a/advtrains/debugitems.lua b/advtrains/debugitems.lua
new file mode 100644
index 0000000..2236cba
--- /dev/null
+++ b/advtrains/debugitems.lua
@@ -0,0 +1,139 @@
+minetest.register_tool("advtrains:tunnelborer",
+{
+ description = "tunnelborer",
+ groups = {cracky=1}, -- key=name, value=rating; rating=1..3.
+ inventory_image = "drwho_screwdriver.png",
+ wield_image = "drwho_screwdriver.png",
+ stack_max = 1,
+ range = 7.0,
+
+ on_place = function(itemstack, placer, pointed_thing)
+
+ end,
+ --[[
+ ^ Shall place item and return the leftover itemstack
+ ^ default: minetest.item_place ]]
+ on_use = function(itemstack, user, pointed_thing)
+ if pointed_thing.type=="node" then
+ for x=-1,1 do
+ for y=-1,1 do
+ for z=-1,1 do
+ minetest.remove_node(vector.add(pointed_thing.under, {x=x, y=y, z=z}))
+ end
+ end
+ end
+ end
+ end,
+}
+)
+
+minetest.register_chatcommand("atyaw",
+ {
+ params = "angledeg conn1 conn2",
+ description = "",
+ func = function(name, param)
+ local angledegs, conn1s, conn2s = string.match(param, "^(%S+)%s(%S+)%s(%S+)$")
+ if angledegs and conn1s and conn2s then
+ local angledeg, conn1, conn2 = angledegs+0,conn1s+0,conn2s+0
+ local yaw = angledeg*math.pi/180
+ local yaw1 = advtrains.dir_to_angle(conn1)
+ local yaw2 = advtrains.dir_to_angle(conn2)
+ local adiff1 = advtrains.minAngleDiffRad(yaw, yaw1)
+ local adiff2 = advtrains.minAngleDiffRad(yaw, yaw2)
+
+ atdebug("yaw1",atfloor(yaw1*180/math.pi))
+ atdebug("yaw2",atfloor(yaw2*180/math.pi))
+ atdebug("dif1",atfloor(adiff1*180/math.pi))
+ atdebug("dif2",atfloor(adiff2*180/math.pi))
+
+ minetest.chat_send_all(advtrains.yawToAnyDir(yaw))
+ return true, advtrains.yawToDirection(yaw, conn1, conn2)
+ end
+ end,
+})
+
+minetest.register_tool("advtrains:wagonpos_tester",
+{
+ description = "Wagon position tester",
+ groups = {cracky=1}, -- key=name, value=rating; rating=1..3.
+ inventory_image = "drwho_screwdriver.png",
+ wield_image = "drwho_screwdriver.png",
+ stack_max = 1,
+ range = 7.0,
+
+ on_place = function(itemstack, placer, pointed_thing)
+
+ end,
+ --[[
+ ^ Shall place item and return the leftover itemstack
+ ^ default: minetest.item_place ]]
+ on_use = function(itemstack, user, pointed_thing)
+ if pointed_thing.type=="node" then
+ local pos = pointed_thing.under
+ local trains = advtrains.occ.get_trains_at(pos)
+ for train_id, index in pairs(trains) do
+ local wagon_num, wagon_id, wagon_data, offset_from_center = advtrains.get_wagon_at_index(train_id, index)
+ if wagon_num then
+ atdebug(wagon_num, wagon_id, offset_from_center)
+ end
+ end
+ end
+ end,
+}
+)
+
+
+local function trackitest(initial_pos, initial_connid)
+ local ti, pos, connid, ok
+ ti = advtrains.get_track_iterator(initial_pos, initial_connid, 500, true)
+ atdebug("Starting at pos:",initial_pos,initial_connid)
+ while ti:has_next_branch() do
+ pos, connid = ti:next_branch() -- in first iteration, this will be the node at initial_pos. In subsequent iterations this will be the switch node from which we are branching off
+ atdebug("Next Branch:",pos, connid)
+ ok = true
+ while ok do
+ ok, pos, connid = ti:next_track()
+ atdebug("Next Track:", ok, pos, connid)
+ end
+ end
+ atdebug("End of traverse. Visited: ",table.concat(ti.visited, ","))
+end
+
+minetest.register_tool("advtrains:trackitest",
+{
+ description = "Track Iterator Tester (leftclick conn 1, rightclick conn 2)",
+ groups = {cracky=1}, -- key=name, value=rating; rating=1..3.
+ inventory_image = "advtrains_track_swlcr_45.png",
+ wield_image = "advtrains_track_swlcr_45.png",
+ stack_max = 1,
+ range = 7.0,
+
+ on_place = function(itemstack, placer, pointed_thing)
+ if pointed_thing.type ~= "node" then return end
+ trackitest(pointed_thing.under, 2)
+ end,
+ on_use = function(itemstack, user, pointed_thing)
+ if pointed_thing.type ~= "node" then return end
+ trackitest(pointed_thing.under, 1)
+ end,
+}
+)
+
+minetest.register_chatcommand("at_trackdef_audit",
+ {
+ params = "",
+ description = "Performs an audit of all track definitions currently loaded and checks for potential problems",
+ func = function(name, param)
+ for name, ndef in pairs(minetest.registered_nodes) do
+ --TODO finish this!
+ if ndef.at_conns then
+ -- check if conn_map is there and if it has enough entries
+ if #ndef.at_conns > 2 then
+ if #ndef.at_conn_map < #ndef.at_conns then
+ atwarn("AUDIT: Node",name,"- Not enough connmap entries! Check ndef:",ndef)
+ end
+ end
+ end
+ end
+ end,
+})
diff --git a/advtrains/debugringbuffer.lua b/advtrains/debugringbuffer.lua
new file mode 100644
index 0000000..bdb4a3a
--- /dev/null
+++ b/advtrains/debugringbuffer.lua
@@ -0,0 +1,47 @@
+--so, some ringbuffers one for each train
+
+local ringbuflen=1000
+
+local ringbufs={}
+local ringbufcnt={}
+
+function advtrains.drb_record(tid, msg)
+ if not ringbufs[tid] then
+ ringbufs[tid]={}
+ ringbufcnt[tid]=0
+ end
+ ringbufs[tid][ringbufcnt[tid]]=msg
+ ringbufcnt[tid]=ringbufcnt[tid]+1
+ if ringbufcnt[tid] > ringbuflen then
+ ringbufcnt[tid]=0
+ end
+end
+function advtrains.drb_dump(tid)
+ atdebug("Debug ring buffer output for '"..tid.."':")
+ local stopcnt=ringbufcnt[tid]
+ if not stopcnt then
+ atdebug("ID unknown!")
+ return
+ end
+ repeat
+ local t = ringbufs[tid][ringbufcnt[tid]]
+ if t then
+ atdebug(t)
+ end
+ ringbufcnt[tid]=ringbufcnt[tid]+1
+ if ringbufcnt[tid] > ringbuflen then
+ ringbufcnt[tid]=0
+ end
+ until ringbufcnt[tid]==stopcnt
+end
+
+minetest.register_chatcommand("atdebug_show",
+ {
+ params = "train sid", -- Short parameter description
+ description = "Dump debug log", -- Full description
+ privs = {train_operator=true}, -- Require the "privs" privilege to run
+ func = function(name, param)
+ advtrains.drb_dump(param)
+ end, -- Called when command is run.
+ -- Returns boolean success and text output.
+ })
diff --git a/advtrains/advtrains/description.txt b/advtrains/description.txt
index ecc5d58..bb13b97 100644
--- a/advtrains/advtrains/description.txt
+++ b/advtrains/description.txt
@@ -1,8 +1,8 @@
-Advanced Trains v1.3.0, by orwell and contributors. Also see readme.
+Advanced Trains v1.3.8, by orwell and contributors. Also see readme.
Good-looking, realistic trains for minetest.
For crafting recipes, see manual.pdf
Website: http://advtrains.bleipb.de/
Manual: https://github.com/orwell96/advtrains/blob/master/manual.pdf
-Forum : https://forum.minetest.net/viewtopic.php?f=11&t=14726 \ No newline at end of file
+Forum : https://forum.minetest.net/viewtopic.php?f=11&t=14726
diff --git a/advtrains/doc/advtrains_speed_lessp.3advtrains.md b/advtrains/doc/advtrains_speed_lessp.3advtrains.md
new file mode 100644
index 0000000..663aa42
--- /dev/null
+++ b/advtrains/doc/advtrains_speed_lessp.3advtrains.md
@@ -0,0 +1,15 @@
+% advtrains_speed_lessp(3advtrains) | Advtrains Developer's Manual
+
+# NAME
+`advtrains.speed.lessp`, `advtrains.speed.greaterp`, `advtrains.speed.not_lessp`, `advtrains.speed_not_greaterp`, `advtrains.speed.equalp`, `advtrains.speed.not_equalp`, `advtrains.speed.max`, `advtrains.speed.min` - speed restriction comparison functions
+
+# SYNOPSIS
+Each function takes two arguments and returns a boolean or (for `advtrains.speed.max` and `advtrains.speed.min`) a valid speed limit
+
+# DESCRIPTION
+
+The functions above correspond to the arithmetic `<`, `>`, `>=`, `<=`, `==`, `~=` operators and the `math.max` and `math.min` functions, respectively. The constants `nil` and `false` are treated as -1.
+
+# NOTES
+
+These functions are trivial to implement and the implementation can be easily embedded into existing code. They are simply provided for convenience.
diff --git a/advtrains/doc/advtrains_speed_set_restriction.3advtrains.md b/advtrains/doc/advtrains_speed_set_restriction.3advtrains.md
new file mode 100644
index 0000000..b3183c6
--- /dev/null
+++ b/advtrains/doc/advtrains_speed_set_restriction.3advtrains.md
@@ -0,0 +1,18 @@
+% advtrains_speed_set_restriction(3advtrains) | Advtrains Developer's Manual
+
+# NAME
+`advtrains.speed.set_restriction`, `advtrains.speed.merge_aspect` - modify speed restriction
+
+# SYNOPSIS
+* `advtrains.speed.set_restriction(train, rtype, rval)`
+* `advtrains.speed.merge_aspect(train, asp)`
+
+# DESCRIPTION
+
+The `advtrains.speed.set_restriction` function sets the speed restriction of type `rtype` of `train` to `rval` and updates the speed restriction value to the strictest speed restriction in the table, or `nil` if all speed restrictions are `nil` or `-1`. If the speed restriction table does not exist, it is created with the `"main"` speed restriction being the speed restriction value of `train`.
+
+The `advtrains.speed.merge_aspect` function merges the main aspect of `asp` into the speed restriction table with the same procedure described above. If the signal aspect table does not provide the type of speed restriction, the restriction type `"main"` is assumed.
+
+# SIDE EFFECTS
+
+Both functions modify `train.speed_restriction` and `train.speed_restrictions_t`.
diff --git a/advtrains/doc/signal_aspect.7advtrains.md b/advtrains/doc/signal_aspect.7advtrains.md
new file mode 100644
index 0000000..827760d
--- /dev/null
+++ b/advtrains/doc/signal_aspect.7advtrains.md
@@ -0,0 +1,24 @@
+% signal_aspect(7advtrains) | Advtrains Developer's Manual
+
+# DESCRIPTION
+
+The signal aspect table used by advtrains has the following fields:
+
+* `main`: The main speed restriction
+* `dst`: The `main` aspect of the distant signal (not implemented)
+* `type`: The type of speed restriction given by the signal
+* `shunt`: Whether shunting is allowed
+* `proceed_as_main`: Whether to proceed without shunting
+
+The `main` and `dst` fields may contain the following values:
+* `-1`: No speed restriction
+* `nil`: No information is available
+
+The `type` field can be any valid table index, but it should usually be one of the following values:
+* "main": The main signal aspect used before the introduction of speed restriction types. This is the default value if the `type` field is absent.
+* "line": The speed limit for the physical line.
+* "temp": The speed limit that is temporarily introduced.
+
+# NOTES
+
+A signal with the `main` aspect of zero should not provide distant signal aspect.
diff --git a/advtrains/formspec.lua b/advtrains/formspec.lua
new file mode 100644
index 0000000..86d8b27
--- /dev/null
+++ b/advtrains/formspec.lua
@@ -0,0 +1,114 @@
+local sformat = string.format
+local fsescape = minetest.formspec_escape
+
+-- Get current translator
+local S = advtrains.translate
+
+local function make_list(entries)
+ local t = {}
+ for k, v in ipairs(entries) do
+ t[k] = fsescape(v)
+ end
+ return table.concat(t, ",")
+end
+
+local function S_wrapper(f, i0)
+ return function(...)
+ local args = {...}
+ args[i0] = S(unpack(args,i0))
+ return f(unpack(args,1,i0))
+ end
+end
+
+local function f_button(x, y, w, id, text)
+ return sformat("button[%f,%f;%f,0.75;%s;%s]", x, y, w, id, text)
+end
+
+local function f_checkbox(x, y, name, selected, label)
+ return sformat("checkbox[%f,%f;%s;%s;%s]", x, y+0.25, name, label, selected and "true" or "false")
+end
+
+local function f_button_exit(x, y, w, id, text)
+ return sformat("button_exit[%f,%f;%f,0.75;%s;%s]", x, y, w, id, text)
+end
+
+local function f_dropdown(x, y, w, id, entries, sel, indexed)
+ return sformat("dropdown[%f,%f;%f,0.75;%s;%s;%d%s]",
+ x, y, w, id, make_list(entries),
+ sel or 1,
+ indexed and ";true" or "")
+end
+
+local function f_image_button(x, y, w, h, texture, id, label, noclip, drawborder, pressed)
+ local st = {string.format("%f,%f;%f,%f;%s;%s;%s", x, y, w, h, fsescape(texture), fsescape(id), fsescape(label))}
+ if pressed then
+ st[#st+1] = tostring(noclip or false)
+ st[#st+1] = tostring(drawborder or false)
+ st[#st+1] = fsescape(pressed)
+ end
+ return sformat("image_button[%s]", table.concat(st, ";"))
+end
+
+local function f_image_button_exit(x, y, w, h, texture, id, label)
+ local st = {string.format("%f,%f;%f,%f;%s;%s;%s", x, y, w, h, fsescape(texture), fsescape(id), fsescape(label))}
+ return sformat("image_button_exit[%s]", table.concat(st, ";"))
+end
+
+local function f_label(x, y, text)
+ return sformat("label[%f,%f;%s]", x, y+0.25, fsescape(text))
+end
+
+local function f_field_aux(x, y, w, id, default)
+ return sformat("field[%f,%f;%f,0.75;%s;;%s]", x, y, w, id, default)
+end
+
+local function f_field(x, y, w, id, label, default)
+ return f_label(x, y-0.5, label) .. f_field_aux(x, y, w, id, default)
+end
+
+local function f_tabheader(x, y, w, h, id, entries, sel, transparent, border)
+ local st = {string.format("%f,%f",x, y)}
+ if h then
+ if w then
+ st[#st+1] = string.format("%f,%f", w, h)
+ else
+ st[#st+1] = tostring(h)
+ end
+ end
+ st[#st+1] = tostring(id)
+ st[#st+1] = make_list(entries)
+ st[#st+1] = tostring(sel)
+ if transparent ~= nil then
+ st[#st+1] = tostring(transparent)
+ if border ~= nil then
+ st[#st+1] = tostring(border)
+ end
+ end
+ return string.format("tabheader[%s]", table.concat(st, ";"))
+end
+
+local function f_textlist(x, y, w, h, id, entries, sel, transparent)
+ local st = {string.format("%f,%f;%f,%f;%s;%s", x, y, w, h, id, make_list(entries))}
+ if sel then
+ st[#st+1] = tostring(sel)
+ st[#st+1] = tostring(transparent or false)
+ end
+ return string.format("textlist[%s]", table.concat(st, ";"))
+end
+
+return {
+ button = f_button,
+ S_button = S_wrapper(f_button, 5),
+ checkbox = f_checkbox,
+ S_checkbox = S_wrapper(f_checkbox, 5),
+ button_exit = f_button_exit,
+ S_button_exit = S_wrapper(f_button_exit, 5),
+ dropdown = f_dropdown,
+ field = f_field,
+ image_button = f_image_button,
+ image_button_exit = f_image_button_exit,
+ label = f_label,
+ S_label = S_wrapper(f_label, 3),
+ tabheader = f_tabheader,
+ textlist = f_textlist,
+}
diff --git a/advtrains/helpers.lua b/advtrains/helpers.lua
new file mode 100644
index 0000000..e58625f
--- /dev/null
+++ b/advtrains/helpers.lua
@@ -0,0 +1,637 @@
+--advtrains by orwell96, see readme.txt
+
+local dir_trans_tbl={
+ [0]={x=0, z=1, y=0},
+ [1]={x=1, z=2, y=0},
+ [2]={x=1, z=1, y=0},
+ [3]={x=2, z=1, y=0},
+ [4]={x=1, z=0, y=0},
+ [5]={x=2, z=-1, y=0},
+ [6]={x=1, z=-1, y=0},
+ [7]={x=1, z=-2, y=0},
+ [8]={x=0, z=-1, y=0},
+ [9]={x=-1, z=-2, y=0},
+ [10]={x=-1, z=-1, y=0},
+ [11]={x=-2, z=-1, y=0},
+ [12]={x=-1, z=0, y=0},
+ [13]={x=-2, z=1, y=0},
+ [14]={x=-1, z=1, y=0},
+ [15]={x=-1, z=2, y=0},
+}
+
+local dir_angle_tbl={}
+for d,v in pairs(dir_trans_tbl) do
+ local uvec = vector.normalize(v)
+ dir_angle_tbl[d] = math.atan2(-uvec.x, uvec.z)
+end
+
+
+function advtrains.dir_to_angle(dir)
+ return dir_angle_tbl[dir] or error("advtrains: in helpers.lua/dir_to_angle() given dir="..(dir or "nil"))
+end
+
+function advtrains.dirCoordSet(coord, dir)
+ return vector.add(coord, advtrains.dirToCoord(dir))
+end
+advtrains.pos_add_dir = advtrains.dirCoordSet
+
+function advtrains.pos_add_angle(pos, ang)
+ -- 0 is +Z -> meaning of sin/cos swapped
+ return vector.add(pos, {x = -math.sin(ang), y = 0, z = math.cos(ang)})
+end
+
+function advtrains.dirToCoord(dir)
+ return dir_trans_tbl[dir] or error("advtrains: in helpers.lua/dir_to_vector() given dir="..(dir or "nil"))
+end
+advtrains.dir_to_vector = advtrains.dirToCoord
+
+function advtrains.maxN(list, expectstart)
+ local n=expectstart or 0
+ while list[n] do
+ n=n+1
+ end
+ return n-1
+end
+
+function advtrains.minN(list, expectstart)
+ local n=expectstart or 0
+ while list[n] do
+ n=n-1
+ end
+ return n+1
+end
+
+function atround(number)
+ return math.floor(number+0.5)
+end
+atfloor = math.floor
+
+
+function advtrains.round_vector_floor_y(vec)
+ return {x=math.floor(vec.x+0.5), y=math.floor(vec.y), z=math.floor(vec.z+0.5)}
+end
+
+function advtrains.yawToDirection(yaw, conn1, conn2)
+ if not conn1 or not conn2 then
+ error("given nil to yawToDirection: conn1="..(conn1 or "nil").." conn2="..(conn1 or "nil"))
+ end
+ local yaw1 = advtrains.dir_to_angle(conn1)
+ local yaw2 = advtrains.dir_to_angle(conn2)
+ local adiff1 = advtrains.minAngleDiffRad(yaw, yaw1)
+ local adiff2 = advtrains.minAngleDiffRad(yaw, yaw2)
+
+ if math.abs(adiff2)<math.abs(adiff1) then
+ return conn2
+ else
+ return conn1
+ end
+end
+
+function advtrains.yawToAnyDir(yaw)
+ local min_conn, min_diff=0, 10
+ for conn, vec in pairs(advtrains.dir_trans_tbl) do
+ local yaw1 = advtrains.dir_to_angle(conn)
+ local diff = math.abs(advtrains.minAngleDiffRad(yaw, yaw1))
+ if diff < min_diff then
+ min_conn = conn
+ min_diff = diff
+ end
+ end
+ return min_conn
+end
+function advtrains.yawToClosestConn(yaw, conns)
+ local min_connid, min_diff=1, 10
+ for connid, conn in ipairs(conns) do
+ local yaw1 = advtrains.dir_to_angle(conn.c)
+ local diff = math.abs(advtrains.minAngleDiffRad(yaw, yaw1))
+ if diff < min_diff then
+ min_connid = connid
+ min_diff = diff
+ end
+ end
+ return min_connid
+end
+
+local pi, pi2 = math.pi, 2*math.pi
+function advtrains.minAngleDiffRad(r1, r2)
+ while r1>pi2 do
+ r1=r1-pi2
+ end
+ while r1<0 do
+ r1=r1+pi2
+ end
+ while r2>pi2 do
+ r2=r2-pi2
+ end
+ while r1<0 do
+ r2=r2+pi2
+ end
+ local try1=r2-r1
+ local try2=r2+pi2-r1
+ local try3=r2-pi2-r1
+
+ local minabs = math.min(math.abs(try1), math.abs(try2), math.abs(try3))
+ if minabs==math.abs(try1) then
+ return try1
+ end
+ if minabs==math.abs(try2) then
+ return try2
+ end
+ if minabs==math.abs(try3) then
+ return try3
+ end
+end
+
+
+-- Takes 2 connections (0...AT_CMAX) as argument
+-- Returns the angle median of those 2 positions from the pov
+-- of standing on the cdir1 side and looking towards cdir2
+-- cdir1 - >NODE> - cdir2
+function advtrains.conn_angle_median(cdir1, cdir2)
+ local ang1 = advtrains.dir_to_angle(advtrains.oppd(cdir1))
+ local ang2 = advtrains.dir_to_angle(cdir2)
+ return ang1 + advtrains.minAngleDiffRad(ang1, ang2)/2
+end
+
+function advtrains.merge_tables(a, ...)
+ local new={}
+ for _,t in ipairs({a,...}) do
+ for k,v in pairs(t) do new[k]=v end
+ end
+ return new
+end
+function advtrains.save_keys(tbl, keys)
+ local new={}
+ for _,key in ipairs(keys) do
+ new[key] = tbl[key]
+ end
+ return new
+end
+
+function advtrains.get_real_index_position(path, index)
+ if not path or not index then return end
+
+ local first_pos=path[math.floor(index)]
+ local second_pos=path[math.floor(index)+1]
+
+ if not first_pos or not second_pos then return nil end
+
+ local factor=index-math.floor(index)
+ local actual_pos={x=first_pos.x-(first_pos.x-second_pos.x)*factor, y=first_pos.y-(first_pos.y-second_pos.y)*factor, z=first_pos.z-(first_pos.z-second_pos.z)*factor,}
+ return actual_pos
+end
+function advtrains.pos_median(pos1, pos2)
+ return {x=pos1.x-(pos1.x-pos2.x)*0.5, y=pos1.y-(pos1.y-pos2.y)*0.5, z=pos1.z-(pos1.z-pos2.z)*0.5}
+end
+function advtrains.abs_ceil(i)
+ return math.ceil(math.abs(i))*math.sign(i)
+end
+
+function advtrains.serialize_inventory(inv)
+ local ser={}
+ local liszts=inv:get_lists()
+ for lisztname, liszt in pairs(liszts) do
+ ser[lisztname]={}
+ for idx, item in ipairs(liszt) do
+ local istring=item:to_string()
+ if istring~="" then
+ ser[lisztname][idx]=istring
+ end
+ end
+ end
+ return minetest.serialize(ser)
+end
+function advtrains.deserialize_inventory(sers, inv)
+ local ser=minetest.deserialize(sers)
+ if ser then
+ inv:set_lists(ser)
+ return true
+ end
+ return false
+end
+
+--is_protected wrapper that checks for protection_bypass privilege
+function advtrains.is_protected(pos, name)
+ if not name then
+ error("advtrains.is_protected() called without name parameter!")
+ end
+ if minetest.check_player_privs(name, {protection_bypass=true}) then
+ --player can bypass protection
+ return false
+ end
+ return minetest.is_protected(pos, name)
+end
+
+function advtrains.is_creative(name)
+ if not name then
+ error("advtrains.is_creative() called without name parameter!")
+ end
+ if minetest.check_player_privs(name, {creative=true}) then
+ return true
+ end
+ return minetest.settings:get_bool("creative_mode")
+end
+
+function advtrains.is_damage_enabled(name)
+ if not name then
+ error("advtrains.is_damage_enabled() called without name parameter!")
+ end
+ if minetest.check_player_privs(name, "train_admin") then
+ return false
+ end
+ return minetest.settings:get_bool("enable_damage")
+end
+
+function advtrains.ms_to_kmh(speed)
+ return speed * 3.6
+end
+
+-- 4 possible inputs:
+-- integer: just do that modulo calculation
+-- table with c set: rotate c
+-- table with tables: rotate each
+-- table with integers: rotate each (probably no use case)
+function advtrains.rotate_conn_by(conn, rotate)
+ if tonumber(conn) then
+ return (conn+rotate)%AT_CMAX
+ elseif conn.c then
+ return { c = (conn.c+rotate)%AT_CMAX, y = conn.y}
+ end
+ local tmp={}
+ for connid, data in ipairs(conn) do
+ tmp[connid]=advtrains.rotate_conn_by(data, rotate)
+ end
+ return tmp
+end
+
+
+function advtrains.oppd(dir)
+ return advtrains.rotate_conn_by(dir, AT_CMAX/2)
+end
+--conn_to_match like rotate_conn_by
+--other_conns have to be a table of conn tables!
+function advtrains.conn_matches_to(conn, other_conns)
+ if tonumber(conn) then
+ for connid, data in ipairs(other_conns) do
+ if advtrains.oppd(conn) == data.c then return connid end
+ end
+ return false
+ elseif conn.c then
+ for connid, data in ipairs(other_conns) do
+ local cmp = advtrains.oppd(conn)
+ if cmp.c == data.c and (cmp.y or 0) == (data.y or 0) then return connid end
+ end
+ return false
+ end
+ local tmp={}
+ for connid, data in ipairs(conn) do
+ local backmatch = advtrains.conn_matches_to(data, other_conns)
+ if backmatch then return backmatch, connid end --returns <connid of other rail> <connid of this rail>
+ end
+ return false
+end
+
+-- Going from the rail at pos (does not need to be rounded) along connection with id conn_idx, if there is a matching rail, return it and the matching connid
+-- returns: <adjacent pos>, <conn index of adjacent>, <my conn index>, <railheight of adjacent>, (adjacent conns table), (adjacent connmap table)
+-- parameter this_conns_p is connection table of this rail and is optional, is determined by get_rail_info_at if not provided.
+function advtrains.get_adjacent_rail(this_posnr, this_conns_p, conn_idx)
+ local this_pos = advtrains.round_vector_floor_y(this_posnr)
+ local this_conns = this_conns_p
+ local _
+ if not this_conns then
+ _, this_conns = advtrains.get_rail_info_at(this_pos)
+ end
+ if not conn_idx then
+ for coni, _ in ipairs(this_conns) do
+ local adj_pos, adj_conn_idx, _, nry, nco, ncm = advtrains.get_adjacent_rail(this_pos, this_conns, coni)
+ if adj_pos then return adj_pos,adj_conn_idx,coni,nry, nco, ncm end
+ end
+ return nil
+ end
+
+ local conn = this_conns[conn_idx]
+ local conn_y = conn.y or 0
+ local adj_pos = advtrains.dirCoordSet(this_pos, conn.c);
+
+ while conn_y>=1 do
+ conn_y = conn_y - 1
+ adj_pos.y = adj_pos.y + 1
+ end
+
+ local nextnode_ok, nextconns, nextrail_y, nextconnmap=advtrains.get_rail_info_at(adj_pos)
+ if not nextnode_ok then
+ adj_pos.y = adj_pos.y - 1
+ conn_y = conn_y + 1
+ nextnode_ok, nextconns, nextrail_y, nextconnmap=advtrains.get_rail_info_at(adj_pos)
+ if not nextnode_ok then
+ return nil
+ end
+ end
+ local adj_connid = advtrains.conn_matches_to({c=conn.c, y=conn_y}, nextconns)
+ if adj_connid then
+ return adj_pos, adj_connid, conn_idx, nextrail_y, nextconns, nextconnmap
+ end
+ return nil
+end
+
+-- when a train enters a rail on connid 'conn', which connid will it go out?
+-- Since 2.5: This mapping is contained in the conn_map table in the node definition!
+-- returns: connid_out
+function advtrains.get_matching_conn(conn, conn_map)
+ if tonumber(conn_map) then
+ error("Legacy call to get_matching_conn! Instead of nconns, conn_map needs to be provided!")
+ end
+ if not conn_map then
+ --OK for two-conn rails, just return the other
+ if conn==1 then return 2 end
+ if conn==2 then return 1 end
+ error("get_matching_conn: For connid >=3, conn_map must not be nil!")
+ end
+ local cout = conn_map[conn]
+ if not cout then
+ error("get_matching_conn: Connid "..conn.." not found in conn_map which is "..atdump(conn_map))
+ end
+ return cout
+end
+
+function advtrains.random_id(lenp)
+ local idst=""
+ local len = lenp or 6
+ for i=1,len do
+ idst=idst..(math.random(0,9))
+ end
+ return idst
+end
+-- Shorthand for pos_to_string and round_vector_floor_y
+function advtrains.roundfloorpts(pos)
+ return minetest.pos_to_string(advtrains.round_vector_floor_y(pos))
+end
+
+-- insert an element into a table if it does not yet exist there
+-- equalfunc is a function to compare equality, defaults to ==
+-- returns true if the element was inserted
+function advtrains.insert_once(tab, elem, equalfunc)
+ for _,e in pairs(tab) do
+ if equalfunc and equalfunc(elem, e) or e==elem then return false end
+ end
+ tab[#tab+1] = elem
+ return true
+end
+
+local hext = { [0]="0",[1]="1",[2]="2",[3]="3",[4]="4",[5]="5",[6]="6",[7]="7",[8]="8",[9]="9",[10]="A",[11]="B",[12]="C",[13]="D",[14]="E",[15]="F"}
+local dect = { ["0"]=0,["1"]=1,["2"]=2,["3"]=3,["4"]=4,["5"]=5,["6"]=6,["7"]=7,["8"]=8,["9"]=9,["A"]=10,["B"]=11,["C"]=12,["D"]=13,["E"]=14,["F"]=15}
+
+local f = atfloor
+
+local function hex(i)
+ local x=i+32768
+ local c4 = x % 16
+ x = f(x / 16)
+ local c3 = x % 16
+ x = f(x / 16)
+ local c2 = x % 16
+ x = f(x / 16)
+ local c1 = x % 16
+ return (hext[c1]) .. (hext[c2]) .. (hext[c3]) .. (hext[c4])
+end
+
+local function c(s,i) return dect[string.sub(s,i,i)] end
+
+local function dec(s)
+ return (c(s,1)*4096 + c(s,2)*256 + c(s,3)*16 + c(s,4))-32768
+end
+-- Takes a position vector and outputs a encoded value suitable as table index
+-- This is essentially a hexadecimal representation of the position (+32768)
+-- Order (YYY)YXXXXZZZZ
+function advtrains.encode_pos(pos)
+ return hex(pos.y) .. hex(pos.x) .. hex(pos.z)
+end
+
+-- decodes a position encoded with encode_pos
+function advtrains.decode_pos(pts)
+ if not pts or not #pts==6 then return nil end
+ local stry = string.sub(pts, 1,4)
+ local strx = string.sub(pts, 5,8)
+ local strz = string.sub(pts, 9,12)
+ return vector.new(dec(strx), dec(stry), dec(strz))
+end
+
+--[[ Benchmarking code
+local tdt = {}
+local tlt = {}
+local tet = {}
+
+for i=1,1000000 do
+ tdt[i] = vector.new(math.random(-65536, 65535), math.random(-65536, 65535), math.random(-65536, 65535))
+ if i%1000 == 0 then
+ tlt[#tlt+1] = tdt[i]
+ end
+end
+
+local t1=os.clock()
+for i=1,1000000 do
+ local pe = advtrains.encode_pos(tdt[i])
+ local pb = advtrains.decode_pos(pe)
+ tet[pe] = i
+end
+for i,v in ipairs(tlt) do
+ local lk = tet[advtrains.encode_pos(v)]
+end
+atdebug("endec",os.clock()-t1,"s")
+
+tet = {}
+
+t1=os.clock()
+for i=1,1000000 do
+ local pe = minetest.pos_to_string(tdt[i])
+ local pb = minetest.string_to_pos(pe)
+ tet[pe] = i
+end
+for i,v in ipairs(tlt) do
+ local lk = tet[minetest.pos_to_string(v)]
+end
+atdebug("pts",os.clock()-t1,"s")
+
+--Results:
+--2018-11-29 16:57:08: ACTION[Main]: [advtrains]endec 1.786451 s
+--2018-11-29 16:57:10: ACTION[Main]: [advtrains]pts 2.566377 s
+]]
+
+
+-- Function to check whether a position is near (within range of) any player
+function advtrains.position_in_range(pos, range)
+ if not pos then
+ return true
+ end
+ for _,p in pairs(minetest.get_connected_players()) do
+ if vector.distance(p:get_pos(),pos)<=range then
+ return true
+ end
+ end
+ return false
+end
+
+local active_node_range = tonumber(minetest.settings:get("active_block_range"))*16 + 16
+-- Function to check whether node at position(pos) is "loaded"/"active"
+-- That is, whether it is within the active_block_range to a player
+if core.compare_block_status then
+ -- latest API
+ function advtrains.is_node_loaded(pos)
+ return core.compare_block_status(pos, "active")
+ end
+elseif minetest.is_block_active then -- define function differently whether minetest.is_block_active is available or not
+ -- API added by my PR but later superseded by the above and now removed
+ advtrains.is_node_loaded = minetest.is_block_active
+else
+ function advtrains.is_node_loaded(pos)
+ if advtrains.position_in_range(pos, active_node_range) then
+ return true
+ end
+ end
+end
+
+
+-- TrackIterator interface --
+
+-- Metatable:
+local trackiter_mt = {
+ -- Internal State:
+ -- branches: A list of {pos, connid, limit} for where to restart
+ -- pos: The *next* position that the track iterator will return
+ -- bconnid: The connid of the connection of the rail at pos that points backward
+ -- tconns: The connections of the rail at pos
+ -- limit: the current limit
+ -- visited: a key-boolean table of already visited rails
+
+ -- get whether there are still unprocessed branches
+ has_next_branch = function(self)
+ return #self.branches > 0
+ end,
+ -- go to the next unprocessed branch
+ -- returns track_pos, track_connid of the switch/crossing node where the track branches off
+ next_branch = function(self)
+ local br = table.remove(self.branches, 1)
+ -- Advance internal state
+ local adj_pos, adj_connid, _, _, adj_conns, adj_connmap = advtrains.get_adjacent_rail(br.pos, nil, br.connid)
+ self.pos = adj_pos
+ self.bconnid = adj_connid
+ self.tconns = adj_conns
+ self.tconnmap = adj_connmap
+ self.limit = br.limit - 1
+ self.visited[advtrains.encode_pos(br.pos)] = true
+ self.last_track_already_visited = false
+ return br.pos, br.connid
+ end,
+ -- get the next track along the current branch,
+ -- potentially adding branching tracks to the unprocessed branches list
+ -- returns track_pos, track_connid, track_backwards_connid
+ -- On error, returns nil, reason; reason is one of "track_end", "limit_hit", "already_visited"
+ next_track = function(self)
+ if self.last_track_already_visited then
+ -- see comment below
+ return nil, "already_visited"
+ end
+ local pos = self.pos
+ if not pos then
+ -- last run found track end. Return false
+ return false, "track_end"
+ end
+ -- if limit hit, return nil to signal this
+ if self.limit <= 0 then
+ return nil, "limit_hit"
+ end
+ -- select next conn (main conn to follow is the associated connection)
+ local old_bconnid = self.bconnid
+ local mconnid = advtrains.get_matching_conn(self.bconnid, self.tconnmap)
+ if self.visited[advtrains.encode_pos(pos)] then
+ -- node was already seen
+ -- Due to special requirements for the track section updater, return this first already visited track once
+ -- but do not process any further rails on this branch
+ -- The next call will then throw already_visited error
+ self.last_track_already_visited = true
+ return pos, mconnid, old_bconnid
+ end
+ -- If there are more connections, add these to branches
+ for nconnid,_ in ipairs(self.tconns) do
+ if nconnid~=mconnid and nconnid~=self.bconnid then
+ table.insert(self.branches, {pos = self.pos, connid = nconnid, limit=self.limit})
+ end
+ end
+ -- Advance internal state
+ local adj_pos, adj_connid, _, _, adj_conns, adj_connmap = advtrains.get_adjacent_rail(pos, self.tconns, mconnid)
+ self.pos = adj_pos
+ self.bconnid = adj_connid
+ self.tconns = adj_conns
+ self.tconnmap = adj_connmap
+ self.limit = self.limit - 1
+ self.visited[advtrains.encode_pos(pos)] = true
+ self.last_track_already_visited = false
+ return pos, mconnid, old_bconnid
+ end,
+
+ add_branch = function(self, pos, connid)
+ table.insert(self.branches, {pos = pos, connid = connid, limit=self.limit})
+ end,
+
+ is_visited = function(self, pos)
+ return self.visited[advtrains.encode_pos(pos)]
+ end,
+}
+
+-- Returns a new TrackIterator object
+
+-- Parameters:
+-- initial_pos: the initial track position of the track iterator
+-- initial_connid: the connection index in which to traverse. If nil, adds a "branch" for every connection of the track (traverse in all directions)
+-- limit: maximum distance from the start point after which the traverser stops
+-- follow_all: NOT IMPLEMENTED (supposed: if true, follows all branches at multi-connection tracks, even the ones pointing backwards or the crossing track on crossings. If false, follows only switches in driving direction.)
+
+-- Functions of the returned TrackIterator can be called via the Lua : notation, such as ti:next_track()
+-- If only the main track needs to be followed, use only the ti:next_track() function and do not call ti:next_branch().
+function advtrains.get_track_iterator(initial_pos, initial_connid, limit, follow_all)
+ local ti = {
+ visited = {}
+ }
+ if initial_connid then
+ ti.branches = { {pos = initial_pos, connid = initial_connid, limit=limit} }
+ else
+ -- get track info here
+ local node_ok, conns, rail_y=advtrains.get_rail_info_at(initial_pos)
+ assert(node_ok, "get_track_iterator called with non-track node!")
+ ti.branches = {}
+ for coni, _ in pairs(conns) do
+ table.insert(ti.branches, {pos = initial_pos, connid = coni, limit=limit})
+ end
+ end
+ ti.limit = limit -- safeguard if someone adds a branch before calling anything
+ setmetatable(ti, {__index=trackiter_mt})
+ return ti
+end
+
+--[[
+Example TrackIterator usage structure:
+
+local ti, pos, connid, ok
+ti = advtrains.get_track_iterator(initial_pos, initial_connid, 500, true)
+while ti:has_next_branch() do
+ pos, connid = ti:next_branch() -- in first iteration, this will be the node at initial_pos. In subsequent iterations this will be the switch node from which we are branching off
+ repeat
+ <do something with the track>
+ if <track satisfies an abort condition> then break end --for example, when traversing should stop at TCBs this can check if there is a tcb here
+ pos, connid = ti:next_track()
+ until not pos -- this stops the loop when either the track end is reached or the limit is hit
+ -- while loop continues with the next branch ( diverging branch of one of the switches/crossings) until no more are left
+end
+
+Example for walking only a single track (without branching):
+
+local ti, pos, connid, ok
+ti = advtrains.get_track_iterator(initial_pos, initial_connid, 500, true)
+
+pos, connid = ti:next_branch() -- this always needs to be done at least one time, and gets the track at initial_pos
+repeat
+ <do something with the track>
+ if <track satisfies an abort condition> then break end --for example, when traversing should stop at TCBs this can check if there is a tcb here
+ ok, pos, connid = ti:next_track()
+until not ok -- this stops the loop when either the track end is reached or the limit is hit
+]]
diff --git a/advtrains/init.lua b/advtrains/init.lua
new file mode 100644
index 0000000..97733c4
--- /dev/null
+++ b/advtrains/init.lua
@@ -0,0 +1,819 @@
+
+--[[
+Advanced Trains - Minetest Mod
+
+Copyright (C) 2016-2020 Moritz Blei (orwell96) and contributors
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as
+ published by the Free Software Foundation, either version 3 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 Affero General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+]]
+
+local lot = os.clock()
+minetest.log("action", "[advtrains] Loading...")
+
+--advtrains
+advtrains = {trains={}, player_to_train_mapping={}}
+
+-- =======================Development/debugging settings=====================
+-- DO NOT USE FOR NORMAL OPERATION
+local DUMP_DEBUG_SAVE = false
+-- dump the save files in human-readable format into advtrains_DUMP
+
+local GENERATE_ATRICIFIAL_LAG = false
+local HOW_MANY_LAG = 1.0
+-- Simulate a higher server step interval, as it occurs when the server is on high load
+
+advtrains.IGNORE_WORLD = false
+-- Run advtrains without respecting the world map
+-- - No world collision checks occur
+-- - The NDB forcibly places all nodes stored in it into the world regardless of the world's content.
+-- - Rails do not set the 'attached_node' group
+-- This mode can be useful for debugging/testing a world without the map data available
+-- In this case, choose 'singlenode' as mapgen
+
+local NO_SAVE = false
+-- Do not save any data to advtrains save files
+
+advtrains.TRAIN_MAX_WAGONS = 20
+-- Limit on the maximum number of wagons that may be in a train
+
+-- ==========================================================================
+
+advtrains.modpath = minetest.get_modpath("advtrains")
+
+-- ask engine for translator instance, this will load the translation files
+advtrains.translate = core.get_translator("advtrains")
+
+-- Get current translator
+local S = advtrains.translate
+
+-- define attrans for old mods
+attrans = function(...)
+ atwarn("Mod",core.get_current_modname(),"still uses attrans(), please update or inform mod author")
+ return S(...)
+end
+
+-- Use a global slowdown factor to slow down train movements. Now a setting
+advtrains.DTIME_LIMIT = tonumber(minetest.settings:get("advtrains_dtime_limit")) or 0.2
+advtrains.SAVE_INTERVAL = tonumber(minetest.settings:get("advtrains_save_interval")) or 60
+
+--Constant for maximum connection value/division of the circle
+AT_CMAX = 16
+
+-- get wagon loading range
+advtrains.wagon_load_range = tonumber(minetest.settings:get("advtrains_wagon_load_range"))
+if not advtrains.wagon_load_range then
+ advtrains.wagon_load_range = tonumber(minetest.settings:get("active_block_range"))*16
+end
+
+--pcall
+local no_action=false
+
+local function reload_saves()
+ atwarn(S("Restoring saved state in 1 second..."))
+ no_action=true
+ advtrains.lock_path_inval = false
+ --read last save state and continue, as if server was restarted
+ for aoi, le in pairs(minetest.luaentities) do
+ if le.is_wagon then
+ le.object:remove()
+ end
+ end
+ minetest.after(1, function()
+ advtrains.load()
+ atwarn(S("Reload successful!"))
+ advtrains.ndb.restore_all()
+ end)
+end
+
+--Advtrains dump (special treatment of pos and sigd)
+function atdump(t, intend)
+ local str
+ if type(t)=="table" then
+ if t.x and t.y and t.z then
+ str=minetest.pos_to_string(t)
+ elseif t.p and t.s then -- interlocking sigd
+ str="S["..minetest.pos_to_string(t.p).."/"..t.s.."]"
+ elseif advtrains.lines and t.s and t.m then -- RwT
+ str=advtrains.lines.rwt.to_string(t)
+ else
+ str="{"
+ local intd = (intend or "") .. " "
+ for k,v in pairs(t) do
+ if type(k)~="string" or not string.match(k, "^path[_]?") then
+ -- do not print anything path-related
+ str = str .. "\n" .. intd .. atdump(k, intd) .. " = " ..atdump(v, intd)
+ end
+ end
+ str = str .. "\n" .. (intend or "") .. "}"
+ end
+ elseif type(t)=="boolean" then
+ if t then
+ str="true"
+ else
+ str="false"
+ end
+ elseif type(t)=="function" then
+ str="<function>"
+ elseif type(t)=="userdata" then
+ str="<userdata>"
+ else
+ str=""..t
+ end
+ return str
+end
+
+function advtrains.print_concat_table(a)
+ local str=""
+ local stra=""
+ local t
+ for i=1,20 do
+ t=a[i]
+ if t==nil then
+ stra=stra.."nil "
+ else
+ str=str..stra
+ stra=""
+ str=str..atdump(t).." "
+ end
+ end
+ return str
+end
+
+atprint=function() end
+atlog=function(t, ...)
+ local text=advtrains.print_concat_table({t, ...})
+ minetest.log("action", "[advtrains]"..text)
+end
+atwarn=function(t, ...)
+ local text=advtrains.print_concat_table({t, ...})
+ minetest.log("warning", "[advtrains]"..text)
+ minetest.chat_send_all("[advtrains] -!- "..text)
+end
+sid=function(id) if id then return string.sub(id, -6) end end
+
+
+--ONLY use this function for temporary debugging. for consistent debug prints use atprint
+atdebug=function(t, ...)
+ local text=advtrains.print_concat_table({t, ...})
+ minetest.log("action", "[advtrains]"..text)
+ minetest.chat_send_all("[advtrains]"..text)
+end
+
+if minetest.settings:get_bool("advtrains_enable_debugging") then
+ atprint=function(t, ...)
+ local context=advtrains.atprint_context_tid or ""
+ if not context then return end
+ local text=advtrains.print_concat_table({t, ...})
+ advtrains.drb_record(context, text)
+
+ --atlog("@@",advtrains.atprint_context_tid,t,...)
+ end
+ dofile(advtrains.modpath.."/debugringbuffer.lua")
+
+end
+
+function assertt(var, typ)
+ if type(var)~=typ then
+ error("Assertion failed, variable has to be of type "..typ)
+ end
+end
+
+dofile(advtrains.modpath.."/helpers.lua")
+--dofile(advtrains.modpath.."/debugitems.lua");
+
+advtrains.meseconrules =
+{{x=0, y=0, z=-1},
+ {x=1, y=0, z=0},
+ {x=-1, y=0, z=0},
+ {x=0, y=0, z=1},
+ {x=1, y=1, z=0},
+ {x=1, y=-1, z=0},
+ {x=-1, y=1, z=0},
+ {x=-1, y=-1, z=0},
+ {x=0, y=1, z=1},
+ {x=0, y=-1, z=1},
+ {x=0, y=1, z=-1},
+ {x=0, y=-1, z=-1},
+ {x=0, y=-2, z=0}}
+
+advtrains.fpath=minetest.get_worldpath().."/advtrains"
+
+advtrains.speed = dofile(advtrains.modpath.."/speed.lua")
+advtrains.formspec = dofile(advtrains.modpath.."/formspec.lua")
+advtrains.texture = dofile(advtrains.modpath.."/texture.lua")
+
+dofile(advtrains.modpath.."/path.lua")
+dofile(advtrains.modpath.."/trainlogic.lua")
+dofile(advtrains.modpath.."/trainhud.lua")
+dofile(advtrains.modpath.."/trackplacer.lua")
+dofile(advtrains.modpath.."/copytool.lua")
+dofile(advtrains.modpath.."/wagonprop_tool.lua")
+dofile(advtrains.modpath.."/tracks.lua")
+dofile(advtrains.modpath.."/track_reg_helper.lua")
+dofile(advtrains.modpath.."/occupation.lua")
+dofile(advtrains.modpath.."/atc.lua")
+dofile(advtrains.modpath.."/wagons.lua")
+dofile(advtrains.modpath.."/protection.lua")
+
+dofile(advtrains.modpath.."/nodedb.lua")
+dofile(advtrains.modpath.."/couple.lua")
+
+dofile(advtrains.modpath.."/signals.lua")
+dofile(advtrains.modpath.."/misc_nodes.lua")
+dofile(advtrains.modpath.."/crafting.lua")
+dofile(advtrains.modpath.."/craft_items.lua")
+
+dofile(advtrains.modpath.."/log.lua")
+dofile(advtrains.modpath.."/passive.lua")
+if mesecon then
+ dofile(advtrains.modpath.."/p_mesecon_iface.lua")
+end
+
+
+dofile(advtrains.modpath.."/lzb.lua")
+
+if minetest.settings:get_bool("advtrains_register_debugitems") then
+ dofile(advtrains.modpath.."/debugitems.lua")
+end
+
+--load/save
+
+-- backup variables, used if someone should accidentally delete a sub-mod
+-- As of version 4, only used once during migration from version 3 to 4
+-- Since version 4, each of the mods stores a separate save file.
+local MDS_interlocking, MDS_lines
+
+
+advtrains.fpath=minetest.get_worldpath().."/advtrains"
+dofile(advtrains.modpath.."/log.lua")
+function advtrains.read_component(name)
+ local path = advtrains.fpath.."_"..name
+ minetest.log("action", "[advtrains] loading "..path)
+ local file, err = io.open(path, "r")
+ if not file then
+ minetest.log("warning", " Failed to read advtrains save data from file "..path..": "..(err or "Unknown Error"))
+ minetest.log("warning", " (this is normal when first enabling advtrains on this world)")
+ return
+ end
+ local tbl = minetest.deserialize(file:read("*a"))
+ file:close()
+ return tbl
+end
+
+function advtrains.avt_load()
+ -- check for new, split advtrains save file
+
+ local version = advtrains.read_component("version")
+ local tbl
+ if version and version == 4 then
+ advtrains.load_version_4()
+ return
+ -- NOTE: From here, legacy loading code!
+ elseif version and version == 3 then
+ -- we are dealing with the split-up system
+ minetest.log("action", "[advtrains] loading savefiles version 3")
+ local il_save = {
+ tcbs = true,
+ ts = true,
+ signalass = true,
+ rs_locks = true,
+ rs_callbacks = true,
+ influence_points = true,
+ npr_rails = true,
+ }
+ tbl={
+ trains = true,
+ wagon_save = true,
+ ptmap = true,
+ atc = true,
+ ndb = true,
+ lines = true,
+ version = 2,
+ }
+ for i,k in pairs(il_save) do
+ il_save[i] = advtrains.read_component("interlocking_"..i)
+ end
+ for i,k in pairs(tbl) do
+ tbl[i] = advtrains.read_component(i)
+ end
+ tbl["interlocking"] = il_save
+ else
+ local file, err = io.open(advtrains.fpath, "r")
+ if not file then
+ minetest.log("warning", " Failed to read advtrains save data from file "..advtrains.fpath..": "..(err or "Unknown Error"))
+ minetest.log("warning", " (this is normal when first enabling advtrains on this world)")
+ return
+ else
+ tbl = minetest.deserialize(file:read("*a"))
+ file:close()
+ end
+ end
+ if type(tbl) == "table" then
+ if tbl.version then
+ --congrats, we have the new save format.
+ advtrains.trains = tbl.trains
+ --Save the train id into the train table to avoid having to pass id around
+ for id, train in pairs(advtrains.trains) do
+ train.id = id
+ end
+ advtrains.wagons = tbl.wagon_save
+ advtrains.player_to_train_mapping = tbl.ptmap or {}
+ advtrains.ndb.load_data_pre_v4(tbl.ndb)
+ advtrains.atc.load_data(tbl.atc)
+ if advtrains.interlocking then
+ advtrains.interlocking.db.load(tbl.interlocking)
+ else
+ MDS_interlocking = tbl.interlocking
+ end
+ if advtrains.lines then
+ advtrains.lines.load(tbl.lines)
+ else
+ MDS_lines = tbl.lines
+ end
+ --remove wagon_save entries that are not part of a train
+ local todel=advtrains.merge_tables(advtrains.wagon_save)
+ for tid, train in pairs(advtrains.trains) do
+ train.id = tid
+ for _, wid in ipairs(train.trainparts) do
+ todel[wid]=nil
+ end
+ end
+ for wid, _ in pairs(todel) do
+ atwarn(S("Removing unused wagon"), wid, S("from wagon_save table."))
+ advtrains.wagon_save[wid]=nil
+ end
+ else
+ --oh no, its the old one...
+ advtrains.trains=tbl
+ --load ATC
+ advtrains.fpath_atc=minetest.get_worldpath().."/advtrains_atc"
+ local file, err = io.open(advtrains.fpath_atc, "r")
+ if not file then
+ local er=err or "Unknown Error"
+ atprint("Failed loading advtrains atc save file "..er)
+ else
+ local tbl = minetest.deserialize(file:read("*a"))
+ if type(tbl) == "table" then
+ advtrains.atc.controllers=tbl.controllers
+ end
+ file:close()
+ end
+ --load wagon saves
+ advtrains.fpath_ws=minetest.get_worldpath().."/advtrains_wagon_save"
+ local file, err = io.open(advtrains.fpath_ws, "r")
+ if not file then
+ local er=err or "Unknown Error"
+ atprint("Failed loading advtrains save file "..er)
+ else
+ local tbl = minetest.deserialize(file:read("*a"))
+ if type(tbl) == "table" then
+ advtrains.wagon_save=tbl
+ end
+ file:close()
+ end
+ end
+ else
+ minetest.log("error", " Failed to deserialize advtrains save data: Not a table!")
+ end
+ -- moved from advtrains.load()
+ atlatc.load_pre_v4()
+ -- end of legacy loading code
+end
+
+function advtrains.load_version_4()
+ minetest.log("action", "[advtrains] loading savefiles version 4 (serialize_lib)")
+
+ --== load core ==
+ local at_save = serialize_lib.load_atomic(advtrains.fpath.."_core.ls")
+ if at_save then
+ advtrains.trains = at_save.trains
+ --Save the train id into the train table to avoid having to pass id around
+ for id, train in pairs(advtrains.trains) do
+ train.id = id
+ end
+ advtrains.wagons = at_save.wagons
+ advtrains.player_to_train_mapping = at_save.ptmap or {}
+ advtrains.atc.load_data(at_save.atc)
+
+ --remove wagon_save entries that are not part of a train
+ local todel=advtrains.merge_tables(advtrains.wagon_save)
+ for tid, train in pairs(advtrains.trains) do
+ train.id = tid
+ for _, wid in ipairs(train.trainparts) do
+ todel[wid]=nil
+ end
+ end
+ for wid, _ in pairs(todel) do
+ atwarn(S("Removing unused wagon"), wid, S("from wagon_save table."))
+ advtrains.wagon_save[wid]=nil
+ end
+ end
+ --== load ndb
+ serialize_lib.load_atomic(advtrains.fpath.."_ndb4.ls", advtrains.ndb.load_callback)
+
+ --== load interlocking ==
+ if advtrains.interlocking then
+ local il_save = serialize_lib.load_atomic(advtrains.fpath.."_interlocking.ls")
+ if il_save then
+ advtrains.interlocking.db.load(il_save)
+ end
+
+ -- TODO 2.5.0 backwards compatibility fallback: Store the pre-v2.5.0 save file so that it can be reverted to if needed
+ local fallback_file = advtrains.fpath.."_interlocking.ls.pre250"
+ local file = io.open(fallback_file, "rb")
+ if file then
+ io.close(file)
+ else
+ atwarn("Backing up pre-2.5.0 version of Interlocking save file to",fallback_file," for potential downgrade to older versions")
+ os.rename(advtrains.fpath.."_interlocking.ls", fallback_file)
+ end
+ end
+
+ --== load lines ==
+ if advtrains.lines then
+ local ln_save = serialize_lib.load_atomic(advtrains.fpath.."_lines.ls")
+ if ln_save then
+ advtrains.lines.load(ln_save)
+ end
+ end
+
+ --== load luaatc ==
+ if atlatc then
+ local la_save = serialize_lib.load_atomic(advtrains.fpath.."_atlatc.ls")
+ if la_save then
+ atlatc.load(la_save)
+ end
+ end
+end
+
+advtrains.save_component = function (tbl, name)
+ -- Saves each component of the advtrains file separately
+ --
+ -- required for now to shrink the advtrains db to overcome lua
+ -- limitations.
+ -- Note: as of version 4, only used for the "advtrains_version" file
+ local datastr = minetest.serialize(tbl)
+ if not datastr then
+ minetest.log("error", " Failed to serialize advtrains save data!")
+ return
+ end
+ local path = advtrains.fpath.."_"..name
+ local success = minetest.safe_file_write(path, datastr)
+
+ if not success then
+ minetest.log("error", " Failed to write advtrains save data to file "..path)
+ end
+
+end
+
+advtrains.avt_save = function(remove_players_from_wagons)
+ --atdebug("Saving advtrains files (version 4)")
+
+ if remove_players_from_wagons then
+ for w_id, data in pairs(advtrains.wagons) do
+ data.seatp={}
+ end
+ advtrains.player_to_train_mapping={}
+ end
+
+ local tmp_trains={}
+ for id, train in pairs(advtrains.trains) do
+ --first, deep_copy the train
+ if #train.trainparts > 0 then
+ local v=advtrains.save_keys(train, {
+ "last_pos", "last_connid", "last_frac", "velocity", "tarvelocity",
+ "trainparts", "recently_collided_with_env",
+ "atc_brake_target", "atc_wait_finish", "atc_command", "atc_delay", "door_open",
+ "text_outside", "text_inside", "line", "routingcode",
+ "il_sections", "speed_restriction", "speed_restrictions_t", "is_shunt",
+ "path_ori_cp", "autocouple", "atc_wait_autocouple", "ars_disable",
+ "staticdata", "line_status",
+ })
+ --then save it
+ tmp_trains[id]=v
+ else
+ atwarn(S("Train @1 had no wagons left because of some bug. It is being deleted. Wave it goodbye!", id))
+ advtrains.remove_train(id)
+ end
+ end
+
+ for id, wdata in pairs(advtrains.wagons) do
+ local _,proto = advtrains.get_wagon_prototype(wdata)
+ if proto.has_inventory then
+ local inv=minetest.get_inventory({type="detached", name="advtrains_wgn_"..id})
+ if inv then -- inventory is not initialized when wagon was never loaded
+ -- TOOD: What happens with unloading rails when they don't find the inventory?
+ wdata.ser_inv=advtrains.serialize_inventory(inv)
+ end
+ end
+ -- TODO apply save-keys here too
+ -- TODO temp
+ wdata.dcpl_lock = nil
+ end
+
+ --versions:
+ -- 1 - Initial new save format.
+ -- 2 - version as of tss branch 11-2018+
+ -- 3 - split-up savefile system by gabriel
+ -- 4 - serialize_lib
+
+ -- save of core advtrains
+ local at_save={
+ trains = tmp_trains,
+ wagons = advtrains.wagons,
+ ptmap = advtrains.player_to_train_mapping,
+ atc = advtrains.atc.save_data(),
+ }
+
+ --save of interlocking
+ local il_save
+ if advtrains.interlocking then
+ il_save = advtrains.interlocking.db.save()
+ else
+ il_save = MDS_interlocking
+ end
+
+ -- save of lines
+ local ln_save
+ if advtrains.lines then
+ ln_save = advtrains.lines.save()
+ else
+ ln_save = MDS_lines
+ end
+
+ -- save of luaatc
+ local la_save
+ if atlatc then
+ la_save = atlatc.save()
+ end
+
+ -- parts table for serialize_lib API:
+ -- any table that is nil will not be included and thus not be overwritten
+ local parts_table = {
+ ["core.ls"] = at_save,
+ ["interlocking.ls"] = il_save,
+ ["lines.ls"] = ln_save,
+ ["atlatc.ls"] = la_save,
+ ["ndb4.ls"] = true, -- data not used
+ }
+ local callbacks_table = {
+ ["ndb4.ls"] = advtrains.ndb.save_callback
+ }
+
+ if DUMP_DEBUG_SAVE then
+ local file, err = io.open(advtrains.fpath.."_DUMP", "w")
+ if err then
+ return
+ end
+ file:write(dump(parts_table))
+ file:close()
+ end
+
+ --THE MAGIC HAPPENS HERE
+ local succ, err = serialize_lib.save_atomic_multiple(parts_table, advtrains.fpath.."_", callbacks_table)
+
+ if not succ then
+ atwarn(S("Saving failed: @1", err))
+ else
+ -- store version
+ advtrains.save_component(4, "version")
+ end
+end
+
+--## MAIN LOOP ##--
+--Calls all subsequent main tasks of both advtrains and atlatc
+local init_load=false
+local save_timer = advtrains.SAVE_INTERVAL
+advtrains.mainloop_runcnt=0
+advtrains.global_slowdown = 1
+
+local t = 0
+local within_mainstep = false
+minetest.register_globalstep(function(dtime_mt)
+ if no_action then
+ -- the advtrains globalstep is skipped by command. Return immediately
+ return
+ end
+ within_mainstep = true
+
+ advtrains.mainloop_runcnt=advtrains.mainloop_runcnt+1
+ --atprint("Running the main loop, runcnt",advtrains.mainloop_runcnt)
+ --call load once. see advtrains.load() comment
+ if not init_load then
+ advtrains.load()
+ end
+
+ local dtime = dtime_mt * advtrains.global_slowdown
+ if GENERATE_ATRICIFIAL_LAG then
+ dtime = HOW_MANY_LAG
+ if os.clock()<t then
+ within_mainstep = false
+ return
+ end
+
+ t = os.clock()+HOW_MANY_LAG
+ end
+ -- if dtime is too high, decrease global slowdown
+ if advtrains.DTIME_LIMIT~=0 then
+ if dtime > advtrains.DTIME_LIMIT then
+ if advtrains.global_slowdown > 0.1 then
+ advtrains.global_slowdown = advtrains.global_slowdown - 0.05
+ else
+ advtrains.global_slowdown = advtrains.global_slowdown / 2
+ end
+ dtime = advtrains.DTIME_LIMIT
+ end
+ -- recover global slowdown slowly over time
+ advtrains.global_slowdown = math.min(advtrains.global_slowdown*1.02, 1)
+ end
+
+ advtrains.mainloop_trainlogic(dtime,advtrains.mainloop_runcnt)
+ if advtrains_itm_mainloop then
+ advtrains_itm_mainloop(dtime)
+ end
+ if atlatc then
+ --atlatc.mainloop_stepcode(dtime)
+ atlatc.interrupt.mainloop(dtime)
+ end
+ if advtrains.lines then
+ advtrains.lines.step(dtime)
+ end
+
+ --trigger a save when necessary
+ save_timer=save_timer-dtime
+ if save_timer<=0 then
+ local t=os.clock()
+ --save
+ advtrains.save()
+ save_timer = advtrains.SAVE_INTERVAL
+ atprintbm("saving", t)
+ end
+
+ within_mainstep = false
+
+end)
+
+--if something goes wrong in these functions, there is no help. no pcall here.
+
+--## MAIN LOAD ROUTINE ##
+-- Causes the loading of everything
+-- first time called in main loop (after the init phase) because luaautomation has to initialize first.
+function advtrains.load()
+ advtrains.avt_load() --loading advtrains. includes ndb at advtrains.ndb.load_data()
+ --if atlatc then
+ -- atlatc.load() --includes interrupts
+ --end == No longer loading here. Now part of avt_save() legacy loading.
+ if advtrains_itm_init then
+ advtrains_itm_init()
+ end
+ init_load=true
+ no_action=false
+ atlog("[load_all]Loaded advtrains save files")
+end
+
+--## MAIN SAVE ROUTINE ##
+-- Causes the saving of everything
+function advtrains.save(remove_players_from_wagons)
+ if not init_load then
+ --wait... we haven't loaded yet?!
+ atwarn(S("Instructed to save() but load() was never called!"))
+ return
+ end
+
+ if advtrains.IGNORE_WORLD then
+ advtrains.ndb.restore_all()
+ end
+
+ if NO_SAVE then
+ return
+ end
+ if no_action then
+ atlog("[save] Saving requested externally, but Advtrains step is disabled. Not saving any data as state may be inconsistent.")
+ return
+ end
+
+ local t1 = os.clock()
+ advtrains.avt_save(remove_players_from_wagons) --saving advtrains. includes ndb at advtrains.ndb.save_data()
+ if atlatc then
+ atlatc.save()
+ end
+ atlog("Saved advtrains save files, took",math.floor((os.clock()-t1) * 1000),"ms")
+
+ -- Cleanup actions
+ --TODO very simple yet hacky workaround for the "green signals" bug
+ advtrains.invalidate_all_paths()
+end
+minetest.register_on_shutdown(function()
+ if within_mainstep then
+ atwarn(S("Crash during advtrains main step - skipping the shutdown save operation to not save inconsistent data!"))
+ else
+ advtrains.save()
+ end
+end)
+
+-- This chat command provides a solution to the problem known on the LinuxWorks server
+-- There are many players that joined a single time, got on a train and then left forever
+-- These players still occupy seats in the trains.
+minetest.register_chatcommand("at_empty_seats",
+ {
+ params = "", -- Short parameter description
+ description = S("Detach all players, especially the offline ones, from all trains. Use only when no one serious is on a train."), -- Full description
+ privs = {train_operator=true, server=true}, -- Require the "privs" privilege to run
+ func = function(name, param)
+ atwarn(S("Data is being saved. While saving, advtrains will remove the players from trains. Save files will be reloaded afterwards!"))
+ advtrains.save(true)
+ reload_saves()
+ end,
+})
+-- This chat command solves another problem: Trains getting randomly stuck.
+minetest.register_chatcommand("at_reroute",
+ {
+ params = "",
+ description = S("Delete all train routes, force them to recalculate"),
+ privs = {train_operator=true}, -- Only train operator is required, since this is relatively safe.
+ func = function(name, param)
+ advtrains.invalidate_all_paths()
+ return true, S("Successfully invalidated train routes")
+ end,
+})
+
+minetest.register_chatcommand("at_whereis",
+ {
+ params = "<train id>",
+ description = S("Returns the position of the train with the given id"),
+ privs = {train_operator = true},
+ func = function(name,param)
+ local train = advtrains.trains[param]
+ if not train or not train.last_pos then
+ return false, S("Train @1 does not exist or is invalid", param)
+ else
+ return true, S("Train @1 is at @2", param, minetest.pos_to_string(train.last_pos))
+ end
+ end,
+})
+minetest.register_chatcommand("at_tp",
+ {
+ params = "<train id>",
+ description = S("Teleports you to the position of the train with the given id"),
+ privs = {train_operator = true, teleport = true},
+ func = function(name,param)
+ local train = advtrains.trains[param]
+ if not train or not train.last_pos then
+ return false, S("Train @1 does not exist or is invalid", param)
+ else
+ minetest.get_player_by_name(name):set_pos(train.last_pos)
+ return true, S("Teleporting to train @1", param)
+ end
+ end,
+})
+minetest.register_chatcommand("at_disable_step",
+ {
+ params = "<yes/no>",
+ description = S("Disable the advtrains globalstep temporarily"),
+ privs = {server=true},
+ func = function(name, param)
+ if minetest.is_yes(param) then
+ -- disable everything, and turn off saving
+ no_action = true;
+ atwarn(S("The advtrains globalstep has been disabled. Trains are not moving, and no data is saved! Run '/at_disable_step no' to enable again!"))
+ return true, S("Disabled advtrains successfully")
+ elseif no_action then
+ atwarn(S("Re-enabling advtrains globalstep..."))
+ reload_saves()
+ return true
+ else
+ return false, S("Advtrains is already running normally!")
+ end
+ end,
+})
+
+minetest.register_chatcommand("at_status",
+ {
+ params = "",
+ description = S("Print advtrains status info"),
+ privs = {train_operator = true},
+ func = function(name, param)
+ return true, S("Advtrains Status: no_action @1 slowdown @2 (log @3)", tostring(no_action), advtrains.global_slowdown, math.log(advtrains.global_slowdown))
+ end,
+})
+
+advtrains.is_no_action = function()
+ return no_action
+end
+
+
+local tot=(os.clock()-lot)*1000
+minetest.log("action", "[advtrains] Loaded in "..tot.."ms")
+
diff --git a/advtrains/license.txt b/advtrains/license.txt
deleted file mode 100644
index 68a4b60..0000000
--- a/advtrains/license.txt
+++ /dev/null
@@ -1,142 +0,0 @@
-GNU LESSER GENERAL PUBLIC LICENSE
-
-Version 2.1, February 1999
-
-Copyright (C) 1991, 1999 Free Software Foundation, Inc.
-51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
-Everyone is permitted to copy and distribute verbatim copies
-of this license document, but changing it is not allowed.
-
-[This is the first released version of the Lesser GPL. It also counts
- as the successor of the GNU Library Public License, version 2, hence
- the version number 2.1.]
-
-Preamble
-
-The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users.
-
-This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below.
-
-When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things.
-
-To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it.
-
-For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights.
-
-We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library.
-
-To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others.
-
-Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license.
-
-Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs.
-
-When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library.
-
-We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances.
-
-For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License.
-
-In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system.
-
-Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library.
-
-The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run.
-TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
-
-0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you".
-
-A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables.
-
-The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".)
-
-"Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library.
-
-Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does.
-
-1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library.
-
-You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee.
-
-2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions:
-
- a) The modified work must itself be a software library.
- b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change.
- c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License.
- d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful.
-
- (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.)
-
-These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it.
-
-Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library.
-
-In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License.
-
-3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices.
-
-Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy.
-
-This option is useful when you wish to copy part of the code of the Library into a program that is not a library.
-
-4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange.
-
-If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code.
-
-5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License.
-
-However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables.
-
-When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law.
-
-If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.)
-
-Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself.
-
-6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications.
-
-You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things:
-
- a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.)
- b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with.
- c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution.
- d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place.
- e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy.
-
-For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable.
-
-It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute.
-
-7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things:
-
- a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above.
- b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work.
-
-8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.
-
-9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it.
-
-10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License.
-
-11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library.
-
-If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances.
-
-It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice.
-
-This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License.
-
-12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License.
-
-13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
-
-Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation.
-
-14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally.
-
-NO WARRANTY
-
-15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
-
-16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
-END OF TERMS AND CONDITIONS
diff --git a/advtrains/license_media.txt b/advtrains/license_media.txt
deleted file mode 100644
index 888cf00..0000000
--- a/advtrains/license_media.txt
+++ /dev/null
@@ -1,68 +0,0 @@
-THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CREATIVE COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). THE WORK IS PROTECTED BY COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED.
-
-BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE TO BE BOUND BY THE TERMS OF THIS LICENSE. TO THE EXTENT THIS LICENSE MAY BE CONSIDERED TO BE A CONTRACT, THE LICENSOR GRANTS YOU THE RIGHTS CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND CONDITIONS.
-
-1. Definitions
-
- "Adaptation" means a work based upon the Work, or upon the Work and other pre-existing works, such as a translation, adaptation, derivative work, arrangement of music or other alterations of a literary or artistic work, or phonogram or performance and includes cinematographic adaptations or any other form in which the Work may be recast, transformed, or adapted including in any form recognizably derived from the original, except that a work that constitutes a Collection will not be considered an Adaptation for the purpose of this License. For the avoidance of doubt, where the Work is a musical work, performance or phonogram, the synchronization of the Work in timed-relation with a moving image ("synching") will be considered an Adaptation for the purpose of this License.
- "Collection" means a collection of literary or artistic works, such as encyclopedias and anthologies, or performances, phonograms or broadcasts, or other works or subject matter other than works listed in Section 1(f) below, which, by reason of the selection and arrangement of their contents, constitute intellectual creations, in which the Work is included in its entirety in unmodified form along with one or more other contributions, each constituting separate and independent works in themselves, which together are assembled into a collective whole. A work that constitutes a Collection will not be considered an Adaptation (as defined below) for the purposes of this License.
- "Creative Commons Compatible License" means a license that is listed at https://creativecommons.org/compatiblelicenses that has been approved by Creative Commons as being essentially equivalent to this License, including, at a minimum, because that license: (i) contains terms that have the same purpose, meaning and effect as the License Elements of this License; and, (ii) explicitly permits the relicensing of adaptations of works made available under that license under this License or a Creative Commons jurisdiction license with the same License Elements as this License.
- "Distribute" means to make available to the public the original and copies of the Work or Adaptation, as appropriate, through sale or other transfer of ownership.
- "License Elements" means the following high-level license attributes as selected by Licensor and indicated in the title of this License: Attribution, ShareAlike.
- "Licensor" means the individual, individuals, entity or entities that offer(s) the Work under the terms of this License.
- "Original Author" means, in the case of a literary or artistic work, the individual, individuals, entity or entities who created the Work or if no individual or entity can be identified, the publisher; and in addition (i) in the case of a performance the actors, singers, musicians, dancers, and other persons who act, sing, deliver, declaim, play in, interpret or otherwise perform literary or artistic works or expressions of folklore; (ii) in the case of a phonogram the producer being the person or legal entity who first fixes the sounds of a performance or other sounds; and, (iii) in the case of broadcasts, the organization that transmits the broadcast.
- "Work" means the literary and/or artistic work offered under the terms of this License including without limitation any production in the literary, scientific and artistic domain, whatever may be the mode or form of its expression including digital form, such as a book, pamphlet and other writing; a lecture, address, sermon or other work of the same nature; a dramatic or dramatico-musical work; a choreographic work or entertainment in dumb show; a musical composition with or without words; a cinematographic work to which are assimilated works expressed by a process analogous to cinematography; a work of drawing, painting, architecture, sculpture, engraving or lithography; a photographic work to which are assimilated works expressed by a process analogous to photography; a work of applied art; an illustration, map, plan, sketch or three-dimensional work relative to geography, topography, architecture or science; a performance; a broadcast; a phonogram; a compilation of data to the extent it is protected as a copyrightable work; or a work performed by a variety or circus performer to the extent it is not otherwise considered a literary or artistic work.
- "You" means an individual or entity exercising rights under this License who has not previously violated the terms of this License with respect to the Work, or who has received express permission from the Licensor to exercise rights under this License despite a previous violation.
- "Publicly Perform" means to perform public recitations of the Work and to communicate to the public those public recitations, by any means or process, including by wire or wireless means or public digital performances; to make available to the public Works in such a way that members of the public may access these Works from a place and at a place individually chosen by them; to perform the Work to the public by any means or process and the communication to the public of the performances of the Work, including by public digital performance; to broadcast and rebroadcast the Work by any means including signs, sounds or images.
- "Reproduce" means to make copies of the Work by any means including without limitation by sound or visual recordings and the right of fixation and reproducing fixations of the Work, including storage of a protected performance or phonogram in digital form or other electronic medium.
-
-2. Fair Dealing Rights. Nothing in this License is intended to reduce, limit, or restrict any uses free from copyright or rights arising from limitations or exceptions that are provided for in connection with the copyright protection under copyright law or other applicable laws.
-
-3. License Grant. Subject to the terms and conditions of this License, Licensor hereby grants You a worldwide, royalty-free, non-exclusive, perpetual (for the duration of the applicable copyright) license to exercise the rights in the Work as stated below:
-
- to Reproduce the Work, to incorporate the Work into one or more Collections, and to Reproduce the Work as incorporated in the Collections;
- to create and Reproduce Adaptations provided that any such Adaptation, including any translation in any medium, takes reasonable steps to clearly label, demarcate or otherwise identify that changes were made to the original Work. For example, a translation could be marked "The original work was translated from English to Spanish," or a modification could indicate "The original work has been modified.";
- to Distribute and Publicly Perform the Work including as incorporated in Collections; and,
- to Distribute and Publicly Perform Adaptations.
-
- For the avoidance of doubt:
- Non-waivable Compulsory License Schemes. In those jurisdictions in which the right to collect royalties through any statutory or compulsory licensing scheme cannot be waived, the Licensor reserves the exclusive right to collect such royalties for any exercise by You of the rights granted under this License;
- Waivable Compulsory License Schemes. In those jurisdictions in which the right to collect royalties through any statutory or compulsory licensing scheme can be waived, the Licensor waives the exclusive right to collect such royalties for any exercise by You of the rights granted under this License; and,
- Voluntary License Schemes. The Licensor waives the right to collect royalties, whether individually or, in the event that the Licensor is a member of a collecting society that administers voluntary licensing schemes, via that society, from any exercise by You of the rights granted under this License.
-
-The above rights may be exercised in all media and formats whether now known or hereafter devised. The above rights include the right to make such modifications as are technically necessary to exercise the rights in other media and formats. Subject to Section 8(f), all rights not expressly granted by Licensor are hereby reserved.
-
-4. Restrictions. The license granted in Section 3 above is expressly made subject to and limited by the following restrictions:
-
- You may Distribute or Publicly Perform the Work only under the terms of this License. You must include a copy of, or the Uniform Resource Identifier (URI) for, this License with every copy of the Work You Distribute or Publicly Perform. You may not offer or impose any terms on the Work that restrict the terms of this License or the ability of the recipient of the Work to exercise the rights granted to that recipient under the terms of the License. You may not sublicense the Work. You must keep intact all notices that refer to this License and to the disclaimer of warranties with every copy of the Work You Distribute or Publicly Perform. When You Distribute or Publicly Perform the Work, You may not impose any effective technological measures on the Work that restrict the ability of a recipient of the Work from You to exercise the rights granted to that recipient under the terms of the License. This Section 4(a) applies to the Work as incorporated in a Collection, but this does not require the Collection apart from the Work itself to be made subject to the terms of this License. If You create a Collection, upon notice from any Licensor You must, to the extent practicable, remove from the Collection any credit as required by Section 4(c), as requested. If You create an Adaptation, upon notice from any Licensor You must, to the extent practicable, remove from the Adaptation any credit as required by Section 4(c), as requested.
- You may Distribute or Publicly Perform an Adaptation only under the terms of: (i) this License; (ii) a later version of this License with the same License Elements as this License; (iii) a Creative Commons jurisdiction license (either this or a later license version) that contains the same License Elements as this License (e.g., Attribution-ShareAlike 3.0 US)); (iv) a Creative Commons Compatible License. If you license the Adaptation under one of the licenses mentioned in (iv), you must comply with the terms of that license. If you license the Adaptation under the terms of any of the licenses mentioned in (i), (ii) or (iii) (the "Applicable License"), you must comply with the terms of the Applicable License generally and the following provisions: (I) You must include a copy of, or the URI for, the Applicable License with every copy of each Adaptation You Distribute or Publicly Perform; (II) You may not offer or impose any terms on the Adaptation that restrict the terms of the Applicable License or the ability of the recipient of the Adaptation to exercise the rights granted to that recipient under the terms of the Applicable License; (III) You must keep intact all notices that refer to the Applicable License and to the disclaimer of warranties with every copy of the Work as included in the Adaptation You Distribute or Publicly Perform; (IV) when You Distribute or Publicly Perform the Adaptation, You may not impose any effective technological measures on the Adaptation that restrict the ability of a recipient of the Adaptation from You to exercise the rights granted to that recipient under the terms of the Applicable License. This Section 4(b) applies to the Adaptation as incorporated in a Collection, but this does not require the Collection apart from the Adaptation itself to be made subject to the terms of the Applicable License.
- If You Distribute, or Publicly Perform the Work or any Adaptations or Collections, You must, unless a request has been made pursuant to Section 4(a), keep intact all copyright notices for the Work and provide, reasonable to the medium or means You are utilizing: (i) the name of the Original Author (or pseudonym, if applicable) if supplied, and/or if the Original Author and/or Licensor designate another party or parties (e.g., a sponsor institute, publishing entity, journal) for attribution ("Attribution Parties") in Licensor's copyright notice, terms of service or by other reasonable means, the name of such party or parties; (ii) the title of the Work if supplied; (iii) to the extent reasonably practicable, the URI, if any, that Licensor specifies to be associated with the Work, unless such URI does not refer to the copyright notice or licensing information for the Work; and (iv) , consistent with Ssection 3(b), in the case of an Adaptation, a credit identifying the use of the Work in the Adaptation (e.g., "French translation of the Work by Original Author," or "Screenplay based on original Work by Original Author"). The credit required by this Section 4(c) may be implemented in any reasonable manner; provided, however, that in the case of a Adaptation or Collection, at a minimum such credit will appear, if a credit for all contributing authors of the Adaptation or Collection appears, then as part of these credits and in a manner at least as prominent as the credits for the other contributing authors. For the avoidance of doubt, You may only use the credit required by this Section for the purpose of attribution in the manner set out above and, by exercising Your rights under this License, You may not implicitly or explicitly assert or imply any connection with, sponsorship or endorsement by the Original Author, Licensor and/or Attribution Parties, as appropriate, of You or Your use of the Work, without the separate, express prior written permission of the Original Author, Licensor and/or Attribution Parties.
- Except as otherwise agreed in writing by the Licensor or as may be otherwise permitted by applicable law, if You Reproduce, Distribute or Publicly Perform the Work either by itself or as part of any Adaptations or Collections, You must not distort, mutilate, modify or take other derogatory action in relation to the Work which would be prejudicial to the Original Author's honor or reputation. Licensor agrees that in those jurisdictions (e.g. Japan), in which any exercise of the right granted in Section 3(b) of this License (the right to make Adaptations) would be deemed to be a distortion, mutilation, modification or other derogatory action prejudicial to the Original Author's honor and reputation, the Licensor will waive or not assert, as appropriate, this Section, to the fullest extent permitted by the applicable national law, to enable You to reasonably exercise Your right under Section 3(b) of this License (right to make Adaptations) but not otherwise.
-
-5. Representations, Warranties and Disclaimer
-
-UNLESS OTHERWISE MUTUALLY AGREED TO BY THE PARTIES IN WRITING, LICENSOR OFFERS THE WORK AS-IS AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE WORK, EXPRESS, IMPLIED, STATUTORY OR OTHERWISE, INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTIBILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OF ABSENCE OF ERRORS, WHETHER OR NOT DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF IMPLIED WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY TO YOU.
-
-6. Limitation on Liability. EXCEPT TO THE EXTENT REQUIRED BY APPLICABLE LAW, IN NO EVENT WILL LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY FOR ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES ARISING OUT OF THIS LICENSE OR THE USE OF THE WORK, EVEN IF LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
-
-7. Termination
-
- This License and the rights granted hereunder will terminate automatically upon any breach by You of the terms of this License. Individuals or entities who have received Adaptations or Collections from You under this License, however, will not have their licenses terminated provided such individuals or entities remain in full compliance with those licenses. Sections 1, 2, 5, 6, 7, and 8 will survive any termination of this License.
- Subject to the above terms and conditions, the license granted here is perpetual (for the duration of the applicable copyright in the Work). Notwithstanding the above, Licensor reserves the right to release the Work under different license terms or to stop distributing the Work at any time; provided, however that any such election will not serve to withdraw this License (or any other license that has been, or is required to be, granted under the terms of this License), and this License will continue in full force and effect unless terminated as stated above.
-
-8. Miscellaneous
-
- Each time You Distribute or Publicly Perform the Work or a Collection, the Licensor offers to the recipient a license to the Work on the same terms and conditions as the license granted to You under this License.
- Each time You Distribute or Publicly Perform an Adaptation, Licensor offers to the recipient a license to the original Work on the same terms and conditions as the license granted to You under this License.
- If any provision of this License is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this License, and without further action by the parties to this agreement, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable.
- No term or provision of this License shall be deemed waived and no breach consented to unless such waiver or consent shall be in writing and signed by the party to be charged with such waiver or consent.
- This License constitutes the entire agreement between the parties with respect to the Work licensed here. There are no understandings, agreements or representations with respect to the Work not specified here. Licensor shall not be bound by any additional provisions that may appear in any communication from You. This License may not be modified without the mutual written agreement of the Licensor and You.
- The rights granted under, and the subject matter referenced, in this License were drafted utilizing the terminology of the Berne Convention for the Protection of Literary and Artistic Works (as amended on September 28, 1979), the Rome Convention of 1961, the WIPO Copyright Treaty of 1996, the WIPO Performances and Phonograms Treaty of 1996 and the Universal Copyright Convention (as revised on July 24, 1971). These rights and subject matter take effect in the relevant jurisdiction in which the License terms are sought to be enforced according to the corresponding provisions of the implementation of those treaty provisions in the applicable national law. If the standard suite of rights granted under applicable copyright law includes additional rights not granted under this License, such additional rights are deemed to be included in the License; this License is not intended to restrict the license of any rights under applicable law.
-
- Creative Commons Notice
-
- Creative Commons is not a party to this License, and makes no warranty whatsoever in connection with the Work. Creative Commons will not be liable to You or any party on any legal theory for any damages whatsoever, including without limitation any general, special, incidental or consequential damages arising in connection to this license. Notwithstanding the foregoing two (2) sentences, if Creative Commons has expressly identified itself as the Licensor hereunder, it shall have all rights and obligations of Licensor.
-
- Except for the limited purpose of indicating to the public that the Work is licensed under the CCPL, Creative Commons does not authorize the use by either party of the trademark "Creative Commons" or any related trademark or logo of Creative Commons without the prior written consent of Creative Commons. Any permitted use will be in compliance with Creative Commons' then-current trademark usage guidelines, as may be published on its website or otherwise made available upon request from time to time. For the avoidance of doubt, this trademark restriction does not form part of the License.
-
- Creative Commons may be contacted at https://creativecommons.org/.
diff --git a/advtrains/locale/README.md b/advtrains/locale/README.md
new file mode 100644
index 0000000..2446cbf
--- /dev/null
+++ b/advtrains/locale/README.md
@@ -0,0 +1,70 @@
+# Translations
+Please read this document before working on any translations.
+
+## Getting Started
+Advtrains uses `.po` files for localization. These can be edited with
+a regular text editor or with specialized programs (e.g. Poedit).
+
+If the translation file for your language does not exist, you can
+create it using:
+
+`msginit -l LL -o <domain>.LL.po`
+
+where `LL` is the language code and `<domain>` is the "domain" of the
+translation file (which, for the Advtrains modpack, corresponds to the
+name of the mods, e.g. `advtrains_interlocking`).
+
+Feel free to use the [discussion mailing list][srht-discuss] if you
+have any questions regarding localization.
+
+You can share your `.po` file directly or [as a patch][gsm] to the [dev
+mailing list][srht-devel]. The latter is encouraged, but, unlike code
+changes, translation files sent directly are also accepted.
+
+[srht-discuss]: https://lists.sr.ht/~gpcf/advtrains-discuss
+[srht-devel]: https://lists.sr.ht/~gpcf/advtrains-devel
+[gsm]: https://git-send-email.io
+
+## Translation Notes
+* Translations should be consistent. You can use other entries or the
+translations in Minetest as a reference.
+* Translations do not have to fully correspond to the original text -
+they only need to provide the same information. In particular,
+translations do not need to have the same linguistical structure as the
+original text.
+* Replacement sequences (`@1`, `@2`, etc) should not be translated.
+* Certain abbreviations or names, such as "Ks" or "Zs 3", should
+generally not be translated.
+
+### (de) German
+* Verwenden Sie die neue Rechtschreibung und die Sie-Form.
+* Mit der deutschen Tastaturbelegung unter Linux können die
+Anführungszeichen „“ mit AltGr-V bzw. AltGr-B eingegeben werden.
+
+### (zh) Chinese
+(This section is written in English to avoid writing the note twice or
+using only one of the variants, as most of this section applies to both
+the traditional and simplified variants.)
+
+* Please use the 「」 quotation marks for Traditional Chinese and “”
+for Simplified Chinese.
+* Please use the fullwidth variants of: , 、 。 ? ! : ;
+* Please use the halfwidth variants of: ( ) [ ] / \ |
+* Please do not leave any space between Han characters (including
+fullwidth punctuation marks).
+* Please leave a space between Han characters (excluding fullwidth
+punctuation marks) and characters from other scripts (including
+halfwidth punctuation marks). However, do not leave any space between
+Han characters and Arabic numerals.
+
+## Notes for developers
+* The `update-translations.sh` script can be used to update the
+translation files.
+* Please make sure that the first argument to `S` _only_ includes
+string literals without formatting or concatenation. This is
+unfortunately a limitation of the `xgettext` utility.
+* Avoid word-by-word translations.
+* Avoid manipulating translated strings (except for concatenation). Use
+server-side translations if you have to modify the text sent to users.
+* Avoid truncating strings unless translations and multibyte characters
+are handled properly.
diff --git a/advtrains/locale/advtrains.de.po b/advtrains/locale/advtrains.de.po
new file mode 100644
index 0000000..0a0282b
--- /dev/null
+++ b/advtrains/locale/advtrains.de.po
@@ -0,0 +1,920 @@
+msgid ""
+msgstr ""
+"Project-Id-Version: advtrains\n"
+"Report-Msgid-Bugs-To: advtrains-discuss@lists.sr.ht\n"
+"POT-Creation-Date: 2026-05-17 09:18+0800\n"
+"PO-Revision-Date: 2026-05-17 09:22+0800\n"
+"Last-Translator: Y. Wang <yw05@forksworld.de>\n"
+"Language-Team: German\n"
+"Language: de\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"X-Generator: Poedit 3.8\n"
+
+#: atc.lua
+msgid "ATC Kick command warning: doors are closed."
+msgstr ""
+"Zugbeeinflussung: Wegen geschlossener Türen werden Fahrgäste nicht zum "
+"Ausstieg gezwungen."
+
+#: atc.lua
+msgid "ATC Kick command warning: train moving."
+msgstr ""
+"Zugbeeinflussung: Der Zug befindet sich in Bewegung, Fahrgäste werden nicht "
+"zum Ausstieg gezwungen."
+
+#: atc.lua
+msgid "ATC Reverse command warning: didn't reverse train, train moving."
+msgstr ""
+"Zugbeeinflussung: Der Zug befindet sich in Bewegung und kann nicht umgekehrt "
+"werden."
+
+#: atc.lua
+msgid "ATC command parse error: Unknown command: @1"
+msgstr "Zugbeeinflussung: Unbekannter Befehl: @1"
+
+#: atc.lua
+msgid "ATC command syntax error: I statement not closed: @1"
+msgstr "Zugbeeinflussung: Unvollständiger I-Befehl: @1"
+
+#: atc.lua
+msgid "ATC controller, Command: @1"
+msgstr "Zugbeeinflussungsgleis, Befehl: @1"
+
+#: atc.lua
+msgid "Command"
+msgstr "Befehl"
+
+#: atc.lua
+msgid "Digiline channel"
+msgstr "Digiline-Kanal"
+
+#: atc.lua wagons.lua
+msgid "Save"
+msgstr "Speichern"
+
+#: atc.lua
+msgid "Unconfigured ATC controller"
+msgstr "Nicht konfiguiertes Zugbeeinflussungsgleis"
+
+#: copytool.lua
+msgid "Back of train would end up off track, cancelling."
+msgstr "Der hinterer Teil dez Zuges wäre nicht auf dem Gleis."
+
+#: copytool.lua
+msgid "No such lua entity."
+msgstr ""
+"Sie zeigen nicht auf einem Objekt, das mit diesem Werkzeug kopiert werden "
+"kann."
+
+#: copytool.lua
+msgid "No such train: @1."
+msgstr "Es gibt keinen mit „@1“ identifizierbaren Zug."
+
+#: copytool.lua
+msgid "No such wagon: @1."
+msgstr "Es gibt keinen mit „@1“ identifizierbaren Waggon."
+
+#: copytool.lua
+msgid "The clipboard couldn't access the metadata. Copy failed."
+msgstr ""
+"Wegen des fehlgeschlagenen Zugriffs auf die Metadaten konnte der Zug nicht "
+"kopiert werden."
+
+#: copytool.lua
+msgid "The clipboard couldn't access the metadata. Paste failed."
+msgstr ""
+"Wegen des fehlgeschlagenen Zugriffs auf die Metadaten konnte eine Kopie des "
+"Zuges nicht eingefügt werden."
+
+#: copytool.lua
+msgid "The clipboard is empty."
+msgstr "Das Clipboard ist leer."
+
+#: copytool.lua
+msgid "The track you are trying to place the wagon on is not long enough."
+msgstr "Das Gleis, auf dem der Waggon platziert werden woll, ist zu kurz."
+
+#: copytool.lua
+msgid "Train copied."
+msgstr "Der Zug wurde kopiert."
+
+#: copytool.lua
+msgid ""
+"Train copy/paste tool\n"
+"\n"
+"Left-click: copy train\n"
+"Right-click: paste train"
+msgstr ""
+"Werkzeug zur Erstellung von Zugkopien\n"
+"\n"
+"Linksklick: Zug ins Clipboard kopieren\n"
+"Right-click: Kopierten Zug einfügen"
+
+#: copytool.lua
+msgid "You do not have the @1 privilege."
+msgstr "Ihnen fehlt das „@1“-Privileg."
+
+#: couple.lua
+msgid "<No coupler>"
+msgstr "<Keine Kupplung vorhanden>"
+
+#: couple.lua
+msgid "Buffer and Chain Coupler"
+msgstr "Schraubenkupplung"
+
+#: couple.lua
+msgid "Can not couple: The couplers of the trains do not match (@1 and @2)."
+msgstr "Die Kupplungen der Züge passen nicht zueinander (@1 und @2)."
+
+#: couple.lua
+msgid ""
+"Cannot couple @1 and @2 - train would have length @3 which is above the "
+"limit of @4"
+msgstr ""
+"Züge @1 und @2 können nicht gekuppelt werden - die resultierende Zuglänge @3 "
+"wäre länger als das Maximum von @4"
+
+#: couple.lua
+msgid "Scharfenberg Coupler"
+msgstr "Scharfenbergkupplung"
+
+#: couple.lua
+msgid ""
+"You are not allowed to couple trains without the train_operator privilege."
+msgstr "Sie dürfen ohne das „train_operator“-Privileg keine Züge ankuppeln."
+
+#: craft_items.lua
+msgid "Boiler"
+msgstr "Kessel"
+
+#: craft_items.lua
+msgid "Chimney"
+msgstr "Schornstein"
+
+#: craft_items.lua
+msgid "Driver's cab"
+msgstr "Führerstand"
+
+#: craft_items.lua
+msgid "Wheel"
+msgstr "Rad"
+
+#: init.lua
+msgid "Advtrains Status: no_action @1 slowdown @2 (log @3)"
+msgstr ""
+"Advtrains Status: keine Aktion: @1 Verlangsamungsfaktor: @2 (logarithmisch "
+"@3)"
+
+#: init.lua
+msgid "Advtrains is already running normally!"
+msgstr "Advtrains läuft bereits normal!"
+
+#: init.lua
+msgid ""
+"Crash during advtrains main step - skipping the shutdown save operation to "
+"not save inconsistent data!"
+msgstr ""
+"Advtrains ist während der Ausführung des Main Step abgestürzt - Daten werden "
+"nicht gespeichert um Inkonsistenzen zu verhindern!"
+
+#: init.lua
+msgid ""
+"Data is being saved. While saving, advtrains will remove the players from "
+"trains. Save files will be reloaded afterwards!"
+msgstr ""
+"Daten werden gespeichert. Beim Speichern werden alle Spieler aus Waggons "
+"entfernt. Anschließend werden die Speicherdateien neu geladen!"
+
+#: init.lua
+msgid "Delete all train routes, force them to recalculate"
+msgstr "Erzwingt die Neuberechnung der Bewegungspfade aller Züge"
+
+#: init.lua
+msgid ""
+"Detach all players, especially the offline ones, from all trains. Use only "
+"when no one serious is on a train."
+msgstr ""
+"Bewirkt, dass alle Spieler (insbesondere Offline-Spieler) aus Waggons "
+"entfernt werden. Nur benutzen, wenn niemand ernsthaft in einem Zug sitzt."
+
+#: init.lua
+msgid "Disable the advtrains globalstep temporarily"
+msgstr "Advtrains-Schrittverarbeitung temporär deaktivieren"
+
+#: init.lua
+msgid "Disabled advtrains successfully"
+msgstr "Advtrains erfolgreich deaktiviert"
+
+#: init.lua
+msgid "Instructed to save() but load() was never called!"
+msgstr "Speichern angefordert, aber Speicherdateien wurden nie geladen!"
+
+#: init.lua
+msgid "Print advtrains status info"
+msgstr "Advtrains-Statusinformationen ausgeben"
+
+#: init.lua
+msgid "Re-enabling advtrains globalstep..."
+msgstr "Advtrains-Schrittverarbeitung wird wieder aktiviert..."
+
+#: init.lua
+msgid "Reload successful!"
+msgstr "Neu Laden Erfolgreich!"
+
+#: init.lua
+msgid "Removing unused wagon"
+msgstr "Ungenutzer Waggon wird entfernt"
+
+#: init.lua
+msgid "Restoring saved state in 1 second..."
+msgstr "Speicherstand wird in 1 Sekunde wiederhergestellt..."
+
+#: init.lua
+msgid "Returns the position of the train with the given id"
+msgstr "Gibt die Position des Zugs mit der gegebenen ID aus"
+
+#: init.lua
+msgid "Saving failed: @1"
+msgstr "Speichern ist fehlgeschlagen: @1"
+
+#: init.lua
+msgid "Successfully invalidated train routes"
+msgstr "Bewegungspfade der Züge erfolgreich invalidiert"
+
+#: init.lua
+msgid "Teleporting to train @1"
+msgstr "Teleportiere zu Zug @1"
+
+#: init.lua
+msgid "Teleports you to the position of the train with the given id"
+msgstr "Teleportiere dich zu dem Zug mit der gegebenen ID"
+
+#: init.lua
+msgid ""
+"The advtrains globalstep has been disabled. Trains are not moving, and no "
+"data is saved! Run '/at_disable_step no' to enable again!"
+msgstr ""
+"Advtrains-Schrittverarbeitung ist deaktiviert. Züge bewegen sich nicht und "
+"Änderungen werden nicht gespeichert. Führe '/at_disable_step no' aus um sie "
+"wieder zu aktivieren!"
+
+#: init.lua
+msgid "Train @1 does not exist or is invalid"
+msgstr "Zug @1 existiert nicht oder ist ungültig"
+
+#: init.lua
+msgid ""
+"Train @1 had no wagons left because of some bug. It is being deleted. Wave "
+"it goodbye!"
+msgstr ""
+"Zug @1 hat keine Wagen mehr und sollte nicht mehr existieren. Er wird "
+"gelöscht. Auf Wiedersehen!"
+
+#: init.lua
+msgid "Train @1 is at @2"
+msgstr "Zug @1 ist bei @2"
+
+#: init.lua
+msgid "from wagon_save table."
+msgstr "aus der wagon_save table"
+
+#: misc_nodes.lua
+msgid "@1 Platform (45 degree)"
+msgstr "Hoher @1-Bahnsteig (45°)"
+
+#: misc_nodes.lua
+msgid "@1 Platform (high)"
+msgstr "Hoher @1-Bahnsteig"
+
+#: misc_nodes.lua
+msgid "@1 Platform (low)"
+msgstr "Niedriger @1-Bahnsteig"
+
+#: misc_nodes.lua
+msgid "@1 Platform (low, 45 degree)"
+msgstr "Niedriger @1-Bahnsteig (45°)"
+
+#: protection.lua
+msgid "Can operate turnouts and signals in unprotected areas"
+msgstr "Darf Weichen und Signale in ungeschütztem Gebiet stellen"
+
+#: protection.lua
+msgid "Can place and dig tracks in unprotected areas"
+msgstr "Darf Gleise in ungeschütztem Gebiet verlegen und entfernen"
+
+#: protection.lua
+msgid ""
+"Can place, remove and operate any train, regardless of owner, whitelist, or "
+"protection"
+msgstr "Darf, unabhängig von Besitzer oder Schutz, sämtliche Züge steuern"
+
+#: protection.lua
+msgid "Can place, remove and operate trains"
+msgstr "Darf Züge platzieren, entfernen und steuern"
+
+#: protection.lua
+msgid "You are not allowed to build near tracks at this protected position."
+msgstr "Sie dürfen an geschützten Stellen nicht in der Nähe von Gleisen bauen."
+
+#: protection.lua
+msgid ""
+"You are not allowed to build near tracks without the track_builder privilege."
+msgstr ""
+"Sie dürfen ohne das „track_builder“-Privileg nicht in der Nähe von Gleisen "
+"bauen."
+
+#: protection.lua
+msgid "You are not allowed to build tracks at this protected position."
+msgstr "Sie dürfen an geschützten Stellen kein Gleis bauen."
+
+#: protection.lua
+msgid ""
+"You are not allowed to build tracks without the track_builder privilege."
+msgstr "Sie dürfen ohne das „track_builder“-Privileg kein Gleis bauen."
+
+#: protection.lua
+msgid ""
+"You are not allowed to operate turnouts and signals without the "
+"railway_operator privilege."
+msgstr ""
+"Sie dürfen ohne das „railway_operator“-Privileg keine Bahnanlage operieren."
+
+#: signals.lua
+msgid "Andrew's Cross"
+msgstr "Andreaskreuz"
+
+#: signals.lua
+msgid "Lampless Signal (deprecated!)"
+msgstr "Mechanisches Signal (veraltet!)"
+
+#: signals.lua
+msgid "Signal (deprecated!)"
+msgstr "Signal (veraltet!)"
+
+#: signals.lua
+msgid "Wallmounted Signal (left) (deprecated!)"
+msgstr "An der linken Seite montiertes Signal (veraltet!)"
+
+#: signals.lua
+msgid "Wallmounted Signal (right) (deprecated!)"
+msgstr "An der rechten Seite montiertes Signal (veraltet!)"
+
+#: signals.lua
+msgid "Wallmounted Signal (top) (deprecated!)"
+msgstr "An der Decke montiertes Signal (veraltet!)"
+
+#: track_reg_helper.lua
+msgid "@1 Slope"
+msgstr "@1 Steigung"
+
+#: track_reg_helper.lua
+#, fuzzy
+msgid "Can't place: Not enough slope items left (@1 required)"
+msgstr ""
+"Es kann nicht platziert werden: Sie haben nicht genug Steigungsblöcke, es "
+"werden insgesamt @1 benötigt."
+
+#: track_reg_helper.lua
+#, fuzzy
+msgid "Can't place: There's no slope of length @1"
+msgstr ""
+"Es kann nicht platziert werden: die Steigung der Länge @1 ist nicht "
+"definiert."
+
+#: track_reg_helper.lua
+#, fuzzy
+msgid "Can't place: no supporting node at upper end."
+msgstr ""
+"Es kann nicht platziert werden: es gibt keinen unterstützenden Block am Ende "
+"der Steigung."
+
+#: track_reg_helper.lua
+#, fuzzy
+msgid "Can't place: not pointing at node"
+msgstr "Es kann nicht platziert werden: Sie zeigen nicht auf einem Block."
+
+#: track_reg_helper.lua
+#, fuzzy
+msgid "Can't place: space occupied!"
+msgstr "Es kann nicht platziert werden: Diese Position ist besetzt."
+
+#: track_reg_helper.lua tracks.lua
+#, fuzzy
+msgid "This track can not be removed!"
+msgstr "Dieses Gleis kann nicht entfernt werden."
+
+#: trackplacer.lua
+msgid ""
+"Left-click: change rail type (straight/curve/switch)\n"
+"Right-click: rotate object"
+msgstr ""
+"Linksklick: Gleistyp ändern\n"
+"Rechtsklick: Objekt drehen"
+
+#: trackplacer.lua
+#, fuzzy
+msgid "This node can't be changed using the trackworker!"
+msgstr "Dieser Block kann nicht mit dem Gleiswerkzeug bearbeitet werden."
+
+#: trackplacer.lua
+#, fuzzy
+msgid "This node can't be rotated using the trackworker!"
+msgstr "Dieser Block kann nicht mit dem Gleiswerkzeug gedreht werden."
+
+#: trackplacer.lua
+#, fuzzy
+msgid "This track can not be rotated!"
+msgstr "Dieses Gleis kann nicht gedreht werden."
+
+#: trackplacer.lua
+msgid "Track Worker Tool"
+msgstr "Gleiswerkzeug"
+
+#: tracks.lua
+msgid "Position is occupied by a train."
+msgstr "Ein Zug steht an dieser Position."
+
+#: tracks.lua
+msgid "There's a Signal Influence Point here."
+msgstr "Hier ist ein Signal-Beeinflussungspunkt."
+
+#: tracks.lua
+msgid "There's a Track Circuit Break here."
+msgstr "Hier ist eine Gleisabschnittsgrenze (TCB)."
+
+#: trainhud.lua
+msgid "OVERRUN RED SIGNAL! Examine situation and reverse train to move again."
+msgstr ""
+"ROTES SIGNAL ÜBERFAHREN! Situation überprüfen und Fahrtrichtung wechseln, um "
+"Bewegungssperre aufzuheben."
+
+#: wagonprop_tool.lua
+msgid "Insufficient privileges to use this!"
+msgstr "Unzureichende Privilegien, um dies zu benutzen!"
+
+#: wagonprop_tool.lua
+msgid "Punch a wagon to view and edit the Wagon Properties"
+msgstr "Auf Waggon anwenden um Waggon-Einstellungen aufzurufen"
+
+#: wagonprop_tool.lua
+msgid "Wagon Properties Tool"
+msgstr "Waggon-Einstellungstool"
+
+#: wagons.lua
+msgid " units"
+msgstr " Einheiten"
+
+#: wagons.lua
+msgid "!!! Train off track !!!"
+msgstr "!!! Abseits vom Gleis !!!"
+
+#: wagons.lua
+msgid "(Doors closed)"
+msgstr "(Türen geschlossen)"
+
+#: wagons.lua
+msgid "Allow these players to access your wagon:"
+msgstr "Diese Spieler dürfen auf den Waggon zugreifen:"
+
+#: wagons.lua
+msgid "Clear 'Disable ARS' flag"
+msgstr "ARS-Sperre aufheben"
+
+#: wagons.lua
+msgid "Current FC: "
+msgstr "Aktueller FC:"
+
+#: wagons.lua
+msgid ""
+"Destroying wagon with inventory, but inventory is not found? Shouldn't "
+"happen!"
+msgstr ""
+"Waggon mit Inventar zerstört, aber Inventar nicht gefunden? Sollte nicht "
+"passieren!"
+
+#: wagons.lua
+msgid "Doors are closed! (Try holding sneak key!)"
+msgstr "Die Türen sind geschlossen! (Probiere Schleichen-Taste!)"
+
+#: wagons.lua
+msgid ""
+"Doors are closed. Use Sneak+rightclick to ignore the closed doors and get "
+"off."
+msgstr ""
+"Die Türen sind geschlossen. Nutzen Sie Schleichen+Rechtsklick, um trotz "
+"geschlossener Türen auszusteigen."
+
+#: wagons.lua
+msgid "Freight Code:"
+msgstr "Frachtcode:"
+
+#: wagons.lua
+msgid "Get off"
+msgstr "Aussteigen"
+
+#: wagons.lua
+msgid "Get off (forced)"
+msgstr "Ausstieg zwingen"
+
+#: wagons.lua
+msgid "Line"
+msgstr "Linie"
+
+#: wagons.lua
+msgid "Liquid: "
+msgstr "Flüssigkeit:"
+
+#: wagons.lua
+msgid "Liquid: empty"
+msgstr "Flüssigkeit: leer"
+
+#: wagons.lua
+msgid "Missing train_operator privilege"
+msgstr "Fehlendes train_operator Privileg"
+
+#: wagons.lua
+msgid "Next FC:"
+msgstr "Nächster FC:"
+
+#: wagons.lua
+msgid "Not a valid wagon id."
+msgstr "Keine gültige Waggon-ID"
+
+#: wagons.lua
+msgid "Not allowed to do this."
+msgstr "Sie dürfen dies nicht tun."
+
+#: wagons.lua
+msgid "Onboard Computer"
+msgstr "Bordcomputer"
+
+#: wagons.lua
+msgid "Please specify a player name to transfer ownership to."
+msgstr ""
+"Geben Sie einen Spielernamen an, an den der Besitz übertragen werden soll."
+
+#: wagons.lua
+msgid "Prev FC"
+msgstr "Vorheriger FC"
+
+#: wagons.lua
+msgid "Remote Routesetting"
+msgstr "Fahrstraße entfernt stellen"
+
+#: wagons.lua
+msgid "Routingcode"
+msgstr "Routingcode"
+
+#: wagons.lua
+msgid "Save wagon properties"
+msgstr "Waggon-Einstellungen speichern"
+
+#: wagons.lua
+msgid "Select seat:"
+msgstr "Wählen Sie einen Sitzplatz aus:"
+
+#: wagons.lua
+msgid "Show Inventory"
+msgstr "Inventar Zeigen"
+
+#: wagons.lua
+msgid "Text displayed inside train"
+msgstr "Innere Anzeige"
+
+#: wagons.lua
+msgid "Text displayed outside on train"
+msgstr "Äußere Anzeige"
+
+#: wagons.lua
+msgid "That player does not exist!"
+msgstr "Dieser Spieler existiert nicht!"
+
+#: wagons.lua
+msgid "That wagon does not exist!"
+msgstr "Dieser Wagen existiert nicht!"
+
+#: wagons.lua
+msgid "The track you are trying to place the wagon on is not long enough!"
+msgstr "Das Gleis, auf dem der Waggon platziert werden woll, ist zu kurz!"
+
+#: wagons.lua
+msgid "The wagon's inventory is not empty."
+msgstr "Das Inventar dieses Waggons ist nicht leer."
+
+#: wagons.lua
+msgid "This Wagon ID"
+msgstr "Dieser Wagen ID"
+
+#: wagons.lua
+msgid "This wagon has no seats."
+msgstr "In diesem Waggon ist kein Sitzplatz vorhanden."
+
+#: wagons.lua
+msgid "This wagon is full."
+msgstr "Der Waggon ist voll."
+
+#: wagons.lua
+msgid "This wagon is owned by @1, you can't destroy it."
+msgstr "Dieser Waggon gehört @1, Sie dürfen ihn nicht abbauen."
+
+#: wagons.lua
+msgid "Train ID"
+msgstr "Zug-ID"
+
+#: wagons.lua
+msgid "Train overview / coupling control is only shown when the train stands."
+msgstr "Zugübersicht / Kupplungssteuerung nur im Stillstand verfügbar."
+
+#: wagons.lua
+msgid "Train overview /coupling control:"
+msgstr "Zugübersicht / Kupplungssteuerung:"
+
+#: wagons.lua
+msgid "Uninitialized, removing"
+msgstr "Nicht initialisiert, entferne"
+
+#: wagons.lua
+msgid "Wagon @1 ownership changed from @2 to @3"
+msgstr "Besitzer von Waggon @1 geändert von @2 auf @3"
+
+#: wagons.lua
+msgid "Wagon needs to be decoupled from other wagons in order to destroy it."
+msgstr "Der Waggon muss abgekoppelt sein, damit Sie ihn abbauen können."
+
+#: wagons.lua
+msgid "Wagon placeholder"
+msgstr "Waggon-Platzhalter"
+
+#: wagons.lua
+msgid "Wagon properties"
+msgstr "Waggon-Einstellungen"
+
+#: wagons.lua
+msgid "Wagon road number:"
+msgstr "Wagennummer:"
+
+#: wagons.lua
+msgid ""
+"Warning: If you destroy this wagon, you only get some steel back! If you are "
+"sure, hold Sneak and left-click the wagon."
+msgstr ""
+"Warnung: Durch den Abbau des Waggons erhalten Sie nur etwas Stahl zurück. "
+"Nutzen Sie Schleichen+Linksklick, um dem Waggon abzubauen."
+
+#: wagons.lua
+msgid "You are not allowed to access the driver stand."
+msgstr "Sie haben keinen Zugang zum Führerstand."
+
+#: wagons.lua
+msgid "You can't get on this wagon."
+msgstr "Sie können nicht in diesen Waggon einsteigen."
+
+#: wagons.lua
+#, fuzzy
+msgid "You don't have the train_operator privilege."
+msgstr "Ihnen fehlt das „@1“-Privileg."
+
+#: wagons.lua
+msgid "You have been given ownership of wagon @1"
+msgstr "Sie sind nun der Besitzer von Waggon @1"
+
+#~ msgid "3-way turnout"
+#~ msgstr "Dreiwegweiche"
+
+#~ msgid "90+Angle Diamond Crossing Track"
+#~ msgstr "Kreuzung mit einem achsenparallelen Gleis"
+
+#~ msgid "ATC controller"
+#~ msgstr "Zugbeeinflussungsgleis"
+
+#~ msgid ""
+#~ "ATC controller, mode @1\n"
+#~ "Channel: @2"
+#~ msgstr ""
+#~ "Zugbeeinflussungsgleis in Betriebsart „@1“\n"
+#~ "Kanal: @2"
+
+#~ msgid "Access to @1"
+#~ msgstr "Zugang zu @1"
+
+#~ msgid "Big Industrial Train Engine"
+#~ msgstr "Große Industrielle Lokomotive"
+
+#~ msgid "Box Wagon"
+#~ msgstr "Güterwaggon"
+
+#~ msgid "Bumper"
+#~ msgstr "Prellbock"
+
+#~ msgid ""
+#~ "Can place and configure LuaATC components, including execute potentially "
+#~ "harmful Lua code"
+#~ msgstr ""
+#~ "Kann LuaATC-Bauteile platzieren und konfigurieren (auch evtl. schädliche "
+#~ "Programme ausführen)"
+
+#~ msgid "Can't get on: wagon full or doors closed!"
+#~ msgstr ""
+#~ "Sie können nicht einsteigen: der Waggon ist voll oder die Türen sind "
+#~ "geschlossen."
+
+#~ msgid "Can't place: protected position!"
+#~ msgstr "Es kann nicht platziert werden: diese Position ist geschützt."
+
+#~ msgid "Command (on)"
+#~ msgstr "Befehl (wenn aktiviert)"
+
+#~ msgid "Default Seat"
+#~ msgstr "Standardsitzplatz"
+
+#~ msgid "Default Seat (driver stand)"
+#~ msgstr "Standardsitzplatz (Führerstand)"
+
+#~ msgid "Dep. Speed"
+#~ msgstr "Zielgeschwindigkeit bei Abfahrt"
+
+#~ msgid "Deprecated Track"
+#~ msgstr "ausrangiertes Gleis, nicht verwenden."
+
+#~ msgid "Detailed Steam Engine"
+#~ msgstr "Detaillierte Dampflokomotive"
+
+#~ msgid "Detector Rail"
+#~ msgstr "Detektorgleis"
+
+#~ msgid "Diagonal Diamond Crossing Track"
+#~ msgstr "Diagonale Gleiskreuzung"
+
+#~ msgid "Door Delay"
+#~ msgstr "Zeit für die Türschließung"
+
+#~ msgid "Door Side"
+#~ msgstr "Türseite"
+
+#, fuzzy
+#~ msgid "Driver Stand"
+#~ msgstr "Führerstand"
+
+#~ msgid "Driver Stand (left)"
+#~ msgstr "Führerstand Links"
+
+#~ msgid "Driver Stand (right)"
+#~ msgstr "Führerstand Rechts"
+
+#~ msgid "Driver stand"
+#~ msgstr "Führerstand"
+
+#~ msgid "Industrial Train Engine"
+#~ msgstr "Industrielle Lokomotive"
+
+#~ msgid "Industrial tank wagon"
+#~ msgstr "Tankwaggon"
+
+#~ msgid "Industrial wood wagon"
+#~ msgstr "Holztransportwaggon"
+
+#~ msgid "Japanese Train Engine"
+#~ msgstr "Japanische Personenzug-Lokomotive"
+
+#~ msgid "Japanese Train Inter-Wagon Connection"
+#~ msgstr "Waggonzwischenverbindung Japanischer Personenzüge"
+
+#~ msgid "Japanese Train Wagon"
+#~ msgstr "Japanischer Personenzug-Passagierwaggon"
+
+#, fuzzy
+#~ msgid "Japanese signal pole"
+#~ msgstr "Japanischer Personenzug-Passagierwaggon"
+
+#~ msgid "Kick out passengers"
+#~ msgstr "Fahrgäste zum Ausstieg zwingen"
+
+#~ msgid "Loading Track"
+#~ msgstr "Beladungsgleis"
+
+#~ msgid "Lock couples"
+#~ msgstr "Kupplungen sperren"
+
+#~ msgid "LuaATC component with error: @1"
+#~ msgstr "LuaATC-Bauteil mit Fehlermeldung: @1"
+
+#~ msgid "Passenger Wagon"
+#~ msgstr "Passagierwaggon"
+
+#, fuzzy
+#~ msgid "Passenger area"
+#~ msgstr "Passagierwaggon"
+
+#~ msgid ""
+#~ "Passive Component Naming Tool\n"
+#~ "\n"
+#~ "Right-click to name a passive component."
+#~ msgstr ""
+#~ "PC-Benennungswerkzeug\n"
+#~ "\n"
+#~ "Rechtsklick zur Benennung der passiven Komponente."
+
+#~ msgid "Perpendicular Diamond Crossing Track"
+#~ msgstr "Kreuzung mit zueinander orthogonalen Gleisen"
+
+#~ msgid "Point Speed Restriction Track"
+#~ msgstr "Geschwindigkeitskontrollgleis"
+
+#~ msgid "Point speed restriction: @1"
+#~ msgstr "Geschwindigkeitskontrolle: @1"
+
+#~ msgid "Reverse train"
+#~ msgstr "Zug Umkehren"
+
+#~ msgid "Signal"
+#~ msgstr "Lichtsignal"
+
+#~ msgid "Speed:"
+#~ msgstr "Geschw.:"
+
+#~ msgid "Station Code"
+#~ msgstr "Kennzeichen der Haltestelle"
+
+#~ msgid "Station Name"
+#~ msgstr "Name der Haltestelle"
+
+#~ msgid "Station code \"@1\" already exists and is owned by @2."
+#~ msgstr ""
+#~ "Die Haltestelle mit dem Kennzeichen „@1“ ist bereits vorhanden und wird "
+#~ "von @2 verwaltet."
+
+#~ msgid "Station/Stop Track"
+#~ msgstr "Gleis zur Kennzeichnung einer Haltestelle"
+
+#~ msgid "Steam Engine"
+#~ msgstr "Dampflokomotive"
+
+#~ msgid "Stop Time"
+#~ msgstr "Wartezeit"
+
+#~ msgid "Subway Passenger Wagon"
+#~ msgstr "U-Bahn-Waggon"
+
+#~ msgid "Target:"
+#~ msgstr "Zielges.:"
+
+#~ msgid "This position is protected!"
+#~ msgstr "Diese Position ist geschützt!"
+
+#~ msgid "This station is owned by @1. You are not allowed to edit its name."
+#~ msgstr ""
+#~ "Diese Haltestelle wird von @1 verwaltet. Sie dürfen sie nicht umbenennen."
+
+#~ msgid "This track can not be changed."
+#~ msgstr "Dieses Gleis kann nicht geändert werden."
+
+#~ msgid "Track"
+#~ msgstr "Gleis"
+
+#, fuzzy
+#~ msgid "Train "
+#~ msgstr "Der Zug wurde Kopiert."
+
+#~ msgid "Unconfigured LuaATC component"
+#~ msgstr "Nicht konfiguierter LuaATC-Bauteil"
+
+#~ msgid "Unloading Track"
+#~ msgstr "Abladungsgleis"
+
+#~ msgid "Use Sneak+rightclick to bypass closed doors!"
+#~ msgstr ""
+#~ "Nutzen Sie Schleichen+Rechtsklick, um trotz geschlossener Türen "
+#~ "einzusteigen."
+
+#~ msgid "Y-turnout"
+#~ msgstr "Y-Weiche"
+
+#~ msgid ""
+#~ "You are not allowed to configure this LuaATC component without the @1 "
+#~ "privilege."
+#~ msgstr ""
+#~ "Sie dürfen ohne das „@1“-Privileg diesen LuaATC-Bauteil nicht "
+#~ "konfigurieren."
+
+#~ msgid ""
+#~ "You are not allowed to configure this track without the @1 privilege."
+#~ msgstr "Sie dürfen ohne das „@1“-Privileg dieses Gleis nicht konfigurieren."
+
+#~ msgid "You are not allowed to configure this track."
+#~ msgstr "Sie dürfen dieses Gleis nicht konfigurieren."
+
+#, fuzzy
+#~ msgid "You are not allowed to modify this protected track."
+#~ msgstr "Sie dürfen an geschützten Stellen kein Gleis bauen."
+
+#~ msgid ""
+#~ "You are not allowed to name LuaATC passive components without the @1 "
+#~ "privilege."
+#~ msgstr "Sie dürfen ohne das „@1“ keinen passiven LuaATC-Bauteil benennen."
+
+#~ msgid ""
+#~ "You need to own at least one neighboring wagon to destroy this couple."
+#~ msgstr ""
+#~ "Sie müssen Besitzer eines angrenzenden Waggons sein, um hier abzukuppeln."
diff --git a/advtrains/locale/advtrains.fr.po b/advtrains/locale/advtrains.fr.po
new file mode 100644
index 0000000..a6bac8a
--- /dev/null
+++ b/advtrains/locale/advtrains.fr.po
@@ -0,0 +1,1020 @@
+msgid ""
+msgstr ""
+"Project-Id-Version: advtrains\n"
+"Report-Msgid-Bugs-To: advtrains-discuss@lists.sr.ht\n"
+"POT-Creation-Date: 2026-05-17 09:18+0800\n"
+"PO-Revision-Date: 2026-05-17 09:23+0800\n"
+"Last-Translator: Tanavit <tanavit@posto.ovh>\n"
+"Language-Team: French\n"
+"Language: fr\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"X-Generator: Poedit 3.8\n"
+
+#: atc.lua
+msgid "ATC Kick command warning: doors are closed."
+msgstr "Avertissement commande ATC Éjecter : portes closes."
+
+#: atc.lua
+msgid "ATC Kick command warning: train moving."
+msgstr "Avertissement commande ATC Éjecter : train en mouvement."
+
+#: atc.lua
+msgid "ATC Reverse command warning: didn't reverse train, train moving."
+msgstr ""
+"Attention : Commande ATC de renversement impossible car le train se déplace."
+
+#: atc.lua
+msgid "ATC command parse error: Unknown command: @1"
+msgstr "Erreur d'analyse de commande ATC : Commande inconnue : @1"
+
+#: atc.lua
+msgid "ATC command syntax error: I statement not closed: @1"
+msgstr "Erreur de syntaxe de commande ATC : instruction \"I\" incomplète : @1"
+
+#: atc.lua
+#, fuzzy
+msgid "ATC controller, Command: @1"
+msgstr ""
+"Controlleur ATC, mode @1\n"
+"Commande : @2"
+
+#: atc.lua
+msgid "Command"
+msgstr "Commande"
+
+#: atc.lua
+msgid "Digiline channel"
+msgstr "Canal Digiline"
+
+#: atc.lua wagons.lua
+msgid "Save"
+msgstr "Sauvegarder"
+
+#: atc.lua
+msgid "Unconfigured ATC controller"
+msgstr "Controlleur ATC, non-configuré"
+
+#: copytool.lua
+msgid "Back of train would end up off track, cancelling."
+msgstr "La fin du train serait hors voie : annulation."
+
+#: copytool.lua
+msgid "No such lua entity."
+msgstr "Pas de telle entité lua."
+
+#: copytool.lua
+msgid "No such train: @1."
+msgstr "Pas de tel train : @1."
+
+#: copytool.lua
+msgid "No such wagon: @1."
+msgstr "Pas de tel wagon : @1."
+
+#: copytool.lua
+msgid "The clipboard couldn't access the metadata. Copy failed."
+msgstr "Le presse-papier ne peut accéder aux métadonnées. Échec de la copie."
+
+#: copytool.lua
+msgid "The clipboard couldn't access the metadata. Paste failed."
+msgstr "Le presse-papier ne peut accéder aux métadonnées. Échec du collage."
+
+#: copytool.lua
+msgid "The clipboard is empty."
+msgstr "Le presse-papier est vide."
+
+#: copytool.lua
+msgid "The track you are trying to place the wagon on is not long enough."
+msgstr "La voie sur laquelle vous tentez de placer le wagon est trop courte."
+
+#: copytool.lua
+msgid "Train copied."
+msgstr "Train copié."
+
+#: copytool.lua
+msgid ""
+"Train copy/paste tool\n"
+"\n"
+"Left-click: copy train\n"
+"Right-click: paste train"
+msgstr ""
+"Outil de copie/collage de train\n"
+"\n"
+"Clic-Gauche : copie\n"
+"\n"
+"Clic-Droit : collage"
+
+#: copytool.lua
+msgid "You do not have the @1 privilege."
+msgstr "Vous ne possédez pas le privilège \"@1\"."
+
+#: couple.lua
+msgid "<No coupler>"
+msgstr "<Pas de coupleur>"
+
+#: couple.lua
+msgid "Buffer and Chain Coupler"
+msgstr "Attelage à tampon et vis"
+
+#: couple.lua
+msgid "Can not couple: The couplers of the trains do not match (@1 and @2)."
+msgstr ""
+"Accouplement impossible: les attelages des trains ne concordent pas (@1 et "
+"@2)."
+
+#: couple.lua
+msgid ""
+"Cannot couple @1 and @2 - train would have length @3 which is above the "
+"limit of @4"
+msgstr ""
+
+#: couple.lua
+msgid "Scharfenberg Coupler"
+msgstr "Attelage Scharfenberg"
+
+#: couple.lua
+msgid ""
+"You are not allowed to couple trains without the train_operator privilege."
+msgstr ""
+"Vous n'êtes pas autorisé à coupler des trains sans le privilège "
+"\"train_operator\"."
+
+#: craft_items.lua
+msgid "Boiler"
+msgstr "Chaudière à vapeur"
+
+#: craft_items.lua
+msgid "Chimney"
+msgstr "Cheminée"
+
+#: craft_items.lua
+msgid "Driver's cab"
+msgstr "Cabine de pilotage"
+
+#: craft_items.lua
+msgid "Wheel"
+msgstr "Roue"
+
+#: init.lua
+#, fuzzy
+msgid "Advtrains Status: no_action @1 slowdown @2 (log @3)"
+msgstr "État d'advtrains : aucune action"
+
+#: init.lua
+msgid "Advtrains is already running normally!"
+msgstr "Advtrains fonctionne déjà correctement !"
+
+#: init.lua
+msgid ""
+"Crash during advtrains main step - skipping the shutdown save operation to "
+"not save inconsistent data!"
+msgstr ""
+"Crash durant le pas principal d'advtrains - saut de l'opération de "
+"sauvegarde de terminaison pour éviter l'enregistrement de données "
+"corrompues !"
+
+#: init.lua
+msgid ""
+"Data is being saved. While saving, advtrains will remove the players from "
+"trains. Save files will be reloaded afterwards!"
+msgstr ""
+"Données en cours de sauvegarde. Durant cette phase, advtrains débarquera les "
+"joueurs des trains. Les fichiers de sauvegarde seront ultérieurement "
+"rechargés !"
+
+# Routage est il le bon terme ?
+#: init.lua
+msgid "Delete all train routes, force them to recalculate"
+msgstr "Suppression et recalcul de tous les routages"
+
+#: init.lua
+msgid ""
+"Detach all players, especially the offline ones, from all trains. Use only "
+"when no one serious is on a train."
+msgstr ""
+"Débarque tous les joueurs, en particulier ceux déconnectés, de tous les "
+"trains. À n'utiliser que quand aucun joueur sérieux n'a embarqué."
+
+#: init.lua
+msgid "Disable the advtrains globalstep temporarily"
+msgstr "Désactive temporairement le pas global d'advtrains"
+
+#: init.lua
+msgid "Disabled advtrains successfully"
+msgstr "Succès de la désactivation d'advtrains"
+
+#: init.lua
+msgid "Instructed to save() but load() was never called!"
+msgstr "Appel de save() requis sans appel préalable de load() !"
+
+#: init.lua
+msgid "Print advtrains status info"
+msgstr "Affiche les informations d'état d'advtrains"
+
+#: init.lua
+msgid "Re-enabling advtrains globalstep..."
+msgstr "Réacivation du pas global d'advtrains..."
+
+#: init.lua
+msgid "Reload successful!"
+msgstr "Succès du rechargement !"
+
+#: init.lua
+msgid "Removing unused wagon"
+msgstr "Suppression d'un wagon inutilisé"
+
+#: init.lua
+msgid "Restoring saved state in 1 second..."
+msgstr "Restauration du l'état sauvegardé dans une seconde..."
+
+#: init.lua
+msgid "Returns the position of the train with the given id"
+msgstr "Affiche la position du train identifié"
+
+#: init.lua
+#, fuzzy
+msgid "Saving failed: @1"
+msgstr "Échec de sauvegarde : "
+
+# Routage est il le bon terme ?
+#: init.lua
+msgid "Successfully invalidated train routes"
+msgstr "Succès d'invalidation des routages des trains"
+
+#: init.lua
+#, fuzzy
+msgid "Teleporting to train @1"
+msgstr "Téléportation au train "
+
+#: init.lua
+msgid "Teleports you to the position of the train with the given id"
+msgstr "Vous téléporte à la position du train identifié"
+
+#: init.lua
+msgid ""
+"The advtrains globalstep has been disabled. Trains are not moving, and no "
+"data is saved! Run '/at_disable_step no' to enable again!"
+msgstr ""
+"Le pas global d'advtrains est désactivé. Les trains sont immobiles et aucune "
+"donnée n'est sauvegardée. Exécutez '/at_disable_step no ' pour le réactiver !"
+
+#: init.lua
+#, fuzzy
+msgid "Train @1 does not exist or is invalid"
+msgstr " n'existe pas ou est invalide"
+
+#: init.lua
+#, fuzzy
+msgid ""
+"Train @1 had no wagons left because of some bug. It is being deleted. Wave "
+"it goodbye!"
+msgstr ""
+"n'a plus de wagon à cause d'un bug quelconque. Il est détruit. Faites lui "
+"coucou !"
+
+#: init.lua
+msgid "Train @1 is at @2"
+msgstr ""
+
+#: init.lua
+msgid "from wagon_save table."
+msgstr "de la table wagon_save."
+
+#: misc_nodes.lua
+msgid "@1 Platform (45 degree)"
+msgstr "Quai @1 (haut, 45°)"
+
+#: misc_nodes.lua
+msgid "@1 Platform (high)"
+msgstr "Quai @1 (haut)"
+
+#: misc_nodes.lua
+msgid "@1 Platform (low)"
+msgstr "Quai @1 (bas)"
+
+#: misc_nodes.lua
+msgid "@1 Platform (low, 45 degree)"
+msgstr "Quai @1 (bas, 45°)"
+
+#: protection.lua
+msgid "Can operate turnouts and signals in unprotected areas"
+msgstr ""
+"Possibilité d'opérer des embranchements et signaux dans les zones non "
+"protégées"
+
+#: protection.lua
+msgid "Can place and dig tracks in unprotected areas"
+msgstr "Possibilité de poser ou retirer des voies dans les zones non protégées"
+
+#: protection.lua
+msgid ""
+"Can place, remove and operate any train, regardless of owner, whitelist, or "
+"protection"
+msgstr ""
+"Possibilité de poser, retirer ou opérer un quelconque train, indépendamment "
+"du propriétaire, de la liste blanche ou de protection"
+
+#: protection.lua
+msgid "Can place, remove and operate trains"
+msgstr "Possibilité de poser, retirer ou opérer les trains"
+
+#: protection.lua
+msgid "You are not allowed to build near tracks at this protected position."
+msgstr ""
+"Vous ne pouvez pas construire à proximité d'une voie à cet emplacement "
+"protégé."
+
+#: protection.lua
+msgid ""
+"You are not allowed to build near tracks without the track_builder privilege."
+msgstr ""
+"Vous ne pouvez pas construire à proximité d'une voie sans le privilège "
+"\"track_builder\" (?)"
+
+#: protection.lua
+msgid "You are not allowed to build tracks at this protected position."
+msgstr "Vous ne pouvez pas construire une voie à cet emplacement protégé."
+
+#: protection.lua
+msgid ""
+"You are not allowed to build tracks without the track_builder privilege."
+msgstr ""
+"Vous ne pouvez pas construire une voie sans le privilège \"track_builder\"."
+
+#: protection.lua
+msgid ""
+"You are not allowed to operate turnouts and signals without the "
+"railway_operator privilege."
+msgstr ""
+"Vous ne pouvez pas actionner les aiguillages ou les signaux (privilège "
+"\"railway_operator\" manquant)"
+
+#: signals.lua
+msgid "Andrew's Cross"
+msgstr "Croix de Saint André"
+
+#: signals.lua
+#, fuzzy
+msgid "Lampless Signal (deprecated!)"
+msgstr "Sémaphore"
+
+#: signals.lua
+msgid "Signal (deprecated!)"
+msgstr ""
+
+#: signals.lua
+#, fuzzy
+msgid "Wallmounted Signal (left) (deprecated!)"
+msgstr "Signal mural (gauche)"
+
+#: signals.lua
+#, fuzzy
+msgid "Wallmounted Signal (right) (deprecated!)"
+msgstr "Signal mural (droit)"
+
+#: signals.lua
+#, fuzzy
+msgid "Wallmounted Signal (top) (deprecated!)"
+msgstr "Signal mural (plafond)"
+
+#: track_reg_helper.lua
+msgid "@1 Slope"
+msgstr "Pente @1"
+
+#: track_reg_helper.lua
+msgid "Can't place: Not enough slope items left (@1 required)"
+msgstr ""
+"Placement impossible : quantité insuffisante de voie pentue (@1 manquant)"
+
+#: track_reg_helper.lua
+msgid "Can't place: There's no slope of length @1"
+msgstr "Placement impossible : il n'y a pas de voie pentue de longueur @1"
+
+#: track_reg_helper.lua
+msgid "Can't place: no supporting node at upper end."
+msgstr "Placement impossible : pas de nœud d'appui à l'extrémité supérieure."
+
+#: track_reg_helper.lua
+msgid "Can't place: not pointing at node"
+msgstr "Placement impossible : ne pointe pas un nœud"
+
+#: track_reg_helper.lua
+msgid "Can't place: space occupied!"
+msgstr "Placement impossible : espace occupé !"
+
+#: track_reg_helper.lua tracks.lua
+msgid "This track can not be removed!"
+msgstr "Cette voie ne peut pas être enlevée !"
+
+#: trackplacer.lua
+msgid ""
+"Left-click: change rail type (straight/curve/switch)\n"
+"Right-click: rotate object"
+msgstr ""
+"Clic-Gauche : change le type de rail (droit/courbé/aiguillage)\n"
+"\n"
+"Clic-Droit : tourne l'objet"
+
+#: trackplacer.lua
+msgid "This node can't be changed using the trackworker!"
+msgstr "Ce nœud ne peut être modifié avec l'outil \"Trackworker\" !"
+
+#: trackplacer.lua
+msgid "This node can't be rotated using the trackworker!"
+msgstr "Ce nœud ne peut être tourné avec l'outil \"Trackworker\" !"
+
+#: trackplacer.lua
+msgid "This track can not be rotated!"
+msgstr "Cette voie ne peut pas être tournée !"
+
+#: trackplacer.lua
+msgid "Track Worker Tool"
+msgstr "Outil \"Trackworker\""
+
+#: tracks.lua
+msgid "Position is occupied by a train."
+msgstr "Cet emplacement est occupé par un train."
+
+#: tracks.lua
+msgid "There's a Signal Influence Point here."
+msgstr "Il y a un \"Signal Influence Point\" ici."
+
+#: tracks.lua
+msgid "There's a Track Circuit Break here."
+msgstr "Il y a un \"Track Circuit Break\" ici."
+
+#: trainhud.lua
+msgid "OVERRUN RED SIGNAL! Examine situation and reverse train to move again."
+msgstr ""
+"Franchissement de signal rouge : examinez la situation et inversez le sens "
+"de marche du train."
+
+#: wagonprop_tool.lua
+msgid "Insufficient privileges to use this!"
+msgstr "Privilèges insuffisants pour utiliser ceci !"
+
+#: wagonprop_tool.lua
+msgid "Punch a wagon to view and edit the Wagon Properties"
+msgstr "Frappez un wagon pour voir et modifier ses propriétés"
+
+#: wagonprop_tool.lua
+msgid "Wagon Properties Tool"
+msgstr "Outil de propriété du wagon"
+
+#: wagons.lua
+msgid " units"
+msgstr " Unités"
+
+#: wagons.lua
+msgid "!!! Train off track !!!"
+msgstr "!!! Train hors voie !!!"
+
+#: wagons.lua
+msgid "(Doors closed)"
+msgstr "(Portes closes)"
+
+#: wagons.lua
+msgid "Allow these players to access your wagon:"
+msgstr "Autoriser ces joueurs à embarquer :"
+
+#: wagons.lua
+msgid "Clear 'Disable ARS' flag"
+msgstr "Effacer le drapeau \"Désactiver l'ARS\""
+
+#: wagons.lua
+msgid "Current FC: "
+msgstr "Code de fret courant: "
+
+#: wagons.lua
+msgid ""
+"Destroying wagon with inventory, but inventory is not found? Shouldn't "
+"happen!"
+msgstr "Desctruction d'un wagon avec inventaire introuvable ? Anomalie !"
+
+#: wagons.lua
+msgid "Doors are closed! (Try holding sneak key!)"
+msgstr "Portes closes : (Essayez la \"sneak key\"!\")"
+
+#: wagons.lua
+msgid ""
+"Doors are closed. Use Sneak+rightclick to ignore the closed doors and get "
+"off."
+msgstr ""
+"Portes closes ! Utilisez \"Marcher lentement (Sneak)\" et Clic-Droit pour "
+"franchir les portes et débarquer."
+
+#: wagons.lua
+msgid "Freight Code:"
+msgstr "Code de frêt :"
+
+#: wagons.lua
+msgid "Get off"
+msgstr "Débarquer"
+
+#: wagons.lua
+msgid "Get off (forced)"
+msgstr "Débarquer (de force)"
+
+#: wagons.lua
+msgid "Line"
+msgstr "Ligne"
+
+#: wagons.lua
+msgid "Liquid: "
+msgstr "Liquide : "
+
+#: wagons.lua
+msgid "Liquid: empty"
+msgstr "Liquide : vide"
+
+#: wagons.lua
+msgid "Missing train_operator privilege"
+msgstr "Privilège \"train_operator\" manquant"
+
+#: wagons.lua
+msgid "Next FC:"
+msgstr "Code de fret suivant :"
+
+#: wagons.lua
+msgid "Not a valid wagon id."
+msgstr "Identificateur de wagon invalide."
+
+#: wagons.lua
+msgid "Not allowed to do this."
+msgstr "Vous n'êtes pas autorisé effectuer ceci."
+
+#: wagons.lua
+msgid "Onboard Computer"
+msgstr "Ordinateur embarqué"
+
+#: wagons.lua
+msgid "Please specify a player name to transfer ownership to."
+msgstr ""
+"Spécifiez le nom du joueur à qui la propriété doit être transférée, SVP."
+
+#: wagons.lua
+msgid "Prev FC"
+msgstr "Code de fret précédent"
+
+#: wagons.lua
+msgid "Remote Routesetting"
+msgstr "Routage à distance"
+
+#: wagons.lua
+msgid "Routingcode"
+msgstr "Code de routage"
+
+#: wagons.lua
+msgid "Save wagon properties"
+msgstr "Sauvegarder les propriétés du wagon"
+
+#: wagons.lua
+msgid "Select seat:"
+msgstr "Choisir le siège :"
+
+#: wagons.lua
+msgid "Show Inventory"
+msgstr "Montrer le stock"
+
+#: wagons.lua
+msgid "Text displayed inside train"
+msgstr "Texte affiché à l'intérieur du train"
+
+#: wagons.lua
+msgid "Text displayed outside on train"
+msgstr "Texte affiché à l'extérieur du train"
+
+#: wagons.lua
+msgid "That player does not exist!"
+msgstr "Ce joueur n'existe pas !"
+
+#: wagons.lua
+msgid "That wagon does not exist!"
+msgstr "Ce wagon n'a pas de siège !"
+
+#: wagons.lua
+msgid "The track you are trying to place the wagon on is not long enough!"
+msgstr "La voie sur laquelle vous tentez de placer le wagon est trop courte !"
+
+#: wagons.lua
+msgid "The wagon's inventory is not empty."
+msgstr "Le stock de ce wagon n'est pas vide."
+
+#: wagons.lua
+msgid "This Wagon ID"
+msgstr "Identificateur du wagon"
+
+#: wagons.lua
+msgid "This wagon has no seats."
+msgstr "Ce wagon n'a pas de siège."
+
+#: wagons.lua
+msgid "This wagon is full."
+msgstr "Ce wagon est plein."
+
+#: wagons.lua
+msgid "This wagon is owned by @1, you can't destroy it."
+msgstr "Ce wagon est la propriété de @1, vous ne pouvez pas le détruire."
+
+#: wagons.lua
+msgid "Train ID"
+msgstr "Identificateur du train"
+
+#: wagons.lua
+msgid "Train overview / coupling control is only shown when the train stands."
+msgstr ""
+"Aperçu du train / commande d'accouplement montré uniquement à l'arrêt du "
+"train."
+
+#: wagons.lua
+msgid "Train overview /coupling control:"
+msgstr "Aperçu du train / commande d'accouplement :"
+
+#: wagons.lua
+msgid "Uninitialized, removing"
+msgstr "Non initialisé, retiré"
+
+#: wagons.lua
+msgid "Wagon @1 ownership changed from @2 to @3"
+msgstr "La propriété du wagon @1 a été transférée de @2 à @3"
+
+#: wagons.lua
+msgid "Wagon needs to be decoupled from other wagons in order to destroy it."
+msgstr ""
+"Les wagons doivent être désaccouplés des autres pour pouvoir être détruits."
+
+#: wagons.lua
+#, fuzzy
+msgid "Wagon placeholder"
+msgstr ", dans un espace réservé"
+
+#: wagons.lua
+msgid "Wagon properties"
+msgstr "Propriétés du wagon"
+
+#: wagons.lua
+msgid "Wagon road number:"
+msgstr "Immatriculation du wagon :"
+
+#: wagons.lua
+msgid ""
+"Warning: If you destroy this wagon, you only get some steel back! If you are "
+"sure, hold Sneak and left-click the wagon."
+msgstr ""
+"Attention: Si vous détruisez ce wagon, vous ne récupérerez que de la "
+"ferraille ! Si vous êtes sûr de vous, appuyez la touche \"Marcher lentement "
+"(Sneak)\" et Clic-Gauche."
+
+#: wagons.lua
+msgid "You are not allowed to access the driver stand."
+msgstr "Accès interdit au poste de pilotage."
+
+#: wagons.lua
+msgid "You can't get on this wagon."
+msgstr "Montée impossible dans ce wagon."
+
+#: wagons.lua
+msgid "You don't have the train_operator privilege."
+msgstr "Vous ne possédez pas le privilège \"train_operator\"."
+
+#: wagons.lua
+msgid "You have been given ownership of wagon @1"
+msgstr "La propriété du wagon @1 vous a été transférée"
+
+#~ msgid " is at "
+#~ msgstr " est à la position "
+
+#~ msgid " wagon:destroy(): data is not set!"
+#~ msgstr " Appel de wagon:destroy() : données non définies !"
+
+#~ msgid "(log"
+#~ msgstr "(log"
+
+#~ msgid "3-way turnout"
+#~ msgstr "Embranchement triple"
+
+#~ msgid "90+Angle Diamond Crossing Track"
+#~ msgstr "Croisement perpendiculo-diagonal"
+
+#~ msgid "ATC controller"
+#~ msgstr "Controlleur ATC"
+
+#~ msgid ""
+#~ "ATC controller, mode @1\n"
+#~ "Channel: @2"
+#~ msgstr ""
+#~ "Controlleur ATC, mode @1\n"
+#~ "Canal : @2"
+
+#~ msgid "Access to @1"
+#~ msgstr "Accès à @1"
+
+#~ msgid "Big Industrial Train Engine"
+#~ msgstr "Grosse locomotive industrielle"
+
+#~ msgid "Box Wagon"
+#~ msgstr "Wagon de frêt"
+
+#~ msgid "Bumper"
+#~ msgstr "Heurtoir"
+
+#~ msgid ""
+#~ "Can place and configure LuaATC components, including execute potentially "
+#~ "harmful Lua code"
+#~ msgstr ""
+#~ "Permet le placement et la configuration de composants LuaATC avec risque "
+#~ "d'exécution de code Lua dangereux"
+
+#~ msgid "Can't get on: wagon full or doors closed!"
+#~ msgstr ""
+#~ "Embarquement impossible : le wagon est plein ou ses portes sont closes !"
+
+#~ msgid "Can't place: protected position!"
+#~ msgstr "Placement impossible : emplacement protégé"
+
+#~ msgid "Caution"
+#~ msgstr "Attention"
+
+#~ msgid "Clear (proceed)"
+#~ msgstr "Autorisation (procédez)"
+
+#~ msgid "Clear Local Environment"
+#~ msgstr "Effacer l'environnement LuaATC"
+
+#~ msgid "Closed"
+#~ msgstr "Fermé"
+
+#~ msgid "Code"
+#~ msgstr "Code"
+
+#~ msgid "Command (on)"
+#~ msgstr "Commande (marche)"
+
+#~ msgid "Danger (halt)"
+#~ msgstr "Danger (stop)"
+
+#~ msgid "Default Seat"
+#~ msgstr "Siège par défaut"
+
+#~ msgid "Default Seat (driver stand)"
+#~ msgstr "Siège par défaut (poste de pilotage)"
+
+#~ msgid "Dep. Speed"
+#~ msgstr "Vit. de départ"
+
+#~ msgid "Deprecated Track"
+#~ msgstr "Voie déconseillée"
+
+#~ msgid "Detailed Steam Engine"
+#~ msgstr "Locomotive à vapeur complexe"
+
+#~ msgid "Detector Rail"
+#~ msgstr "Voie détectrice"
+
+#~ msgid "Diagonal Diamond Crossing Track"
+#~ msgstr "Croisement diagonal"
+
+#~ msgid "Door Delay"
+#~ msgstr "Durée d'ouverture des portes"
+
+#~ msgid "Door Side"
+#~ msgstr "Ouv. des portes coté"
+
+#~ msgid "Driver Stand"
+#~ msgstr "Poste de pilotage"
+
+#~ msgid "Driver Stand (left)"
+#~ msgstr "Poste de pilotage (gauche)"
+
+#~ msgid "Driver Stand (right)"
+#~ msgstr "Poste de pilotage (droit)"
+
+#~ msgid "Driver stand"
+#~ msgstr "Poste de pilotage"
+
+#~ msgid "Industrial Train Engine"
+#~ msgstr "Locomotive industrielle"
+
+#~ msgid "Industrial tank wagon"
+#~ msgstr "Wagon-citerne industriel"
+
+#~ msgid "Industrial wood wagon"
+#~ msgstr "Wagon grumier industriel"
+
+#~ msgid "Japanese Train Engine"
+#~ msgstr "Motrice Japonaise"
+
+#~ msgid "Japanese Train Inter-Wagon Connection"
+#~ msgstr "Passage inter-voiture de train Japonais"
+
+#~ msgid "Japanese Train Wagon"
+#~ msgstr "Voiture Japonaise"
+
+#~ msgid "Japanese signal pole"
+#~ msgstr "Voiture Japonaise"
+
+#~ msgid "Kick out passengers"
+#~ msgstr "Éjecter les passagers"
+
+#~ msgid "Left"
+#~ msgstr "Gauche"
+
+#~ msgid "Left,Right,Closed;"
+#~ msgstr "Gauche,Droit,Fermé;"
+
+#~ msgid "Loading Track"
+#~ msgstr "Voie de Chargement"
+
+#~ msgid "Lock couples"
+#~ msgstr "Verrouiller l'accouplement"
+
+#~ msgid "LuaATC Environment"
+#~ msgstr "Environnement LuaATC"
+
+#~ msgid "LuaATC Mesecon Controller"
+#~ msgstr "Commande Mesecon de LuaATC"
+
+#~ msgid "LuaATC Operation Panel"
+#~ msgstr "Panneau de commande de LuaATC"
+
+#~ msgid "LuaATC component assigned to an invalid environment"
+#~ msgstr "Composant LuaATC assigné à un environnement invalide"
+
+#~ msgid "LuaATC component assigned to environment '@1'"
+#~ msgstr "Composant LuaATC assigné à l'environnement '@1'"
+
+#~ msgid "LuaATC component with error: @1"
+#~ msgstr "Erreur @1 du composant LuaATC"
+
+#~ msgid "Munich U-Bahn Distant Signal ("
+#~ msgstr "Signal distant métro de Munich ("
+
+#~ msgid "Munich U-Bahn Main Signal ("
+#~ msgstr "Signal principal métro de Munich ("
+
+#~ msgid "Next Stop:\n"
+#~ msgstr "Prochain arrêt :\n"
+
+#~ msgid "No callback to handle schedule"
+#~ msgstr "Absence de fonction de gestion de planning"
+
+#~ msgid "Passenger Wagon"
+#~ msgstr "Voiture passager"
+
+#~ msgid "Passenger area"
+#~ msgstr "Voiture Passager"
+
+#~ msgid ""
+#~ "Passive Component Naming Tool\n"
+#~ "\n"
+#~ "Right-click to name a passive component."
+#~ msgstr ""
+#~ "Outil de nommage de composant passif\n"
+#~ "\n"
+#~ "Clic-Droit pour nommer un composant passif."
+
+#~ msgid "Perpendicular Diamond Crossing Track"
+#~ msgstr "Croisement perpendiculaire"
+
+#~ msgid "Point Speed Restriction Track"
+#~ msgstr "Voie de point de limitation de vitesse"
+
+#~ msgid "Point speed restriction: @1"
+#~ msgstr "Point de limitation de vitesse : @1"
+
+#~ msgid "Reduced speed"
+#~ msgstr "Vitesse réduite"
+
+#~ msgid "Restricted speed"
+#~ msgstr "Vitesse limitée"
+
+#~ msgid "Reverse train"
+#~ msgstr "Inversion du sens de marche"
+
+#~ msgid "Right"
+#~ msgstr "Droit"
+
+#~ msgid "Route state changed."
+#~ msgstr "Changement d'état de l'itinéraire."
+
+#~ msgid "Set name of component (empty to clear)"
+#~ msgstr "Nommer le composant (chaîne vide pour effacer)"
+
+#~ msgid "Set point speed restriction:"
+#~ msgstr "Placez un point de limitation de vitesse :"
+
+#~ msgid "Signal"
+#~ msgstr "Signal"
+
+#~ msgid "Speed:"
+#~ msgstr "Vitesse : "
+
+#~ msgid "Station Code"
+#~ msgstr "Code de Station"
+
+#~ msgid "Station Name"
+#~ msgstr "Nom de Station"
+
+#~ msgid "Station code \"@1\" already exists and is owned by @2."
+#~ msgstr "Le code de station \"@1\" existe et est possédé par @2."
+
+#~ msgid "Station/Stop Track"
+#~ msgstr "Voie d'arrêt en station"
+
+#~ msgid "Steam Engine"
+#~ msgstr "Locomotive à vapeur"
+
+#~ msgid "Stop Time"
+#~ msgstr "Durée d'arrêt"
+
+#~ msgid "Subway Passenger Wagon"
+#~ msgstr "Voiture de Métropolitain"
+
+#~ msgid "Target:"
+#~ msgstr "Destination : "
+
+#, fuzzy
+#~ msgid "This node can't be rotated using the trackworker,"
+#~ msgstr "Ce nœud ne peut être tourné avec l'outil \"Trackworker\" !"
+
+#~ msgid "This position is protected!"
+#~ msgstr "Cet emplacement est protégé !"
+
+#~ msgid "This station is owned by @1. You are not allowed to edit its name."
+#~ msgstr ""
+#~ "Cette station est la propriété de @1. Vous n'êtes pas autorisé à modifier "
+#~ "son nom."
+
+#~ msgid "This track can not be changed."
+#~ msgstr "Cette voie ne peut pas être modifiée."
+
+#~ msgid "Track"
+#~ msgstr "Voie"
+
+#~ msgid "Train"
+#~ msgstr "Identificateur du train"
+
+#~ msgid "Train "
+#~ msgstr "Identificateur du train "
+
+#~ msgid "Trains stopping here (ARS rules)"
+#~ msgstr "Trains marquant l'arrêt (règles ARS)"
+
+#~ msgid "Unable to load wagon type"
+#~ msgstr "Impossible de charger le type du wagon"
+
+#~ msgid "Unconfigured LuaATC component"
+#~ msgstr "Composant LuaATC non configuré"
+
+#~ msgid "Uninitialized init="
+#~ msgstr "Variable init non initialisée"
+
+#~ msgid "Unknown Station"
+#~ msgstr "Gare inconnue"
+
+#~ msgid "Unloading Track"
+#~ msgstr "Voie de Déchargement"
+
+#~ msgid "Use Sneak+rightclick to bypass closed doors!"
+#~ msgstr ""
+#~ "Utilisez \"Marcher lentement (Sneak)\" et Clic-Droit pour franchir les "
+#~ "portes closes !"
+
+#~ msgid "Wait for signal to clear"
+#~ msgstr "En attente de signal d'autorisation"
+
+#~ msgid "Y-turnout"
+#~ msgstr "Embranchement en Y"
+
+#~ msgid ""
+#~ "You are not allowed to configure this LuaATC component without the @1 "
+#~ "privilege."
+#~ msgstr "Vous ne pouvez configurer ce composant LuaATC sans le privilege @1."
+
+#~ msgid ""
+#~ "You are not allowed to configure this track without the @1 privilege."
+#~ msgstr ""
+#~ "Vous n'êtes pas autorisé à configurer cette voie sans le privilège @1."
+
+#~ msgid "You are not allowed to configure this track."
+#~ msgstr "Vous n'êtes pas autorisé à configurer cette voie."
+
+#, fuzzy
+#~ msgid "You are not allowed to modify this protected track."
+#~ msgstr "Vous ne pouvez pas construire une voie à cet emplacement protégé"
+
+#~ msgid ""
+#~ "You are not allowed to name LuaATC passive components without the @1 "
+#~ "privilege."
+#~ msgstr ""
+#~ "Vous ne pouvez nommer un composant LuaATC passif sans le privilege @1."
+
+#~ msgid ""
+#~ "You need to own at least one neighboring wagon to destroy this couple."
+#~ msgstr ""
+#~ "Vous devez être propriétaire d'au moins un wagon voisin pour supprimer "
+#~ "cet attelage."
+
+#~ msgid "slowdown"
+#~ msgstr "ralentissement"
diff --git a/advtrains/locale/advtrains.pot b/advtrains/locale/advtrains.pot
new file mode 100644
index 0000000..b33588e
--- /dev/null
+++ b/advtrains/locale/advtrains.pot
@@ -0,0 +1,625 @@
+# SOME DESCRIPTIVE TITLE.
+# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
+# This file is distributed under the same license as the advtrains package.
+# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
+#
+#, fuzzy
+msgid ""
+msgstr ""
+"Project-Id-Version: advtrains\n"
+"Report-Msgid-Bugs-To: advtrains-discuss@lists.sr.ht\n"
+"POT-Creation-Date: 2026-05-17 09:18+0800\n"
+"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
+"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
+"Language-Team: LANGUAGE <LL@li.org>\n"
+"Language: \n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=CHARSET\n"
+"Content-Transfer-Encoding: 8bit\n"
+
+#: atc.lua
+msgid "Unconfigured ATC controller"
+msgstr ""
+
+#: atc.lua
+msgid "ATC controller, Command: @1"
+msgstr ""
+
+#: atc.lua
+msgid "Command"
+msgstr ""
+
+#: atc.lua
+msgid "Digiline channel"
+msgstr ""
+
+#: atc.lua wagons.lua
+msgid "Save"
+msgstr ""
+
+#: atc.lua
+msgid "ATC Reverse command warning: didn't reverse train, train moving."
+msgstr ""
+
+#: atc.lua
+msgid "ATC Kick command warning: doors are closed."
+msgstr ""
+
+#: atc.lua
+msgid "ATC Kick command warning: train moving."
+msgstr ""
+
+#: atc.lua
+msgid "ATC command syntax error: I statement not closed: @1"
+msgstr ""
+
+#: atc.lua
+msgid "ATC command parse error: Unknown command: @1"
+msgstr ""
+
+#: copytool.lua
+msgid ""
+"Train copy/paste tool\n"
+"\n"
+"Left-click: copy train\n"
+"Right-click: paste train"
+msgstr ""
+
+#: copytool.lua
+msgid "You do not have the @1 privilege."
+msgstr ""
+
+#: copytool.lua
+msgid "The track you are trying to place the wagon on is not long enough."
+msgstr ""
+
+#: copytool.lua
+msgid "The clipboard couldn't access the metadata. Paste failed."
+msgstr ""
+
+#: copytool.lua
+msgid "The clipboard is empty."
+msgstr ""
+
+#: copytool.lua
+msgid "Back of train would end up off track, cancelling."
+msgstr ""
+
+#: copytool.lua
+msgid "No such lua entity."
+msgstr ""
+
+#: copytool.lua
+msgid "No such wagon: @1."
+msgstr ""
+
+#: copytool.lua
+msgid "No such train: @1."
+msgstr ""
+
+#: copytool.lua
+msgid "The clipboard couldn't access the metadata. Copy failed."
+msgstr ""
+
+#: copytool.lua
+msgid "Train copied."
+msgstr ""
+
+#: couple.lua
+msgid "Buffer and Chain Coupler"
+msgstr ""
+
+#: couple.lua
+msgid "Scharfenberg Coupler"
+msgstr ""
+
+#: couple.lua
+msgid ""
+"You are not allowed to couple trains without the train_operator privilege."
+msgstr ""
+
+#: couple.lua
+msgid ""
+"Cannot couple @1 and @2 - train would have length @3 which is above the "
+"limit of @4"
+msgstr ""
+
+#: couple.lua
+msgid "<No coupler>"
+msgstr ""
+
+#: couple.lua
+msgid "Can not couple: The couplers of the trains do not match (@1 and @2)."
+msgstr ""
+
+#: craft_items.lua
+msgid "Boiler"
+msgstr ""
+
+#: craft_items.lua
+msgid "Driver's cab"
+msgstr ""
+
+#: craft_items.lua
+msgid "Wheel"
+msgstr ""
+
+#: craft_items.lua
+msgid "Chimney"
+msgstr ""
+
+#: init.lua
+msgid "Restoring saved state in 1 second..."
+msgstr ""
+
+#: init.lua
+msgid "Reload successful!"
+msgstr ""
+
+#: init.lua
+msgid "Removing unused wagon"
+msgstr ""
+
+#: init.lua
+msgid "from wagon_save table."
+msgstr ""
+
+#: init.lua
+msgid ""
+"Train @1 had no wagons left because of some bug. It is being deleted. Wave "
+"it goodbye!"
+msgstr ""
+
+#: init.lua
+msgid "Saving failed: @1"
+msgstr ""
+
+#: init.lua
+msgid "Instructed to save() but load() was never called!"
+msgstr ""
+
+#: init.lua
+msgid ""
+"Crash during advtrains main step - skipping the shutdown save operation to "
+"not save inconsistent data!"
+msgstr ""
+
+#: init.lua
+msgid ""
+"Detach all players, especially the offline ones, from all trains. Use only "
+"when no one serious is on a train."
+msgstr ""
+
+#: init.lua
+msgid ""
+"Data is being saved. While saving, advtrains will remove the players from "
+"trains. Save files will be reloaded afterwards!"
+msgstr ""
+
+#: init.lua
+msgid "Delete all train routes, force them to recalculate"
+msgstr ""
+
+#: init.lua
+msgid "Successfully invalidated train routes"
+msgstr ""
+
+#: init.lua
+msgid "Returns the position of the train with the given id"
+msgstr ""
+
+#: init.lua
+msgid "Train @1 does not exist or is invalid"
+msgstr ""
+
+#: init.lua
+msgid "Train @1 is at @2"
+msgstr ""
+
+#: init.lua
+msgid "Teleports you to the position of the train with the given id"
+msgstr ""
+
+#: init.lua
+msgid "Teleporting to train @1"
+msgstr ""
+
+#: init.lua
+msgid "Disable the advtrains globalstep temporarily"
+msgstr ""
+
+#: init.lua
+msgid ""
+"The advtrains globalstep has been disabled. Trains are not moving, and no "
+"data is saved! Run '/at_disable_step no' to enable again!"
+msgstr ""
+
+#: init.lua
+msgid "Disabled advtrains successfully"
+msgstr ""
+
+#: init.lua
+msgid "Re-enabling advtrains globalstep..."
+msgstr ""
+
+#: init.lua
+msgid "Advtrains is already running normally!"
+msgstr ""
+
+#: init.lua
+msgid "Print advtrains status info"
+msgstr ""
+
+#: init.lua
+msgid "Advtrains Status: no_action @1 slowdown @2 (log @3)"
+msgstr ""
+
+#: misc_nodes.lua
+msgid "@1 Platform (low)"
+msgstr ""
+
+#: misc_nodes.lua
+msgid "@1 Platform (high)"
+msgstr ""
+
+#: misc_nodes.lua
+msgid "@1 Platform (45 degree)"
+msgstr ""
+
+#: misc_nodes.lua
+msgid "@1 Platform (low, 45 degree)"
+msgstr ""
+
+#: protection.lua
+msgid "Can place, remove and operate trains"
+msgstr ""
+
+#: protection.lua
+msgid ""
+"Can place, remove and operate any train, regardless of owner, whitelist, or "
+"protection"
+msgstr ""
+
+#: protection.lua
+msgid "Can place and dig tracks in unprotected areas"
+msgstr ""
+
+#: protection.lua
+msgid "Can operate turnouts and signals in unprotected areas"
+msgstr ""
+
+#: protection.lua
+msgid ""
+"You are not allowed to build near tracks without the track_builder privilege."
+msgstr ""
+
+#: protection.lua
+msgid ""
+"You are not allowed to build tracks without the track_builder privilege."
+msgstr ""
+
+#: protection.lua
+msgid "You are not allowed to build near tracks at this protected position."
+msgstr ""
+
+#: protection.lua
+msgid "You are not allowed to build tracks at this protected position."
+msgstr ""
+
+#: protection.lua
+msgid ""
+"You are not allowed to operate turnouts and signals without the "
+"railway_operator privilege."
+msgstr ""
+
+#: signals.lua
+msgid "Lampless Signal (deprecated!)"
+msgstr ""
+
+#: signals.lua
+msgid "Signal (deprecated!)"
+msgstr ""
+
+#: signals.lua
+msgid "Wallmounted Signal (left) (deprecated!)"
+msgstr ""
+
+#: signals.lua
+msgid "Wallmounted Signal (right) (deprecated!)"
+msgstr ""
+
+#: signals.lua
+msgid "Wallmounted Signal (top) (deprecated!)"
+msgstr ""
+
+#: signals.lua
+msgid "Andrew's Cross"
+msgstr ""
+
+#: track_reg_helper.lua tracks.lua
+msgid "This track can not be removed!"
+msgstr ""
+
+#: track_reg_helper.lua
+msgid "@1 Slope"
+msgstr ""
+
+#: track_reg_helper.lua
+msgid "Can't place: not pointing at node"
+msgstr ""
+
+#: track_reg_helper.lua
+msgid "Can't place: space occupied!"
+msgstr ""
+
+#: track_reg_helper.lua
+msgid "Can't place: Not enough slope items left (@1 required)"
+msgstr ""
+
+#: track_reg_helper.lua
+msgid "Can't place: There's no slope of length @1"
+msgstr ""
+
+#: track_reg_helper.lua
+msgid "Can't place: no supporting node at upper end."
+msgstr ""
+
+#: trackplacer.lua
+msgid "This node can't be rotated using the trackworker!"
+msgstr ""
+
+#: trackplacer.lua
+msgid "This track can not be rotated!"
+msgstr ""
+
+#: trackplacer.lua
+msgid "This node can't be changed using the trackworker!"
+msgstr ""
+
+#: trackplacer.lua
+msgid ""
+"Left-click: change rail type (straight/curve/switch)\n"
+"Right-click: rotate object"
+msgstr ""
+
+#: trackplacer.lua
+msgid "Track Worker Tool"
+msgstr ""
+
+#: tracks.lua
+msgid "Position is occupied by a train."
+msgstr ""
+
+#: tracks.lua
+msgid "There's a Track Circuit Break here."
+msgstr ""
+
+#: tracks.lua
+msgid "There's a Signal Influence Point here."
+msgstr ""
+
+#: trainhud.lua
+msgid "OVERRUN RED SIGNAL! Examine situation and reverse train to move again."
+msgstr ""
+
+#: wagonprop_tool.lua
+msgid "Punch a wagon to view and edit the Wagon Properties"
+msgstr ""
+
+#: wagonprop_tool.lua
+msgid "Wagon Properties Tool"
+msgstr ""
+
+#: wagonprop_tool.lua
+msgid "Insufficient privileges to use this!"
+msgstr ""
+
+#: wagons.lua
+msgid "Uninitialized, removing"
+msgstr ""
+
+#: wagons.lua
+msgid "This wagon is owned by @1, you can't destroy it."
+msgstr ""
+
+#: wagons.lua
+msgid ""
+"Destroying wagon with inventory, but inventory is not found? Shouldn't "
+"happen!"
+msgstr ""
+
+#: wagons.lua
+msgid "The wagon's inventory is not empty."
+msgstr ""
+
+#: wagons.lua
+msgid "Wagon needs to be decoupled from other wagons in order to destroy it."
+msgstr ""
+
+#: wagons.lua
+msgid ""
+"Warning: If you destroy this wagon, you only get some steel back! If you are "
+"sure, hold Sneak and left-click the wagon."
+msgstr ""
+
+#: wagons.lua
+msgid "!!! Train off track !!!"
+msgstr ""
+
+#: wagons.lua
+msgid " units"
+msgstr ""
+
+#: wagons.lua
+msgid "Liquid: "
+msgstr ""
+
+#: wagons.lua
+msgid "Liquid: empty"
+msgstr ""
+
+#: wagons.lua
+msgid "Show Inventory"
+msgstr ""
+
+#: wagons.lua
+msgid "Onboard Computer"
+msgstr ""
+
+#: wagons.lua
+msgid "Wagon properties"
+msgstr ""
+
+#: wagons.lua
+msgid "Get off"
+msgstr ""
+
+#: wagons.lua
+msgid "Get off (forced)"
+msgstr ""
+
+#: wagons.lua
+msgid "(Doors closed)"
+msgstr ""
+
+#: wagons.lua
+msgid "This wagon has no seats."
+msgstr ""
+
+#: wagons.lua
+msgid "This wagon is full."
+msgstr ""
+
+#: wagons.lua
+msgid "Doors are closed! (Try holding sneak key!)"
+msgstr ""
+
+#: wagons.lua
+msgid "You can't get on this wagon."
+msgstr ""
+
+#: wagons.lua
+msgid "Select seat:"
+msgstr ""
+
+#: wagons.lua
+msgid "This Wagon ID"
+msgstr ""
+
+#: wagons.lua
+msgid "Allow these players to access your wagon:"
+msgstr ""
+
+#: wagons.lua
+msgid "Wagon road number:"
+msgstr ""
+
+#: wagons.lua
+msgid "Freight Code:"
+msgstr ""
+
+#: wagons.lua
+msgid "Prev FC"
+msgstr ""
+
+#: wagons.lua
+msgid "Current FC: "
+msgstr ""
+
+#: wagons.lua
+msgid "Next FC:"
+msgstr ""
+
+#: wagons.lua
+msgid "Save wagon properties"
+msgstr ""
+
+#: wagons.lua
+msgid "Train ID"
+msgstr ""
+
+#: wagons.lua
+msgid "Text displayed outside on train"
+msgstr ""
+
+#: wagons.lua
+msgid "Text displayed inside train"
+msgstr ""
+
+#: wagons.lua
+msgid "Line"
+msgstr ""
+
+#: wagons.lua
+msgid "Routingcode"
+msgstr ""
+
+#: wagons.lua
+msgid "Train overview /coupling control:"
+msgstr ""
+
+#: wagons.lua
+msgid "Train overview / coupling control is only shown when the train stands."
+msgstr ""
+
+#: wagons.lua
+msgid "Remote Routesetting"
+msgstr ""
+
+#: wagons.lua
+msgid "Clear 'Disable ARS' flag"
+msgstr ""
+
+#: wagons.lua
+msgid ""
+"Doors are closed. Use Sneak+rightclick to ignore the closed doors and get "
+"off."
+msgstr ""
+
+#: wagons.lua
+msgid "You are not allowed to access the driver stand."
+msgstr ""
+
+#: wagons.lua
+msgid "Missing train_operator privilege"
+msgstr ""
+
+#: wagons.lua
+msgid "Not allowed to do this."
+msgstr ""
+
+#: wagons.lua
+msgid "You don't have the train_operator privilege."
+msgstr ""
+
+#: wagons.lua
+msgid "The track you are trying to place the wagon on is not long enough!"
+msgstr ""
+
+#: wagons.lua
+msgid "Wagon placeholder"
+msgstr ""
+
+#: wagons.lua
+msgid "Please specify a player name to transfer ownership to."
+msgstr ""
+
+#: wagons.lua
+msgid "That player does not exist!"
+msgstr ""
+
+#: wagons.lua
+msgid "Not a valid wagon id."
+msgstr ""
+
+#: wagons.lua
+msgid "That wagon does not exist!"
+msgstr ""
+
+#: wagons.lua
+msgid "You have been given ownership of wagon @1"
+msgstr ""
+
+#: wagons.lua
+msgid "Wagon @1 ownership changed from @2 to @3"
+msgstr ""
diff --git a/advtrains/locale/advtrains.zh_CN.po b/advtrains/locale/advtrains.zh_CN.po
new file mode 100644
index 0000000..873da07
--- /dev/null
+++ b/advtrains/locale/advtrains.zh_CN.po
@@ -0,0 +1,861 @@
+msgid ""
+msgstr ""
+"Project-Id-Version: advtrains\n"
+"Report-Msgid-Bugs-To: advtrains-discuss@lists.sr.ht\n"
+"POT-Creation-Date: 2026-05-17 09:18+0800\n"
+"PO-Revision-Date: 2026-05-17 09:25+0800\n"
+"Last-Translator: Y. Wang <yw05@forksworld.de>\n"
+"Language-Team: Chinese (Simplified)\n"
+"Language: zh_CN\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"X-Generator: Poedit 3.8\n"
+
+#: atc.lua
+msgid "ATC Kick command warning: doors are closed."
+msgstr "ATC 警告:车门已关闭,无法踢出乘客。"
+
+#: atc.lua
+msgid "ATC Kick command warning: train moving."
+msgstr "ATC 警告:火车正在移动,无法踢出乘客。"
+
+#: atc.lua
+msgid "ATC Reverse command warning: didn't reverse train, train moving."
+msgstr "ATC 警告:火车正在移动,无法改变行车方向。"
+
+#: atc.lua
+msgid "ATC command parse error: Unknown command: @1"
+msgstr "ATC 语法错误:未知命令:@1"
+
+#: atc.lua
+msgid "ATC command syntax error: I statement not closed: @1"
+msgstr "ATC 语法错误:“I”命令不完整:@1"
+
+#: atc.lua
+#, fuzzy
+msgid "ATC controller, Command: @1"
+msgstr ""
+"ATC 控制器\n"
+"模式:@1\n"
+"命令:@2"
+
+#: atc.lua
+msgid "Command"
+msgstr "命令"
+
+#: atc.lua
+msgid "Digiline channel"
+msgstr "Digiline 频道"
+
+#: atc.lua wagons.lua
+msgid "Save"
+msgstr "保存"
+
+#: atc.lua
+msgid "Unconfigured ATC controller"
+msgstr "ATC 控制器 (未配置)"
+
+#: copytool.lua
+msgid "Back of train would end up off track, cancelling."
+msgstr "火车后部不在轨道上。"
+
+#: copytool.lua
+msgid "No such lua entity."
+msgstr "您没有指向一个可以用火车复制工具复制的物体。"
+
+#: copytool.lua
+msgid "No such train: @1."
+msgstr "ID 为“@1”的列车不存在。"
+
+#: copytool.lua
+msgid "No such wagon: @1."
+msgstr "ID 为“@1”的车厢不存在。"
+
+#: copytool.lua
+msgid "The clipboard couldn't access the metadata. Copy failed."
+msgstr "无法复制:剪贴板无法访问元数据。"
+
+#: copytool.lua
+msgid "The clipboard couldn't access the metadata. Paste failed."
+msgstr "无法粘贴:剪贴板无法访问元数据。"
+
+#: copytool.lua
+msgid "The clipboard is empty."
+msgstr "剪贴板是空的。"
+
+#: copytool.lua
+msgid "The track you are trying to place the wagon on is not long enough."
+msgstr "轨道太短。"
+
+#: copytool.lua
+msgid "Train copied."
+msgstr "已复制列车。"
+
+#: copytool.lua
+msgid ""
+"Train copy/paste tool\n"
+"\n"
+"Left-click: copy train\n"
+"Right-click: paste train"
+msgstr ""
+"火车复制工具\n"
+"\n"
+"左键单击:复制\n"
+"右键单击:粘帖"
+
+#: copytool.lua
+msgid "You do not have the @1 privilege."
+msgstr "您没有“@1”权限。"
+
+#: couple.lua
+msgid "<No coupler>"
+msgstr "<没有车钩>"
+
+#: couple.lua
+msgid "Buffer and Chain Coupler"
+msgstr "链式车钩"
+
+#: couple.lua
+msgid "Can not couple: The couplers of the trains do not match (@1 and @2)."
+msgstr "您无法连接这两节车厢:这两节车厢使用不同的车钩 (@1和@2)。"
+
+#: couple.lua
+msgid ""
+"Cannot couple @1 and @2 - train would have length @3 which is above the "
+"limit of @4"
+msgstr ""
+
+#: couple.lua
+msgid "Scharfenberg Coupler"
+msgstr "Scharfenberg 式车钩"
+
+#: couple.lua
+msgid ""
+"You are not allowed to couple trains without the train_operator privilege."
+msgstr "您没有“train_operator”权限,不能连接这两节车厢。"
+
+#: craft_items.lua
+msgid "Boiler"
+msgstr "锅炉"
+
+#: craft_items.lua
+msgid "Chimney"
+msgstr "烟囱"
+
+#: craft_items.lua
+msgid "Driver's cab"
+msgstr "驾驶室"
+
+#: craft_items.lua
+msgid "Wheel"
+msgstr "车轮"
+
+#: init.lua
+msgid "Advtrains Status: no_action @1 slowdown @2 (log @3)"
+msgstr ""
+
+#: init.lua
+msgid "Advtrains is already running normally!"
+msgstr ""
+
+#: init.lua
+msgid ""
+"Crash during advtrains main step - skipping the shutdown save operation to "
+"not save inconsistent data!"
+msgstr ""
+
+#: init.lua
+msgid ""
+"Data is being saved. While saving, advtrains will remove the players from "
+"trains. Save files will be reloaded afterwards!"
+msgstr ""
+
+#: init.lua
+msgid "Delete all train routes, force them to recalculate"
+msgstr ""
+
+#: init.lua
+msgid ""
+"Detach all players, especially the offline ones, from all trains. Use only "
+"when no one serious is on a train."
+msgstr ""
+
+#: init.lua
+msgid "Disable the advtrains globalstep temporarily"
+msgstr ""
+
+#: init.lua
+msgid "Disabled advtrains successfully"
+msgstr ""
+
+#: init.lua
+msgid "Instructed to save() but load() was never called!"
+msgstr ""
+
+#: init.lua
+msgid "Print advtrains status info"
+msgstr ""
+
+#: init.lua
+msgid "Re-enabling advtrains globalstep..."
+msgstr ""
+
+#: init.lua
+msgid "Reload successful!"
+msgstr ""
+
+#: init.lua
+msgid "Removing unused wagon"
+msgstr ""
+
+#: init.lua
+msgid "Restoring saved state in 1 second..."
+msgstr ""
+
+#: init.lua
+msgid "Returns the position of the train with the given id"
+msgstr ""
+
+#: init.lua
+msgid "Saving failed: @1"
+msgstr ""
+
+#: init.lua
+msgid "Successfully invalidated train routes"
+msgstr ""
+
+#: init.lua
+msgid "Teleporting to train @1"
+msgstr ""
+
+#: init.lua
+msgid "Teleports you to the position of the train with the given id"
+msgstr ""
+
+#: init.lua
+msgid ""
+"The advtrains globalstep has been disabled. Trains are not moving, and no "
+"data is saved! Run '/at_disable_step no' to enable again!"
+msgstr ""
+
+#: init.lua
+msgid "Train @1 does not exist or is invalid"
+msgstr ""
+
+#: init.lua
+msgid ""
+"Train @1 had no wagons left because of some bug. It is being deleted. Wave "
+"it goodbye!"
+msgstr ""
+
+#: init.lua
+msgid "Train @1 is at @2"
+msgstr ""
+
+#: init.lua
+msgid "from wagon_save table."
+msgstr ""
+
+#: misc_nodes.lua
+msgid "@1 Platform (45 degree)"
+msgstr "较高的@1站台 (45°)"
+
+#: misc_nodes.lua
+msgid "@1 Platform (high)"
+msgstr "较高的@1站台"
+
+#: misc_nodes.lua
+msgid "@1 Platform (low)"
+msgstr "较低的@1站台"
+
+#: misc_nodes.lua
+msgid "@1 Platform (low, 45 degree)"
+msgstr "较低的@1站台 (45°)"
+
+#: protection.lua
+msgid "Can operate turnouts and signals in unprotected areas"
+msgstr ""
+
+#: protection.lua
+msgid "Can place and dig tracks in unprotected areas"
+msgstr ""
+
+#: protection.lua
+msgid ""
+"Can place, remove and operate any train, regardless of owner, whitelist, or "
+"protection"
+msgstr ""
+
+#: protection.lua
+msgid "Can place, remove and operate trains"
+msgstr ""
+
+#: protection.lua
+msgid "You are not allowed to build near tracks at this protected position."
+msgstr "这里已被保护,您不能在这里的铁路附近建任何东西。"
+
+#: protection.lua
+msgid ""
+"You are not allowed to build near tracks without the track_builder privilege."
+msgstr "您没有“train_operator”权限,不能在铁路附近建任何东西。"
+
+#: protection.lua
+msgid "You are not allowed to build tracks at this protected position."
+msgstr "这里已被保护,您不能在这里建造铁路。"
+
+#: protection.lua
+msgid ""
+"You are not allowed to build tracks without the track_builder privilege."
+msgstr "您没有“train_operator”权限,不能在这里建造铁路。"
+
+#: protection.lua
+msgid ""
+"You are not allowed to operate turnouts and signals without the "
+"railway_operator privilege."
+msgstr "您没有“railway_operator”权限,不能控制铁路设施。"
+
+#: signals.lua
+msgid "Andrew's Cross"
+msgstr "铁路道口信号灯"
+
+#: signals.lua
+#, fuzzy
+msgid "Lampless Signal (deprecated!)"
+msgstr "臂板信号机"
+
+#: signals.lua
+msgid "Signal (deprecated!)"
+msgstr ""
+
+#: signals.lua
+#, fuzzy
+msgid "Wallmounted Signal (left) (deprecated!)"
+msgstr "壁挂式信号灯 (左侧)"
+
+#: signals.lua
+#, fuzzy
+msgid "Wallmounted Signal (right) (deprecated!)"
+msgstr "壁挂式信号灯 (右侧)"
+
+#: signals.lua
+#, fuzzy
+msgid "Wallmounted Signal (top) (deprecated!)"
+msgstr "悬挂式信号灯"
+
+#: track_reg_helper.lua
+msgid "@1 Slope"
+msgstr "@1斜坡"
+
+#: track_reg_helper.lua
+#, fuzzy
+msgid "Can't place: Not enough slope items left (@1 required)"
+msgstr "无法放置斜坡:您没有足够的铁路斜坡放置工具 (您总共需要@1个)"
+
+#: track_reg_helper.lua
+#, fuzzy
+msgid "Can't place: There's no slope of length @1"
+msgstr "无法放置斜坡:advtrains 不支持长度为@1米的斜坡。"
+
+#: track_reg_helper.lua
+#, fuzzy
+msgid "Can't place: no supporting node at upper end."
+msgstr "无法放置斜坡:较高端没有支撑方块。"
+
+#: track_reg_helper.lua
+#, fuzzy
+msgid "Can't place: not pointing at node"
+msgstr "无法放置斜坡:您没有选择任何方块。"
+
+#: track_reg_helper.lua
+#, fuzzy
+msgid "Can't place: space occupied!"
+msgstr "无法放置斜坡:此区域已被占用。"
+
+#: track_reg_helper.lua tracks.lua
+#, fuzzy
+msgid "This track can not be removed!"
+msgstr "您不能移除这段轨道。"
+
+#: trackplacer.lua
+msgid ""
+"Left-click: change rail type (straight/curve/switch)\n"
+"Right-click: rotate object"
+msgstr ""
+"左键单击:切换轨道类型\n"
+"右键单击:旋转方块"
+
+#: trackplacer.lua
+#, fuzzy
+msgid "This node can't be changed using the trackworker!"
+msgstr "您不能使用铁路调整工具调整这个方块。"
+
+#: trackplacer.lua
+#, fuzzy
+msgid "This node can't be rotated using the trackworker!"
+msgstr "您不能使用铁路调整工具旋转这个方块。"
+
+#: trackplacer.lua
+#, fuzzy
+msgid "This track can not be rotated!"
+msgstr "您不能旋转这段轨道。"
+
+#: trackplacer.lua
+msgid "Track Worker Tool"
+msgstr "铁路调整工具"
+
+#: tracks.lua
+msgid "Position is occupied by a train."
+msgstr ""
+
+#: tracks.lua
+msgid "There's a Signal Influence Point here."
+msgstr ""
+
+#: tracks.lua
+msgid "There's a Track Circuit Break here."
+msgstr ""
+
+#: trainhud.lua
+msgid "OVERRUN RED SIGNAL! Examine situation and reverse train to move again."
+msgstr ""
+
+#: wagonprop_tool.lua
+msgid "Insufficient privileges to use this!"
+msgstr ""
+
+#: wagonprop_tool.lua
+msgid "Punch a wagon to view and edit the Wagon Properties"
+msgstr ""
+
+#: wagonprop_tool.lua
+#, fuzzy
+msgid "Wagon Properties Tool"
+msgstr "车厢属性"
+
+#: wagons.lua
+msgid " units"
+msgstr ""
+
+#: wagons.lua
+msgid "!!! Train off track !!!"
+msgstr ""
+
+#: wagons.lua
+msgid "(Doors closed)"
+msgstr "(车门已关闭)"
+
+#: wagons.lua
+msgid "Allow these players to access your wagon:"
+msgstr ""
+
+#: wagons.lua
+msgid "Clear 'Disable ARS' flag"
+msgstr ""
+
+#: wagons.lua
+msgid "Current FC: "
+msgstr ""
+
+#: wagons.lua
+msgid ""
+"Destroying wagon with inventory, but inventory is not found? Shouldn't "
+"happen!"
+msgstr ""
+
+#: wagons.lua
+msgid "Doors are closed! (Try holding sneak key!)"
+msgstr ""
+
+#: wagons.lua
+msgid ""
+"Doors are closed. Use Sneak+rightclick to ignore the closed doors and get "
+"off."
+msgstr "车门已关闭,请使用潜行+右键单击下车。"
+
+#: wagons.lua
+msgid "Freight Code:"
+msgstr ""
+
+#: wagons.lua
+msgid "Get off"
+msgstr "下车"
+
+#: wagons.lua
+msgid "Get off (forced)"
+msgstr "强制下车"
+
+#: wagons.lua
+msgid "Line"
+msgstr "火车线路"
+
+#: wagons.lua
+msgid "Liquid: "
+msgstr ""
+
+#: wagons.lua
+msgid "Liquid: empty"
+msgstr ""
+
+#: wagons.lua
+msgid "Missing train_operator privilege"
+msgstr ""
+
+#: wagons.lua
+msgid "Next FC:"
+msgstr ""
+
+#: wagons.lua
+msgid "Not a valid wagon id."
+msgstr ""
+
+#: wagons.lua
+#, fuzzy
+msgid "Not allowed to do this."
+msgstr "您不能调整这段轨道。"
+
+#: wagons.lua
+msgid "Onboard Computer"
+msgstr ""
+
+#: wagons.lua
+msgid "Please specify a player name to transfer ownership to."
+msgstr ""
+
+#: wagons.lua
+msgid "Prev FC"
+msgstr ""
+
+#: wagons.lua
+msgid "Remote Routesetting"
+msgstr ""
+
+#: wagons.lua
+msgid "Routingcode"
+msgstr "路由码"
+
+#: wagons.lua
+msgid "Save wagon properties"
+msgstr "保存车厢属性"
+
+#: wagons.lua
+msgid "Select seat:"
+msgstr "请选择座位:"
+
+#: wagons.lua
+msgid "Show Inventory"
+msgstr "显示物品栏"
+
+#: wagons.lua
+msgid "Text displayed inside train"
+msgstr "车厢内部显示"
+
+#: wagons.lua
+msgid "Text displayed outside on train"
+msgstr "车厢外部显示"
+
+#: wagons.lua
+msgid "That player does not exist!"
+msgstr ""
+
+#: wagons.lua
+#, fuzzy
+msgid "That wagon does not exist!"
+msgstr "这节车厢没有座位。"
+
+#: wagons.lua
+#, fuzzy
+msgid "The track you are trying to place the wagon on is not long enough!"
+msgstr "轨道太短。"
+
+#: wagons.lua
+msgid "The wagon's inventory is not empty."
+msgstr ""
+
+#: wagons.lua
+#, fuzzy
+msgid "This Wagon ID"
+msgstr "车厢已满。"
+
+#: wagons.lua
+msgid "This wagon has no seats."
+msgstr "这节车厢没有座位。"
+
+#: wagons.lua
+msgid "This wagon is full."
+msgstr "车厢已满。"
+
+#: wagons.lua
+msgid "This wagon is owned by @1, you can't destroy it."
+msgstr "这是 @1 的车厢,您不能摧毁它。"
+
+#: wagons.lua
+msgid "Train ID"
+msgstr ""
+
+#: wagons.lua
+msgid "Train overview / coupling control is only shown when the train stands."
+msgstr ""
+
+#: wagons.lua
+msgid "Train overview /coupling control:"
+msgstr ""
+
+#: wagons.lua
+msgid "Uninitialized, removing"
+msgstr ""
+
+#: wagons.lua
+msgid "Wagon @1 ownership changed from @2 to @3"
+msgstr ""
+
+#: wagons.lua
+msgid "Wagon needs to be decoupled from other wagons in order to destroy it."
+msgstr ""
+
+#: wagons.lua
+#, fuzzy
+msgid "Wagon placeholder"
+msgstr "车厢属性"
+
+#: wagons.lua
+msgid "Wagon properties"
+msgstr "车厢属性"
+
+#: wagons.lua
+msgid "Wagon road number:"
+msgstr ""
+
+#: wagons.lua
+msgid ""
+"Warning: If you destroy this wagon, you only get some steel back! If you are "
+"sure, hold Sneak and left-click the wagon."
+msgstr ""
+"警告:如果您摧毁此车厢,您只能拿到一些钢方块。如果您确定要摧毁这节车厢,请按"
+"潜行键并左键单击此车厢。"
+
+#: wagons.lua
+msgid "You are not allowed to access the driver stand."
+msgstr ""
+
+#: wagons.lua
+msgid "You can't get on this wagon."
+msgstr ""
+
+#: wagons.lua
+#, fuzzy
+msgid "You don't have the train_operator privilege."
+msgstr "您没有“@1”权限。"
+
+#: wagons.lua
+msgid "You have been given ownership of wagon @1"
+msgstr ""
+
+#~ msgid "3-way turnout"
+#~ msgstr "三开道岔"
+
+#~ msgid "90+Angle Diamond Crossing Track"
+#~ msgstr "交叉轨道 (其中一条轨道与坐标轴平行)"
+
+#~ msgid "ATC controller"
+#~ msgstr "ATC 控制器"
+
+#~ msgid ""
+#~ "ATC controller, mode @1\n"
+#~ "Channel: @2"
+#~ msgstr ""
+#~ "ATC 控制器\n"
+#~ "模式:@1\n"
+#~ "频道:@2"
+
+#~ msgid "Access to @1"
+#~ msgstr "可前往@1"
+
+#~ msgid "Big Industrial Train Engine"
+#~ msgstr "大型工业用火车头"
+
+#~ msgid "Box Wagon"
+#~ msgstr "货运车厢"
+
+#~ msgid "Bumper"
+#~ msgstr "保险杠"
+
+#~ msgid "Can't get on: wagon full or doors closed!"
+#~ msgstr "无法上车:车门已关闭或车厢已满。"
+
+#~ msgid "Can't place: protected position!"
+#~ msgstr "无法放置:此区域已被保护。"
+
+#~ msgid "Command (on)"
+#~ msgstr "命令 (激活时)"
+
+#~ msgid "Default Seat"
+#~ msgstr "默认座位"
+
+#~ msgid "Default Seat (driver stand)"
+#~ msgstr "默认座位 (司机座位)"
+
+#~ msgid "Dep. Speed"
+#~ msgstr "出发速度"
+
+#~ msgid "Deprecated Track"
+#~ msgstr "请不要使用"
+
+#~ msgid "Detailed Steam Engine"
+#~ msgstr "精细的蒸汽机车"
+
+#~ msgid "Detector Rail"
+#~ msgstr "探测轨道"
+
+#~ msgid "Diagonal Diamond Crossing Track"
+#~ msgstr "交叉轨道"
+
+#~ msgid "Door Delay"
+#~ msgstr "车门关闭时间"
+
+#, fuzzy
+#~ msgid "Driver Stand"
+#~ msgstr "司机座位"
+
+#~ msgid "Driver Stand (left)"
+#~ msgstr "左侧司机座位"
+
+#~ msgid "Driver Stand (right)"
+#~ msgstr "右侧司机座位"
+
+#~ msgid "Driver stand"
+#~ msgstr "司机座位"
+
+#~ msgid "Industrial Train Engine"
+#~ msgstr "工业用火车头"
+
+#~ msgid "Industrial tank wagon"
+#~ msgstr "液体运输车厢"
+
+#~ msgid "Industrial wood wagon"
+#~ msgstr "木材运输车厢"
+
+#~ msgid "Japanese Train Engine"
+#~ msgstr "高速列车车头"
+
+#~ msgid "Japanese Train Inter-Wagon Connection"
+#~ msgstr "日本火车车钩"
+
+#~ msgid "Japanese Train Wagon"
+#~ msgstr "高速列车车厢"
+
+#, fuzzy
+#~ msgid "Japanese signal pole"
+#~ msgstr "高速列车车厢"
+
+#~ msgid "Kick out passengers"
+#~ msgstr "踢出乘客"
+
+#~ msgid "Loading Track"
+#~ msgstr "装货轨道"
+
+#~ msgid "Lock couples"
+#~ msgstr "锁定连接处"
+
+#~ msgid "Passenger Wagon"
+#~ msgstr "客车"
+
+#, fuzzy
+#~ msgid "Passenger area"
+#~ msgstr "客车"
+
+#~ msgid ""
+#~ "Passive Component Naming Tool\n"
+#~ "\n"
+#~ "Right-click to name a passive component."
+#~ msgstr ""
+#~ "被动元件命名工具\n"
+#~ "\n"
+#~ "右键单击命名所选元件。"
+
+#~ msgid "Perpendicular Diamond Crossing Track"
+#~ msgstr "垂直交叉轨道"
+
+#~ msgid "Reverse train"
+#~ msgstr "改变行车方向"
+
+#~ msgid "Signal"
+#~ msgstr "信号灯"
+
+#~ msgid "Speed:"
+#~ msgstr "速度"
+
+#~ msgid "Station Code"
+#~ msgstr "车站代码"
+
+#~ msgid "Station Name"
+#~ msgstr "车站名称"
+
+#~ msgid "Station/Stop Track"
+#~ msgstr "车站轨道"
+
+#~ msgid "Steam Engine"
+#~ msgstr "蒸汽机车"
+
+#~ msgid "Stop Time"
+#~ msgstr "停站时间"
+
+#~ msgid "Subway Passenger Wagon"
+#~ msgstr "地铁车厢"
+
+#~ msgid "Target:"
+#~ msgstr "目标速度"
+
+#, fuzzy
+#~ msgid "This node can't be rotated using the trackworker,"
+#~ msgstr "您不能使用铁路调整工具旋转这个方块。"
+
+#~ msgid "This position is protected!"
+#~ msgstr "这里已被保护。"
+
+#~ msgid "This track can not be changed."
+#~ msgstr "您不能调整这段轨道。"
+
+#~ msgid "Track"
+#~ msgstr "轨道"
+
+#, fuzzy
+#~ msgid "Train "
+#~ msgstr "已复制列车。"
+
+#~ msgid "Unconfigured LuaATC component"
+#~ msgstr "LuaATC 部件 (未配置)"
+
+#~ msgid "Unloading Track"
+#~ msgstr "卸货轨道"
+
+#~ msgid "Use Sneak+rightclick to bypass closed doors!"
+#~ msgstr "请使用潜行+右键上车。"
+
+#~ msgid "Y-turnout"
+#~ msgstr "对称道岔"
+
+#~ msgid ""
+#~ "You are not allowed to configure this LuaATC component without the @1 "
+#~ "privilege."
+#~ msgstr "您没有“@1”权限,不能配置这个 LuaATC 部件。"
+
+#~ msgid ""
+#~ "You are not allowed to configure this track without the @1 privilege."
+#~ msgstr "您没有“@1”权限,不能调整这段轨道。"
+
+#~ msgid "You are not allowed to configure this track."
+#~ msgstr "您不能调整这段轨道。"
+
+#, fuzzy
+#~ msgid "You are not allowed to modify this protected track."
+#~ msgstr "这里已被保护,您不能在这里建造铁路。"
+
+#~ msgid ""
+#~ "You are not allowed to name LuaATC passive components without the @1 "
+#~ "privilege."
+#~ msgstr "您没有“@1”权限,不能命名被动元件。"
+
+#~ msgid ""
+#~ "You need to own at least one neighboring wagon to destroy this couple."
+#~ msgstr "您必须至少拥有其中一节车厢才能分开这两节车厢。"
diff --git a/advtrains/locale/advtrains.zh_TW.po b/advtrains/locale/advtrains.zh_TW.po
new file mode 100644
index 0000000..5801f59
--- /dev/null
+++ b/advtrains/locale/advtrains.zh_TW.po
@@ -0,0 +1,860 @@
+msgid ""
+msgstr ""
+"Project-Id-Version: advtrains\n"
+"Report-Msgid-Bugs-To: advtrains-discuss@lists.sr.ht\n"
+"POT-Creation-Date: 2026-05-17 09:18+0800\n"
+"PO-Revision-Date: 2026-05-17 09:27+0800\n"
+"Last-Translator: Y. Wang <yw05@forksworld.de>\n"
+"Language-Team: Chinese (Traditional)\n"
+"Language: zh_TW\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"X-Generator: Poedit 3.8\n"
+
+#: atc.lua
+msgid "ATC Kick command warning: doors are closed."
+msgstr "ATC 警告:車門已關閉,無法踢出乘客。"
+
+#: atc.lua
+msgid "ATC Kick command warning: train moving."
+msgstr "ATC 警告:火車正在移動,無法踢出乘客。"
+
+#: atc.lua
+msgid "ATC Reverse command warning: didn't reverse train, train moving."
+msgstr "ATC 警告:火車正在移動,無法改變行車方向。"
+
+#: atc.lua
+msgid "ATC command parse error: Unknown command: @1"
+msgstr "ATC 語法錯誤:未知命令:@1"
+
+#: atc.lua
+msgid "ATC command syntax error: I statement not closed: @1"
+msgstr "ATC 語法錯誤:「I」命令不完整:@1"
+
+#: atc.lua
+#, fuzzy
+msgid "ATC controller, Command: @1"
+msgstr ""
+"ATC 控制器\n"
+"模式:@1\n"
+"命令:@2"
+
+#: atc.lua
+msgid "Command"
+msgstr "命令"
+
+#: atc.lua
+msgid "Digiline channel"
+msgstr "Digiline 頻道"
+
+#: atc.lua wagons.lua
+msgid "Save"
+msgstr "儲存"
+
+#: atc.lua
+msgid "Unconfigured ATC controller"
+msgstr "ATC 控制器 (未配置)"
+
+#: copytool.lua
+msgid "Back of train would end up off track, cancelling."
+msgstr "火車後部不在軌道上。"
+
+#: copytool.lua
+msgid "No such lua entity."
+msgstr "您沒有指向一個可以用火車複製工具複製的物體。"
+
+#: copytool.lua
+msgid "No such train: @1."
+msgstr "ID 為「@1」的列車不存在。"
+
+#: copytool.lua
+msgid "No such wagon: @1."
+msgstr "ID 為「@1」的車廂不存在。"
+
+#: copytool.lua
+msgid "The clipboard couldn't access the metadata. Copy failed."
+msgstr "無法複製:剪貼簿無法訪問元資料。"
+
+#: copytool.lua
+msgid "The clipboard couldn't access the metadata. Paste failed."
+msgstr "無法貼上:剪貼簿無法訪問元資料。"
+
+#: copytool.lua
+msgid "The clipboard is empty."
+msgstr "剪貼簿是空的。"
+
+#: copytool.lua
+msgid "The track you are trying to place the wagon on is not long enough."
+msgstr "軌道太短。"
+
+#: copytool.lua
+msgid "Train copied."
+msgstr "已複製火車。"
+
+#: copytool.lua
+msgid ""
+"Train copy/paste tool\n"
+"\n"
+"Left-click: copy train\n"
+"Right-click: paste train"
+msgstr ""
+"火車複製工具\n"
+"\n"
+"左鍵單擊:複製\n"
+"右鍵單擊:粘帖"
+
+#: copytool.lua
+msgid "You do not have the @1 privilege."
+msgstr "您沒有「@1」許可權。"
+
+#: couple.lua
+msgid "<No coupler>"
+msgstr "<無連結器>"
+
+#: couple.lua
+msgid "Buffer and Chain Coupler"
+msgstr "鏈式連結器"
+
+#: couple.lua
+msgid "Can not couple: The couplers of the trains do not match (@1 and @2)."
+msgstr "您無法連結這兩節車廂:這兩節車廂使用不同的連結器 (@1和@2)。"
+
+#: couple.lua
+msgid ""
+"Cannot couple @1 and @2 - train would have length @3 which is above the "
+"limit of @4"
+msgstr ""
+
+#: couple.lua
+msgid "Scharfenberg Coupler"
+msgstr "Scharfenberg 式連結器"
+
+#: couple.lua
+msgid ""
+"You are not allowed to couple trains without the train_operator privilege."
+msgstr "您沒有「train_operator」許可權,不能連結這兩節車廂。"
+
+#: craft_items.lua
+msgid "Boiler"
+msgstr "鍋爐"
+
+#: craft_items.lua
+msgid "Chimney"
+msgstr "煙囪"
+
+#: craft_items.lua
+msgid "Driver's cab"
+msgstr "駕駛室"
+
+#: craft_items.lua
+msgid "Wheel"
+msgstr "車輪"
+
+#: init.lua
+msgid "Advtrains Status: no_action @1 slowdown @2 (log @3)"
+msgstr ""
+
+#: init.lua
+msgid "Advtrains is already running normally!"
+msgstr ""
+
+#: init.lua
+msgid ""
+"Crash during advtrains main step - skipping the shutdown save operation to "
+"not save inconsistent data!"
+msgstr ""
+
+#: init.lua
+msgid ""
+"Data is being saved. While saving, advtrains will remove the players from "
+"trains. Save files will be reloaded afterwards!"
+msgstr ""
+
+#: init.lua
+msgid "Delete all train routes, force them to recalculate"
+msgstr ""
+
+#: init.lua
+msgid ""
+"Detach all players, especially the offline ones, from all trains. Use only "
+"when no one serious is on a train."
+msgstr ""
+
+#: init.lua
+msgid "Disable the advtrains globalstep temporarily"
+msgstr ""
+
+#: init.lua
+msgid "Disabled advtrains successfully"
+msgstr ""
+
+#: init.lua
+msgid "Instructed to save() but load() was never called!"
+msgstr ""
+
+#: init.lua
+msgid "Print advtrains status info"
+msgstr ""
+
+#: init.lua
+msgid "Re-enabling advtrains globalstep..."
+msgstr ""
+
+#: init.lua
+msgid "Reload successful!"
+msgstr ""
+
+#: init.lua
+msgid "Removing unused wagon"
+msgstr ""
+
+#: init.lua
+msgid "Restoring saved state in 1 second..."
+msgstr ""
+
+#: init.lua
+msgid "Returns the position of the train with the given id"
+msgstr ""
+
+#: init.lua
+msgid "Saving failed: @1"
+msgstr ""
+
+#: init.lua
+msgid "Successfully invalidated train routes"
+msgstr ""
+
+#: init.lua
+msgid "Teleporting to train @1"
+msgstr ""
+
+#: init.lua
+msgid "Teleports you to the position of the train with the given id"
+msgstr ""
+
+#: init.lua
+msgid ""
+"The advtrains globalstep has been disabled. Trains are not moving, and no "
+"data is saved! Run '/at_disable_step no' to enable again!"
+msgstr ""
+
+#: init.lua
+msgid "Train @1 does not exist or is invalid"
+msgstr ""
+
+#: init.lua
+msgid ""
+"Train @1 had no wagons left because of some bug. It is being deleted. Wave "
+"it goodbye!"
+msgstr ""
+
+#: init.lua
+msgid "Train @1 is at @2"
+msgstr ""
+
+#: init.lua
+msgid "from wagon_save table."
+msgstr ""
+
+#: misc_nodes.lua
+msgid "@1 Platform (45 degree)"
+msgstr "較高的@1月臺 (45°)"
+
+#: misc_nodes.lua
+msgid "@1 Platform (high)"
+msgstr "較高的@1月臺"
+
+#: misc_nodes.lua
+msgid "@1 Platform (low)"
+msgstr "較低的@1月臺"
+
+#: misc_nodes.lua
+msgid "@1 Platform (low, 45 degree)"
+msgstr "較低的@1月臺 (45°)"
+
+#: protection.lua
+msgid "Can operate turnouts and signals in unprotected areas"
+msgstr ""
+
+#: protection.lua
+msgid "Can place and dig tracks in unprotected areas"
+msgstr ""
+
+#: protection.lua
+msgid ""
+"Can place, remove and operate any train, regardless of owner, whitelist, or "
+"protection"
+msgstr ""
+
+#: protection.lua
+msgid "Can place, remove and operate trains"
+msgstr ""
+
+#: protection.lua
+msgid "You are not allowed to build near tracks at this protected position."
+msgstr "這裡已被保護,您不能在這裡的鐵路附近建任何東西。"
+
+#: protection.lua
+msgid ""
+"You are not allowed to build near tracks without the track_builder privilege."
+msgstr "您沒有「train_operator」許可權,不能在鐵路附近建任何東西。"
+
+#: protection.lua
+msgid "You are not allowed to build tracks at this protected position."
+msgstr "這裡已被保護,您不能在這裡建造鐵路。"
+
+#: protection.lua
+msgid ""
+"You are not allowed to build tracks without the track_builder privilege."
+msgstr "您沒有「train_operator」許可權,不能在這裡建造鐵路。"
+
+#: protection.lua
+msgid ""
+"You are not allowed to operate turnouts and signals without the "
+"railway_operator privilege."
+msgstr "您沒有「railway_operator」許可權,不能控制鐵路設施。"
+
+#: signals.lua
+msgid "Andrew's Cross"
+msgstr "平交道號誌燈"
+
+#: signals.lua
+#, fuzzy
+msgid "Lampless Signal (deprecated!)"
+msgstr "臂木式號誌機"
+
+#: signals.lua
+msgid "Signal (deprecated!)"
+msgstr ""
+
+#: signals.lua
+#, fuzzy
+msgid "Wallmounted Signal (left) (deprecated!)"
+msgstr "壁掛式色燈號誌機 (左側)"
+
+#: signals.lua
+#, fuzzy
+msgid "Wallmounted Signal (right) (deprecated!)"
+msgstr "壁掛式色燈號誌機 (右側)"
+
+#: signals.lua
+#, fuzzy
+msgid "Wallmounted Signal (top) (deprecated!)"
+msgstr "懸掛式色燈號誌機"
+
+#: track_reg_helper.lua
+msgid "@1 Slope"
+msgstr "@1斜坡"
+
+#: track_reg_helper.lua
+#, fuzzy
+msgid "Can't place: Not enough slope items left (@1 required)"
+msgstr "無法放置斜坡:您沒有足夠的鐵路斜坡放置工具 (您總共需要@1個)"
+
+#: track_reg_helper.lua
+#, fuzzy
+msgid "Can't place: There's no slope of length @1"
+msgstr "無法放置斜坡:advtrains 不支援長度為@1米的斜坡。"
+
+#: track_reg_helper.lua
+#, fuzzy
+msgid "Can't place: no supporting node at upper end."
+msgstr "無法放置斜坡:較高階沒有支撐方塊。"
+
+#: track_reg_helper.lua
+#, fuzzy
+msgid "Can't place: not pointing at node"
+msgstr "無法放置斜坡:您沒有選擇任何方塊。"
+
+#: track_reg_helper.lua
+#, fuzzy
+msgid "Can't place: space occupied!"
+msgstr "無法放置斜坡:此區域已被佔用。"
+
+#: track_reg_helper.lua tracks.lua
+#, fuzzy
+msgid "This track can not be removed!"
+msgstr "您不能移除這段軌道。"
+
+#: trackplacer.lua
+msgid ""
+"Left-click: change rail type (straight/curve/switch)\n"
+"Right-click: rotate object"
+msgstr ""
+"左鍵單擊:切換軌道型別\n"
+"右鍵單擊:旋轉方塊"
+
+#: trackplacer.lua
+#, fuzzy
+msgid "This node can't be changed using the trackworker!"
+msgstr "您不能使用鐵路調整工具調整這個方塊。"
+
+#: trackplacer.lua
+#, fuzzy
+msgid "This node can't be rotated using the trackworker!"
+msgstr "您不能使用鐵路調整工具旋轉這個方塊。"
+
+#: trackplacer.lua
+#, fuzzy
+msgid "This track can not be rotated!"
+msgstr "您不能旋轉這段軌道。"
+
+#: trackplacer.lua
+msgid "Track Worker Tool"
+msgstr "鐵路調整工具"
+
+#: tracks.lua
+msgid "Position is occupied by a train."
+msgstr ""
+
+#: tracks.lua
+msgid "There's a Signal Influence Point here."
+msgstr ""
+
+#: tracks.lua
+msgid "There's a Track Circuit Break here."
+msgstr ""
+
+#: trainhud.lua
+msgid "OVERRUN RED SIGNAL! Examine situation and reverse train to move again."
+msgstr ""
+
+#: wagonprop_tool.lua
+msgid "Insufficient privileges to use this!"
+msgstr ""
+
+#: wagonprop_tool.lua
+msgid "Punch a wagon to view and edit the Wagon Properties"
+msgstr ""
+
+#: wagonprop_tool.lua
+msgid "Wagon Properties Tool"
+msgstr ""
+
+#: wagons.lua
+msgid " units"
+msgstr ""
+
+#: wagons.lua
+msgid "!!! Train off track !!!"
+msgstr ""
+
+#: wagons.lua
+msgid "(Doors closed)"
+msgstr "(車門已關閉)"
+
+#: wagons.lua
+msgid "Allow these players to access your wagon:"
+msgstr ""
+
+#: wagons.lua
+msgid "Clear 'Disable ARS' flag"
+msgstr ""
+
+#: wagons.lua
+msgid "Current FC: "
+msgstr ""
+
+#: wagons.lua
+msgid ""
+"Destroying wagon with inventory, but inventory is not found? Shouldn't "
+"happen!"
+msgstr ""
+
+#: wagons.lua
+msgid "Doors are closed! (Try holding sneak key!)"
+msgstr ""
+
+#: wagons.lua
+msgid ""
+"Doors are closed. Use Sneak+rightclick to ignore the closed doors and get "
+"off."
+msgstr "車門已關閉,請使用潛行+右鍵單擊下車。"
+
+#: wagons.lua
+msgid "Freight Code:"
+msgstr ""
+
+#: wagons.lua
+msgid "Get off"
+msgstr "下車"
+
+#: wagons.lua
+msgid "Get off (forced)"
+msgstr "強制下車"
+
+#: wagons.lua
+msgid "Line"
+msgstr "火車線路"
+
+#: wagons.lua
+msgid "Liquid: "
+msgstr ""
+
+#: wagons.lua
+msgid "Liquid: empty"
+msgstr ""
+
+#: wagons.lua
+msgid "Missing train_operator privilege"
+msgstr ""
+
+#: wagons.lua
+msgid "Next FC:"
+msgstr ""
+
+#: wagons.lua
+msgid "Not a valid wagon id."
+msgstr ""
+
+#: wagons.lua
+#, fuzzy
+msgid "Not allowed to do this."
+msgstr "您不能調整這段軌道。"
+
+#: wagons.lua
+msgid "Onboard Computer"
+msgstr ""
+
+#: wagons.lua
+msgid "Please specify a player name to transfer ownership to."
+msgstr ""
+
+#: wagons.lua
+msgid "Prev FC"
+msgstr ""
+
+#: wagons.lua
+msgid "Remote Routesetting"
+msgstr ""
+
+#: wagons.lua
+msgid "Routingcode"
+msgstr "路由碼"
+
+#: wagons.lua
+msgid "Save wagon properties"
+msgstr "儲存車廂屬性"
+
+#: wagons.lua
+msgid "Select seat:"
+msgstr "請選擇座位:"
+
+#: wagons.lua
+msgid "Show Inventory"
+msgstr "顯示物品欄"
+
+#: wagons.lua
+msgid "Text displayed inside train"
+msgstr "車廂內部顯示"
+
+#: wagons.lua
+msgid "Text displayed outside on train"
+msgstr "車廂外部顯示"
+
+#: wagons.lua
+msgid "That player does not exist!"
+msgstr ""
+
+#: wagons.lua
+#, fuzzy
+msgid "That wagon does not exist!"
+msgstr "這節車廂沒有座位。"
+
+#: wagons.lua
+#, fuzzy
+msgid "The track you are trying to place the wagon on is not long enough!"
+msgstr "軌道太短。"
+
+#: wagons.lua
+msgid "The wagon's inventory is not empty."
+msgstr ""
+
+#: wagons.lua
+#, fuzzy
+msgid "This Wagon ID"
+msgstr "車廂已滿。"
+
+#: wagons.lua
+msgid "This wagon has no seats."
+msgstr "這節車廂沒有座位。"
+
+#: wagons.lua
+msgid "This wagon is full."
+msgstr "車廂已滿。"
+
+#: wagons.lua
+msgid "This wagon is owned by @1, you can't destroy it."
+msgstr "這是 @1 的車廂,您不能摧毀它。"
+
+#: wagons.lua
+msgid "Train ID"
+msgstr ""
+
+#: wagons.lua
+msgid "Train overview / coupling control is only shown when the train stands."
+msgstr ""
+
+#: wagons.lua
+msgid "Train overview /coupling control:"
+msgstr ""
+
+#: wagons.lua
+msgid "Uninitialized, removing"
+msgstr ""
+
+#: wagons.lua
+msgid "Wagon @1 ownership changed from @2 to @3"
+msgstr ""
+
+#: wagons.lua
+msgid "Wagon needs to be decoupled from other wagons in order to destroy it."
+msgstr ""
+
+#: wagons.lua
+#, fuzzy
+msgid "Wagon placeholder"
+msgstr "車廂屬性"
+
+#: wagons.lua
+msgid "Wagon properties"
+msgstr "車廂屬性"
+
+#: wagons.lua
+msgid "Wagon road number:"
+msgstr ""
+
+#: wagons.lua
+msgid ""
+"Warning: If you destroy this wagon, you only get some steel back! If you are "
+"sure, hold Sneak and left-click the wagon."
+msgstr ""
+"警告:如果您摧毀此車廂,您只能拿到一些鋼方塊。如果您確定要摧毀這節車廂,請按"
+"潛行鍵並左鍵單擊此車廂。"
+
+#: wagons.lua
+msgid "You are not allowed to access the driver stand."
+msgstr ""
+
+#: wagons.lua
+msgid "You can't get on this wagon."
+msgstr ""
+
+#: wagons.lua
+#, fuzzy
+msgid "You don't have the train_operator privilege."
+msgstr "您沒有「@1」許可權。"
+
+#: wagons.lua
+msgid "You have been given ownership of wagon @1"
+msgstr ""
+
+#~ msgid "3-way turnout"
+#~ msgstr "三開道岔"
+
+#~ msgid "90+Angle Diamond Crossing Track"
+#~ msgstr "交叉軌道 (其中一條軌道與座標軸平行)"
+
+#~ msgid "ATC controller"
+#~ msgstr "ATC 控制器"
+
+#~ msgid ""
+#~ "ATC controller, mode @1\n"
+#~ "Channel: @2"
+#~ msgstr ""
+#~ "ATC 控制器\n"
+#~ "模式:@1\n"
+#~ "頻道:@2"
+
+#~ msgid "Access to @1"
+#~ msgstr "可前往@1"
+
+#~ msgid "Big Industrial Train Engine"
+#~ msgstr "大型工業用火車頭"
+
+#~ msgid "Box Wagon"
+#~ msgstr "貨運車廂"
+
+#~ msgid "Bumper"
+#~ msgstr "保險槓"
+
+#~ msgid "Can't get on: wagon full or doors closed!"
+#~ msgstr "無法上車:車門已關閉或車廂已滿。"
+
+#~ msgid "Can't place: protected position!"
+#~ msgstr "無法放置:此區域已被保護。"
+
+#~ msgid "Command (on)"
+#~ msgstr "命令 (啟用時)"
+
+#~ msgid "Default Seat"
+#~ msgstr "預設座位"
+
+#~ msgid "Default Seat (driver stand)"
+#~ msgstr "預設座位 (司機座位)"
+
+#~ msgid "Dep. Speed"
+#~ msgstr "出發速度"
+
+#~ msgid "Deprecated Track"
+#~ msgstr "請不要使用"
+
+#~ msgid "Detailed Steam Engine"
+#~ msgstr "精細的蒸汽機車"
+
+#~ msgid "Detector Rail"
+#~ msgstr "探測軌道"
+
+#~ msgid "Diagonal Diamond Crossing Track"
+#~ msgstr "交叉軌道"
+
+#~ msgid "Door Delay"
+#~ msgstr "車門關閉時間"
+
+#, fuzzy
+#~ msgid "Driver Stand"
+#~ msgstr "司機座位"
+
+#~ msgid "Driver Stand (left)"
+#~ msgstr "左側司機座位"
+
+#~ msgid "Driver Stand (right)"
+#~ msgstr "右側司機座位"
+
+#~ msgid "Driver stand"
+#~ msgstr "司機座位"
+
+#~ msgid "Industrial Train Engine"
+#~ msgstr "工業用火車頭"
+
+#~ msgid "Industrial tank wagon"
+#~ msgstr "液體運輸車廂"
+
+#~ msgid "Industrial wood wagon"
+#~ msgstr "木材運輸車廂"
+
+#~ msgid "Japanese Train Engine"
+#~ msgstr "高速列車車頭"
+
+#~ msgid "Japanese Train Inter-Wagon Connection"
+#~ msgstr "日本火車連結器"
+
+#~ msgid "Japanese Train Wagon"
+#~ msgstr "高速列車車廂"
+
+#, fuzzy
+#~ msgid "Japanese signal pole"
+#~ msgstr "高速列車車廂"
+
+#~ msgid "Kick out passengers"
+#~ msgstr "踢出乘客"
+
+#~ msgid "Loading Track"
+#~ msgstr "裝貨軌道"
+
+#~ msgid "Lock couples"
+#~ msgstr "鎖定連結處"
+
+#~ msgid "Passenger Wagon"
+#~ msgstr "客車"
+
+#, fuzzy
+#~ msgid "Passenger area"
+#~ msgstr "客車"
+
+#~ msgid ""
+#~ "Passive Component Naming Tool\n"
+#~ "\n"
+#~ "Right-click to name a passive component."
+#~ msgstr ""
+#~ "被動元件命名工具\n"
+#~ "\n"
+#~ "右鍵單擊命名所選元件。"
+
+#~ msgid "Perpendicular Diamond Crossing Track"
+#~ msgstr "垂直交叉軌道"
+
+#~ msgid "Reverse train"
+#~ msgstr "改變行車方向"
+
+#~ msgid "Signal"
+#~ msgstr "色燈號誌機"
+
+#~ msgid "Speed:"
+#~ msgstr "速度"
+
+#~ msgid "Station Code"
+#~ msgstr "車站碼"
+
+#~ msgid "Station Name"
+#~ msgstr "車站名稱"
+
+#~ msgid "Station/Stop Track"
+#~ msgstr "車站軌道"
+
+#~ msgid "Steam Engine"
+#~ msgstr "蒸汽機車"
+
+#~ msgid "Stop Time"
+#~ msgstr "停站時間"
+
+#~ msgid "Subway Passenger Wagon"
+#~ msgstr "地鐵車廂"
+
+#~ msgid "Target:"
+#~ msgstr "目標速度"
+
+#, fuzzy
+#~ msgid "This node can't be rotated using the trackworker,"
+#~ msgstr "您不能使用鐵路調整工具旋轉這個方塊。"
+
+#~ msgid "This position is protected!"
+#~ msgstr "這裡已被保護。"
+
+#~ msgid "This track can not be changed."
+#~ msgstr "您不能調整這段軌道。"
+
+#~ msgid "Track"
+#~ msgstr "軌道"
+
+#, fuzzy
+#~ msgid "Train "
+#~ msgstr "已複製火車。"
+
+#~ msgid "Unconfigured LuaATC component"
+#~ msgstr "LuaATC 元件 (未配置)"
+
+#~ msgid "Unloading Track"
+#~ msgstr "卸貨軌道"
+
+#~ msgid "Use Sneak+rightclick to bypass closed doors!"
+#~ msgstr "請使用潛行+右鍵上車。"
+
+#~ msgid "Y-turnout"
+#~ msgstr "對稱道岔"
+
+#~ msgid ""
+#~ "You are not allowed to configure this LuaATC component without the @1 "
+#~ "privilege."
+#~ msgstr "您沒有「@1」許可權,不能配置這個 LuaATC 元件。"
+
+#~ msgid ""
+#~ "You are not allowed to configure this track without the @1 privilege."
+#~ msgstr "您沒有「@1」許可權,不能調整這段軌道。"
+
+#~ msgid "You are not allowed to configure this track."
+#~ msgstr "您不能調整這段軌道。"
+
+#, fuzzy
+#~ msgid "You are not allowed to modify this protected track."
+#~ msgstr "這裡已被保護,您不能在這裡建造鐵路。"
+
+#~ msgid ""
+#~ "You are not allowed to name LuaATC passive components without the @1 "
+#~ "privilege."
+#~ msgstr "您沒有「@1」許可權,不能命名這個元件。"
+
+#~ msgid ""
+#~ "You need to own at least one neighboring wagon to destroy this couple."
+#~ msgstr "您必須至少擁有其中一節車廂才能分開這兩節車廂。"
diff --git a/advtrains/log.lua b/advtrains/log.lua
new file mode 100644
index 0000000..d7053a2
--- /dev/null
+++ b/advtrains/log.lua
@@ -0,0 +1,17 @@
+-- Log accesses to driver stands and changes to switches
+
+advtrains.log = function() end
+
+if minetest.settings:get_bool("advtrains_enable_logging") then
+ advtrains.logfile = advtrains.fpath .. "_log"
+
+ local log = io.open(advtrains.logfile, "a+")
+
+ function advtrains.log (event, player, pos, data)
+ log:write(os.date()..": "..event.." by "..player.." at "..minetest.pos_to_string(pos).." -- "..(data or "").."\n")
+ end
+
+ minetest.register_on_shutdown(function()
+ log:close()
+ end)
+end
diff --git a/advtrains/lzb.lua b/advtrains/lzb.lua
new file mode 100644
index 0000000..116777c
--- /dev/null
+++ b/advtrains/lzb.lua
@@ -0,0 +1,285 @@
+-- lzb.lua
+-- Enforced and/or automatic train override control, providing the on_train_approach callback
+
+--[[
+Documentation of train.lzb table
+train.lzb = {
+ trav_index = Current index that the traverser has advanced so far
+ checkpoints = table containing oncoming signals, in order of index
+ {
+ pos = position of the point
+ index = where this is on the path
+ speed = speed allowed to pass. nil = no effect
+ callback = function(pos, id, train, index, speed, lzbdata)
+ -- Function that determines what to do on the train in the moment it drives over that point.
+ -- When spd==0, called instead when train has stopped in front
+ -- nil = no effect
+ lzbdata = {}
+ -- Table of custom data filled in by approach callbacks
+ -- Whenever an approach callback inserts an LZB checkpoint with changed lzbdata,
+ -- all consecutive approach callbacks will see these passed as lzbdata table.
+
+ udata = arbitrary user data, no official way to retrieve (do not use)
+ }
+ trav_lzbdata = currently active lzbdata table at traverser index
+}
+The LZB subsystem keeps track of "checkpoints" the train will pass in the future, and has two main tasks:
+1. run approach callbacks, and run callbacks when passing LZB checkpoints
+2. keep track of the permitted speed at checkpoints, and make sure that the train brakes accordingly
+To perform 2, it populates the train.path_speed table which is handled along with the path subsystem.
+This table is used in trainlogic.lua/train_step_b() and applied to the velocity calculations.
+
+Note: As of 2024-11-25, node enter callbacks as well as LZB callbacks are executed on passing the .0 index mark!
+If an LZB checkpoint has speed 0, it will stop at the 0.9 index mark (for details, see SLOW_APPROACH in trainlogic.lua) and will not enter the node.
+(previous behavior: node enter callback was called at .5 index mark)
+
+The start point for the LZB traverser (and thus the first node that will receive an approach callback) is floor(train.index) + 1. This means, once the LZB checkpoint callback has fired,
+this path node will not receive any further approach callbacks for the same approach situation
+]]
+
+
+local params = {
+ BRAKE_SPACE = 10,
+ AWARE_ZONE = 50,
+
+ ADD_STAND = 2.5,
+ ADD_SLOW = 1.5,
+ ADD_FAST = 7,
+ ZONE_ROLL = 2,
+ ZONE_HOLD = 5, -- added on top of ZONE_ROLL
+ ZONE_VSLOW = 3, -- When speed is <2, still allow accelerating
+
+ DST_FACTOR = 3,--1.5,
+
+ SHUNT_SPEED_MAX = advtrains.SHUNT_SPEED_MAX,
+}
+
+function advtrains.set_lzb_param(par, val)
+ if params[par] and tonumber(val) then
+ params[par] = tonumber(val)
+ else
+ error("Inexistant param or not a number")
+ end
+end
+
+local function resolve_latest_lzbdata(ckp, index)
+ local i = #ckp
+ local ckpi
+ while i>0 do
+ ckpi = ckp[i]
+ if ckpi.index <= index and ckpi.lzbdata then
+ return ckpi.lzbdata
+ end
+ i=i-1
+ end
+ return {}
+end
+
+local function look_ahead(id, train)
+ local lzb = train.lzb
+ if lzb.zero_checkpoint then
+ -- if the checkpoints list contains a zero checkpoint, don't look ahead
+ -- in order to not trigger approach callbacks on the wrong path
+ return
+ end
+
+ local acc = advtrains.get_acceleration(train, 1)
+ -- worst-case: the starting point is maximum speed
+ local vel = train.max_speed or train.velocity
+ local brakedst = ( -(vel*vel) / (2*acc) ) * params.DST_FACTOR
+
+ --local brake_i = advtrains.path_get_index_by_offset(train, train.index, brakedst + params.BRAKE_SPACE)
+ -- worst case (don't use index_by_offset)
+ local brake_i = atfloor(train.index + brakedst + params.BRAKE_SPACE)
+ --atprint("LZB: looking ahead up to ", brake_i)
+
+ --local aware_i = advtrains.path_get_index_by_offset(train, brake_i, AWARE_ZONE)
+
+ local trav = lzb.trav_index
+ -- retrieve latest lzbdata
+ if not lzb.trav_lzbdata then
+ lzb.trav_lzbdata = resolve_latest_lzbdata(lzb.checkpoints, trav)
+ end
+
+ if lzb.trav_lzbdata.off_track then
+ --previous position was off track, do not scan any further
+ end
+
+ while trav <= brake_i and not lzb.zero_checkpoint do
+ local pos = advtrains.path_get(train, trav)
+ -- check offtrack
+ if trav - 1 == train.path_trk_f then
+ lzb.trav_lzbdata.off_track = true
+ advtrains.lzb_add_checkpoint(train, trav - 1, 0, nil, lzb.trav_lzbdata)
+ else
+ -- run callbacks
+ -- Note: those callbacks are defined in trainlogic.lua for consistency with the other node callbacks
+ advtrains.tnc_call_approach_callback(pos, id, train, trav, lzb.trav_lzbdata)
+
+ end
+ trav = trav + 1
+
+ end
+
+ lzb.trav_index = trav
+
+end
+advtrains.lzb_look_ahead = look_ahead
+
+
+local function call_runover_callbacks(id, train)
+ if not train.lzb then return end
+
+ local i = 1
+ local idx = atfloor(train.index)
+ local ckp = train.lzb.checkpoints
+ while ckp[i] do
+ if ckp[i].index <= idx then
+ --atprint("LZB: checkpoint run over: i=",ckp[i].index,"s=",ckp[i].speed,"p=",ckp[i].pos)
+ -- call callback
+ local it = ckp[i]
+ if it.callback then
+ it.callback(it.pos, id, train, it.index, it.speed, train.lzb.lzbdata)
+ end
+ -- note: lzbdata is always defined as look_ahead was called before
+ table.remove(ckp, i)
+ else
+ i = i + 1
+ end
+ end
+end
+
+-- Flood-fills train.path_speed, based on this checkpoint
+local function apply_checkpoint_to_path(train, checkpoint)
+ if not checkpoint.speed then
+ return
+ end
+ --atprint("LZB: applying checkpoint: i=",checkpoint.index,"s=",checkpoint.speed,"p=",checkpoint.pos)
+
+ if checkpoint.speed == 0 then
+ train.lzb.zero_checkpoint = true
+ end
+
+ -- make sure path exists until checkpoint
+ local pos = advtrains.path_get(train, checkpoint.index)
+
+ local brake_accel = advtrains.get_acceleration(train, 11)
+
+ -- start with the checkpoint index at specified speed
+ local index = checkpoint.index
+ local p_speed -- speed in path_speed
+ local c_speed = checkpoint.speed -- calculated speed at current index
+ while true do
+ p_speed = train.path_speed[index]
+ if (p_speed and p_speed <= c_speed) or index < train.index then
+ --we're done. train already slower than wanted at this position
+ return
+ end
+ -- insert calculated target speed
+ train.path_speed[index] = c_speed
+ -- calculate c_speed at previous index
+ advtrains.path_get(train, index-1)
+ local eldist = train.path_dist[index] - train.path_dist[index-1]
+ -- Calculate the start velocity the train would have if it had a end velocity of c_speed and accelerating with brake_accel, after a distance of eldist:
+ -- v0² = v1² - 2*a*s
+ c_speed = math.sqrt( (c_speed * c_speed) - (2 * brake_accel * eldist) )
+ index = index - 1
+ end
+end
+
+--[[
+Distance needed to accelerate from v0 to v1 with constant acceleration a:
+
+ v1 - v0 a / v1 - v0 \ 2 v1^2 - v0^2
+s = v0 * ------- + - * | ------- | = -----------
+ a 2 \ a / 2*a
+]]
+
+-- Removes all LZB checkpoints and restarts the traverser at the current train index
+function advtrains.lzb_invalidate(train)
+ --advtrains.atprint_context_tid = train.id
+ --atprint("LZB: invalidate")
+ --advtrains.atprint_context_tid = nil
+ train.lzb = {
+ trav_index = atfloor(train.index) + 1,
+ checkpoints = {},
+ }
+end
+
+-- LZB part of path_invalidate_ahead. Clears all checkpoints that are ahead of start_idx
+-- in contrast to path_inv_ahead, doesn't complain if start_idx is behind train.index, clears everything then
+function advtrains.lzb_invalidate_ahead(train, start_idx)
+ --advtrains.atprint_context_tid = train.id
+ --atprint("LZB: invalidate ahead i=",start_idx)
+ if train.lzb then
+ local idx = atfloor(start_idx)
+ --atprint("LZB: invalidate ahead p=",train.path[start_idx])
+ local i = 1
+ while train.lzb.checkpoints[i] do
+ if train.lzb.checkpoints[i].index >= idx then
+ table.remove(train.lzb.checkpoints, i)
+ else
+ i=i+1
+ end
+ end
+ train.lzb.trav_index = idx
+ -- FIX reset trav_lzbdata (look_ahead fetches these when required)
+ train.lzb.trav_lzbdata = nil
+ -- re-apply all checkpoints to path_speed
+ train.path_speed = {}
+ train.lzb.zero_checkpoint = false
+ for _,ckp in ipairs(train.lzb.checkpoints) do
+ apply_checkpoint_to_path(train, ckp)
+ end
+ end
+ --advtrains.atprint_context_tid = nil
+end
+
+-- Add LZB control point
+-- lzbdata: If you modify lzbdata in an approach callback, you MUST add a checkpoint AND pass the (modified) lzbdata into it.
+-- If you DON'T modify lzbdata, you MUST pass nil as lzbdata. Always modify the lzbdata table in place, never overwrite it!
+-- udata: user-defined data, do not use externally
+function advtrains.lzb_add_checkpoint(train, index, speed, callback, lzbdata, udata)
+ local lzb = train.lzb
+ local pos = advtrains.path_get(train, index)
+ local lzbdata_c = nil
+ if lzbdata then
+ -- make a shallow copy of lzbdata
+ lzbdata_c = {}
+ for k,v in pairs(lzbdata) do lzbdata_c[k] = v end
+ end
+ local ckp = {
+ pos = pos,
+ index = index,
+ speed = speed,
+ callback = callback,
+ lzbdata = lzbdata_c,
+ udata = udata,
+ }
+ table.insert(lzb.checkpoints, ckp)
+
+ apply_checkpoint_to_path(train, ckp)
+end
+
+
+advtrains.te_register_on_new_path(function(id, train)
+ advtrains.lzb_invalidate(train)
+ -- Taken care of in pre-move hook (see train_step_b)
+ -- 2025-01-28 - do anyway, there seems to be an issue
+ look_ahead(id, train)
+end)
+
+advtrains.te_register_on_invalidate_ahead(function(id, train, start_idx)
+ advtrains.lzb_invalidate_ahead(train, start_idx)
+end)
+
+advtrains.te_register_on_update(function(id, train)
+ if not train.path or not train.lzb then
+ atprint("LZB run: no path on train, skip step")
+ return
+ end
+ -- Note: look_ahead called from train_step_b before applying movement
+ -- TODO: if more pre-move hooks are added, make a separate callback hook
+ --look_ahead(id, train)
+ call_runover_callbacks(id, train)
+end, true)
diff --git a/advtrains/manual.pdf b/advtrains/manual.pdf
deleted file mode 100644
index 68691a2..0000000
--- a/advtrains/manual.pdf
+++ /dev/null
Binary files differ
diff --git a/advtrains/misc_nodes.lua b/advtrains/misc_nodes.lua
new file mode 100644
index 0000000..8720272
--- /dev/null
+++ b/advtrains/misc_nodes.lua
@@ -0,0 +1,126 @@
+--all nodes that do not fit in any other category
+
+-- Get current translator
+local S = advtrains.translate
+
+function advtrains.register_platform(modprefix, preset)
+ local ndef=minetest.registered_nodes[preset]
+ if not ndef then
+ minetest.log("warning", " register_platform couldn't find preset node "..preset)
+ return
+ end
+ local btex=ndef.tiles
+ if type(btex)=="table" then
+ btex=btex[1]
+ end
+ local desc=ndef.description or ""
+ local nodename=string.match(preset, ":(.+)$")
+ minetest.register_node(modprefix .. ":platform_low_"..nodename, {
+ description = S("@1 Platform (low)", desc),
+ tiles = {btex.."^advtrains_platform.png", btex, btex, btex, btex, btex},
+ groups = {cracky = 1, not_blocking_trains = 1, platform=1},
+ sounds = ndef.sounds,
+ drawtype = "nodebox",
+ node_box = {
+ type = "fixed",
+ fixed = {
+ {-0.5, -0.1, -0.1, 0.5, 0 , 0.5},
+ {-0.5, -0.5, 0 , 0.5, -0.1, 0.5}
+ },
+ },
+ paramtype2="facedir",
+ paramtype = "light",
+ sunlight_propagates = true,
+ })
+ minetest.register_node(modprefix .. ":platform_high_"..nodename, {
+ description = S("@1 Platform (high)", desc),
+ tiles = {btex.."^advtrains_platform.png", btex, btex, btex, btex, btex},
+ groups = {cracky = 1, not_blocking_trains = 1, platform=2},
+ sounds = ndef.sounds,
+ drawtype = "nodebox",
+ node_box = {
+ type = "fixed",
+ fixed = {
+ {-0.5, 0.3, 0, 0.5, 0.5, 0.5},
+ {-0.5, -0.5, 0.1 , 0.5, 0.3, 0.5}
+ },
+ },
+ paramtype2="facedir",
+ paramtype = "light",
+ sunlight_propagates = true,
+ })
+ local diagonalbox = {
+ type = "fixed",
+ fixed = {
+ {-0.5, -0.5, 0.5, -0.25, 0.5, -0.8 },
+ {-0.25, -0.5, 0.5 , 0, 0.5, -0.55},
+ {0, -0.5, 0.5 , 0.25, 0.5, -0.3 },
+ {0.25 , -0.5, 0.5, 0.5, 0.5, -0.05}
+ }
+ }
+ minetest.register_node(modprefix..":platform_45_"..nodename, {
+ description = S("@1 Platform (45 degree)", desc),
+ groups = {cracky = 1, not_blocking_trains = 1, platform=2},
+ sounds = ndef.sounds,
+ drawtype = "mesh",
+ mesh = "advtrains_platform_diag.b3d",
+ selection_box = diagonalbox,
+ collision_box = diagonalbox,
+ tiles = {btex, btex.."^advtrains_platform_diag.png"},
+ paramtype2 = "facedir",
+ paramtype = "light",
+ sunlight_propagates = true,
+ })
+ local diagonalbox_low = {
+ type = "fixed",
+ fixed = {
+ {-0.5, -0.5, 0.5, -0.25, 0, -0.8 },
+ {-0.25, -0.5, 0.5 , 0, 0, -0.55},
+ {0, -0.5, 0.5 , 0.25, 0, -0.3 },
+ {0.25 , -0.5, 0.5, 0.5, 0, -0.05}
+ }
+ }
+ minetest.register_node(modprefix..":platform_45_low_"..nodename, {
+ description = S("@1 Platform (low, 45 degree)", desc),
+ groups = {cracky = 1, not_blocking_trains = 1, platform=2},
+ sounds = ndef.sounds,
+ drawtype = "mesh",
+ mesh = "advtrains_platform_diag_low.b3d",
+ selection_box = diagonalbox_low,
+ collision_box = diagonalbox_low,
+ tiles = {btex, btex.."^advtrains_platform_diag.png"},
+ paramtype2 = "facedir",
+ paramtype = "light",
+ sunlight_propagates = true,
+ })
+ minetest.register_craft({
+ type="shapeless",
+ output = modprefix .. ":platform_high_"..nodename.." 4",
+ recipe = {
+ "dye:yellow", preset, preset
+ },
+ })
+ minetest.register_craft({
+ type="shapeless",
+ output = modprefix .. ":platform_low_"..nodename.." 4",
+ recipe = {
+ "dye:yellow", preset
+ },
+ })
+ minetest.register_craft({
+ type="shapeless",
+ output = modprefix .. ":platform_45_"..nodename.." 2",
+ recipe = {
+ "dye:yellow", preset, preset, preset
+ }
+ })
+ minetest.register_craft({
+ type="shapeless",
+ output = modprefix .. ":platform_45_low_"..nodename.." 2",
+ recipe = { modprefix .. ":platform_45_"..nodename },
+ })
+end
+
+
+advtrains.register_platform("advtrains", "default:stonebrick")
+advtrains.register_platform("advtrains", "default:sandstonebrick")
diff --git a/advtrains/mod.conf b/advtrains/mod.conf
new file mode 100644
index 0000000..5808d1a
--- /dev/null
+++ b/advtrains/mod.conf
@@ -0,0 +1,7 @@
+name=advtrains
+title=Advanced Trains Core
+description=Core system for realistic trains in Minetest
+author=orwell96
+
+depends=serialize_lib
+optional_depends=mesecons,mesecons_switch,digtron
diff --git a/advtrains/advtrains/models/advtrains_across.obj b/advtrains/models/advtrains_across.obj
index 4ebf393..4ebf393 100644
--- a/advtrains/advtrains/models/advtrains_across.obj
+++ b/advtrains/models/advtrains_across.obj
diff --git a/advtrains/advtrains/models/advtrains_dtrack_bumper_st.b3d b/advtrains/models/advtrains_dtrack_bumper_st.b3d
index a6d9745..a6d9745 100644
--- a/advtrains/advtrains/models/advtrains_dtrack_bumper_st.b3d
+++ b/advtrains/models/advtrains_dtrack_bumper_st.b3d
Binary files differ
diff --git a/advtrains/advtrains/models/advtrains_dtrack_bumper_st_30.b3d b/advtrains/models/advtrains_dtrack_bumper_st_30.b3d
index 5f5b3f4..5f5b3f4 100644
--- a/advtrains/advtrains/models/advtrains_dtrack_bumper_st_30.b3d
+++ b/advtrains/models/advtrains_dtrack_bumper_st_30.b3d
Binary files differ
diff --git a/advtrains/advtrains/models/advtrains_dtrack_bumper_st_45.b3d b/advtrains/models/advtrains_dtrack_bumper_st_45.b3d
index f13ae75..f13ae75 100644
--- a/advtrains/advtrains/models/advtrains_dtrack_bumper_st_45.b3d
+++ b/advtrains/models/advtrains_dtrack_bumper_st_45.b3d
Binary files differ
diff --git a/advtrains/advtrains/models/advtrains_dtrack_bumper_st_60.b3d b/advtrains/models/advtrains_dtrack_bumper_st_60.b3d
index 59a2285..59a2285 100644
--- a/advtrains/advtrains/models/advtrains_dtrack_bumper_st_60.b3d
+++ b/advtrains/models/advtrains_dtrack_bumper_st_60.b3d
Binary files differ
diff --git a/advtrains/advtrains/models/advtrains_dtrack_cr.b3d b/advtrains/models/advtrains_dtrack_cr.b3d
index c708292..c708292 100644
--- a/advtrains/advtrains/models/advtrains_dtrack_cr.b3d
+++ b/advtrains/models/advtrains_dtrack_cr.b3d
Binary files differ
diff --git a/advtrains/advtrains/models/advtrains_dtrack_cr_30.b3d b/advtrains/models/advtrains_dtrack_cr_30.b3d
index 7ca0bda..7ca0bda 100644
--- a/advtrains/advtrains/models/advtrains_dtrack_cr_30.b3d
+++ b/advtrains/models/advtrains_dtrack_cr_30.b3d
Binary files differ
diff --git a/advtrains/advtrains/models/advtrains_dtrack_cr_45.b3d b/advtrains/models/advtrains_dtrack_cr_45.b3d
index b22ea0d..b22ea0d 100644
--- a/advtrains/advtrains/models/advtrains_dtrack_cr_45.b3d
+++ b/advtrains/models/advtrains_dtrack_cr_45.b3d
Binary files differ
diff --git a/advtrains/advtrains/models/advtrains_dtrack_cr_60.b3d b/advtrains/models/advtrains_dtrack_cr_60.b3d
index e9b16d6..e9b16d6 100644
--- a/advtrains/advtrains/models/advtrains_dtrack_cr_60.b3d
+++ b/advtrains/models/advtrains_dtrack_cr_60.b3d
Binary files differ
diff --git a/advtrains/advtrains/models/advtrains_dtrack_st.b3d b/advtrains/models/advtrains_dtrack_st.b3d
index c240416..c240416 100644
--- a/advtrains/advtrains/models/advtrains_dtrack_st.b3d
+++ b/advtrains/models/advtrains_dtrack_st.b3d
Binary files differ
diff --git a/advtrains/advtrains/models/advtrains_dtrack_st_30.b3d b/advtrains/models/advtrains_dtrack_st_30.b3d
index fd77e66..fd77e66 100644
--- a/advtrains/advtrains/models/advtrains_dtrack_st_30.b3d
+++ b/advtrains/models/advtrains_dtrack_st_30.b3d
Binary files differ
diff --git a/advtrains/advtrains/models/advtrains_dtrack_st_45.b3d b/advtrains/models/advtrains_dtrack_st_45.b3d
index af3afb1..af3afb1 100644
--- a/advtrains/advtrains/models/advtrains_dtrack_st_45.b3d
+++ b/advtrains/models/advtrains_dtrack_st_45.b3d
Binary files differ
diff --git a/advtrains/advtrains/models/advtrains_dtrack_st_60.b3d b/advtrains/models/advtrains_dtrack_st_60.b3d
index 6cb19e6..6cb19e6 100644
--- a/advtrains/advtrains/models/advtrains_dtrack_st_60.b3d
+++ b/advtrains/models/advtrains_dtrack_st_60.b3d
Binary files differ
diff --git a/advtrains/advtrains/models/advtrains_dtrack_swlcr.b3d b/advtrains/models/advtrains_dtrack_swlcr.b3d
index 8b1ac0e..8b1ac0e 100644
--- a/advtrains/advtrains/models/advtrains_dtrack_swlcr.b3d
+++ b/advtrains/models/advtrains_dtrack_swlcr.b3d
Binary files differ
diff --git a/advtrains/advtrains/models/advtrains_dtrack_swlcr_30.b3d b/advtrains/models/advtrains_dtrack_swlcr_30.b3d
index 6def7ab..6def7ab 100644
--- a/advtrains/advtrains/models/advtrains_dtrack_swlcr_30.b3d
+++ b/advtrains/models/advtrains_dtrack_swlcr_30.b3d
Binary files differ
diff --git a/advtrains/advtrains/models/advtrains_dtrack_swlcr_45.b3d b/advtrains/models/advtrains_dtrack_swlcr_45.b3d
index cc874ca..cc874ca 100644
--- a/advtrains/advtrains/models/advtrains_dtrack_swlcr_45.b3d
+++ b/advtrains/models/advtrains_dtrack_swlcr_45.b3d
Binary files differ
diff --git a/advtrains/advtrains/models/advtrains_dtrack_swlcr_60.b3d b/advtrains/models/advtrains_dtrack_swlcr_60.b3d
index 1472a00..1472a00 100644
--- a/advtrains/advtrains/models/advtrains_dtrack_swlcr_60.b3d
+++ b/advtrains/models/advtrains_dtrack_swlcr_60.b3d
Binary files differ
diff --git a/advtrains/advtrains/models/advtrains_dtrack_swlst.b3d b/advtrains/models/advtrains_dtrack_swlst.b3d
index ecdb326..ecdb326 100644
--- a/advtrains/advtrains/models/advtrains_dtrack_swlst.b3d
+++ b/advtrains/models/advtrains_dtrack_swlst.b3d
Binary files differ
diff --git a/advtrains/advtrains/models/advtrains_dtrack_swlst_30.b3d b/advtrains/models/advtrains_dtrack_swlst_30.b3d
index fd6e91d..fd6e91d 100644
--- a/advtrains/advtrains/models/advtrains_dtrack_swlst_30.b3d
+++ b/advtrains/models/advtrains_dtrack_swlst_30.b3d
Binary files differ
diff --git a/advtrains/advtrains/models/advtrains_dtrack_swlst_45.b3d b/advtrains/models/advtrains_dtrack_swlst_45.b3d
index dae694e..dae694e 100644
--- a/advtrains/advtrains/models/advtrains_dtrack_swlst_45.b3d
+++ b/advtrains/models/advtrains_dtrack_swlst_45.b3d
Binary files differ
diff --git a/advtrains/advtrains/models/advtrains_dtrack_swlst_60.b3d b/advtrains/models/advtrains_dtrack_swlst_60.b3d
index 8f2b0e2..8f2b0e2 100644
--- a/advtrains/advtrains/models/advtrains_dtrack_swlst_60.b3d
+++ b/advtrains/models/advtrains_dtrack_swlst_60.b3d
Binary files differ
diff --git a/advtrains/advtrains/models/advtrains_dtrack_swrcr.b3d b/advtrains/models/advtrains_dtrack_swrcr.b3d
index 4610826..4610826 100644
--- a/advtrains/advtrains/models/advtrains_dtrack_swrcr.b3d
+++ b/advtrains/models/advtrains_dtrack_swrcr.b3d
Binary files differ
diff --git a/advtrains/advtrains/models/advtrains_dtrack_swrcr_30.b3d b/advtrains/models/advtrains_dtrack_swrcr_30.b3d
index 71b87f3..71b87f3 100644
--- a/advtrains/advtrains/models/advtrains_dtrack_swrcr_30.b3d
+++ b/advtrains/models/advtrains_dtrack_swrcr_30.b3d
Binary files differ
diff --git a/advtrains/advtrains/models/advtrains_dtrack_swrcr_45.b3d b/advtrains/models/advtrains_dtrack_swrcr_45.b3d
index 5457972..5457972 100644
--- a/advtrains/advtrains/models/advtrains_dtrack_swrcr_45.b3d
+++ b/advtrains/models/advtrains_dtrack_swrcr_45.b3d
Binary files differ
diff --git a/advtrains/advtrains/models/advtrains_dtrack_swrcr_60.b3d b/advtrains/models/advtrains_dtrack_swrcr_60.b3d
index 167a3ff..167a3ff 100644
--- a/advtrains/advtrains/models/advtrains_dtrack_swrcr_60.b3d
+++ b/advtrains/models/advtrains_dtrack_swrcr_60.b3d
Binary files differ
diff --git a/advtrains/advtrains/models/advtrains_dtrack_swrst.b3d b/advtrains/models/advtrains_dtrack_swrst.b3d
index 69b6996..69b6996 100644
--- a/advtrains/advtrains/models/advtrains_dtrack_swrst.b3d
+++ b/advtrains/models/advtrains_dtrack_swrst.b3d
Binary files differ
diff --git a/advtrains/advtrains/models/advtrains_dtrack_swrst_30.b3d b/advtrains/models/advtrains_dtrack_swrst_30.b3d
index 19ee483..19ee483 100644
--- a/advtrains/advtrains/models/advtrains_dtrack_swrst_30.b3d
+++ b/advtrains/models/advtrains_dtrack_swrst_30.b3d
Binary files differ
diff --git a/advtrains/advtrains/models/advtrains_dtrack_swrst_45.b3d b/advtrains/models/advtrains_dtrack_swrst_45.b3d
index 70d051f..70d051f 100644
--- a/advtrains/advtrains/models/advtrains_dtrack_swrst_45.b3d
+++ b/advtrains/models/advtrains_dtrack_swrst_45.b3d
Binary files differ
diff --git a/advtrains/advtrains/models/advtrains_dtrack_swrst_60.b3d b/advtrains/models/advtrains_dtrack_swrst_60.b3d
index 69a58fb..69a58fb 100644
--- a/advtrains/advtrains/models/advtrains_dtrack_swrst_60.b3d
+++ b/advtrains/models/advtrains_dtrack_swrst_60.b3d
Binary files differ
diff --git a/advtrains/advtrains/models/advtrains_dtrack_vst1.obj b/advtrains/models/advtrains_dtrack_vst1.obj
index 33d9bf3..33d9bf3 100644
--- a/advtrains/advtrains/models/advtrains_dtrack_vst1.obj
+++ b/advtrains/models/advtrains_dtrack_vst1.obj
diff --git a/advtrains/advtrains/models/advtrains_dtrack_vst1_45.obj b/advtrains/models/advtrains_dtrack_vst1_45.obj
index 8ff8343..8ff8343 100644
--- a/advtrains/advtrains/models/advtrains_dtrack_vst1_45.obj
+++ b/advtrains/models/advtrains_dtrack_vst1_45.obj
diff --git a/advtrains/advtrains/models/advtrains_dtrack_vst2.obj b/advtrains/models/advtrains_dtrack_vst2.obj
index 444ce42..444ce42 100644
--- a/advtrains/advtrains/models/advtrains_dtrack_vst2.obj
+++ b/advtrains/models/advtrains_dtrack_vst2.obj
diff --git a/advtrains/advtrains/models/advtrains_dtrack_vst2_45.obj b/advtrains/models/advtrains_dtrack_vst2_45.obj
index 5dc708b..5dc708b 100644
--- a/advtrains/advtrains/models/advtrains_dtrack_vst2_45.obj
+++ b/advtrains/models/advtrains_dtrack_vst2_45.obj
diff --git a/advtrains/advtrains/models/advtrains_dtrack_vst31.obj b/advtrains/models/advtrains_dtrack_vst31.obj
index c4cb84f..c4cb84f 100644
--- a/advtrains/advtrains/models/advtrains_dtrack_vst31.obj
+++ b/advtrains/models/advtrains_dtrack_vst31.obj
diff --git a/advtrains/advtrains/models/advtrains_dtrack_vst32.obj b/advtrains/models/advtrains_dtrack_vst32.obj
index 297d46b..297d46b 100644
--- a/advtrains/advtrains/models/advtrains_dtrack_vst32.obj
+++ b/advtrains/models/advtrains_dtrack_vst32.obj
diff --git a/advtrains/advtrains/models/advtrains_dtrack_vst33.obj b/advtrains/models/advtrains_dtrack_vst33.obj
index 8cb5f04..8cb5f04 100644
--- a/advtrains/advtrains/models/advtrains_dtrack_vst33.obj
+++ b/advtrains/models/advtrains_dtrack_vst33.obj
diff --git a/advtrains/advtrains/models/advtrains_modernwagon.b3d b/advtrains/models/advtrains_modernwagon.b3d
index aacddca..aacddca 100644
--- a/advtrains/advtrains/models/advtrains_modernwagon.b3d
+++ b/advtrains/models/advtrains_modernwagon.b3d
Binary files differ
diff --git a/advtrains/models/advtrains_platform_diag.b3d b/advtrains/models/advtrains_platform_diag.b3d
new file mode 100644
index 0000000..9464e63
--- /dev/null
+++ b/advtrains/models/advtrains_platform_diag.b3d
Binary files differ
diff --git a/advtrains/models/advtrains_platform_diag_low.b3d b/advtrains/models/advtrains_platform_diag_low.b3d
new file mode 100644
index 0000000..5a8054b
--- /dev/null
+++ b/advtrains/models/advtrains_platform_diag_low.b3d
Binary files differ
diff --git a/advtrains/advtrains/models/advtrains_retrosignal_off.b3d b/advtrains/models/advtrains_retrosignal_off.b3d
index 3d231dd..3d231dd 100644
--- a/advtrains/advtrains/models/advtrains_retrosignal_off.b3d
+++ b/advtrains/models/advtrains_retrosignal_off.b3d
Binary files differ
diff --git a/advtrains/advtrains/models/advtrains_retrosignal_off_30.b3d b/advtrains/models/advtrains_retrosignal_off_30.b3d
index da258e1..da258e1 100644
--- a/advtrains/advtrains/models/advtrains_retrosignal_off_30.b3d
+++ b/advtrains/models/advtrains_retrosignal_off_30.b3d
Binary files differ
diff --git a/advtrains/advtrains/models/advtrains_retrosignal_off_45.b3d b/advtrains/models/advtrains_retrosignal_off_45.b3d
index 338224a..338224a 100644
--- a/advtrains/advtrains/models/advtrains_retrosignal_off_45.b3d
+++ b/advtrains/models/advtrains_retrosignal_off_45.b3d
Binary files differ
diff --git a/advtrains/advtrains/models/advtrains_retrosignal_off_60.b3d b/advtrains/models/advtrains_retrosignal_off_60.b3d
index c560ca1..c560ca1 100644
--- a/advtrains/advtrains/models/advtrains_retrosignal_off_60.b3d
+++ b/advtrains/models/advtrains_retrosignal_off_60.b3d
Binary files differ
diff --git a/advtrains/advtrains/models/advtrains_retrosignal_on.b3d b/advtrains/models/advtrains_retrosignal_on.b3d
index 3d19439..3d19439 100644
--- a/advtrains/advtrains/models/advtrains_retrosignal_on.b3d
+++ b/advtrains/models/advtrains_retrosignal_on.b3d
Binary files differ
diff --git a/advtrains/advtrains/models/advtrains_retrosignal_on_30.b3d b/advtrains/models/advtrains_retrosignal_on_30.b3d
index 98f8a92..98f8a92 100644
--- a/advtrains/advtrains/models/advtrains_retrosignal_on_30.b3d
+++ b/advtrains/models/advtrains_retrosignal_on_30.b3d
Binary files differ
diff --git a/advtrains/advtrains/models/advtrains_retrosignal_on_45.b3d b/advtrains/models/advtrains_retrosignal_on_45.b3d
index 414e121..414e121 100644
--- a/advtrains/advtrains/models/advtrains_retrosignal_on_45.b3d
+++ b/advtrains/models/advtrains_retrosignal_on_45.b3d
Binary files differ
diff --git a/advtrains/advtrains/models/advtrains_retrosignal_on_60.b3d b/advtrains/models/advtrains_retrosignal_on_60.b3d
index a51529a..a51529a 100644
--- a/advtrains/advtrains/models/advtrains_retrosignal_on_60.b3d
+++ b/advtrains/models/advtrains_retrosignal_on_60.b3d
Binary files differ
diff --git a/advtrains/advtrains/models/advtrains_signal.b3d b/advtrains/models/advtrains_signal.b3d
index 7f69560..7f69560 100644
--- a/advtrains/advtrains/models/advtrains_signal.b3d
+++ b/advtrains/models/advtrains_signal.b3d
Binary files differ
diff --git a/advtrains/advtrains/models/advtrains_signal_30.b3d b/advtrains/models/advtrains_signal_30.b3d
index 0b949a7..0b949a7 100644
--- a/advtrains/advtrains/models/advtrains_signal_30.b3d
+++ b/advtrains/models/advtrains_signal_30.b3d
Binary files differ
diff --git a/advtrains/advtrains/models/advtrains_signal_45.b3d b/advtrains/models/advtrains_signal_45.b3d
index ccaebf4..ccaebf4 100644
--- a/advtrains/advtrains/models/advtrains_signal_45.b3d
+++ b/advtrains/models/advtrains_signal_45.b3d
Binary files differ
diff --git a/advtrains/advtrains/models/advtrains_signal_60.b3d b/advtrains/models/advtrains_signal_60.b3d
index cf41e6d..cf41e6d 100644
--- a/advtrains/advtrains/models/advtrains_signal_60.b3d
+++ b/advtrains/models/advtrains_signal_60.b3d
Binary files differ
diff --git a/advtrains/advtrains/models/advtrains_signal_wall_l.b3d b/advtrains/models/advtrains_signal_wall_l.b3d
index b1bcbcf..b1bcbcf 100644
--- a/advtrains/advtrains/models/advtrains_signal_wall_l.b3d
+++ b/advtrains/models/advtrains_signal_wall_l.b3d
Binary files differ
diff --git a/advtrains/advtrains/models/advtrains_signal_wall_r.b3d b/advtrains/models/advtrains_signal_wall_r.b3d
index cf26389..cf26389 100644
--- a/advtrains/advtrains/models/advtrains_signal_wall_r.b3d
+++ b/advtrains/models/advtrains_signal_wall_r.b3d
Binary files differ
diff --git a/advtrains/advtrains/models/advtrains_signal_wall_t.b3d b/advtrains/models/advtrains_signal_wall_t.b3d
index 30e77f6..30e77f6 100644
--- a/advtrains/advtrains/models/advtrains_signal_wall_t.b3d
+++ b/advtrains/models/advtrains_signal_wall_t.b3d
Binary files differ
diff --git a/advtrains/advtrains/models/advtrains_track_cr.b3d b/advtrains/models/advtrains_track_cr.b3d
index b0f5e4b..b0f5e4b 100644
--- a/advtrains/advtrains/models/advtrains_track_cr.b3d
+++ b/advtrains/models/advtrains_track_cr.b3d
Binary files differ
diff --git a/advtrains/advtrains/models/advtrains_track_st.b3d b/advtrains/models/advtrains_track_st.b3d
index 10b5d90..10b5d90 100644
--- a/advtrains/advtrains/models/advtrains_track_st.b3d
+++ b/advtrains/models/advtrains_track_st.b3d
Binary files differ
diff --git a/advtrains/advtrains/models/advtrains_track_st_45.b3d b/advtrains/models/advtrains_track_st_45.b3d
index 32505a1..32505a1 100644
--- a/advtrains/advtrains/models/advtrains_track_st_45.b3d
+++ b/advtrains/models/advtrains_track_st_45.b3d
Binary files differ
diff --git a/advtrains/advtrains/models/trackplane.b3d b/advtrains/models/trackplane.b3d
index b4728c3..b4728c3 100644
--- a/advtrains/advtrains/models/trackplane.b3d
+++ b/advtrains/models/trackplane.b3d
Binary files differ
diff --git a/advtrains/modpack.txt b/advtrains/modpack.txt
deleted file mode 100644
index e69de29..0000000
--- a/advtrains/modpack.txt
+++ /dev/null
diff --git a/advtrains/nodedb.lua b/advtrains/nodedb.lua
new file mode 100644
index 0000000..62405ce
--- /dev/null
+++ b/advtrains/nodedb.lua
@@ -0,0 +1,397 @@
+--nodedb.lua
+--database of all nodes that have 'save_in_at_nodedb' field set to true in node definition
+
+
+--serialization format:
+--(2byte z) (2byte y) (2byte x) (2byte contentid)
+--contentid := (14bit nodeid, 2bit param2)
+
+local function int_to_bytes(i)
+ local x=i+32768--clip to positive integers
+ local cH = math.floor(x / 256) % 256;
+ local cL = math.floor(x ) % 256;
+ return(string.char(cH, cL));
+end
+local function bytes_to_int(bytes)
+ local t={string.byte(bytes,1,-1)}
+ local n =
+ t[1] * 256 +
+ t[2]
+ return n-32768
+end
+local function l2b(x)
+ return x%4
+end
+local function u14b(x)
+ return math.floor(x/4)
+end
+local ndb={}
+
+--local variables for performance
+local ndb_nodeids={}
+local ndb_nodes={}
+local ndb_ver
+
+local function ndbget(x,y,z)
+ local ny=ndb_nodes[y]
+ if ny then
+ local nx=ny[x]
+ if nx then
+ return nx[z]
+ end
+ end
+ return nil
+end
+local function ndbset(x,y,z,v)
+ if not ndb_nodes[y] then
+ ndb_nodes[y]={}
+ end
+ if not ndb_nodes[y][x] then
+ ndb_nodes[y][x]={}
+ end
+ ndb_nodes[y][x][z]=v
+end
+
+-- load/save
+
+local path_pre_v4=minetest.get_worldpath()..DIR_DELIM.."advtrains_ndb2"
+--load pre_v4 format
+--nodeids get loaded by advtrains init.lua and passed here
+function ndb.load_data_pre_v4(data)
+ atlog("nodedb: Loading pre v4 format")
+
+ ndb_nodeids = data and data.nodeids or {}
+ ndb_ver = data and data.ver or 0
+ if ndb_ver < 1 then
+ for k,v in pairs(ndb_nodeids) do
+ if v == "advtrains:dtrack_xing4590_st" then
+ cidDepr = k
+ elseif v == "advtrains:dtrack_xing90plusx_45l" then
+ cidNew = k
+ end
+ end
+ end
+ local file, err = io.open(path_pre_v4, "rb")
+ if not file then
+ atwarn("Couldn't load the node database: ", err or "Unknown Error")
+ else
+ -- Note: code duplication because of weird coordinate order in ndb2 format (z,y,x)
+ local cnt=0
+ local hst_z=file:read(2)
+ local hst_y=file:read(2)
+ local hst_x=file:read(2)
+ local cid=file:read(2)
+ while hst_z and hst_y and hst_x and cid and #hst_z==2 and #hst_y==2 and #hst_x==2 and #cid==2 do
+ if (ndb_ver < 1 and cid == cidDepr) then
+ cid = cidNew
+ end
+ ndbset(bytes_to_int(hst_x), bytes_to_int(hst_y), bytes_to_int(hst_z), bytes_to_int(cid))
+ cnt=cnt+1
+ hst_z=file:read(2)
+ hst_y=file:read(2)
+ hst_x=file:read(2)
+ cid=file:read(2)
+ end
+ atlog("nodedb (ndb2 format): read", cnt, "nodes.")
+ file:close()
+ end
+ ndb_ver = 1
+end
+
+-- the new ndb file format is backported from cellworld, and stores the cids also in the ndb file.
+-- These functions have the form of a serialize_lib atomic load/save callback and are called from avt_save/avt_load.
+function ndb.load_callback(file)
+ -- read version
+ local vers_byte = file:read(1)
+ local version = string.byte(vers_byte)
+ if version~=1 then
+ file:close()
+ error("Doesn't support v4 nodedb file of version "..version)
+ end
+
+ -- read cid mappings
+ local nstr_byte = file:read(2)
+ local nstr = bytes_to_int(nstr_byte)
+ for i = 1,nstr do
+ local stid_byte = file:read(2)
+ local stid = bytes_to_int(stid_byte)
+ local stna = file:read("*l")
+ -- possibly windows fix: strip trailing \r's from line
+ stna = string.gsub(stna, "\r$", "")
+ --atdebug("content id:", stid, "->", stna)
+ ndb_nodeids[stid] = stna
+ end
+ atlog("[nodedb] read", nstr, "node content ids.")
+
+ -- read nodes
+ local cnt=0
+ local hst_x=file:read(2)
+ local hst_y=file:read(2)
+ local hst_z=file:read(2)
+ local cid=file:read(2)
+ local cidi
+ while hst_z and hst_y and hst_x and cid and #hst_z==2 and #hst_y==2 and #hst_x==2 and #cid==2 do
+ cidi = bytes_to_int(cid)
+ -- prevent file corruption already here
+ if not ndb_nodeids[u14b(cidi)] then
+ -- clear the ndb data, to reinitialize it
+ -- in strict loading mode, doesn't matter as starting will be interrupted anyway
+ ndb_nodeids = {}
+ ndb_nodes = {}
+ error("NDB file is corrupted (found entry with invalid cid)")
+ end
+ ndbset(bytes_to_int(hst_x), bytes_to_int(hst_y), bytes_to_int(hst_z), cidi)
+ cnt=cnt+1
+ hst_x=file:read(2)
+ hst_y=file:read(2)
+ hst_z=file:read(2)
+ cid=file:read(2)
+ end
+ atlog("[nodedb] read", cnt, "nodes.")
+ file:close()
+end
+
+--save
+function ndb.save_callback(data, file)
+ --atdebug("storing ndb...")
+ -- write version
+ file:write(string.char(1))
+
+ -- how many cid entries
+ local cnt = 0
+ for _,_ in pairs(ndb_nodeids) do
+ cnt = cnt + 1
+ end
+ -- write cids
+ local nstr = 0
+ file:write(int_to_bytes(cnt))
+ for stid,stna in pairs(ndb_nodeids) do
+ file:write(int_to_bytes(stid))
+ file:write(stna)
+ file:write("\n")
+ nstr = nstr+1
+ end
+ --atdebug("saved cids count ", nstr)
+
+ -- write entries
+ local cnt = 0
+ for y, ny in pairs(ndb_nodes) do
+ for x, nx in pairs(ny) do
+ for z, cid in pairs(nx) do
+ file:write(int_to_bytes(x))
+ file:write(int_to_bytes(y))
+ file:write(int_to_bytes(z))
+ file:write(int_to_bytes(cid))
+ cnt=cnt+1
+ end
+ end
+ end
+ --atdebug("saved nodes count ", cnt)
+ file:close()
+end
+
+
+
+--function to get node. track database is not helpful here.
+function ndb.get_node_or_nil(pos)
+ -- FIX for bug found on linuxworks server:
+ -- a loaded node might get read before the LBM has updated its state, resulting in wrongly set signals and switches
+ -- -> Using the saved node prioritarily.
+ local node = ndb.get_node_raw(pos)
+ if node then
+ return node
+ else
+ --try reading the node from the map
+ return minetest.get_node_or_nil(pos)
+ end
+end
+function ndb.get_node(pos)
+ local n=ndb.get_node_or_nil(pos)
+ if not n then
+ return {name="ignore", param2=0}
+ end
+ return n
+end
+function ndb.get_ndef(pos)
+ local n=ndb.get_node_or_nil(pos)
+ return n and minetest.registered_nodes[n.name]
+end
+function ndb.get_node_raw(pos)
+ local cid=ndbget(pos.x, pos.y, pos.z)
+ if cid then
+ local nodeid = ndb_nodeids[u14b(cid)]
+ if nodeid then
+ return {name=nodeid, param2 = l2b(cid)}
+ end
+ end
+ return nil
+end
+
+
+function ndb.swap_node(pos, node, no_inval)
+ if advtrains.is_node_loaded(pos) then
+ minetest.swap_node(pos, node)
+ end
+ ndb.update(pos, node)
+end
+
+function ndb.update(pos, pnode)
+ local node = pnode or minetest.get_node_or_nil(pos)
+ if not node or node.name=="ignore" then return end
+ if minetest.registered_nodes[node.name] and minetest.registered_nodes[node.name].groups.save_in_at_nodedb then
+ local nid
+ for tnid, nname in pairs(ndb_nodeids) do
+ if nname==node.name then
+ nid=tnid
+ end
+ end
+ if not nid then
+ nid=#ndb_nodeids+1
+ ndb_nodeids[nid]=node.name
+ end
+ local resid = (nid * 4) + (l2b(node.param2 or 0))
+ ndbset(pos.x, pos.y, pos.z, resid )
+ --atdebug("nodedb: updating node", pos, "stored nid",nid,"assigned",ndb_nodeids[nid],"resulting cid",resid)
+ advtrains.invalidate_all_paths_ahead(pos)
+ else
+ --at this position there is no longer a node that needs to be tracked.
+ --atdebug("nodedb: updating node", pos, "cleared")
+ ndbset(pos.x, pos.y, pos.z, nil)
+ end
+end
+
+function ndb.clear(pos)
+ ndbset(pos.x, pos.y, pos.z, nil)
+end
+
+
+--get_node with pseudoload. now we only need track data, so we can use the trackdb as second fallback
+--nothing new will be saved inside the trackdb.
+--returns:
+--true, conns, railheight, connmap in case everything's right.
+--false if it's not a rail or the train does not drive on this rail, but it is loaded or
+--nil if the node is neither loaded nor in trackdb
+--the distraction between false and nil will be needed only in special cases.(train initpos)
+function advtrains.get_rail_info_at(pos)
+ local rdp=advtrains.round_vector_floor_y(pos)
+
+ local node=ndb.get_node_or_nil(rdp)
+ if not node then return end
+
+ local nodename=node.name
+ if(not advtrains.is_track(nodename)) then
+ return false
+ end
+ local conns, railheight, connmap = advtrains.get_track_connections(node.name, node.param2)
+
+ return true, conns, railheight, connmap
+end
+
+local IGNORE_WORLD = advtrains.IGNORE_WORLD
+
+ndb.run_lbm = function(pos, node)
+ local cid=ndbget(pos.x, pos.y, pos.z)
+ if cid then
+ --if in database, detect changes and apply.
+ local nodeid = ndb_nodeids[u14b(cid)]
+ local param2 = l2b(cid)
+ if not nodeid then
+ --something went wrong
+ atwarn("Node Database corruption, couldn't determine node to set at", pos)
+ ndb.update(pos, node)
+ else
+ if (nodeid~=node.name or param2~=node.param2) then
+ --atprint("nodedb: lbm replaced", pos, "with nodeid", nodeid, "param2", param2, "cid is", cid)
+ local newnode = {name=nodeid, param2 = param2}
+ minetest.swap_node(pos, newnode)
+ local ndef=minetest.registered_nodes[nodeid]
+ if ndef and ndef.advtrains and ndef.advtrains.on_updated_from_nodedb then
+ ndef.advtrains.on_updated_from_nodedb(pos, newnode, node)
+ end
+ return true
+ end
+ end
+ else
+ --if not in database, take it.
+ --atlog("Node Database:", pos, "was not found in the database, have you used worldedit?")
+ ndb.update(pos, node)
+ end
+ return false
+end
+
+
+minetest.register_lbm({
+ name = "advtrains:nodedb_on_load_update",
+ nodenames = {"group:save_in_at_nodedb"},
+ run_at_every_load = true,
+ run_on_every_load = true,
+ action = ndb.run_lbm,
+ interval=30,
+ chance=1,
+ })
+
+--used when restoring stuff after a crash
+ndb.restore_all = function()
+ --atlog("Updating the map from the nodedb, this may take a while")
+ local t1 = os.clock()
+ local cnt=0
+ local dcnt=0
+ for y, ny in pairs(ndb_nodes) do
+ for x, nx in pairs(ny) do
+ for z, _ in pairs(nx) do
+ local pos={x=x, y=y, z=z}
+ local node=minetest.get_node_or_nil(pos)
+ if node then
+ local ori_ndef=minetest.registered_nodes[node.name]
+ local ndbnode=ndb.get_node_raw(pos)
+ if (ori_ndef and ori_ndef.groups.save_in_at_nodedb) or IGNORE_WORLD then --check if this node has been worldedited, and don't replace then
+ if (ndbnode.name~=node.name or ndbnode.param2~=node.param2) then
+ minetest.swap_node(pos, ndbnode)
+ --atlog("Replaced",node.name,"@",pos,"with",ndbnode.name)
+ cnt=cnt+1
+ end
+ else
+ ndb.clear(pos)
+ dcnt=dcnt+1
+ --atlog("Found ghost node (former",ndbnode and ndbnode.name,") @",pos,"deleting")
+ end
+ end
+ end
+ end
+ end
+ local text="Restore node database: Replaced "..cnt.." nodes, removed "..dcnt.." ghost nodes. (took "..math.floor((os.clock()-t1) * 1000).."ms)"
+ atlog(text)
+ return text
+end
+
+minetest.register_on_dignode(function(pos, oldnode, digger)
+ ndb.clear(pos)
+end)
+
+function ndb.get_nodes()
+ return ndb_nodes
+end
+function ndb.get_nodeids()
+ return ndb_nodeids
+end
+
+
+advtrains.ndb=ndb
+
+local ptime=0
+
+minetest.register_chatcommand("at_sync_ndb",
+ {
+ params = "", -- Short parameter description
+ description = "Write node db back to map and find ghost nodes", -- Full description
+ privs = {train_operator=true},
+ func = function(name, param)
+ if os.time() < ptime+30 and not minetest.get_player_privs(name, "server") then
+ return false, "Please wait at least 30s from the previous execution of /at_restore_ndb!"
+ end
+ local text = ndb.restore_all()
+ ptime=os.time()
+ return true, text
+ end,
+ })
+
diff --git a/advtrains/occupation.lua b/advtrains/occupation.lua
new file mode 100644
index 0000000..20a986e
--- /dev/null
+++ b/advtrains/occupation.lua
@@ -0,0 +1,236 @@
+-- occupation.lua
+--[[
+Collects and manages positions where trains occupy and/or reserve/require space
+
+It turned out that, especially for the TSS, some more, even overlapping zones are required.
+Packing those into a data structure would just become a huge mess!
+Instead, this occupation system will store the path indices of positions in the corresponding.
+train's paths.
+So, the occupation is a reverse lookup of paths.
+Then, a callback system will handle changes in those indices, as follows:
+
+Whenever the train generates new path items (path_get/path_create), their counterpart indices will be filled in here.
+Whenever a path gets invalidated or path items are deleted, their index counterpart is erased from here.
+
+When a train needs to know whether a position is blocked by another train, it will (and is permitted to)
+query the train.index and train.end_index and compare them to the blocked position's index.
+
+Callback system for 3rd-party path checkers:
+advtrains.te_register_on_new_path(func(id, train))
+-- Called when a train's path is re-initalized, either when it was invalidated
+-- or the saves were just loaded
+-- It can be assumed that everything is in the state of when the last run
+-- of on_update was made, but all indices are shifted by an unknown amount.
+
+advtrains.te_register_on_update(func(id, train))
+-- Called each step and after a train moved, its length changed or some other event occured
+-- The path is unmodified, and train.index and train.end_index can be reliably
+-- queried for the new position and length of the train.
+-- note that this function might be called multiple times per step, and this
+-- function being called does not necessarily mean that something has changed.
+-- It is ensured that on_new_path callbacks are executed prior to these callbacks whenever
+-- an invalidation or a reload occured.
+
+advtrains.te_register_on_create(func(id, train))
+-- Called right after a train is created, right after the initial new_path callback
+advtrains.te_register_on_remove(func(id, train))
+-- Called right before a train is deleted
+
+
+All callbacks are allowed to save certain values inside the train table, but they must ensure that
+those are reinitialized in the on_new_path callback. The on_new_path callback must explicitly
+set ALL OF those values to nil or to a new updated value, and must not rely on their existence.
+
+]]--
+local o = {}
+
+local occ = {}
+local occ_chg = {}
+
+
+local function occget(p)
+ local t = occ[p.y]
+ if not t then
+ occ[p.y] = {}
+ t = occ[p.y]
+ end
+ local s = t
+ t = t[p.x]
+ if not t then
+ s[p.x] = {}
+ t = s[p.x]
+ end
+ return t[p.z]
+end
+local function occgetcreate(p)
+ local t = occ[p.y]
+ if not t then
+ occ[p.y] = {}
+ t = occ[p.y]
+ end
+ local s = t
+ t = t[p.x]
+ if not t then
+ s[p.x] = {}
+ t = s[p.x]
+ end
+ s = t
+ t = t[p.z]
+ if not t then
+ s[p.z] = {}
+ t = s[p.z]
+ end
+ return t
+end
+
+
+function o.set_item(train_id, pos, idx)
+ local t = occgetcreate(pos)
+ assert(idx)
+ local i = 1
+ while t[i] do
+ if t[i]==train_id and t[i+1]==idx then
+ return
+ end
+ i = i + 2
+ end
+ t[i] = train_id
+ t[i+1] = idx
+end
+
+
+function o.clear_all_items(train_id, pos)
+ local t = occget(pos)
+ if not t then return end
+ local i = 1
+ while t[i] do
+ if t[i]==train_id then
+ table.remove(t, i)
+ table.remove(t, i)
+ else
+ i = i + 2
+ end
+ end
+end
+function o.clear_specific_item(train_id, pos, index)
+ local t = occget(pos)
+ if not t then return end
+ local i = 1
+ while t[i] do
+ if t[i]==train_id and t[i+1]==index then
+ table.remove(t, i)
+ table.remove(t, i)
+ else
+ i = i + 2
+ end
+ end
+end
+
+-- Checks whether some other train (apart from train_id) has it's 0 zone here
+function o.check_collision(pos, train_id)
+ local npos = advtrains.round_vector_floor_y(pos)
+ local t = occget(npos)
+ if not t then return end
+ local i = 1
+ while t[i] do
+ local ti = t[i]
+ if ti~=train_id then
+ local idx = t[i+1]
+ local train = advtrains.trains[ti]
+
+ --atdebug("checking train",t[i],"index",idx,"<>",train.index,train.end_index)
+ if train and idx >= train.end_index and idx <= train.index then
+ --atdebug("collides.")
+ return train -- return train it collided with so we can couple when shunting is enabled
+ end
+ end
+ i = i + 2
+ end
+ return false
+end
+
+-- Gets a mapping of train id's to indexes of trains that have a path item at this position
+-- Note that the case where 2 or more indices are at a position only occurs if there is a track loop.
+-- returns (table with train_id->{index1, index2...})
+function o.reverse_lookup(ppos)
+ local pos = advtrains.round_vector_floor_y(ppos)
+ local t = occget(pos)
+ if not t then return {} end
+ local r = {}
+ local i = 1
+ while t[i] do
+ if not r[t[i]] then r[t[i]] = {} end
+ table.insert(r[t[i]], t[i+1])
+ i = i + 2
+ end
+ return r
+end
+
+-- Gets a mapping of train id's to indexes of trains that have a path item at this position.
+-- Quick variant: will only return one index per train (the latest one added)
+-- returns (table with train_id->index)
+function o.reverse_lookup_quick(ppos)
+ local pos = advtrains.round_vector_floor_y(ppos)
+ local t = occget(pos)
+ if not t then return {} end
+ local r = {}
+ local i = 1
+ while t[i] do
+ r[t[i]] = t[i+1]
+ i = i + 2
+ end
+ return r
+end
+
+local OCC_CLOSE_PROXIMITY = 3
+-- Gets a mapping of train id's to index of trains that have a path item at this position. Selects at most one index based on a given heuristic, or even none if it does not match the heuristic criterion
+-- returns (table with train_id->index), position
+-- "in_train": first index that lies between train index and end index
+-- "train_at_node": first index where the train is standing on that node (like in_train but with +-0.5 added to index)
+-- "first_ahead": smallest index that is > current index
+-- "before_end"(default): smallest index that is > end index
+-- "close_proximity": within 3 indices close to the train index and end_index
+-- "any": just output the first index found and do not check further (also occurs if both "in_train" and "first_ahead" heuristics have failed
+function o.reverse_lookup_sel(pos, heuristic)
+ if not heuristic then heuristic = "before_end" end
+ local om = o.reverse_lookup(pos)
+ local r = {}
+ for tid, idxs in pairs(om) do
+ r[tid] = idxs[1]
+ if heuristic~="any" then
+ --must run a heuristic
+ --atdebug("reverse_lookup_sel is running heuristic for", pos,heuristic,"idxs",table.concat(idxs,","))
+ local otrn = advtrains.trains[tid]
+ advtrains.train_ensure_init(tid, otrn)
+ local h_value
+ for _,idx in ipairs(idxs) do
+ if heuristic == "first_ahead" and idx > otrn.index and (not h_value or h_value>idx) then
+ h_value = idx
+ end
+ if heuristic == "before_end" and idx > otrn.end_index and (not h_value or h_value>idx) then
+ h_value = idx
+ end
+ if heuristic == "in_train" and idx < otrn.index and idx > otrn.end_index then
+ h_value = idx
+ end
+ if heuristic == "train_at_node" and idx < (otrn.index+0.5) and idx > (otrn.end_index-0.5) then
+ h_value = idx
+ end
+ if heuristic == "close_proximity" and idx < (otrn.index + OCC_CLOSE_PROXIMITY) and idx > (otrn.end_index - OCC_CLOSE_PROXIMITY) then
+ h_value = idx
+ end
+ end
+ r[tid] = h_value
+ --atdebug(h_value,"chosen")
+ end
+ end
+ return r, pos
+end
+-- Gets a mapping of train id's to indexes of trains that stand or drive over
+-- returns (table with train_id->index)
+function o.get_trains_at(ppos)
+ local pos = advtrains.round_vector_floor_y(ppos)
+ return o.reverse_lookup_sel(pos, "train_at_node")
+end
+
+advtrains.occ = o
diff --git a/advtrains/advtrains_luaautomation/p_mesecon_iface.lua b/advtrains/p_mesecon_iface.lua
index 95e5d8a..0426e2b 100644
--- a/advtrains/advtrains_luaautomation/p_mesecon_iface.lua
+++ b/advtrains/p_mesecon_iface.lua
@@ -1,36 +1,36 @@
-- p_mesecon_iface.lua
-- Mesecons interface by overriding the switch
-if not mesecon then return end
+if minetest.get_modpath("mesecons_switch") == nil then return end
minetest.override_item("mesecons_switch:mesecon_switch_off", {
groups = {
dig_immediate=2,
- save_in_nodedb=1,
+ save_in_at_nodedb=1,
},
on_rightclick = function (pos, node)
advtrains.ndb.swap_node(pos, {name="mesecons_switch:mesecon_switch_on", param2=node.param2})
mesecon.receptor_on(pos)
minetest.sound_play("mesecons_switch", {pos=pos})
end,
- on_updated_from_nodedb = function(pos, node)
- mesecon.receptor_off(pos)
- end,
- luaautomation = {
- getstate = "off",
- setstate = function(pos, node, newstate)
- if newstate=="on" then
- advtrains.ndb.swap_node(pos, {name="mesecons_switch:mesecon_switch_on", param2=node.param2})
+ advtrains = {
+ node_state = "off",
+ node_state_map = { on = "mesecons_switch:mesecon_switch_on", off = "mesecons_switch:mesecon_switch_off" },
+ node_on_switch_state = function(pos, new_node, old_state, new_state)
+ if advtrains.is_node_loaded(pos) then
mesecon.receptor_on(pos)
end
end,
+ on_updated_from_nodedb = function(pos, node)
+ mesecon.receptor_off(pos)
+ end,
},
})
minetest.override_item("mesecons_switch:mesecon_switch_on", {
groups = {
dig_immediate=2,
- save_in_nodedb=1,
+ save_in_at_nodedb=1,
not_in_creative_inventory=1,
},
on_rightclick = function (pos, node)
@@ -38,16 +38,17 @@ minetest.override_item("mesecons_switch:mesecon_switch_on", {
mesecon.receptor_off(pos)
minetest.sound_play("mesecons_switch", {pos=pos})
end,
- on_updated_from_nodedb = function(pos, node)
- mesecon.receptor_on(pos)
- end,
- luaautomation = {
- getstate = "on",
- setstate = function(pos, node, newstate)
- if newstate=="off" then
- advtrains.ndb.swap_node(pos, {name="mesecons_switch:mesecon_switch_off", param2=node.param2})
+ advtrains = {
+ node_state = "on",
+ node_state_map = { on = "mesecons_switch:mesecon_switch_on", off = "mesecons_switch:mesecon_switch_off" },
+ node_on_switch_state = function(pos, new_node, old_state, new_state)
+ if advtrains.is_node_loaded(pos) then
mesecon.receptor_off(pos)
end
end,
+ node_fallback_state = "off",
+ on_updated_from_nodedb = function(pos, node)
+ mesecon.receptor_on(pos)
+ end,
},
})
diff --git a/advtrains/passive.lua b/advtrains/passive.lua
new file mode 100644
index 0000000..37b79e4
--- /dev/null
+++ b/advtrains/passive.lua
@@ -0,0 +1,107 @@
+-- passive.lua
+-- Rework for advtrains 2.5: The passive API now uses the reworked node_state system. Please see the comment in tracks.lua
+
+function advtrains.getstate(parpos, pnode)
+ local pos
+ if atlatc then
+ pos = atlatc.pcnaming.resolve_pos(parpos)
+ else
+ pos = advtrains.round_vector_floor_y(parpos)
+ end
+ if type(pos)~="table" or (not pos.x or not pos.y or not pos.z) then
+ debug.sethook()
+ error("Invalid position supplied to getstate")
+ end
+ local node=pnode or advtrains.ndb.get_node(pos)
+ local ndef=minetest.registered_nodes[node.name]
+ local st
+ if ndef and ndef.advtrains then
+ return ndef.advtrains.node_state
+ end
+end
+
+function advtrains.setstate(parpos, newstate, pnode)
+ local pos
+ if atlatc then
+ pos = atlatc.pcnaming.resolve_pos(parpos)
+ else
+ pos = advtrains.round_vector_floor_y(parpos)
+ end
+ if type(pos)~="table" or (not pos.x or not pos.y or not pos.z) then
+ debug.sethook()
+ error("Invalid position supplied to setstate")
+ end
+ local node=pnode or advtrains.ndb.get_node(pos)
+ local ndef=minetest.registered_nodes[node.name]
+
+ if not ndef or not ndef.advtrains then
+ return false, "missing_node_def"
+ end
+ local old_state = ndef.advtrains.node_state
+
+ if old_state == newstate then
+ -- nothing needs to be done
+ return true
+ end
+
+ if not ndef.advtrains.node_state_map then
+ return false, "missing_node_state_map"
+ end
+ local new_node_name = ndef.advtrains.node_state_map[newstate]
+ if not new_node_name then
+ return false, "no_such_state"
+ end
+
+ -- prevent state switching when route lock or train is present
+ if advtrains.get_train_at_pos(pos) then
+ return false, "train_here"
+ end
+
+ if advtrains.interlocking and advtrains.interlocking.route.has_route_lock(advtrains.encode_pos(pos)) then
+ return false, "route_lock_here"
+ end
+
+ -- perform the switch
+ local new_node = {name = new_node_name, param2 = node.param2}
+ advtrains.ndb.swap_node(pos, new_node)
+ -- if callback is present, call it
+ if ndef.advtrains.node_on_switch_state then
+ ndef.advtrains.node_on_switch_state(pos, new_node, old_state, newstate)
+ end
+ -- invalidate paths (only relevant if this is a track)
+ advtrains.invalidate_all_paths(pos)
+
+ return true
+end
+
+function advtrains.is_passive(parpos, pnode)
+ local pos
+ if atlatc then
+ pos = atlatc.pcnaming.resolve_pos(parpos)
+ else
+ pos = advtrains.round_vector_floor_y(parpos)
+ end
+ if type(pos)~="table" or (not pos.x or not pos.y or not pos.z) then
+ debug.sethook()
+ error("Invalid position supplied to getstate")
+ end
+ local node=pnode or advtrains.ndb.get_node(pos)
+ local ndef=minetest.registered_nodes[node.name]
+ if ndef and ndef.advtrains and ndef.advtrains.node_state_map then
+ return true
+ else
+ return false
+ end
+end
+
+-- switches a node back to fallback state, if defined. Doesn't support pcnaming.
+function advtrains.set_fallback_state(pos, pnode)
+ local node=pnode or advtrains.ndb.get_node(pos)
+ local ndef=minetest.registered_nodes[node.name]
+
+ if not ndef or not ndef.advtrains or not ndef.advtrains.node_fallback_state then
+ return false, "no_fallback_state"
+ end
+
+ return advtrains.setstate(pos, ndef.advtrains.node_fallback_state, node)
+end
diff --git a/advtrains/path.lua b/advtrains/path.lua
new file mode 100644
index 0000000..2b17d6d
--- /dev/null
+++ b/advtrains/path.lua
@@ -0,0 +1,489 @@
+-- path.lua
+-- Functions for pathpredicting, put in a separate file.
+
+-- Naming conventions:
+-- 'index' - An index of the train.path table.
+-- 'offset' - A value in meters that determines how far on the path to walk relative to a certain index
+-- 'n' - Referring or pointing towards the 'next' path item, the one with index+1
+-- 'p' - Referring or pointing towards the 'prev' path item, the one with index-1
+-- 'f' - Referring to the positive end of the path (the end with the higher index)
+-- 'b' - Referring to the negative end of the path (the end with the lower index)
+
+-- New path structure of trains:
+--Tables:
+-- path - path positions. 'indices' are relative to this. At the moment, at.round_vector_floor_y(path[i])
+-- is the node this item corresponds to, however, this will change in the future.
+-- path_node - (reserved)
+-- path_cn - Connid of the current node that points towards path[i+1]
+-- path_cp - Connid of the current node that points towards path[i-1]
+-- When the day comes on that path!=node, these will only be set if this index represents a transition between rail nodes
+-- path_dist - The total distance of this path element from path element 0
+-- path_dir - The direction of this path item's transition to the next path item, which is the angle of conns[path_cn[i]].c
+-- path_speed- Populated by the LZB system. The maximum speed (velocity) permitted in the moment this path item is passed.
+-- (this saves brake distance calculations every step to determine LZB control). nil means no limit.
+--Variables:
+-- path_ext_f/b - how far path[i] is set
+-- path_trk_f/b - how far the path extends along a track. beyond those values, paths are generated in a straight line.
+-- path_req_f/b - how far path items were requested in the last step
+--
+--Distance and index:
+-- There is an important difference between the path index and the actual distance on the track: The distance between two path items can be larger than 1,
+-- but the corresponding index increment is still 1.
+-- Indexes in advtrains can be fractional values. If they are, it means that the actual position is interpolated between the 2 adjacent path items.
+-- If you need to proceed along the path by a specific actual distance, it does NOT work to simply add it to the index. You should use the path_get_index_by_offset() function.
+
+-- creates the path data structure, reconstructing the train from a position and a connid
+-- returns: true - successful
+-- nil - node not yet available/unloaded, please wait
+-- false - node definitely gone, remove train
+function advtrains.path_create(train, pos, connid, rel_index)
+ local posr = advtrains.round_vector_floor_y(pos)
+ local node_ok, conns, rhe, connmap = advtrains.get_rail_info_at(pos)
+ if not node_ok then
+ return node_ok
+ end
+ local mconnid = advtrains.get_matching_conn(connid, connmap)
+ train.index = rel_index
+ train.path = { [0] = { x=posr.x, y=posr.y+rhe, z=posr.z } }
+ train.path_cn = { [0] = connid }
+ train.path_cp = { [0] = mconnid }
+ train.path_dist = { [0] = 0 }
+
+ train.path_dir = {
+ [0] = advtrains.conn_angle_median(conns[mconnid].c, conns[connid].c)
+ }
+
+ train.path_speed = { }
+
+ train.path_ext_f=0
+ train.path_ext_b=0
+ train.path_trk_f=0
+ train.path_trk_b=0
+ train.path_req_f=0
+ train.path_req_b=0
+
+ advtrains.occ.set_item(train.id, posr, 0)
+ return true
+end
+
+-- Sets position and connid to properly restore after a crash, e.g. in order
+-- to save the train or to invalidate its path
+-- Assumes that the train is in clean state
+-- if invert ist true, setrestore will use the end index
+function advtrains.path_setrestore(train, invert)
+ local idx = train.index
+ if invert then
+ idx = train.end_index
+ end
+
+ local pos, connid, frac = advtrains.path_getrestore(train, idx, invert, true)
+
+ train.last_pos = pos
+ train.last_connid = connid
+ train.last_frac = frac
+end
+-- Get restore position, connid and frac (in this order) for a train that will originate at the passed index
+-- If invert is set, it will return path_cp and multiply frac by -1, in order to reverse the train there.
+function advtrains.path_getrestore(train, index, invert)
+ local idx = index
+ local cns = train.path_cn
+
+ if invert then
+ cns = train.path_cp
+ end
+
+ local fli = atfloor(index)
+ advtrains.path_get(train, fli)
+ if fli > train.path_trk_f then
+ fli = train.path_trk_f
+ end
+ if fli < train.path_trk_b then
+ fli = train.path_trk_b
+ end
+ return advtrains.path_get(train, fli),
+ cns[fli],
+ (idx - fli) * (invert and -1 or 1)
+end
+
+-- Invalidates a path
+-- this is supposed to clear stuff from the occupation tables
+-- This function throws a warning whenever any code calls it while the train steps are run, since that must not happen.
+-- The ignore_lock parameter can be used to ignore this, however, it should then be accompanied by a call to train_ensure_init
+-- before returning from the calling function.
+function advtrains.path_invalidate(train, ignore_lock)
+ if advtrains.lock_path_inval and not ignore_lock then
+ atwarn("Train ",train.id,": Illegal path invalidation has occured during train step:")
+ atwarn(debug.traceback())
+ end
+ if train.path then
+ --atdebug("path_invalidate for",train.id)
+ local _cnt = 0
+ for i,p in pairs(train.path) do
+ _cnt = _cnt + 1
+ if _cnt > 10000 then
+ atdebug(train)
+ error("Loop trap in advtrains.path_invalidate was triggered!")
+ end
+ advtrains.occ.clear_all_items(train.id, advtrains.round_vector_floor_y(p))
+ end
+ --atdebug("occ cleared")
+ end
+ train.path = nil
+ train.path_dist = nil
+ train.path_cp = nil
+ train.path_cn = nil
+ train.path_dir = nil
+ train.path_speed = nil
+ train.path_ext_f=0
+ train.path_ext_b=0
+ train.path_trk_f=0
+ train.path_trk_b=0
+ train.path_req_f=0
+ train.path_req_b=0
+
+ train.dirty = true
+ --atdebug(train.id, "Path invalidated")
+end
+
+-- Keeps the path intact, but invalidates all path nodes from the specified index (inclusive)
+-- onwards. This has the advantage that we don't need to recalculate the whole path, and we can do it synchronously.
+function advtrains.path_invalidate_ahead(train, start_idx, ignore_when_passed)
+ if not train.path then
+ -- the path wasn't even initialized. Nothing to do
+ return
+ end
+
+ local idx = atfloor(start_idx)
+ --atdebug("Invalidate_ahead:",train.id,"start_index",start_idx,"cur_idx",train.index)
+
+ if(idx <= train.index - 0.5) then
+ if ignore_when_passed then
+ --atdebug("ignored passed")
+ return
+ end
+ advtrains.path_print(train, atwarn)
+ error("Train "+train.id+": Cannot path_invalidate_ahead start_idx="+idx+" as train has already passed!")
+ end
+
+ -- leave current node in path, it won't change. What might change is the path onward from here (e.g. switch)
+ local i = idx + 1
+ while train.path[i] do
+ advtrains.occ.clear_specific_item(train.id, advtrains.round_vector_floor_y(train.path[i]), i)
+ i = i+1
+ end
+ train.path_ext_f=idx
+ train.path_trk_f=math.min(idx, train.path_trk_f)
+
+ -- callbacks called anyway for current node, because of LZB
+ advtrains.run_callbacks_invahead(train.id, train, idx)
+end
+
+-- Prints a path using the passed print function
+-- This function should be 'atprint', 'atlog', 'atwarn' or 'atdebug', because it needs to use print_concat_table
+function advtrains.path_print(train, printf)
+ printf("path_print: tid =",train.id," index =",train.index," end_index =",train.end_index," vel =",train.velocity)
+ if not train.path then
+ printf("path_print: Path is invalidated/inexistant.")
+ return
+ end
+ printf("i: CP Position Dir CN Dist Speed")
+ for i = train.path_ext_b, train.path_ext_f do
+ if i==train.path_trk_b then
+ printf("--Back on-track border here--")
+ end
+ printf(i,": ",train.path_cp[i]," ",train.path[i]," ",train.path_dir[i]," ",train.path_cn[i]," ",train.path_dist[i]," ",train.path_speed[i])
+ if i==train.path_trk_f then
+ printf("--Front on-track border here--")
+ end
+ end
+end
+
+-- Function to get path entry at a position. This function will automatically calculate more of the path when required.
+-- returns: pos, on_track
+function advtrains.path_get(train, index)
+ if not train.path then
+ error("For train "..train.id..": path_get called but there's no path set yet!")
+ end
+ if index ~= atfloor(index) then
+ error("For train "..train.id..": Called path_get() but index="..index.." is not a round number")
+ end
+
+ local pef = train.path_ext_f
+ -- generate forward (front of train, positive)
+ while index > pef do
+ local pos = train.path[pef]
+ local connid = train.path_cn[pef]
+ local node_ok, this_conns, adj_pos, adj_connid, conn_idx, nextrail_y, next_conns, next_connmap
+ if pef == train.path_trk_f then
+ node_ok, this_conns = advtrains.get_rail_info_at(pos)
+ if not node_ok then error("For train "..train.id..": Path item "..pef.." on-track but not a valid node!") end
+ adj_pos, adj_connid, conn_idx, nextrail_y, next_conns, next_connmap = advtrains.get_adjacent_rail(pos, this_conns, connid)
+ end
+ pef = pef + 1
+ if adj_pos then
+ advtrains.occ.set_item(train.id, adj_pos, pef)
+
+ local mconnid = advtrains.get_matching_conn(adj_connid, next_connmap)
+ -- NO split points handling here. It is only required for backwards path calculation
+
+ adj_pos.y = adj_pos.y + nextrail_y
+ train.path_cp[pef] = adj_connid
+ train.path_cn[pef] = mconnid
+ train.path_dir[pef] = advtrains.conn_angle_median(next_conns[adj_connid].c, next_conns[mconnid].c)
+ train.path_trk_f = pef
+ else
+ -- off-track fallback behavior
+ adj_pos = advtrains.pos_add_angle(pos, train.path_dir[pef-1])
+ --atdebug("Offtrack overgenerating(front) at",adj_pos,"index",peb,"trkf",train.path_trk_f)
+ train.path_dir[pef] = train.path_dir[pef-1]
+ end
+ train.path[pef] = adj_pos
+ train.path_dist[pef] = train.path_dist[pef-1] + vector.distance(pos, adj_pos)
+ end
+ train.path_ext_f = pef
+
+
+ local peb = train.path_ext_b
+ -- generate backward (back of train, negative)
+ while index < peb do
+ local pos = train.path[peb]
+ local connid = train.path_cp[peb]
+ local node_ok, this_conns, adj_pos, adj_connid, conn_idx, nextrail_y, next_conns, next_connmap
+ if peb == train.path_trk_b then
+ node_ok, this_conns = advtrains.get_rail_info_at(pos)
+ if not node_ok then error("For train "..train.id..": Path item "..peb.." on-track but not a valid node!") end
+ adj_pos, adj_connid, conn_idx, nextrail_y, next_conns, next_connmap = advtrains.get_adjacent_rail(pos, this_conns, connid)
+ end
+ peb = peb - 1
+ if adj_pos then
+ advtrains.occ.set_item(train.id, adj_pos, peb)
+
+ local mconnid = advtrains.get_matching_conn(adj_connid, next_connmap)
+ -- If, for this position, we have remembered the origin conn, apply it here
+ if next_connmap then -- only needs to be done when this track is a turnout (>2 conns)
+ local origin_conn = train.path_ori_cp[advtrains.encode_pos(adj_pos)]
+ if origin_conn then
+ --atdebug("Train",train.id,"at",adj_pos,"restoring turnout origin CP",origin_conn,"for path item",index)
+ mconnid = origin_conn
+ end
+ end
+
+ adj_pos.y = adj_pos.y + nextrail_y
+ train.path_cn[peb] = adj_connid
+ train.path_cp[peb] = mconnid
+ train.path_dir[peb] = advtrains.conn_angle_median(next_conns[mconnid].c, next_conns[adj_connid].c)
+ train.path_trk_b = peb
+ else
+ -- off-track fallback behavior
+ adj_pos = advtrains.pos_add_angle(pos, train.path_dir[peb+1] + math.pi)
+ --atdebug("Offtrack overgenerating(back) at",adj_pos,"index",peb,"trkb",train.path_trk_b)
+ train.path_dir[peb] = train.path_dir[peb+1]
+ end
+ train.path[peb] = adj_pos
+ train.path_dist[peb] = train.path_dist[peb+1] - vector.distance(pos, adj_pos)
+ end
+ train.path_ext_b = peb
+
+ if index < train.path_req_b then
+ train.path_req_b = index
+ end
+ if index > train.path_req_f then
+ train.path_req_f = index
+ end
+
+ return train.path[index], (index<=train.path_trk_f and index>=train.path_trk_b)
+
+end
+
+-- interpolated position to fractional index given, and angle based on path_dir
+-- returns: pos, angle(yaw), p_floor, p_ceil
+function advtrains.path_get_interpolated(train, index)
+ local i_floor = atfloor(index)
+ local i_ceil = i_floor + 1
+ local frac = index - i_floor
+ local p_floor = advtrains.path_get(train, i_floor)
+ local p_ceil = advtrains.path_get(train, i_ceil)
+ -- Note: minimal code duplication to path_get_adjacent, for performance
+
+ local a_floor = train.path_dir[i_floor]
+ local a_ceil = train.path_dir[i_ceil]
+
+ local ang = advtrains.minAngleDiffRad(a_floor, a_ceil)
+
+ return vector.add(p_floor, vector.multiply(vector.subtract(p_ceil, p_floor), frac)), (a_floor + frac * ang)%(2*math.pi), p_floor, p_ceil
+end
+-- returns the 2 path positions directly adjacent to index and the fraction on how to interpolate between them
+-- returns: pos_floor, pos_ceil, fraction
+function advtrains.path_get_adjacent(train, index)
+ local i_floor = atfloor(index)
+ local i_ceil = i_floor + 1
+ local frac = index - i_floor
+ local p_floor = advtrains.path_get(train, i_floor)
+ local p_ceil = advtrains.path_get(train, i_ceil)
+ return p_floor, p_ceil, frac
+end
+
+local function n_interpolate(s, e, f)
+ return s + (e-s)*f
+end
+
+-- This function determines the index resulting from moving along the path by 'offset' meters
+-- starting from 'index'. See also the comment on the top of the file.
+function advtrains.path_get_index_by_offset(train, index, offset)
+ local advtrains_path_get = advtrains.path_get
+
+ -- Step 1: determine my current absolute pos on the path
+ local start_index_f = atfloor(index)
+ local end_index_f = start_index_f + 1
+ local c_idx = atfloor(index + offset)
+ local c_idx_f = c_idx + 1
+
+ local frac = index - start_index_f
+ --atdebug("in path_get_index_by_offset(",train.id,index,offset,")")
+ --atdebug("start_index_f=",start_index_f,"end_index_f=",end_index_f,"c_idx=",c_idx,"c_idx_f=",c_idx,"frac=",frac)
+
+ -- FIX 2026-02-08 due to rounding errors when searching backward it might be slightly behind the index, so add +-1 item buffer
+ advtrains_path_get(train, math.min(start_index_f, end_index_f, c_idx, c_idx_f) - 1)
+ advtrains_path_get(train, math.max(start_index_f, end_index_f, c_idx, c_idx_f) + 1)
+
+ local dist1, dist2 = train.path_dist[start_index_f], train.path_dist[start_index_f+1]
+ local start_dist = dist1 + (dist2-dist1)*frac
+
+ -- Step 2: determine the total end distance and estimate the index we'd come out
+ local end_dist = start_dist + offset
+
+ local c_idx = atfloor(index + offset)
+ --atdebug("c_idx=",c_idx,"end_dist=",end_dist)
+
+ -- Step 3: move forward/backward to find real index
+ -- We assume here that the distance between 2 path items is never smaller than 1.
+ -- Our estimated index is therefore either exact or too far over, and we're going to go back
+ -- towards the origin. It is therefore sufficient to query path_get a single time
+
+ -- How we'll adjust c_idx
+ -- Desired position: -------#------
+ -- Path items : --|--|--|--|--
+ -- c_idx : ^
+
+ while train.path_dist[c_idx] < end_dist do
+ c_idx = c_idx + 1
+ if not train.path_dist[c_idx] then
+ atdebug("path_dist out of generated range (first loop):",c_idx)
+ advtrains.path_print(train, atdebug)
+ end
+ end
+
+ while train.path_dist[c_idx] > end_dist do
+ c_idx = c_idx - 1
+ if not train.path_dist[c_idx] then
+ atdebug("path_dist out of generated range (second loop):",c_idx)
+ advtrains.path_print(train, atdebug)
+ end
+ end
+
+ -- Step 4: now c_idx points to the place shown above. Find out the fractional part.
+
+ dist1, dist2 = train.path_dist[c_idx], train.path_dist[c_idx+1]
+
+ frac = (end_dist - dist1) / (dist2 - dist1)
+
+ assert(frac>=0 and frac<1, frac)
+
+ return c_idx + frac
+end
+
+
+-- The path_dist[] table contains absolute distance values for every whole index.
+-- Use this function to retrieve the correct absolute distance for a fractional index value (interpolate between floor and ceil index)
+-- returns: absolute distance from path item 0
+function advtrains.path_get_path_dist_fractional(train, index)
+ local start_index_f = atfloor(index)
+ local frac = index - start_index_f
+ -- ensure path exists
+ advtrains.path_get_adjacent(train, index)
+ local dist1, dist2 = train.path_dist[start_index_f], train.path_dist[start_index_f+1]
+ return dist1 + (dist2-dist1)*frac
+end
+
+local PATH_CLEAR_KEEP = 4
+
+function advtrains.path_clear_unused(train)
+ local i
+ for i = train.path_ext_b, train.path_req_b - PATH_CLEAR_KEEP do
+ advtrains.occ.clear_specific_item(train.id, advtrains.round_vector_floor_y(train.path[i]), i)
+ train.path[i] = nil
+ train.path_dist[i-1] = nil
+ train.path_cp[i] = nil
+ train.path_cn[i] = nil
+ train.path_dir[i] = nil
+ train.path_ext_b = i + 1
+ end
+
+ --[[ Why exactly are we clearing path from the front? This doesn't make sense!
+ for i = train.path_ext_f,train.path_req_f + PATH_CLEAR_KEEP,-1 do
+ advtrains.occ.clear_item(train.id, advtrains.round_vector_floor_y(train.path[i]))
+ train.path[i] = nil
+ train.path_dist[i] = nil
+ train.path_cp[i] = nil
+ train.path_cn[i] = nil
+ train.path_dir[i+1] = nil
+ train.path_ext_f = i - 1
+ end ]]
+ train.path_trk_b = math.max(train.path_trk_b, train.path_ext_b)
+ --train.path_trk_f = math.min(train.path_trk_f, train.path_ext_f)
+
+ train.path_req_f = math.ceil(train.index)
+ train.path_req_b = math.floor(train.end_index or train.index)
+end
+
+-- Scan the path of the train for position, without querying the occupation table
+-- returns index, or nil if pos is not on the path
+function advtrains.path_lookup(train, pos)
+ local cp = advtrains.round_vector_floor_y(pos)
+ for i = train.path_ext_b, train.path_ext_f do
+ if vector.equals(advtrains.round_vector_floor_y(train.path[i]), cp) then
+ return i
+ end
+ end
+ return nil
+end
+
+-- Projects the path of "train" onto the path of "onto_train_id", and returns the index on onto_train's path
+-- that corresponds to "index" on "train"'s path, as well as whether both trains face each other
+-- index may be fractional
+-- heuristic: see advtrains.occ.reverse_lookup_sel()
+-- returns: res_index, trains_facing
+-- returns nil when path can not be projected, either because trains are on different tracks or
+-- node at "index" happens to be on a turnout and it's the wrong direction
+-- Note - duplicate with similar functionality is in train_step_b() - that code combines train detection with projecting
+function advtrains.path_project(train, index, onto_train_id, heuristic)
+ local base_idx = atfloor(index)
+ local frac_part = index - base_idx
+ local base_pos = advtrains.path_get(train, base_idx)
+ local base_cn = train.path_cn[base_idx]
+ local otrn = advtrains.trains[onto_train_id]
+ -- query occupation
+ local occ = advtrains.occ.reverse_lookup_sel(base_pos, heuristic)
+ -- is wanted train id contained?
+ local ob_idx = occ[onto_train_id]
+ if not ob_idx then
+ return nil
+ end
+
+ -- retrieve other train's cn and cp
+ local ocn = otrn.path_cn[ob_idx]
+ local ocp = otrn.path_cp[ob_idx]
+
+ if base_cn == ocn then
+ -- same direction
+ return ob_idx + frac_part, false
+ elseif base_cn == ocp then
+ -- facing trains - subtract index frac
+ return ob_idx - frac_part, true
+ else
+ -- same path item but no common connections - deny
+ return nil
+ end
+end
+
+
diff --git a/advtrains/protection.lua b/advtrains/protection.lua
new file mode 100644
index 0000000..6bb1ccb
--- /dev/null
+++ b/advtrains/protection.lua
@@ -0,0 +1,199 @@
+-- advtrains
+-- protection.lua: privileges and rail protection, and some helpers
+
+-- Get current translator
+local S = advtrains.translate
+
+-- Privileges to control TRAIN DRIVING/COUPLING
+minetest.register_privilege("train_operator", {
+ description = S("Can place, remove and operate trains"),
+ give_to_singleplayer= true,
+});
+
+minetest.register_privilege("train_admin", {
+ description = S("Can place, remove and operate any train, regardless of owner, whitelist, or protection"),
+ give_to_singleplayer= true,
+});
+
+-- Privileges to control TRACK BUILDING
+minetest.register_privilege("track_builder", {
+ description = S("Can place and dig tracks in unprotected areas"),
+ give_to_singleplayer= true,
+});
+
+-- Privileges to control OPERATING TURNOUTS/SIGNALS
+minetest.register_privilege("railway_operator", {
+ description = S("Can operate turnouts and signals in unprotected areas"),
+ give_to_singleplayer= true,
+});
+
+-- there is a configuration option "allow_build_only_owner". If this is active, a player having track_builder can only build rails and operate signals/turnouts in an area explicitly belonging to him
+-- (checked using a dummy player called "*dummy*" (which is not an allowed player name))
+
+
+-- Protection ranges
+local npr_r = tonumber(minetest.settings:get("advtrains_prot_range_side")) or 1
+local npr_vr = tonumber(minetest.settings:get("advtrains_prot_range_up")) or 3
+local npr_vrd = tonumber(minetest.settings:get("advtrains_prot_range_down")) or 1
+
+local boo = minetest.settings:get_bool("advtrains_allow_build_to_owner")
+
+--[[
+Protection/privilege concept:
+Tracks:
+ Protected 1 node all around a rail and 4 nodes upward (maybe make this dynamically determined by the rail...)
+ if track_builder privilege:
+ if not protected from* player:
+ if allow_build_only_owner:
+ if unprotected:
+ deny
+ else:
+ allow
+ deny
+Wagons in general:
+ Players can only place/destroy wagons if they have train_operator
+Wagon driving controls:
+ The former seat_access tables are unnecessary, instead there is a whitelist for the driving stands
+ on player trying to access a driver stand:
+ if is owner or is on whitelist:
+ allow
+ else:
+ deny
+Wagon coupling:
+ Derived from the privileges for driving stands. The whitelist is shared (and also settable on non-driverstand wagons)
+ for each of the two bordering wagons:
+ if is owner or is on whitelist:
+ allow
+
+*"protected from" means the player is not allowed to do things, while "protected by" means that the player is (one of) the owner(s) of this area
+
+]]--
+
+-- temporarily prevent scanning for neighboring rail nodes recursively
+local nocheck
+
+local old_is_protected = minetest.is_protected
+
+-- Check if the node we are about to check is in the range of a track that is protected from a player
+minetest.is_protected = function(pos, pname)
+
+ -- old_is_protected:
+ -- If an earlier callback decided that pos is protected, we wouldn't have been called
+ -- if a later callback decides it, get that here.
+ -- this effectively puts this function into a final-choice position
+ local oprot = old_is_protected(pos, pname)
+ if oprot then
+ return true
+ end
+
+ if nocheck or pname=="" then
+ return false
+ end
+
+ -- Special exception: to allow seamless rail connections between 2 separately protected
+ -- networks, rails itself are not affected by the radius setting. So, if the node here is
+ -- a rail, we skip the check and just use check_track_protection on same pos.
+ local node = minetest.get_node(pos)
+ if minetest.get_item_group(node.name, "advtrains_track") > 0 then
+ -- by here, we know that no other protection callback has this protected, we can safely pass "false".
+ -- hope this doesn't lead to bugs!
+ return not advtrains.check_track_protection(pos, pname, nil, false)
+ end
+
+ local nodes = minetest.find_nodes_in_area(
+ {x = pos.x - npr_r, y = pos.y - npr_vr, z = pos.z - npr_r},
+ {x = pos.x + npr_r, y = pos.y + npr_vrd, z = pos.z + npr_r},
+ {"group:advtrains_track"})
+ for _,npos in ipairs(nodes) do
+ if not advtrains.check_track_protection(npos, pname, pos) then
+ return true
+ end
+ end
+ nocheck=false
+ return false
+end
+
+-- Check whether the player is permitted to modify this track
+-- Shall be called only for nodes that are or are about to become tracks.
+-- The range check from is_track_near_protected is disabled here.
+-- this splits in 1. track_builder privilege and 2. is_protected
+-- also respects the allow_build_to_owner property.
+--WARN: true means here that the action is allowed!
+function advtrains.check_track_protection(pos, pname, near, prot_p)
+ -- Parameter "near" is an optional position, the original node that the player
+ -- was about to affect, while "pos" represents the checked rail node
+ -- if "near" is not set, pos is the same node.
+ local nears = near and "near " or ""
+ local apos = near or pos
+
+ -- note that having protection_bypass implicitly implies having track_builder, because else it would be possible to dig rails
+ -- (only checked by is_protected, which is not respected) but not place them.
+ -- We won't impose restrictions on protection_bypass owners.
+ if minetest.check_player_privs(pname, {protection_bypass = true}) then
+ return true
+ end
+
+ nocheck = true
+ local priv = minetest.check_player_privs(pname, {track_builder = true})
+
+ -- note: is_protected above already checks the is_protected value against the current player, so checking it again is useless.
+ local prot = prot_p
+ if prot==nil then
+ prot = advtrains.is_protected(pos, pname)
+ end
+ local dprot = minetest.is_protected(pos, "*dummy*")
+ nocheck = false
+
+ --atdebug("CTP: ",pos,pname,near,prot_p,"priv=",priv,"prot=",prot,"dprot=",dprot)
+
+ if not priv and (not boo or prot or not dprot) then
+ minetest.chat_send_player(pname, near and S("You are not allowed to build near tracks without the track_builder privilege.") or S("You are not allowed to build tracks without the track_builder privilege."))
+ minetest.log("action", pname.." tried to modify terrain "..nears.."track at "..minetest.pos_to_string(apos).." but is not permitted to (no privilege)")
+ return false
+ end
+ if prot then
+ minetest.chat_send_player(pname, near and S("You are not allowed to build near tracks at this protected position.") or S("You are not allowed to build tracks at this protected position."))
+ minetest.record_protection_violation(pos, pname)
+ minetest.log("action", pname.." tried to modify "..nears.."track at "..minetest.pos_to_string(apos).." but position is protected!")
+ return false
+ end
+ return true
+end
+
+--WARN: true means here that the action is allowed!
+function advtrains.check_driving_couple_protection(pname, owner, whitelist)
+ if minetest.check_player_privs(pname, {train_admin = true}) then
+ return true
+ end
+ if not minetest.check_player_privs(pname, {train_operator = true}) then
+ return false
+ end
+ if not owner or owner == pname then
+ return true
+ end
+ if whitelist and string.find(" "..whitelist.." ", " "..pname.." ", nil, true) then
+ return true
+ end
+ return false
+end
+function advtrains.check_turnout_signal_protection(pos, pname)
+ nocheck=true
+ if not minetest.check_player_privs(pname, {railway_operator = true}) then
+ if boo and not advtrains.is_protected(pos, pname) and minetest.is_protected(pos, "*dummy*") then
+ nocheck=false
+ return true
+ else
+ minetest.chat_send_player(pname, S("You are not allowed to operate turnouts and signals without the railway_operator privilege."))
+ minetest.log("action", pname.." tried to operate turnout/signal at "..minetest.pos_to_string(pos).." but does not have railway_operator")
+ nocheck=false
+ return false
+ end
+ end
+ if advtrains.is_protected(pos, pname) then
+ minetest.record_protection_violation(pos, pname)
+ nocheck=false
+ return false
+ end
+ nocheck=false
+ return true
+end
diff --git a/advtrains/readme.txt b/advtrains/readme.txt
deleted file mode 100644
index eaed121..0000000
--- a/advtrains/readme.txt
+++ /dev/null
@@ -1,25 +0,0 @@
-
-## ADVTRAINS ## realistic trains in Minetest!
-by orwell96 and contributors(see below)
-
-For up-to-date information, visit https://forum.minetest.net/viewtopic.php?f=9&t=14726
-
-
-Manual:
-If manual.pdf is not present (which is the case when you downloaded the zip file), see https://github.com/orwell96/advtrains/blob/master/manual.pdf
-
-License of code: LGPL 2.1
-License of media: CC-BY-SA 3.0
-
-Contributions:
-
-Gravel Texture : from Minetest Game
-Initial rail model/texture : DS-minetest
-Models for signals/bumpers : mbb
-Steam engine / wagon texture: mbb
-Detailed Steam engine : mbb / Krokoschlange(animation)
-Industrial engine/wagons : mbb
-Inventory images : mbb
-Small code contributions : NaruTrey / gpcf
-Mod Description : hajo
-If I forgot someone please punish me for that. \ No newline at end of file
diff --git a/advtrains/screenshot.png b/advtrains/screenshot.png
deleted file mode 100644
index 78783e1..0000000
--- a/advtrains/screenshot.png
+++ /dev/null
Binary files differ
diff --git a/advtrains/settingtypes.txt b/advtrains/settingtypes.txt
new file mode 100644
index 0000000..a09da71
--- /dev/null
+++ b/advtrains/settingtypes.txt
@@ -0,0 +1,70 @@
+# Display train and wagon ID in the infotext of trains.
+# Useful when working with LuaATC or while debugging.
+advtrains_show_ids (Show ID's in infotext) bool false
+
+# Enable the debug ring buffer
+# This has no effect on the user experience, except decreased performance. Debug outputs are saved in a ring buffer to be printed when an error occurs.
+# You probably want to leave this setting set to false.
+advtrains_enable_debugging (Enable debugging) bool false
+
+# Register certain debug items, for example the tunnelborer
+# Do not use on productive servers!
+advtrains_register_debugitems (Register Debug Items) bool false
+
+# Enable the logging of certain events related to advtrains
+# Logs are saved in the world directory as advtrains.log
+# This setting is useful for multiplayer servers
+advtrains_enable_logging (Enable logging) bool false
+
+# If this is active, any player can do the following things inside (and only inside) an area that is explicitly protected by him
+# (checked using a dummy player called "*dummy*" (which is not an allowed player name)):
+# - build tracks and near tracks without the track_builder privilege
+# - operate turnouts and signals without the railway_operator privilege
+advtrains_allow_build_to_owner (Allow building/operating to privilegeless area owner) bool false
+
+# Track protection range (horizontal)
+# Players without the 'track_builder' privilege can not build within a box around any tracks determined by these range settings
+# This setting is to be read as "r-0.5", so a value of 1 means a diameter of 3, a value of 2 a diameter of 5 a.s.o.
+# The spanned area is a square. Fractional values are not supported.
+advtrains_prot_range_side (Track protection range [horizontal]) int 1 0 10
+
+# Track protection range (up)
+# Players without the 'track_builder' privilege can not build within a box around any tracks determined by these range settings
+# This setting determines the upper y bound of the box, a value of 3 means that the rail and 3 nodes above it are protected
+advtrains_prot_range_up (Track protection range [up]) int 3 0 10
+
+# Track protection range (down)
+# Players without the 'track_builder' privilege can not build within a box around any tracks determined by these range settings
+# This setting determines the lower y bound of the box, a value of 1 means that the rail and 1 node below it are protected
+advtrains_prot_range_down (Track protection range [down]) int 1 0 10
+
+# Determine what effect "being overrun by a train" has.
+# none: No damage is dealt at all.
+# drop: Player is killed, all items are dropped as items on the tracks.
+# normal: Player is killed, game-defined behavior is applied as if the player died by other means.
+advtrains_overrun_mode (Overrun mode) enum drop none,drop,normal
+
+# Wagon entity loading/unloading range, in nodes
+# When a wagon is within this range to a player, it is loaded
+# When a wagon leaves this range + 32 nodes, it is unloaded
+# If unset, defaults to active_block_range*16
+advtrains_wagon_load_range (Wagon Entity Load/Unload Range) int 96 32 512
+
+# Simulation DTime Limit after which slow-down becomes effective
+# When the dtime value (time since last server step) is higher than this value,
+# advtrains applies a global slow-down factor to the dtime and to the velocity and
+# acceleration of wagons to decrease server load.
+# A value of 0 (default) disables this behavior.
+advtrains_dtime_limit (DTime Limit for slow-down) float 0.2 0 5
+
+# Time interval in seconds in which advtrains stores its save data to disk
+# Nevertheless, advtrains saves all data when shutting down the server.
+advtrains_save_interval (Save Interval) int 60 20 3600
+
+# Enable forgiving collision mode
+# If enabled, trains only collide with nodes with "normal" drawtype.
+advtrains_forgiving_collision (Forgiving Collision mode) bool false
+
+# Enable universal couplers for wagons
+# If enabled, wagons will bypass the checks that compare the coupler types when coupling.
+advtrains_universal_couplers (Universal Couplers) bool false \ No newline at end of file
diff --git a/advtrains/signals.lua b/advtrains/signals.lua
new file mode 100644
index 0000000..198507a
--- /dev/null
+++ b/advtrains/signals.lua
@@ -0,0 +1,342 @@
+--advtrains by orwell96
+--signals.lua
+
+-- Get current translator
+local S = advtrains.translate
+
+local mrules_wallsignal = advtrains.meseconrules
+
+local function can_dig_func(pos, player)
+ if advtrains.interlocking then
+ return advtrains.interlocking.signal.can_dig(pos, player)
+ end
+ return true
+end
+local function after_dig_func(pos, oldnode, oldmetadata, digger)
+ if advtrains.interlocking then
+ return advtrains.interlocking.signal.after_dig(pos, oldnode, oldmetadata, digger)
+ end
+ return true
+end
+
+local function aspect(b)
+return {
+ main = b and -1 or 0,
+ shunt = false,
+ proceed_as_main = true,
+ dst = false,
+ info = {}
+}
+end
+
+local main_aspects = {
+ { name = "free", description = "Free" }
+}
+
+local function simple_apply_aspect(offname, onname)
+ return function(pos, node, main_aspect, rem_aspect, rem_aspinfo)
+ if main_aspect.halt then
+ advtrains.ndb.swap_node(pos, {name = offname, param2 = node.param2})
+ else
+ advtrains.ndb.swap_node(pos, {name = onname, param2 = node.param2})
+ end
+ end
+end
+
+for r,f in pairs({on={as="off", ls="green", als="red"}, off={as="on", ls="red", als="green"}}) do
+
+ for rotid, rotation in ipairs({"", "_30", "_45", "_60"}) do
+ local crea=1
+ if rotid==1 and r=="off" then crea=0 end
+
+ minetest.register_node("advtrains:retrosignal_"..r..rotation, {
+ drawtype = "mesh",
+ paramtype="light",
+ paramtype2="facedir",
+ walkable = false,
+ selection_box = {
+ type = "fixed",
+ fixed = {-1/4, -1/2, -1/4, 1/4, 2, 1/4},
+ },
+ mesh = "advtrains_retrosignal_"..r..rotation..".b3d",
+ tiles = {"advtrains_retrosignal.png"},
+ inventory_image="advtrains_retrosignal_inv.png",
+ drop="advtrains:retrosignal_off",
+ description=S("Lampless Signal (deprecated!)"),
+ sunlight_propagates=true,
+ groups = {
+ cracky=3,
+ not_blocking_trains=1,
+ not_in_creative_inventory=crea,
+ save_in_at_nodedb=1,
+ advtrains_signal = 2,
+ },
+ mesecons = {effector = {
+ rules=advtrains.meseconrules,
+ ["action_"..f.as] = function (pos, node)
+ advtrains.ndb.swap_node(pos, {name = "advtrains:retrosignal_"..f.as..rotation, param2 = node.param2}, true)
+ if advtrains.interlocking then
+ -- forcefully clears any set aspect, so that aspect system doesnt override it again
+ advtrains.interlocking.signal.unregister_aspect(pos)
+ -- notify trains
+ advtrains.interlocking.signal.notify_trains(pos)
+ end
+ end
+ }},
+ on_rightclick=function(pos, node, player)
+ local pname = player:get_player_name()
+ local sigd = advtrains.interlocking and advtrains.interlocking.db.get_sigd_for_signal(pos)
+ if sigd and not player:get_player_control().aux1 then
+ advtrains.interlocking.show_signalling_form(sigd, pname)
+ elseif advtrains.interlocking and player:get_player_control().aux1 then
+ advtrains.interlocking.show_ip_form(pos, pname)
+ elseif advtrains.check_turnout_signal_protection(pos, player:get_player_name()) then
+ advtrains.ndb.swap_node(pos, {name = "advtrains:retrosignal_"..f.as..rotation, param2 = node.param2}, true)
+ if advtrains.interlocking then
+ -- forcefully clears any set aspect, so that aspect system doesnt override it again
+ advtrains.interlocking.signal.unregister_aspect(pos)
+ -- notify trains
+ advtrains.interlocking.signal.notify_trains(pos)
+ end
+ end
+ end,
+ -- very new signal API
+ advtrains = {
+ main_aspects = main_aspects,
+ apply_aspect = simple_apply_aspect("advtrains:retrosignal_off"..rotation, "advtrains:retrosignal_on"..rotation),
+ get_aspect_info = function() return aspect(r=="on") end,
+ route_role = "main",
+ },
+ can_dig = can_dig_func,
+ after_dig_node = after_dig_func,
+ --TODO add rotation using trackworker
+ })
+
+ minetest.register_node("advtrains:signal_"..r..rotation, {
+ drawtype = "mesh",
+ paramtype="light",
+ paramtype2="facedir",
+ walkable = false,
+ selection_box = {
+ type = "fixed",
+ fixed = {-1/4, -1/2, -1/4, 1/4, 2, 1/4},
+ },
+ mesh = "advtrains_signal"..rotation..".b3d",
+ tiles = {"advtrains_signal_"..r..".png"},
+ inventory_image="advtrains_signal_inv.png",
+ drop="advtrains:signal_off",
+ description=S("Signal (deprecated!)"),
+ groups = {
+ cracky=3,
+ not_blocking_trains=1,
+ not_in_creative_inventory=crea,
+ save_in_at_nodedb=1,
+ advtrains_signal = 2,
+ },
+ light_source = 1,
+ sunlight_propagates=true,
+ mesecons = {effector = {
+ rules=advtrains.meseconrules,
+ ["action_"..f.as] = function (pos, node)
+ advtrains.setstate(pos, f.als, node)
+ end
+ }},
+ on_rightclick=function(pos, node, player)
+ local pname = player:get_player_name()
+ local sigd = advtrains.interlocking and advtrains.interlocking.db.get_sigd_for_signal(pos)
+ if sigd and not player:get_player_control().aux1 then
+ advtrains.interlocking.show_signalling_form(sigd, pname)
+ elseif advtrains.interlocking and player:get_player_control().aux1 then
+ advtrains.interlocking.show_ip_form(pos, pname)
+ elseif advtrains.check_turnout_signal_protection(pos, player:get_player_name()) then
+ advtrains.setstate(pos, f.als, node)
+ end
+ end,
+ -- very new signal API
+ advtrains = {
+ main_aspects = main_aspects,
+ apply_aspect = simple_apply_aspect("advtrains:signal_off"..rotation, "advtrains:signal_on"..rotation),
+ get_aspect_info = function() return aspect(r=="on") end,
+ route_role = "main",
+ node_state = f.ls,
+ node_state_map = { red = "advtrains:signal_off"..rotation, green = "advtrains:signal_on"..rotation},
+ node_on_switch_state = function(pos, new_node, old_state, new_state)
+ if advtrains.interlocking then
+ -- forcefully clears any set aspect, so that aspect system doesnt override it again
+ advtrains.interlocking.signal.unregister_aspect(pos)
+ -- notify trains
+ advtrains.interlocking.signal.notify_trains(pos)
+ end
+ end,
+ },
+ can_dig = can_dig_func,
+ after_dig_node = after_dig_func,
+ --TODO add rotation using trackworker
+ })
+ end
+
+ local crea=1
+ if r=="off" then crea=0 end
+
+ --tunnel signals. no rotations.
+ local swdesc = { -- needed for xgettext
+ l = S("Wallmounted Signal (left) (deprecated!)"),
+ r = S("Wallmounted Signal (right) (deprecated!)"),
+ t = S("Wallmounted Signal (top) (deprecated!)"),
+ }
+ for loc, sbox in pairs({l={-1/2, -1/2, -1/4, 0, 1/2, 1/4}, r={0, -1/2, -1/4, 1/2, 1/2, 1/4}, t={-1/2, 0, -1/4, 1/2, 1/2, 1/4}}) do
+ minetest.register_node("advtrains:signal_wall_"..loc.."_"..r, {
+ drawtype = "mesh",
+ paramtype="light",
+ paramtype2="facedir",
+ walkable = false,
+ selection_box = {
+ type = "fixed",
+ fixed = sbox,
+ },
+ mesh = "advtrains_signal_wall_"..loc..".b3d",
+ tiles = {"advtrains_signal_wall_"..r..".png"},
+ drop="advtrains:signal_wall_"..loc.."_off",
+ description=swdesc[loc],
+ groups = {
+ cracky=3,
+ not_blocking_trains=1,
+ not_in_creative_inventory=crea,
+ save_in_at_nodedb=1,
+ advtrains_signal = 2,
+ },
+ light_source = 1,
+ sunlight_propagates=true,
+ mesecons = {effector = {
+ rules = mrules_wallsignal,
+ ["action_"..f.as] = function (pos, node)
+ advtrains.setstate(pos, f.als, node)
+ end
+ }},
+ on_rightclick=function(pos, node, player)
+ local pname = player:get_player_name()
+ local sigd = advtrains.interlocking and advtrains.interlocking.db.get_sigd_for_signal(pos)
+ if sigd and not player:get_player_control().aux1 then
+ advtrains.interlocking.show_signalling_form(sigd, pname)
+ elseif advtrains.interlocking and player:get_player_control().aux1 then
+ advtrains.interlocking.show_ip_form(pos, pname)
+ elseif advtrains.check_turnout_signal_protection(pos, player:get_player_name()) then
+ advtrains.setstate(pos, f.als, node)
+ end
+ end,
+ -- very new signal API
+ advtrains = {
+ main_aspects = main_aspects,
+ apply_aspect = simple_apply_aspect("advtrains:signal_wall_"..loc.."_off", "advtrains:signal_wall_"..loc.."_on"),
+ get_aspect_info = function() return aspect(r=="on") end,
+ route_role = "main",
+ node_state = f.ls,
+ node_state_map = { red = "advtrains:signal_wall_"..loc.."_off", green = "advtrains:signal_wall_"..loc.."_on" },
+ node_on_switch_state = function(pos, new_node, old_state, new_state)
+ if advtrains.interlocking then
+ -- forcefully clears any set aspect, so that aspect system doesnt override it again
+ advtrains.interlocking.signal.unregister_aspect(pos)
+ -- notify trains
+ advtrains.interlocking.signal.notify_trains(pos)
+ end
+ end,
+ },
+ can_dig = can_dig_func,
+ after_dig_node = after_dig_func,
+ })
+ end
+end
+
+-- level crossing
+-- german version (Andrew's Cross)
+minetest.register_node("advtrains:across_off", {
+ drawtype = "mesh",
+ paramtype="light",
+ paramtype2="facedir",
+ walkable = false,
+ selection_box = {
+ type = "fixed",
+ fixed = {-1/4, -1/2, -1/2, 1/4, 1.5, 0},
+ },
+ mesh = "advtrains_across.obj",
+ tiles = {"advtrains_across.png"},
+ drop="advtrains:across_off",
+ description=S("Andrew's Cross"),
+ groups = {
+ cracky=3,
+ not_blocking_trains=1,
+ save_in_at_nodedb=1,
+ not_in_creative_inventory=nil,
+ },
+ light_source = 1,
+ sunlight_propagates=true,
+ mesecons = {effector = {
+ rules = advtrains.meseconrules,
+ action_on = function (pos, node)
+ advtrains.ndb.swap_node(pos, {name = "advtrains:across_on", param2 = node.param2}, true)
+ end
+ }},
+ advtrains = {
+ node_state = "off",
+ node_state_map = { on = "advtrains:across_on", off = "advtrains:across_off" },
+ },
+ on_rightclick=function(pos, node, player)
+ if advtrains.check_turnout_signal_protection(pos, player:get_player_name()) then
+ advtrains.ndb.swap_node(pos, {name = "advtrains:across_on", param2 = node.param2}, true)
+ end
+ end,
+})
+minetest.register_node("advtrains:across_on", {
+ drawtype = "mesh",
+ paramtype="light",
+ paramtype2="facedir",
+ walkable = false,
+ selection_box = {
+ type = "fixed",
+ fixed = {-1/4, -1/2, -1/2, 1/4, 1.5, 0},
+ },
+ mesh = "advtrains_across.obj",
+ tiles = {{name="advtrains_across_anim.png", animation={type="vertical_frames", aspect_w=64, aspect_h=64, length=1.0}}},
+ drop="advtrains:across_off",
+ description=S("Andrew's Cross"),
+ groups = {
+ cracky=3,
+ not_blocking_trains=1,
+ save_in_at_nodedb=1,
+ not_in_creative_inventory=1,
+ },
+ light_source = 1,
+ sunlight_propagates=true,
+ mesecons = {effector = {
+ rules = advtrains.meseconrules,
+ action_off = function (pos, node)
+ advtrains.ndb.swap_node(pos, {name = "advtrains:across_off", param2 = node.param2}, true)
+ end
+ }},
+ advtrains = {
+ node_state = "on",
+ node_state_map = { on = "advtrains:across_on", off = "advtrains:across_off" },
+ node_fallback_state = "off",
+ },
+ on_rightclick=function(pos, node, player)
+ if advtrains.check_turnout_signal_protection(pos, player:get_player_name()) then
+ advtrains.ndb.swap_node(pos, {name = "advtrains:across_off", param2 = node.param2}, true)
+ end
+ end,
+})
+
+minetest.register_abm(
+ {
+ label = "Sound for Level Crossing",
+ nodenames = {"advtrains:across_on"},
+ interval = 3,
+ chance = 1,
+ action = function(pos, node, active_object_count, active_object_count_wider)
+ minetest.sound_play("advtrains_crossing_bell", {
+ pos = pos,
+ gain = 1.0, -- default
+ max_hear_distance = 16, -- default, uses an euclidean metric
+ })
+ end,
+ }
+)
diff --git a/advtrains/sounds/advtrains_crossing_bell.ogg b/advtrains/sounds/advtrains_crossing_bell.ogg
new file mode 100644
index 0000000..2b441ae
--- /dev/null
+++ b/advtrains/sounds/advtrains_crossing_bell.ogg
Binary files differ
diff --git a/advtrains/spec/speed_spec.lua b/advtrains/spec/speed_spec.lua
new file mode 100644
index 0000000..97f8ffa
--- /dev/null
+++ b/advtrains/spec/speed_spec.lua
@@ -0,0 +1,70 @@
+package.path = "../?.lua;" .. package.path
+advtrains = {}
+_G.advtrains = advtrains
+local speed = require("speed")
+
+describe("Arithmetic functions on speed restrictions", function()
+ it("should work", function()
+ local a = math.random()
+ local b = math.random(20)
+ -- This test is basically a "typo check"
+ assert.is_true (speed.lessp(a, b))
+ assert.is_false(speed.greaterp(a, b))
+ assert.is_false(speed.not_lessp(a, b))
+ assert.is_true (speed.not_greaterp(a, b))
+ assert.is_false(speed.lessp(a, a))
+ assert.is_false(speed.greaterp(a, a))
+ assert.is_true (speed.equalp(a, a))
+ assert.is_false(speed.not_equalp(a, a))
+ assert.equal(b, speed.max(a, b))
+ assert.equal(a, speed.min(a, b))
+ end)
+ it("should handle -1", function()
+ assert.is_false(speed.lessp(-1, math.random()))
+ end)
+ it("should handle nil", function()
+ assert.is_true(speed.greaterp(nil, math.random()))
+ end)
+ it("should handle mixed nil and -1", function()
+ assert.is_true(speed.equalp(nil, -1))
+ end)
+end)
+
+describe("The speed restriction setter", function()
+ it("should set the signal aspect", function()
+ local t = {speed_restrictions_t = {x = 5, y = 9}}
+ local u = {speed_restrictions_t = {x = 7, y = 9}, speed_restriction = 7}
+ speed.merge_aspect(t, {main = 7, type = "x"})
+ assert.same(u, t)
+ end)
+ it("should work with existing signal aspect tables", function()
+ local t = {speed_restrictions_t = {main = 5, foo = 3}}
+ local u = {speed_restrictions_t = {main = 7, foo = 3}, speed_restriction = 3}
+ speed.merge_aspect(t, {main = 7})
+ assert.same(u, t)
+ end)
+ it("should work with distant signals", function()
+ local t = {speed_restrictions_t = {main = 5}}
+ local u = {speed_restrictions_t = {main = 5}, speed_restriction = 5}
+ speed.merge_aspect(t, {})
+ assert.same(u, t)
+ end)
+ it("should create the restriction table if necessary", function()
+ local t = {speed_restriction = 5}
+ local u = {speed_restriction = 3, speed_restrictions_t = {main = 5, foo = 3}}
+ speed.merge_aspect(t, {main = 3, type = "foo"})
+ assert.same(u, t)
+ end)
+ it("should also create the restriction table for trains without any speed limit", function()
+ local t = {}
+ local u = {speed_restrictions_t = {}}
+ speed.merge_aspect(t, {})
+ assert.same(u, t)
+ end)
+ it("should set the speed restriction to nil if that is the case", function()
+ local t = {speed_restriction = math.random(20)}
+ local u = {speed_restrictions_t = {main = -1}}
+ speed.merge_aspect(t, {main = -1})
+ assert.same(u, t)
+ end)
+end)
diff --git a/advtrains/spec/texture_spec.lua b/advtrains/spec/texture_spec.lua
new file mode 100644
index 0000000..2e3bd5d
--- /dev/null
+++ b/advtrains/spec/texture_spec.lua
@@ -0,0 +1,19 @@
+package.path = "../?.lua;" .. package.path
+local T = require "texture"
+
+describe("Texture creation", function()
+ it("works", function()
+ assert.same("^.png", tostring(T.raw"^.png"))
+ assert.same("foo\\:bar.png", tostring(T"foo:bar.png"))
+ end)
+end)
+
+describe("Texture modifiers", function()
+ it("work", function()
+ assert.same("x^[colorize:c", tostring(T"x":colorize"c"))
+ assert.same("x^[colorize:c:alpha", tostring(T"x":colorize("c", "alpha")))
+ assert.same("x^[multiply:c", tostring(T"x":multiply"c"))
+ assert.same("x^[resize:2x3", tostring(T"x":resize(2, 3)))
+ assert.same("x^[transformI", tostring(T"x":transform"I"))
+ end)
+end)
diff --git a/advtrains/spec/wagons_spec.lua b/advtrains/spec/wagons_spec.lua
new file mode 100644
index 0000000..df0687b
--- /dev/null
+++ b/advtrains/spec/wagons_spec.lua
@@ -0,0 +1,40 @@
+require "mineunit"
+mineunit "core"
+
+_G.advtrains = {
+ wagon_load_range = 32
+}
+sourcefile "wagons"
+
+local myproto = {_test = true}
+advtrains.register_wagon(":mywagon", myproto, "My wagon", "", false)
+advtrains.register_wagon_alias(":myalias", ":mywagon")
+advtrains.register_wagon_alias(":myotheralias", ":myalias")
+
+local myotherproto = {_other = true}
+advtrains.register_wagon(":noalias", myotherproto, "Not aliased wagon", "", false)
+advtrains.register_wagon_alias(":noalias", ":mywagon")
+
+advtrains.register_wagon_alias(":nilalias", ":nil")
+
+advtrains.register_wagon_alias(":R1", ":R2")
+advtrains.register_wagon_alias(":R2", ":R3")
+advtrains.register_wagon_alias(":R3", ":R1")
+
+describe("wagon alias system", function()
+ it("should work", function()
+ assert.same({":mywagon", myproto}, {advtrains.resolve_wagon_alias(":myalias")})
+ assert.equal(myproto, advtrains.wagon_prototypes[":myalias"])
+ assert.same({":mywagon", myproto}, {advtrains.resolve_wagon_alias(":myotheralias")})
+ end)
+ it("should respect wagon registration", function()
+ assert.same({":noalias", myotherproto}, {advtrains.resolve_wagon_alias(":noalias")})
+ end)
+ it("should handle recursive loops", function()
+ assert.same({}, {advtrains.resolve_wagon_alias(":R1")})
+ end)
+ it("should return nil for missing entries", function()
+ assert.same({}, {advtrains.resolve_wagon_alias(":what")})
+ assert.same({}, {advtrains.resolve_wagon_alias(":nilalias")})
+ end)
+end)
diff --git a/advtrains/speed.lua b/advtrains/speed.lua
new file mode 100644
index 0000000..ec4f928
--- /dev/null
+++ b/advtrains/speed.lua
@@ -0,0 +1,88 @@
+-- auxiliary functions for the reworked speed restriction system
+
+local function s_lessp(a, b)
+ if not a or a == -1 then
+ return false
+ elseif not b or b == -1 then
+ return true
+ else
+ return a < b
+ end
+end
+
+local function s_greaterp(a, b)
+ return s_lessp(b, a)
+end
+
+local function s_not_lessp(a, b)
+ return not s_lessp(a, b)
+end
+
+local function s_not_greaterp(a, b)
+ return not s_greaterp(a, b)
+end
+
+local function s_equalp(a, b)
+ return (a or -1) == (b or -1)
+end
+
+local function s_not_equalp(a, b)
+ return (a or -1) ~= (b or -1)
+end
+
+local function s_max(a, b)
+ if s_lessp(a, b) then
+ return b
+ else
+ return a
+ end
+end
+
+local function s_min(a, b)
+ if s_lessp(a, b) then
+ return a
+ else
+ return b
+ end
+end
+
+local function get_speed_restriction_from_table (tbl)
+ local strictest = -1
+ for _, v in pairs(tbl) do
+ strictest = s_min(strictest, v)
+ end
+ if strictest == -1 then
+ return nil
+ end
+ return strictest
+end
+
+local function set_speed_restriction (tbl, rtype, rval)
+ if rval then
+ tbl[rtype or "main"] = rval
+ end
+ return tbl
+end
+
+local function set_speed_restriction_for_train (train, rtype, rval)
+ local t = train.speed_restrictions_t or {main = train.speed_restriction}
+ train.speed_restrictions_t = set_speed_restriction(t, rtype, rval)
+ train.speed_restriction = get_speed_restriction_from_table(t)
+end
+
+local function merge_speed_restriction_from_aspect_to_train (train, asp)
+ return set_speed_restriction_for_train(train, asp.type, asp.main)
+end
+
+return {
+ lessp = s_lessp,
+ greaterp = s_greaterp,
+ not_lessp = s_not_lessp,
+ not_greaterp = s_not_greaterp,
+ equalp = s_equalp,
+ not_equalp = s_not_equalp,
+ max = s_max,
+ min = s_min,
+ set_restriction = set_speed_restriction_for_train,
+ merge_aspect = merge_speed_restriction_from_aspect_to_train,
+}
diff --git a/advtrains/texture.lua b/advtrains/texture.lua
new file mode 100644
index 0000000..e6d83b0
--- /dev/null
+++ b/advtrains/texture.lua
@@ -0,0 +1,228 @@
+local tx = {}
+setmetatable(tx, {__call = function(_, ...) return tx.base(...) end})
+
+function tx.escape(str)
+ return (string.gsub(tostring(str), [[([%^:\])]], [[\%1]]))
+end
+
+local function getargs(...)
+ return select("#", ...), {...}
+end
+
+local function curry(f, x)
+ return function(...)
+ return f(x, ...)
+ end
+end
+
+local function xmkmodifier(func)
+ return function(self, ...)
+ table.insert(self, (func(...)))
+ return self
+ end
+end
+
+local function mkmodifier(fmt, spec)
+ return xmkmodifier(function(...)
+ local count = select("#", ...)
+ local args = {...}
+ for k, f in pairs(spec) do
+ args[k] = f(args[k])
+ end
+ return string.format(fmt, unpack(args, 1, count))
+ end)
+end
+
+-- Texture object
+local tx_lib = {}
+local tx_mt = {
+ __index = tx_lib,
+ __tostring = function(self)
+ return table.concat(self, "^")
+ end,
+ __concat = function(a, b)
+ return tx.raw(("%s^%s"):format(tostring(a), tostring(b)))
+ end,
+}
+
+function tx.raw(str)
+ return setmetatable({str}, tx_mt)
+end
+function tx.base(str)
+ return tx.raw(tx.escape(str))
+end
+-- TODO: use [fill when 5.8.0 becomes widely used client-side
+function tx.fill(w, h, color)
+ return tx"advtrains_hud_bg.png":resize(w, h):colorize(color)
+end
+
+-- Most texture modifiers
+tx_lib.colorize = xmkmodifier(function(c, a)
+ local str = ("[colorize:%s"):format(tx.escape(c))
+ if a then
+ str = str .. ":" .. a
+ end
+ return str
+end)
+tx_lib.multiply = mkmodifier("[multiply:%s", {tx.escape})
+tx_lib.resize = mkmodifier("[resize:%dx%d", {})
+tx_lib.transform = mkmodifier("[transform%s", {tx.escape})
+
+-- [combine
+
+local combine = {}
+
+function combine:add(x, y, ent)
+ table.insert(self.st, ([[%d,%d=%s]]):format(x, y, tx.escape(tostring(ent))))
+ return self
+end
+
+local combine_mt = {
+ __index = combine,
+ __tostring = function(self)
+ return table.concat(self.st, ":")
+ end,
+}
+
+function tx.combine(w, h, bg)
+ local base = ("[combine:%dx%d"):format(w, h)
+ local obj = setmetatable({width = w, height = h, st = {base}}, combine_mt)
+ if bg then
+ obj:add_fill(0, 0, w, h, bg)
+ end
+ return obj
+end
+
+function combine:add_fill(x, y, ...)
+ return self:add(x, y, tx.fill(...))
+end
+
+local function add_multicolor_fill(n, self, x, y, w, h, ...)
+ local argc, argv = getargs(...)
+ local t = 0
+ for k = 1, argc, 2 do
+ t = t + argv[k]
+ end
+ local newargs = {x, y, w, h}
+ local sk, wk = n, n+2
+ local s = newargs[wk]/t
+ for k = 1, argc, 2 do
+ local v = argv[k] * s
+ newargs[wk] = v
+ newargs[5] = argv[k+1]
+ self:add_fill(unpack(newargs))
+ newargs[sk] = newargs[sk] + v
+ end
+ return self
+end
+combine.add_multicolor_fill_topdown = curry(add_multicolor_fill, 2)
+combine.add_multicolor_fill_leftright = curry(add_multicolor_fill, 1)
+
+local function add_segmentbar(n, self, x, y, w, h, m, c, ...)
+ local argc, argv = getargs(...)
+ local baseargs = {x, y, w, h}
+ local ss = (baseargs[n+2]+m)/c
+ local bs = ss - m
+ for k = 1, argc, 3 do
+ local lower, upper, fill = argv[k], argv[k+1], argv[k+2]
+ lower = math.max(0, math.floor(lower))+1
+ upper = math.min(c, math.floor(upper))
+ if lower <= upper then
+ local args = {x, y, w, h, fill}
+ args[n+2] = bs
+ args[n] = args[n] + ss*(lower-1)
+ for i = lower, upper do
+ self:add_fill(unpack(args))
+ args[n] = args[n] + ss
+ end
+ end
+ end
+ return self
+end
+combine.add_segmentbar_topdown = curry(add_segmentbar, 2)
+combine.add_segmentbar_leftright = curry(add_segmentbar, 1)
+
+local function add_lever(n, self, x, y, w, h, hs, ss, val, hf, sf)
+ local baseargs = {x, y, w, h}
+ local sargs = {x, y, w, h, sf}
+ sargs[5-n] = ss
+ sargs[n+2] = baseargs[n+2] + ss - hs
+ for k = 1, 2 do
+ sargs[k] = baseargs[k] + (baseargs[k+2] - sargs[k+2])/2
+ end
+ self:add_fill(unpack(sargs))
+ local hargs = {x, y, w, h, hf}
+ hargs[n+2] = hs
+ hargs[n] = baseargs[n] + (baseargs[n+2]-hs)*val
+ self:add_fill(unpack(hargs))
+ return self
+end
+combine.add_lever_topdown = curry(add_lever, 2)
+combine.add_lever_leftright = curry(add_lever, 1)
+
+--[[ Seven-segment display
+ -1-
+6 2
+ -7-
+5 3
+ -4-
+--]]
+local sevenseg_digits = {
+ ["0"] = {1, 2, 3, 4, 5, 6},
+ ["1"] = {2, 3},
+ ["2"] = {1, 2, 4, 5, 7},
+ ["3"] = {1, 2, 3, 4, 7},
+ ["4"] = {2, 3, 6, 7},
+ ["5"] = {1, 3, 4, 6, 7},
+ ["6"] = {1, 3, 4, 5, 6, 7},
+ ["7"] = {1, 2, 3},
+ ["8"] = {1, 2, 3, 4, 5, 6, 7},
+ ["9"] = {1, 2, 3, 4, 6, 7},
+}
+
+function combine:add_str7seg(x0, y0, tw, th, str, fill)
+ --[[ w and h (as width/height of individual (horizontal) segments) have the following properties:
+ tw = n(w+3h)-h
+ th = 2w+3h
+ --]]
+ local len = #str
+ local h = (2*tw-len*th)/(3*len-2)
+ local w = (th-3*h)/2
+ local ws = w+3*h
+ local segs = {
+ {h, 0, w, h},
+ {w+h, h, h, w},
+ {w+h, w+2*h, h, w},
+ {h, 2*(w+h), w, h},
+ {0, w+2*h, h, w},
+ {0, h, h, w},
+ {h, w+h, w, h},
+ }
+ for i = 1, len do
+ for _, k in pairs(sevenseg_digits[string.sub(str, i, i)] or {}) do
+ local s = segs[k]
+ self:add_fill(s[1]+x0, s[2]+y0, s[3], s[4], fill)
+ end
+ x0 = x0 + ws
+ end
+ return self
+end
+
+function combine:add_n7seg(x, y, w, h, n, prec, ...)
+ if not (type(n) == "number" and type(prec) == "number") then
+ error("passed non-numeric value or precision to numeric display")
+ elseif prec < 0 then
+ error("negative length")
+ end
+ local pfx = ""
+ if n >= 0 then
+ n = math.min(10^prec-1, n)
+ else
+ n = math.min(10^(prec-1)-1, -n)
+ pfx = "-"
+ end
+ local str = ("%d"):format(n)
+ return self:add_str7seg(x, y, w, h, pfx .. ("0"):rep(prec-#str-#pfx) .. str, ...)
+end
+
+return tx
diff --git a/advtrains/advtrains/textures/advtrains_across.png b/advtrains/textures/advtrains_across.png
index da65a61..da65a61 100644..100755
--- a/advtrains/advtrains/textures/advtrains_across.png
+++ b/advtrains/textures/advtrains_across.png
Binary files differ
diff --git a/advtrains/advtrains/textures/advtrains_across_anim.png b/advtrains/textures/advtrains_across_anim.png
index 584d023..584d023 100644..100755
--- a/advtrains/advtrains/textures/advtrains_across_anim.png
+++ b/advtrains/textures/advtrains_across_anim.png
Binary files differ
diff --git a/advtrains/advtrains/textures/advtrains_boiler.png b/advtrains/textures/advtrains_boiler.png
index 8c7ff0d..8c7ff0d 100644..100755
--- a/advtrains/advtrains/textures/advtrains_boiler.png
+++ b/advtrains/textures/advtrains_boiler.png
Binary files differ
diff --git a/advtrains/advtrains/textures/advtrains_chimney.png b/advtrains/textures/advtrains_chimney.png
index 285a1a6..285a1a6 100644..100755
--- a/advtrains/advtrains/textures/advtrains_chimney.png
+++ b/advtrains/textures/advtrains_chimney.png
Binary files differ
diff --git a/advtrains/textures/advtrains_copytool.png b/advtrains/textures/advtrains_copytool.png
new file mode 100644
index 0000000..a8ea557
--- /dev/null
+++ b/advtrains/textures/advtrains_copytool.png
Binary files differ
diff --git a/advtrains/textures/advtrains_couple.png b/advtrains/textures/advtrains_couple.png
new file mode 100755
index 0000000..eda3704
--- /dev/null
+++ b/advtrains/textures/advtrains_couple.png
Binary files differ
diff --git a/advtrains/textures/advtrains_cpl_lock.png b/advtrains/textures/advtrains_cpl_lock.png
new file mode 100644
index 0000000..a25aaf4
--- /dev/null
+++ b/advtrains/textures/advtrains_cpl_lock.png
Binary files differ
diff --git a/advtrains/textures/advtrains_cpl_unlock.png b/advtrains/textures/advtrains_cpl_unlock.png
new file mode 100644
index 0000000..f58d00a
--- /dev/null
+++ b/advtrains/textures/advtrains_cpl_unlock.png
Binary files differ
diff --git a/advtrains/textures/advtrains_discouple.png b/advtrains/textures/advtrains_discouple.png
new file mode 100755
index 0000000..5c064c3
--- /dev/null
+++ b/advtrains/textures/advtrains_discouple.png
Binary files differ
diff --git a/advtrains/advtrains/textures/advtrains_driver_cab.png b/advtrains/textures/advtrains_driver_cab.png
index 331bcc9..331bcc9 100644..100755
--- a/advtrains/advtrains/textures/advtrains_driver_cab.png
+++ b/advtrains/textures/advtrains_driver_cab.png
Binary files differ
diff --git a/advtrains/advtrains/textures/advtrains_dtrack_atc_placer.png b/advtrains/textures/advtrains_dtrack_atc_placer.png
index 31c2b30..31c2b30 100644..100755
--- a/advtrains/advtrains/textures/advtrains_dtrack_atc_placer.png
+++ b/advtrains/textures/advtrains_dtrack_atc_placer.png
Binary files differ
diff --git a/advtrains/advtrains/textures/advtrains_dtrack_bumper_placer.png b/advtrains/textures/advtrains_dtrack_bumper_placer.png
index 27191fe..27191fe 100644..100755
--- a/advtrains/advtrains/textures/advtrains_dtrack_bumper_placer.png
+++ b/advtrains/textures/advtrains_dtrack_bumper_placer.png
Binary files differ
diff --git a/advtrains/advtrains/textures/advtrains_dtrack_detector_placer.png b/advtrains/textures/advtrains_dtrack_detector_placer.png
index e6c6ad6..e6c6ad6 100644..100755
--- a/advtrains/advtrains/textures/advtrains_dtrack_detector_placer.png
+++ b/advtrains/textures/advtrains_dtrack_detector_placer.png
Binary files differ
diff --git a/advtrains/textures/advtrains_dtrack_load_placer.png b/advtrains/textures/advtrains_dtrack_load_placer.png
new file mode 100755
index 0000000..427c011
--- /dev/null
+++ b/advtrains/textures/advtrains_dtrack_load_placer.png
Binary files differ
diff --git a/advtrains/advtrains/textures/advtrains_dtrack_placer.png b/advtrains/textures/advtrains_dtrack_placer.png
index 7bef8a9..7bef8a9 100644..100755
--- a/advtrains/advtrains/textures/advtrains_dtrack_placer.png
+++ b/advtrains/textures/advtrains_dtrack_placer.png
Binary files differ
diff --git a/advtrains/advtrains/textures/advtrains_dtrack_rail.png b/advtrains/textures/advtrains_dtrack_rail.png
index bd0c217..bd0c217 100644..100755
--- a/advtrains/advtrains/textures/advtrains_dtrack_rail.png
+++ b/advtrains/textures/advtrains_dtrack_rail.png
Binary files differ
diff --git a/advtrains/advtrains/textures/advtrains_dtrack_shared.png b/advtrains/textures/advtrains_dtrack_shared.png
index 736c7db..736c7db 100644..100755
--- a/advtrains/advtrains/textures/advtrains_dtrack_shared.png
+++ b/advtrains/textures/advtrains_dtrack_shared.png
Binary files differ
diff --git a/advtrains/advtrains/textures/advtrains_dtrack_shared_atc.png b/advtrains/textures/advtrains_dtrack_shared_atc.png
index 1f83c37..1f83c37 100644..100755
--- a/advtrains/advtrains/textures/advtrains_dtrack_shared_atc.png
+++ b/advtrains/textures/advtrains_dtrack_shared_atc.png
Binary files differ
diff --git a/advtrains/advtrains/textures/advtrains_dtrack_shared_detector_off.png b/advtrains/textures/advtrains_dtrack_shared_detector_off.png
index 724d907..724d907 100644..100755
--- a/advtrains/advtrains/textures/advtrains_dtrack_shared_detector_off.png
+++ b/advtrains/textures/advtrains_dtrack_shared_detector_off.png
Binary files differ
diff --git a/advtrains/advtrains/textures/advtrains_dtrack_shared_detector_on.png b/advtrains/textures/advtrains_dtrack_shared_detector_on.png
index 7bb29d6..7bb29d6 100644..100755
--- a/advtrains/advtrains/textures/advtrains_dtrack_shared_detector_on.png
+++ b/advtrains/textures/advtrains_dtrack_shared_detector_on.png
Binary files differ
diff --git a/advtrains/textures/advtrains_dtrack_shared_load.png b/advtrains/textures/advtrains_dtrack_shared_load.png
new file mode 100755
index 0000000..5fd0d7a
--- /dev/null
+++ b/advtrains/textures/advtrains_dtrack_shared_load.png
Binary files differ
diff --git a/advtrains/textures/advtrains_dtrack_shared_unload.png b/advtrains/textures/advtrains_dtrack_shared_unload.png
new file mode 100755
index 0000000..e9fc5bd
--- /dev/null
+++ b/advtrains/textures/advtrains_dtrack_shared_unload.png
Binary files differ
diff --git a/advtrains/advtrains/textures/advtrains_dtrack_slopeplacer.png b/advtrains/textures/advtrains_dtrack_slopeplacer.png
index 1d456b0..1d456b0 100644..100755
--- a/advtrains/advtrains/textures/advtrains_dtrack_slopeplacer.png
+++ b/advtrains/textures/advtrains_dtrack_slopeplacer.png
Binary files differ
diff --git a/advtrains/textures/advtrains_dtrack_unload_placer.png b/advtrains/textures/advtrains_dtrack_unload_placer.png
new file mode 100755
index 0000000..486861e
--- /dev/null
+++ b/advtrains/textures/advtrains_dtrack_unload_placer.png
Binary files differ
diff --git a/advtrains/textures/advtrains_hud_arrow.png b/advtrains/textures/advtrains_hud_arrow.png
new file mode 100644
index 0000000..71d75b0
--- /dev/null
+++ b/advtrains/textures/advtrains_hud_arrow.png
Binary files differ
diff --git a/advtrains/textures/advtrains_hud_atc.png b/advtrains/textures/advtrains_hud_atc.png
new file mode 100644
index 0000000..e033653
--- /dev/null
+++ b/advtrains/textures/advtrains_hud_atc.png
Binary files differ
diff --git a/advtrains/textures/advtrains_hud_bg.png b/advtrains/textures/advtrains_hud_bg.png
new file mode 100644
index 0000000..aa168d4
--- /dev/null
+++ b/advtrains/textures/advtrains_hud_bg.png
Binary files differ
diff --git a/advtrains/textures/advtrains_hud_lzb.png b/advtrains/textures/advtrains_hud_lzb.png
new file mode 100644
index 0000000..e1b5f70
--- /dev/null
+++ b/advtrains/textures/advtrains_hud_lzb.png
Binary files differ
diff --git a/advtrains/textures/advtrains_hud_shunt.png b/advtrains/textures/advtrains_hud_shunt.png
new file mode 100644
index 0000000..f4d27a5
--- /dev/null
+++ b/advtrains/textures/advtrains_hud_shunt.png
Binary files differ
diff --git a/advtrains/advtrains/textures/advtrains_platform.png b/advtrains/textures/advtrains_platform.png
index 5ba9663..5ba9663 100644..100755
--- a/advtrains/advtrains/textures/advtrains_platform.png
+++ b/advtrains/textures/advtrains_platform.png
Binary files differ
diff --git a/advtrains/textures/advtrains_platform_diag.png b/advtrains/textures/advtrains_platform_diag.png
new file mode 100644
index 0000000..6e262e2
--- /dev/null
+++ b/advtrains/textures/advtrains_platform_diag.png
Binary files differ
diff --git a/advtrains/advtrains/textures/advtrains_retrosignal.png b/advtrains/textures/advtrains_retrosignal.png
index 141198d..141198d 100644..100755
--- a/advtrains/advtrains/textures/advtrains_retrosignal.png
+++ b/advtrains/textures/advtrains_retrosignal.png
Binary files differ
diff --git a/advtrains/advtrains/textures/advtrains_retrosignal_inv.png b/advtrains/textures/advtrains_retrosignal_inv.png
index 1036594..1036594 100644..100755
--- a/advtrains/advtrains/textures/advtrains_retrosignal_inv.png
+++ b/advtrains/textures/advtrains_retrosignal_inv.png
Binary files differ
diff --git a/advtrains/advtrains/textures/advtrains_signal_inv.png b/advtrains/textures/advtrains_signal_inv.png
index ed64ed9..ed64ed9 100644..100755
--- a/advtrains/advtrains/textures/advtrains_signal_inv.png
+++ b/advtrains/textures/advtrains_signal_inv.png
Binary files differ
diff --git a/advtrains/advtrains/textures/advtrains_signal_off.png b/advtrains/textures/advtrains_signal_off.png
index 8046e52..8046e52 100644..100755
--- a/advtrains/advtrains/textures/advtrains_signal_off.png
+++ b/advtrains/textures/advtrains_signal_off.png
Binary files differ
diff --git a/advtrains/advtrains/textures/advtrains_signal_on.png b/advtrains/textures/advtrains_signal_on.png
index 5228bb3..5228bb3 100644..100755
--- a/advtrains/advtrains/textures/advtrains_signal_on.png
+++ b/advtrains/textures/advtrains_signal_on.png
Binary files differ
diff --git a/advtrains/advtrains/textures/advtrains_signal_wall_off.png b/advtrains/textures/advtrains_signal_wall_off.png
index 3e7b1e1..3e7b1e1 100644..100755
--- a/advtrains/advtrains/textures/advtrains_signal_wall_off.png
+++ b/advtrains/textures/advtrains_signal_wall_off.png
Binary files differ
diff --git a/advtrains/advtrains/textures/advtrains_signal_wall_on.png b/advtrains/textures/advtrains_signal_wall_on.png
index b628c7e..b628c7e 100644..100755
--- a/advtrains/advtrains/textures/advtrains_signal_wall_on.png
+++ b/advtrains/textures/advtrains_signal_wall_on.png
Binary files differ
diff --git a/advtrains/advtrains/textures/advtrains_track_cr.png b/advtrains/textures/advtrains_track_cr.png
index 40f0cc5..40f0cc5 100644..100755
--- a/advtrains/advtrains/textures/advtrains_track_cr.png
+++ b/advtrains/textures/advtrains_track_cr.png
Binary files differ
diff --git a/advtrains/advtrains/textures/advtrains_track_cr_45.png b/advtrains/textures/advtrains_track_cr_45.png
index 54966b3..54966b3 100644..100755
--- a/advtrains/advtrains/textures/advtrains_track_cr_45.png
+++ b/advtrains/textures/advtrains_track_cr_45.png
Binary files differ
diff --git a/advtrains/advtrains/textures/advtrains_track_placer.png b/advtrains/textures/advtrains_track_placer.png
index 03e17ed..03e17ed 100644..100755
--- a/advtrains/advtrains/textures/advtrains_track_placer.png
+++ b/advtrains/textures/advtrains_track_placer.png
Binary files differ
diff --git a/advtrains/advtrains/textures/advtrains_track_st.png b/advtrains/textures/advtrains_track_st.png
index 5ad7e4f..5ad7e4f 100644..100755
--- a/advtrains/advtrains/textures/advtrains_track_st.png
+++ b/advtrains/textures/advtrains_track_st.png
Binary files differ
diff --git a/advtrains/advtrains/textures/advtrains_track_st_45.png b/advtrains/textures/advtrains_track_st_45.png
index 63b4c96..63b4c96 100644..100755
--- a/advtrains/advtrains/textures/advtrains_track_st_45.png
+++ b/advtrains/textures/advtrains_track_st_45.png
Binary files differ
diff --git a/advtrains/advtrains/textures/advtrains_track_swlcr.png b/advtrains/textures/advtrains_track_swlcr.png
index d9b5c0b..d9b5c0b 100644..100755
--- a/advtrains/advtrains/textures/advtrains_track_swlcr.png
+++ b/advtrains/textures/advtrains_track_swlcr.png
Binary files differ
diff --git a/advtrains/advtrains/textures/advtrains_track_swlcr_45.png b/advtrains/textures/advtrains_track_swlcr_45.png
index f098fc9..f098fc9 100644..100755
--- a/advtrains/advtrains/textures/advtrains_track_swlcr_45.png
+++ b/advtrains/textures/advtrains_track_swlcr_45.png
Binary files differ
diff --git a/advtrains/advtrains/textures/advtrains_track_swlst.png b/advtrains/textures/advtrains_track_swlst.png
index 314bd2d..314bd2d 100644..100755
--- a/advtrains/advtrains/textures/advtrains_track_swlst.png
+++ b/advtrains/textures/advtrains_track_swlst.png
Binary files differ
diff --git a/advtrains/advtrains/textures/advtrains_track_swlst_45.png b/advtrains/textures/advtrains_track_swlst_45.png
index 765d0ec..765d0ec 100644..100755
--- a/advtrains/advtrains/textures/advtrains_track_swlst_45.png
+++ b/advtrains/textures/advtrains_track_swlst_45.png
Binary files differ
diff --git a/advtrains/advtrains/textures/advtrains_track_swrcr.png b/advtrains/textures/advtrains_track_swrcr.png
index f74e1bc..f74e1bc 100644..100755
--- a/advtrains/advtrains/textures/advtrains_track_swrcr.png
+++ b/advtrains/textures/advtrains_track_swrcr.png
Binary files differ
diff --git a/advtrains/advtrains/textures/advtrains_track_swrcr_45.png b/advtrains/textures/advtrains_track_swrcr_45.png
index fa432aa..fa432aa 100644..100755
--- a/advtrains/advtrains/textures/advtrains_track_swrcr_45.png
+++ b/advtrains/textures/advtrains_track_swrcr_45.png
Binary files differ
diff --git a/advtrains/advtrains/textures/advtrains_track_swrst.png b/advtrains/textures/advtrains_track_swrst.png
index 06ea29e..06ea29e 100644..100755
--- a/advtrains/advtrains/textures/advtrains_track_swrst.png
+++ b/advtrains/textures/advtrains_track_swrst.png
Binary files differ
diff --git a/advtrains/advtrains/textures/advtrains_track_swrst_45.png b/advtrains/textures/advtrains_track_swrst_45.png
index be477b7..be477b7 100644..100755
--- a/advtrains/advtrains/textures/advtrains_track_swrst_45.png
+++ b/advtrains/textures/advtrains_track_swrst_45.png
Binary files differ
diff --git a/advtrains/advtrains/textures/advtrains_trackworker.png b/advtrains/textures/advtrains_trackworker.png
index b50bcae..b50bcae 100644..100755
--- a/advtrains/advtrains/textures/advtrains_trackworker.png
+++ b/advtrains/textures/advtrains_trackworker.png
Binary files differ
diff --git a/advtrains/textures/advtrains_wagon_placeholder.png b/advtrains/textures/advtrains_wagon_placeholder.png
new file mode 100644
index 0000000..383c181
--- /dev/null
+++ b/advtrains/textures/advtrains_wagon_placeholder.png
Binary files differ
diff --git a/advtrains/textures/advtrains_wagon_prop_tool.png b/advtrains/textures/advtrains_wagon_prop_tool.png
new file mode 100644
index 0000000..6352c55
--- /dev/null
+++ b/advtrains/textures/advtrains_wagon_prop_tool.png
Binary files differ
diff --git a/advtrains/advtrains/textures/advtrains_wheel.png b/advtrains/textures/advtrains_wheel.png
index fb72879..fb72879 100644..100755
--- a/advtrains/advtrains/textures/advtrains_wheel.png
+++ b/advtrains/textures/advtrains_wheel.png
Binary files differ
diff --git a/advtrains/advtrains/textures/drwho_screwdriver.png b/advtrains/textures/drwho_screwdriver.png
index b50bcae..b50bcae 100644..100755
--- a/advtrains/advtrains/textures/drwho_screwdriver.png
+++ b/advtrains/textures/drwho_screwdriver.png
Binary files differ
diff --git a/advtrains/track_reg_helper.lua b/advtrains/track_reg_helper.lua
new file mode 100644
index 0000000..fe1d11d
--- /dev/null
+++ b/advtrains/track_reg_helper.lua
@@ -0,0 +1,751 @@
+-- New track registration helper
+-- Retains the old table-template-based definition format, but adapts it to the new (advtrains 2.5)
+-- track definition system
+-- Note to future: This is actually just a work-saver, avoiding me to port over all the crossing nodes as well as the linetrack tracks.
+-- Future track mods should please directly use the appropriate advtrains.register_node_4rot() API and not rely on this!
+
+-- Get current translator
+local S = advtrains.translate
+
+--definition preparation
+local function conns(c1, c2, r1, r2) return {{c=c1, y=r1}, {c=c2, y=r2}} end
+local function conns3(c1, c2, c3, r1, r2, r3) return {{c=c1, y=r1}, {c=c2, y=r2}, {c=c3, y=r3}} end
+
+advtrains.ap={}
+advtrains.ap.t_30deg_flat={
+ v25_format = true,
+ regstep=1,
+ variant={
+ st={
+ conns = conns(0,8),
+ desc = "straight",
+ tpdouble = true,
+ tpsingle = true,
+ trackworker = "cr",
+ },
+ cr={
+ conns = conns(0,7),
+ desc = "curve",
+ tpdouble = true,
+ trackworker = "swlst",
+ },
+ swlst={
+ conns = conns3(0,8,7),
+ desc = "left switch (straight)",
+ trackworker = "swrst",
+ switchalt = "cr",
+ switchmc = "on",
+ switchst = "st",
+ switchprefix = "swl",
+ conn_map = {2,1,1},
+ stmref = "swl",
+ },
+ swlcr={
+ conns = conns3(0,8,7),
+ desc = "left switch (curve)",
+ trackworker = "swrcr",
+ switchalt = "st",
+ switchmc = "off",
+ switchst = "cr",
+ switchprefix = "swl",
+ conn_map = {3,1,1},
+ stmref = "swl",
+ },
+ swrst={
+ conns = conns3(0,8,9),
+ desc = "right switch (straight)",
+ trackworker = "st",
+ switchalt = "cr",
+ switchmc = "on",
+ switchst = "st",
+ switchprefix = "swr",
+ conn_map = {2,1,1},
+ stmref = "swr",
+ },
+ swrcr={
+ conns = conns3(0,8,9),
+ desc = "right switch (curve)",
+ trackworker = "st",
+ switchalt = "st",
+ switchmc = "off",
+ switchst = "cr",
+ switchprefix = "swr",
+ conn_map = {3,1,1},
+ stmref = "swr",
+ },
+ },
+ regtp=true,
+ tpdefault="st",
+ trackworker={
+ ["swrcr"]="st",
+ ["swrst"]="st",
+ ["cr"]="swlst",
+ ["swlcr"]="swrcr",
+ ["swlst"]="swrst",
+ },
+ rotation={"", "_30", "_45", "_60"},
+ statemaps = {
+ swl = { st = "swlst", cr = "swlcr"},
+ swr = { st = "swrst", cr = "swrcr"}
+ }
+}
+advtrains.ap.t_yturnout={
+ v25_format = true,
+ regstep=1,
+ variant={
+ l={
+ conns = conns3(0,7,9),
+ desc = "Y-turnout (left)",
+ switchalt = "r",
+ switchmc = "off",
+ switchst = "l",
+ switchprefix = "",
+ conn_map = {2,1,1},
+ stmref = "sw",
+ tpsingle = true,
+ },
+ r={
+ conns = conns3(0,7,9),
+ desc = "Y-turnout (right)",
+ switchalt = "l",
+ switchmc = "on",
+ switchst = "r",
+ switchprefix = "",
+ conn_map = {3,1,1},
+ stmref = "sw",
+ }
+ },
+ regtp=true,
+ tpdefault="l",
+ rotation={"", "_30", "_45", "_60"},
+ statemaps = {
+ sw = { l = "l", r = "r"}
+ }
+}
+advtrains.ap.t_s3way={
+ v25_format = true,
+ regstep=1,
+ variant={
+ l={
+ conns = { {c=0}, {c=7}, {c=8}, {c=9}},
+ desc = "3-way turnout (left)",
+ switchalt = "s",
+ switchst="l",
+ switchprefix = "",
+ conn_map = {2,1,1,1},
+ stmref = "sw",
+ },
+ s={
+ conns = { {c=0}, {c=7}, {c=8}, {c=9}},
+ desc = "3-way turnout (straight)",
+ switchalt ="r",
+ switchst = "s",
+ switchprefix = "",
+ conn_map = {3,1,1,1},
+ stmref = "sw",
+ tpsingle = true,
+ },
+ r={
+ conns = { {c=0}, {c=7}, {c=8}, {c=9}},
+ desc = "3-way turnout (right)",
+ switchalt = "l",
+ switchst="r",
+ switchprefix = "",
+ conn_map = {4,1,1,1},
+ stmref = "sw",
+ }
+ },
+ regtp=true,
+ tpdefault="l",
+ rotation={"", "_30", "_45", "_60"},
+ statemaps = {
+ sw = { l = "l", s = "s", r = "r"}
+ }
+}
+advtrains.ap.t_30deg_slope={
+ v25_format = true,
+ regstep=1,
+ variant={
+ vst1={conns = conns(8,0,0,0.5), rail_y = 0.25, desc = "steep uphill 1/2", slope=true},
+ vst2={conns = conns(8,0,0.5,1), rail_y = 0.75, desc = "steep uphill 2/2", slope=true},
+ vst31={conns = conns(8,0,0,0.33), rail_y = 0.16, desc = "uphill 1/3", slope=true},
+ vst32={conns = conns(8,0,0.33,0.66), rail_y = 0.5, desc = "uphill 2/3", slope=true},
+ vst33={conns = conns(8,0,0.66,1), rail_y = 0.83, desc = "uphill 3/3", slope=true},
+ },
+ regsp=true,
+ slopeplacer={
+ [2]={"vst1", "vst2"},
+ [3]={"vst31", "vst32", "vst33"},
+ max=3,--highest entry
+ },
+ slopeplacer_45={
+ [2]={"vst1_45", "vst2_45"},
+ max=2,
+ },
+ rotation={"", "_30", "_45", "_60"},
+ trackworker={},
+ increativeinv={},
+}
+advtrains.ap.t_30deg_straightonly={
+ v25_format = true,
+ regstep=1,
+ variant={
+ st={
+ conns = conns(0,8),
+ desc = "straight",
+ tpdouble = true,
+ tpsingle = true,
+ trackworker = "st",
+ },
+ },
+ regtp=true,
+ tpdefault="st",
+ rotation={"", "_30", "_45", "_60"},
+}
+advtrains.ap.t_30deg_straightonly_noplacer={
+ v25_format = true,
+ regstep=1,
+ variant={
+ st={
+ conns = conns(0,8),
+ desc = "straight",
+ tpdouble = true,
+ tpsingle = true,
+ trackworker = "st",
+ },
+ },
+ tpdefault="st",
+ rotation={"", "_30", "_45", "_60"},
+}
+advtrains.ap.t_45deg={
+ v25_format = true,
+ regstep=2,
+ variant={
+ st={
+ conns = conns(0,8),
+ desc = "straight",
+ tpdouble = true,
+ tpsingle = true,
+ trackworker = "cr",
+ },
+ cr={
+ conns = conns(0,6),
+ desc = "curve",
+ tpdouble = true,
+ trackworker = "swlst",
+ },
+ swlst={
+ conns = conns3(0,8,6),
+ desc = "left switch (straight)",
+ trackworker = "swrst",
+ switchalt = "cr",
+ switchmc = "on",
+ switchst = "st",
+ },
+ swlcr={
+ conns = conns3(0,6,8),
+ desc = "left switch (curve)",
+ trackworker = "swrcr",
+ switchalt = "st",
+ switchmc = "off",
+ switchst = "cr",
+ },
+ swrst={
+ conns = conns3(0,8,10),
+ desc = "right switch (straight)",
+ trackworker = "st",
+ switchalt = "cr",
+ switchmc = "on",
+ switchst = "st",
+ },
+ swrcr={
+ conns = conns3(0,10,8),
+ desc = "right switch (curve)",
+ trackworker = "st",
+ switchalt = "st",
+ switchmc = "off",
+ switchst = "cr",
+ },
+ },
+ regtp=true,
+ tpdefault="st",
+ trackworker={
+ ["swrcr"]="st",
+ ["swrst"]="st",
+ ["cr"]="swlst",
+ ["swlcr"]="swrcr",
+ ["swlst"]="swrst",
+ },
+ rotation={"", "_30", "_45", "_60"},
+}
+advtrains.ap.t_perpcrossing={
+ v25_format = true,
+ regstep = 1,
+ variant={
+ st={
+ conns = { {c=0}, {c=8}, {c=4}, {c=12} },
+ desc = "perpendicular crossing",
+ tpdouble = true,
+ tpsingle = true,
+ trackworker = "st",
+ conn_map = {2,1,4,3},
+ },
+ },
+ regtp=true,
+ tpdefault="st",
+ rotation={"", "_30", "_45", "_60"},
+}
+advtrains.ap.t_90plusx_crossing={
+ v25_format = true,
+ regstep = 1,
+ variant={
+ ["30l"]={
+ conns = { {c=0}, {c=8}, {c=1}, {c=9} },
+ desc = "30/90 degree crossing (left)",
+ tpdouble = true,
+ tpsingle = true,
+ trackworker = "45l",
+ conn_map = {2,1,4,3},
+ },
+ ["45l"]={
+ conns = { {c=0}, {c=8}, {c=2}, {c=10} },
+ desc = "45/90 degree crossing (left)",
+ tpdouble = true,
+ tpsingle = true,
+ trackworker = "60l",
+ conn_map = {2,1,4,3},
+ },
+ ["60l"]={
+ conns = { {c=0}, {c=8}, {c=3}, {c=11}},
+ desc = "60/90 degree crossing (left)",
+ tpdouble = true,
+ tpsingle = true,
+ trackworker = "60r",
+ conn_map = {2,1,4,3},
+ },
+ ["60r"]={
+ conns = { {c=0}, {c=8}, {c=5}, {c=13} },
+ desc = "60/90 degree crossing (right)",
+ tpdouble = true,
+ tpsingle = true,
+ trackworker = "45r",
+ conn_map = {2,1,4,3},
+ },
+ ["45r"]={
+ conns = { {c=0}, {c=8}, {c=6}, {c=14} },
+ desc = "45/90 degree crossing (right)",
+ tpdouble = true,
+ tpsingle = true,
+ trackworker = "30r",
+ conn_map = {2,1,4,3},
+ },
+ ["30r"]={
+ conns = { {c=0}, {c=8}, {c=7}, {c=15}},
+ desc = "30/90 degree crossing (right)",
+ tpdouble = true,
+ tpsingle = true,
+ trackworker = "30l",
+ conn_map = {2,1,4,3},
+ },
+ },
+ regtp=true,
+ tpdefault="30l",
+ rotation={""},
+ trackworker = {
+ ["30l"] = "45l",
+ ["45l"] = "60l",
+ ["60l"] = "60r",
+ ["60r"] = "45r",
+ ["45r"] = "30r",
+ ["30r"] = "30l",
+ }
+}
+
+advtrains.ap.t_diagonalcrossing = {
+ v25_format = true,
+ regstep=1,
+ variant={
+ ["30l45r"]={
+ conns = {{c=1}, {c=9}, {c=6}, {c=14}},
+ desc = "30left-45right diagonal crossing",
+ tpdouble=true,
+ tpsingle=true,
+ trackworker="60l30l",
+ conn_map = {2,1,4,3},
+ },
+ ["60l30l"]={
+ conns = {{c=3}, {c=11}, {c=1}, {c=9}},
+ desc = "30left-60right diagonal crossing",
+ tpdouble=true,
+ tpsingle=true,
+ trackworker="60l45r",
+ conn_map = {2,1,4,3},
+ },
+ ["60l45r"]={
+ conns = {{c=3}, {c=11}, {c=6}, {c=14}},
+ desc = "60left-45right diagonal crossing",
+ tpdouble=true,
+ tpsingle=true,
+ trackworker="60l60r",
+ conn_map = {2,1,4,3},
+ },
+ ["60l60r"]={
+ conns = {{c=3}, {c=11}, {c=5}, {c=13}},
+ desc = "60left-60right diagonal crossing",
+ tpdouble=true,
+ tpsingle=true,
+ trackworker="60r45l",
+ conn_map = {2,1,4,3},
+ },
+ --If 60l60r had a mirror image, it would be here, but it's symmetric.
+ -- 60l60r is also equivalent to 30l30r but rotated 90 degrees.
+ ["60r45l"]={
+ conns = {{c=5}, {c=13}, {c=2}, {c=10}},
+ desc = "60right-45left diagonal crossing",
+ tpdouble=true,
+ tpsingle=true,
+ trackworker="60r30r",
+ conn_map = {2,1,4,3},
+ },
+ ["60r30r"]={
+ conns = {{c=5}, {c=13}, {c=7}, {c=15}},
+ desc = "60right-30right diagonal crossing",
+ tpdouble=true,
+ tpsingle=true,
+ trackworker="30r45l",
+ conn_map = {2,1,4,3},
+ },
+ ["30r45l"]={
+ conns = {{c=7}, {c=15}, {c=2}, {c=10}},
+ desc = "30right-45left diagonal crossing",
+ tpdouble=true,
+ tpsingle=true,
+ trackworker="30l45r",
+ conn_map = {2,1,4,3},
+ },
+
+ },
+ regtp=true,
+ tpdefault="30l45r",
+ rotation={""},
+ trackworker = {
+ ["30l45r"] = "60l30l",
+ ["60l30l"] = "60l45r",
+ ["60l45r"] = "60l60r",
+ ["60l60r"] = "60r45l",
+ ["60r45l"] = "60r30r",
+ ["60r30r"] = "30r45l",
+ ["30r45l"] = "30l45r",
+ }
+}
+
+advtrains.trackpresets = advtrains.ap
+
+--definition format: ([] optional)
+--[[{
+ nodename_prefix
+ texture_prefix
+ [shared_texture]
+ models_prefix
+ models_suffix (with dot)
+ [shared_model]
+ formats={
+ st,cr,swlst,swlcr,swrst,swrcr,vst1,vst2
+ (each a table with indices 0-3, for if to register a rail with this 'rotation' table entry. nil is assumed as 'all', set {} to not register at all)
+ }
+ common={} change something on common rail appearance
+}
+[18.12.17] Note on new connection system:
+In order to support real rail crossing nodes and finally make the trackplacer respect switches, I changed the connection system.
+There can be a variable number of connections available. These are specified as tuples {c=<connection>, y=<rely>}
+The table "at_conns" consists of {<conn1>, <conn2>...}
+the "at_rail_y" property holds the value that was previously called "railheight"
+Depending on the number of connections:
+2 conns: regular rail
+3 conns: switch:
+ - when train passes in at conn1, will move out of conn2
+ - when train passes in at conn2 or conn3, will move out of conn1
+4 conns: cross (or cross switch, depending on arrangement of conns):
+ - conn1 <> conn2
+ - conn3 <> conn4
+]]
+
+-- Notify the user if digging the rail is not allowed
+local function can_dig_callback(pos, player)
+ local ok, reason = advtrains.can_dig_or_modify_track(pos)
+ if not ok and player then
+ minetest.chat_send_player(player:get_player_name(), S("This track can not be removed!") .. " " .. reason)
+ end
+ return ok
+end
+
+local function append_statemap_suffix(state_map, nnpref, rot)
+ local t = {}
+ for state, nn in pairs(state_map) do
+ t[state] = nnpref .. "_" .. nn .. rot
+ end
+ return t
+end
+
+function advtrains.default_suitable_substrate(upos)
+ return core.registered_nodes[core.get_node(upos).name]
+ and core.registered_nodes[core.get_node(upos).name].walkable
+end
+
+function advtrains.register_tracks(tracktype, def, preset)
+ if not preset.v25_format then
+ error("advtrains.register_tracks(): A track preset for pre-v2.5 is used with advtrains 2.5+. Mod probably defines own track preset instead of using it from the advtrains.ap table! Please check track mod compatibility!")
+ end
+
+ if preset.regtp then
+ local nnprefix = def.nodename_prefix
+ minetest.register_craftitem(":"..nnprefix.."_placer", {
+ description = def.description,
+ inventory_image = def.texture_prefix.."_placer.png",
+ wield_image = def.texture_prefix.."_placer.png",
+ groups={advtrains_trackplacer=1, digtron_on_place=1},
+ liquids_pointable = false,
+ on_place = function(itemstack, placer, pointed_thing)
+ local name = placer:get_player_name()
+ if not name then
+ return itemstack, false
+ end
+ if pointed_thing.type=="node" then
+ local pos=pointed_thing.above
+ local upos=vector.subtract(pointed_thing.above, {x=0, y=1, z=0})
+ if not advtrains.check_track_protection(pos, name) then
+ return itemstack, false
+ end
+ if minetest.registered_nodes[minetest.get_node(pos).name] and minetest.registered_nodes[minetest.get_node(pos).name].buildable_to then
+ if (def.suitable_substrate and def.suitable_substrate or advtrains.default_suitable_substrate)(upos) then
+ -- minetest.chat_send_all(nnprefix)
+ local yaw = placer:get_look_horizontal()
+ advtrains.trackplacer.place_track(pos, nnprefix, name, yaw)
+ if not advtrains.is_creative(name) then
+ itemstack:take_item()
+ end
+ end
+ end
+ end
+ return itemstack, true
+ end,
+ })
+
+ advtrains.trackplacer.set_default_place_candidate(def.nodename_prefix, def.nodename_prefix.."_"..preset.tpdefault)
+ end
+ if preset.regsp then
+ advtrains.slope.register_placer(def, preset)
+ end
+
+ for suffix, var in pairs(preset.variant) do
+ for rotid, rotation in ipairs(preset.rotation) do
+ if not def.formats[suffix] or def.formats[suffix][rotid] then
+ local img_suffix = suffix..rotation
+ local ndef = advtrains.merge_tables({
+ description=def.description.."("..(var.desc or "any")..rotation..")",
+ drawtype = "mesh",
+ paramtype="light",
+ paramtype2="facedir",
+ use_texture_alpha = "clip",
+ walkable = false,
+ selection_box = {
+ type = "fixed",
+ fixed = {-1/2-1/16, -1/2, -1/2, 1/2+1/16, -1/2+2/16, 1/2},
+ },
+
+ mesh = def.shared_model or (def.models_prefix.."_"..img_suffix..def.models_suffix),
+ tiles = {def.shared_texture or (def.texture_prefix.."_"..img_suffix..".png"), def.second_texture},
+
+ groups = {
+ attached_node = advtrains.IGNORE_WORLD and 0 or 1,
+ advtrains_track=1,
+ ["advtrains_track_"..tracktype]=1,
+ save_in_at_nodedb=1,
+ dig_immediate=2,
+ not_in_creative_inventory=1,
+ not_blocking_trains=1,
+ },
+
+ can_dig = advtrains.track_can_dig_callback,
+ after_dig_node = advtrains.track_update_callback,
+ after_place_node = advtrains.track_update_callback,
+
+ at_rail_y = var.rail_y
+ }, def.common or {})
+
+ if preset.regtp then
+ ndef.drop = def.nodename_prefix.."_placer"
+ end
+ if preset.regsp and var.slope then
+ ndef.drop = def.nodename_prefix.."_slopeplacer"
+ end
+
+ --connections
+ ndef.at_conns = advtrains.rotate_conn_by(var.conns, (rotid-1)*preset.regstep)
+ -- NEW since 2.5
+ ndef.at_conn_map = var.conn_map
+
+ local ndef_avt_table = {}
+
+ if var.switchalt and var.switchst then
+ -- NEW since 2.5
+ ndef.on_rightclick = advtrains.state_node_on_rightclick_callback
+ ndef_avt_table.node_state = var.switchst
+ ndef_avt_table.node_next_state = var.switchalt
+ -- obtain and build statemap
+ local state_map = preset.statemaps[var.stmref]
+ if not state_map then error("On registering "..def.nodename_prefix.."_"..suffix..rotation..", stmref of variant doesn't reference entry in preset.statemaps") end
+ ndef_avt_table.node_state_map = append_statemap_suffix(state_map, def.nodename_prefix, rotation)
+
+ if var.switchmc then
+ local vswitchalt = var.switchalt
+ ndef.mesecons = {effector = {
+ ["action_"..var.switchmc] = function(pos, node)
+ advtrains.setstate(pos, vswitchalt, node)
+ end,
+ rules=advtrains.meseconrules
+ }}
+ end
+ end
+
+ local adef={}
+ if def.get_additional_definiton then
+ adef=def.get_additional_definiton(def, preset, suffix, rotation)
+ end
+ ndef = advtrains.merge_tables(ndef, adef)
+
+ -- insert getstate/setstate functions after merging the additional definitions
+ if ndef_avt_table then
+ ndef.advtrains = advtrains.merge_tables(ndef.advtrains or {}, ndef_avt_table)
+ end
+
+ -- NEW since 2.5: add appropriate fields for trackworker rotation
+ -- get the next rotation step
+ local num_rots = #preset.rotation
+ if rotid >= num_rots then
+ ndef.advtrains.trackworker_next_rot = def.nodename_prefix.."_"..suffix..preset.rotation[1]
+ ndef.advtrains.trackworker_rot_incr_param2 = true
+ else
+ ndef.advtrains.trackworker_next_rot = def.nodename_prefix.."_"..suffix..preset.rotation[rotid+1]
+ end
+ if var.trackworker then
+ ndef.advtrains.trackworker_next_var = def.nodename_prefix.."_"..var.trackworker..rotation
+ end
+
+ local the_node_name = def.nodename_prefix.."_"..suffix..rotation
+
+ --trackplacer
+ if preset.regtp and (var.tpsingle or var.tpdouble) then
+ advtrains.trackplacer.register_candidate(
+ def.nodename_prefix,
+ the_node_name,
+ ndef,
+ var.tpsingle,
+ var.tpdouble,
+ true)
+ end
+
+ -- All set, go ahead and register node!
+ --atdebug("track_reg_helper: Registering ",the_node_name," as",ndef)
+ minetest.register_node(":"..the_node_name, ndef)
+
+ end
+ end
+ end
+end
+
+-- slope placer. Defined in register_tracks.
+--crafted with rail and gravel
+local sl={}
+function sl.register_placer(def, preset)
+ minetest.register_craftitem(":"..def.nodename_prefix.."_slopeplacer",{
+ description = S("@1 Slope", def.description),
+ inventory_image = def.texture_prefix.."_slopeplacer.png",
+ wield_image = def.texture_prefix.."_slopeplacer.png",
+ groups={},
+ on_place = sl.create_slopeplacer_on_place(def, preset)
+ })
+end
+--(itemstack, placer, pointed_thing)
+function sl.create_slopeplacer_on_place(def, preset)
+ return function(istack, player, pt)
+ if not pt.type=="node" then
+ minetest.chat_send_player(player:get_player_name(), S("Can't place: not pointing at node"))
+ return istack
+ end
+ local pos=pt.above
+ if not pos then
+ minetest.chat_send_player(player:get_player_name(), S("Can't place: not pointing at node"))
+ return istack
+ end
+ local node=minetest.get_node(pos)
+ if not minetest.registered_nodes[node.name] or not minetest.registered_nodes[node.name].buildable_to then
+ minetest.chat_send_player(player:get_player_name(), S("Can't place: space occupied!"))
+ return istack
+ end
+ if not advtrains.check_track_protection(pos, player:get_player_name()) then
+ minetest.record_protection_violation(pos, player:get_player_name())
+ return istack
+ end
+ --determine player orientation (only horizontal component)
+ --get_look_horizontal may not be available
+ local yaw=player.get_look_horizontal and player:get_look_horizontal() or (player:get_look_yaw() - math.pi/2)
+
+ --rounding unit vectors is a nice way for selecting 1 of 8 directions since sin(30°) is 0.5.
+ local dirvec={x=math.floor(math.sin(-yaw)+0.5), y=0, z=math.floor(math.cos(-yaw)+0.5)}
+ --translate to direction to look up inside the preset table
+ local param2, rot45=({
+ [-1]={
+ [-1]=2,
+ [0]=3,
+ [1]=3,
+ },
+ [0]={
+ [-1]=2,
+ [1]=0,
+ },
+ [1]={
+ [-1]=1,
+ [0]=1,
+ [1]=0,
+ },
+ })[dirvec.x][dirvec.z], dirvec.x~=0 and dirvec.z~=0
+ local lookup=preset.slopeplacer
+ if rot45 then lookup=preset.slopeplacer_45 end
+
+ --go unitvector forward and look how far the next node is
+ local step=1
+ while step<=lookup.max do
+ local node=minetest.get_node(vector.add(pos, dirvec))
+ --next node solid?
+ if not minetest.registered_nodes[node.name] or not minetest.registered_nodes[node.name].buildable_to or advtrains.is_protected(pos, player:get_player_name()) then
+ --do slopes of this distance exist?
+ if lookup[step] then
+ if minetest.settings:get_bool("creative_mode") or istack:get_count()>=step then
+ --start placing
+ local placenodes=lookup[step]
+ while step>0 do
+ minetest.set_node(pos, {name=def.nodename_prefix.."_"..placenodes[step], param2=param2})
+ if not minetest.settings:get_bool("creative_mode") then
+ istack:take_item()
+ end
+ step=step-1
+ pos=vector.subtract(pos, dirvec)
+ end
+ else
+ minetest.chat_send_player(player:get_player_name(), S("Can't place: Not enough slope items left (@1 required)", step))
+ end
+ else
+ minetest.chat_send_player(player:get_player_name(), S("Can't place: There's no slope of length @1",step))
+ end
+ return istack
+ end
+ step=step+1
+ pos=vector.add(pos, dirvec)
+ end
+ minetest.chat_send_player(player:get_player_name(), S("Can't place: no supporting node at upper end."))
+ return itemstack
+ end
+end
+
+advtrains.slope=sl
diff --git a/advtrains/trackplacer.lua b/advtrains/trackplacer.lua
new file mode 100644
index 0000000..b9c2c68
--- /dev/null
+++ b/advtrains/trackplacer.lua
@@ -0,0 +1,374 @@
+--trackplacer.lua
+--holds code for the track-placing system. the default 'track' item will be a craftitem that places rails as needed. this will neither place or change switches nor place vertical rails.
+
+-- Get current translator
+local S = advtrains.translate
+
+--all new trackplacer code
+local tp={
+ groups={}
+}
+
+--[[ New in version 2.5:
+
+The track placer no longer uses hacky nodename pattern matching.
+The base criterion for rotating or matching tracks is the common "ndef.advtrains.track_place_group" property.
+Only rails where this field is set are considered for replacement. Other rails can still be considered for connection.
+Replacement ("bending") of rails can only happen within their respective track place group. Only two-conn rails are allowed in the trackplacer.
+
+The track registration functions register the candidates for any given track_place_group in two separate collections:
+- double: tracks that can be used to connect both ends of the rail
+- single: tracks that will be used to connect conn1 when only a single end is to be connected
+
+When track placing is requested, the calling code just supplies the track_place_group to be placed.
+
+]]--
+
+local function rotate(conn, rot)
+ return (conn + rot) % 16
+end
+
+-- Register a track node as candidate
+-- tpg: the track place group to register the candidates for
+-- NOTE: This value is automatically added to the node definition (ndef) in field ndef.advtrains.track_place_group!
+-- name, ndef: the node name and node definition table to register
+-- as_single: whether the rail should be considered as candidate for one-endpoint connection
+-- Typically only set for the straight rail variants
+-- as_double: whether the rail should be considered as candidate for two-endpoint connection
+-- Typically set for straights and curves
+-- ignore_2conn_for_legacy_xing: skips the 2-connection assertion - ONLY for compatibility with the legacy crossing nodes, DO NOT USE!
+function tp.register_candidate(tpg, name, ndef, as_single, as_double, ignore_2conn_for_legacy_xing)
+ --atdebug("TP Register candidate:",tpg, name, as_single, as_double)
+ --get or create TP group
+ if not tp.groups[tpg] then
+ tp.groups[tpg] = {double = {}, single1 = {}, single2 = {}, default = {name = name, param2 = 0} }
+ -- note: this causes the first candidate to ever be registered to be the default (which is typically what you want)
+ -- But it can be overwritten using tp.set_default_place_candidate
+ end
+ local g = tp.groups[tpg]
+
+ -- get conns
+ if not ignore_2conn_for_legacy_xing then
+ assert(#ndef.at_conns == 2)
+ end
+ local c1, c2 = ndef.at_conns[1].c, ndef.at_conns[2].c
+ local is_symmetrical = (rotate(c1, 8) == c2)
+
+ -- store all possible rotations (param2 values)
+ for i=0,3 do
+ if as_double then
+ g.double[rotate(c1,i*4).."_"..rotate(c2,i*4)] = {name=name, param2=i}
+ if not is_symmetrical then
+ g.double[rotate(c2,i*4).."_"..rotate(c1,i*4)] = {name=name, param2=i}
+ -- if the track is unsymmetric (e.g. a curve), we may require the "wrong" orientation to fill a gap.
+ end
+ end
+ if as_single then
+ g.single1[rotate(c1,i*4)] = {name=name, param2=i}
+ g.single2[rotate(c2,i*4)] = {name=name, param2=i}
+ end
+ end
+
+ -- Set track place group on the node
+ if not ndef.advtrains then
+ ndef.advtrains = {}
+ end
+ ndef.advtrains.track_place_group = tpg
+end
+
+-- Sets the node that is placed by the track placer when there is no track nearby. param2 defaults to 0
+function tp.set_default_place_candidate(tpg, name, param2)
+ if not tp.groups[tpg] then
+ tp.groups[tpg] = {double = {}, single1 = {}, single2 = {}, default = {name = name, param2 = param2 or 0} }
+ else
+ tp.groups[tpg].default = {name = name, param2 = param2 or 0}
+ end
+end
+
+local function check_or_bend_rail(origin, dir, pname, commit)
+ local pos = advtrains.pos_add_dir(origin, dir)
+ local back_dir = advtrains.oppd(dir);
+
+ local node_ok, conns = advtrains.get_rail_info_at(pos)
+ if not node_ok then
+ -- try the node one level below
+ pos.y = pos.y - 1
+ node_ok, conns = advtrains.get_rail_info_at(pos)
+ end
+ if not node_ok then
+ return false
+ end
+ -- if one conn of the node here already points towards us, nothing to do
+ for connid, conn in ipairs(conns) do
+ if back_dir == conn.c then
+ return true
+ end
+ end
+ -- can we bend the node here?
+ local node = advtrains.ndb.get_node(pos)
+ local ndef = minetest.registered_nodes[node.name]
+ if not ndef or not ndef.advtrains or not ndef.advtrains.track_place_group then
+ return false
+ end
+ -- now the track must be two-conn, else it wouldn't be allowed to have track_place_group set.
+ --assert(#conns == 2) -- cannot check here, because of legacy crossing hack
+ -- Is player and game allowed to do this?
+ if not advtrains.can_dig_or_modify_track(pos) then
+ return false
+ end
+ if not advtrains.check_track_protection(pos, pname) then
+ return false
+ end
+ -- we confirmed that track can be modified. Does there exist a suitable connection candidate?
+ -- check if there are any unbound ends
+ local bound_connids = {}
+ for connid, conn in ipairs(conns) do
+ local adj_pos, adj_connid = advtrains.get_adjacent_rail(pos, conns, connid)
+ if adj_pos then
+ bound_connids[#bound_connids+1] = connid
+ end
+ end
+ -- depending on the nummber of ends, decide
+ if #bound_connids == 2 then
+ -- rail is within a fixed track, do not break up
+ return false
+ end
+ -- obtain the group table
+ local g = tp.groups[ndef.advtrains.track_place_group]
+ if #bound_connids == 1 then
+ -- we can attempt double
+ local bound_dir = conns[bound_connids[1]].c
+ if g.double[back_dir.."_"..bound_dir] then
+ if commit then
+ advtrains.ndb.swap_node(pos, g.double[back_dir.."_"..bound_dir])
+ end
+ return true
+ end
+ else
+ -- rail is entirely unbound, we can attempt single1
+ if g.single1[back_dir] then
+ if commit then
+ advtrains.ndb.swap_node(pos, g.single1[back_dir])
+ end
+ return true
+ end
+ end
+end
+
+local function track_place_node(pos, node, ndef_p, pname)
+ --atdebug("track_place_node: ",pos, node)
+ advtrains.ndb.swap_node(pos, node)
+ local ndef = ndef_p or minetest.registered_nodes[node.name]
+ if ndef and ndef.after_place_node then
+ -- resolve player again
+ local player = pname and core.get_player_by_name(pname) or nil
+ ndef.after_place_node(pos, player) -- note: itemstack and pointed_thing are NOT available here anymore (crap!)
+ end
+end
+
+
+-- Main API function to place a track. Replaces the older "placetrack"
+-- This function will attempt to place a track of the specified track placing group at the specified position, connecting it
+-- with neighboring rails. Neighboring rails can themselves be replaced ("bent") within their own track place group,
+-- if the player is permitted to do this.
+-- Order of preference is:
+-- Connect two track ends if possible
+-- Connect one track end if any rail is near
+-- Place the default track if no tracks are near
+-- The function returns true on success.
+function tp.place_track(pos, tpg, pname, yaw)
+ -- 1. collect neighboring tracks and whether they can be connected
+ --atdebug("tp.place_track(",pos, tpg, pname, yaw,")")
+ local cand = {}
+ for i=0,15 do
+ if check_or_bend_rail(pos, i, pname) then
+ cand[#cand+1] = i
+ end
+ end
+ --atdebug("Candidates: ",cand)
+ -- obtain the group table
+ local g = tp.groups[tpg]
+ if not g then
+ error("tp.place_track: for tpg="..tpg.." couldn't find the group table")
+ end
+ --atdebug("Group table:",g)
+ -- 2. try all possible two-endpoint connections
+ for k1, conn1 in ipairs(cand) do
+ for k2, conn2 in ipairs(cand) do
+ if k1~=k2 then
+ -- order of conn1/conn2: prefer conn1 being in the direction of the player facing.
+ -- the combination the other way round will be run through in a later loop iteration
+ if advtrains.yawToDirection(yaw, conn1, conn2) == conn1 then
+ -- does there exist a suitable double-connection rail?
+ --atdebug("Try double conn: ",conn1, conn2)
+ local node = g.double[conn1.."_"..conn2]
+ if node then
+ check_or_bend_rail(pos, conn1, pname, true)
+ check_or_bend_rail(pos, conn2, pname, true)
+ track_place_node(pos, node, nil, pname) -- calls after_place_node implicitly
+ return true
+ end
+ end
+ end
+ end
+ end
+ -- 3. try all possible one_endpoint connections
+ for k1, conn1 in ipairs(cand) do
+ -- select single1 or single2? depending on yaw
+ local single
+ if advtrains.yawToDirection(yaw, conn1, advtrains.oppd(conn1)) == conn1 then
+ single = g.single1
+ else
+ single = g.single2
+ end
+ --atdebug("Try single conn: ",conn1)
+ local node = single[conn1]
+ if node then
+ check_or_bend_rail(pos, conn1, pname, true)
+ track_place_node(pos, node, nil, pname) -- calls after_place_node implicitly
+ return true
+ end
+ end
+ -- 4. if nothing worked, set the default
+ local node = g.default
+ track_place_node(pos, node, nil, pname) -- calls after_place_node implicitly
+ return true
+end
+
+
+-- TRACK WORKER --
+
+-- function called when placing (right-clicking) with track worker
+function advtrains.trackworker_cycle_node_rotation(pos, node, player)
+ local name = player:get_player_name()
+ if not name then
+ return
+ end
+ local has_aux1_down = player:get_player_control().aux1
+
+ if not advtrains.check_track_protection(pos, name) then
+ return
+ end
+
+ -- New since 2.5: only the fields in the node definition are considered, no more hacky pattern matching on the nodename
+
+ local ndef = minetest.registered_nodes[node.name]
+
+ if not ndef.advtrains or not ndef.advtrains.trackworker_next_rot then
+ minetest.chat_send_player(name, S("This node can't be rotated using the trackworker!"))
+ return
+ end
+
+ -- check if the node is modify-protected
+ if advtrains.is_track(node.name) then
+ -- is a track, we can query
+ local can_modify, reason = advtrains.can_dig_or_modify_track(pos)
+ if not can_modify then
+ local str = S("This track can not be rotated!")
+ if reason then
+ str = str .. " " .. reason
+ end
+ minetest.chat_send_player(name, str)
+ return
+ end
+ end
+
+ local new_node
+ if has_aux1_down then
+ --feature: flip the node by 180°
+ --i've always wanted this!
+ new_node = {name=node.name, param2=(node.param2+2)%4}
+ else
+ new_node = {name = ndef.advtrains.trackworker_next_rot, param2 = node.param2}
+ if ndef.advtrains.trackworker_rot_incr_param2 then
+ new_node.param2 = ((node.param2 + 1) % 4)
+ end
+ end
+
+ -- check if the node has a callback and check if it inhibits (like screwdriver)
+ if ndef.advtrains.trackworker_on_cycle_rotation then
+ if ndef.advtrains.trackworker_on_cycle_rotation(pos, node, player, new_node, has_aux1_down) == false then
+ -- inhibit action
+ return
+ end
+ end
+
+ advtrains.ndb.swap_node(pos, new_node)
+
+end
+
+-- function called when using (left-clicking) with track worker
+function advtrains.trackworker_cycle_node_variant(pos, node, player)
+ local name = player:get_player_name()
+ if not name then
+ return
+ end
+
+ if not advtrains.check_track_protection(pos, name) then
+ return
+ end
+
+ -- New since 2.5: only the fields in the node definition are considered, no more hacky pattern matching on the nodename
+
+ local ndef = minetest.registered_nodes[node.name]
+
+ if not ndef.advtrains or not ndef.advtrains.trackworker_next_var then
+ minetest.chat_send_player(name, S("This node can't be changed using the trackworker!"))
+ return
+ end
+
+ -- check if the node is modify-protected
+ if advtrains.is_track(node.name) then
+ -- is a track, we can query
+ local can_modify, reason = advtrains.can_dig_or_modify_track(pos)
+ if not can_modify then
+ local str = S("This track can not be rotated!")
+ if reason then
+ str = str .. " " .. reason
+ end
+ minetest.chat_send_player(name, str)
+ return
+ end
+ end
+
+ local new_node = {name = ndef.advtrains.trackworker_next_var, param2 = node.param2}
+
+ -- check if the node has a callback and check if it inhibits (like screwdriver)
+ if ndef.advtrains.trackworker_on_cycle_variant then
+ if ndef.advtrains.trackworker_on_cycle_variant(pos, node, player, new_node) == false then
+ -- inhibit action
+ return
+ end
+ end
+
+ advtrains.ndb.swap_node(pos, new_node)
+
+end
+
+minetest.register_craftitem("advtrains:trackworker",{
+ description = S("Track Worker Tool") .. "\n\n" .. S("Left-click: change rail type (straight/curve/switch)\nRight-click: rotate object"),
+ short_description = S("Track Worker Tool"),
+ groups = {cracky=1}, -- key=name, value=rating; rating=1..3.
+ inventory_image = "advtrains_trackworker.png",
+ wield_image = "advtrains_trackworker.png",
+ stack_max = 1,
+ on_place = function(itemstack, player, pointed_thing)
+ if pointed_thing.type=="node" then
+ local pos=pointed_thing.under
+ local node=minetest.get_node(pos)
+
+ advtrains.trackworker_cycle_node_rotation(pos, node, player)
+ end
+ end,
+ on_use = function(itemstack, player, pointed_thing)
+ if pointed_thing.type=="node" then
+ local pos=pointed_thing.under
+ local node=minetest.get_node(pos)
+
+ advtrains.trackworker_cycle_node_variant(pos, node, player)
+ end
+ end,
+})
+
+--putting into right place
+advtrains.trackplacer=tp
diff --git a/advtrains/tracks.lua b/advtrains/tracks.lua
new file mode 100644
index 0000000..e6d08a7
--- /dev/null
+++ b/advtrains/tracks.lua
@@ -0,0 +1,275 @@
+-- tracks.lua
+-- rewritten with advtrains 2.5 according to new track registration system
+
+-- Get current translator
+local S = advtrains.translate
+
+--[[
+
+Tracks in advtrains are defined by the node definition. They must have at least 2 connections, but can have any number.
+Switchable nodes (turnouts, single/double-slip switches) are implemented by having a separate node (node name) for each of the possible states.
+
+ minetest.register_node(nodename, {
+ ... usual node definition ...
+ groups = {
+ advtrains_track = 1,
+ advtrains_track_<tracktype>=1
+ ^- these groups tell that the node is a track
+ not_blocking_trains=1,
+ ^- this group tells that the node should not block trains although it's walkable.
+ },
+
+ at_rail_y = 0,
+ ^- Height of this rail node (the y position of a wagon that stands centered on this rail)
+ at_conns = {
+ [1] = { c=0..15, y=0..1 },
+ [2] = { c=0..15, y=0..1 },
+ ( [3] = { c=0..15, y=0..1 }, )
+ ( [4] = { c=0..15, y=0..1 }, )
+ ( ... )
+ }
+ ^- Connections of this rail. There are two general cases:
+ a) SIMPLE TRACK - the track has exactly 2 connections, and does not feature a turnout, crossing or other contraption
+ For simple tracks, except for the at_conns table no further setup needs to be specified. A train entering on conn 1 will go out at conn 2 and vice versa.
+ A track with only one connection defined is not permitted.
+ b) COMPOUND TRACK - the track has more than 2 connections
+ This will be used for turnouts and crossings. Tracks with more than 2 conns MUST define 'at_conn_map'.
+ Switchable nodes, whose state can be changed (e.g. turnouts) MUST define a 'state_map' within the advtrains table as well.
+ This differs from the behavior up until 2.4.2, where the conn mapping was fixed.
+ ^- Connection definition:
+ - c is the direction of the connection (0-16). For the mapping to world directions see helpers.lua.
+ - Connections will be auto-rotated with param2 of the node (horizontal, param2 values 0-3 only)
+ - y is the height of the connection (rail will only connect when this matches)
+ ^- The index of a connection inside the conns table (1, 2, 3, ...) is referred throughout advtrains code as 'connid'
+ ^- IMPORTANT: For switchable nodes (any kind of turnout), it is crucial that for all of the node's variants the at_conns table stays the same. See below.
+
+ at_conn_map = {
+ [1] = 2,
+ [2] = 1,
+ [3] = 1,
+ }
+ ^- Connection map of this rail. It specifies when a train enters the track on connid X, on which connid it will leave
+ This field MUST be specified when the number of connections in at_conns is greater than 2
+ This field may, and obviously will, vary between nodes for switchable nodes.
+
+ can_dig = advtrains.track_can_dig_callback
+ after_dig_node = advtrains.track_update_callback
+ after_place_node = advtrains.track_update_callback
+ ^- the code in these 3 default minetest API functions is required for advtrains to work, however you can add your own code
+
+ on_rightclick = advtrains.state_node_on_rightclick_callback
+ ^- Must be added if the node is a turnout and if it should be switched by right-click. It will cause the turnout to be switched to next_state.
+
+ advtrains = {
+ on_train_enter=function(pos, train_id, train, index) end
+ ^- called when a train enters the rail
+ on_train_leave=function(pos, train_id, train, index) end
+ ^- called when a train leaves the rail
+
+ -- The following function is only in effect when interlocking is enabled:
+ on_train_approach = function(pos, train_id, train, index, has_entered, lzbdata)
+ ^- called when a train is approaching this position, called exactly once for every path recalculation (which can happen at any time)
+ ^- This is called so that if the train would start braking now, it would come to halt about(wide approx) 5 nodes before the rail.
+ ^- has_entered: when true, the train is already standing on this node with its front tip, and the enter callback has already been called.
+ Possibly, some actions need not to be taken in this case. Only set if it's the very first node the train is standing on.
+ ^- lzbdata should be ignored and nothing should be assigned to it
+
+ -- The following information is required if the node is a turnout (e.g. can be switched into different positions)
+ node_state = "st"
+ ^- The name of the state this node represents
+ ^- Conventions for this field are as follows:
+ - Two-way straight/turn switches: 'st'=straight branch, 'cr'=diverting/turn branch
+ - 3-way turnouts, Y-turnouts: 'l'=left branch, 's'=straight branch, 'r'=right branch
+
+ node_next_state = "cr"
+ ^- The name of the state that the turnout should be switched to when it is right-clicked
+
+ node_fallback_state = "st"
+ ^- The name of the state that the turnout should "fall back" to when it is released
+ Only used by the interlocking system, when a route on the node is released it is switched back to this state.
+
+ node_state_map = {
+ ["st"] = "<node name of the st variant>",
+ ["cr"] = "<node name of the cr variant>",
+ ... etc ...
+ }
+ ^- Map of state name to the appropriate node name that should be set by advtrains when a switch is requested
+ Note that for all of those nodes, the at_conns table must be identical (however the conn_map will vary)
+
+ node_on_switch_state = function(pos, node, oldstate, newstate)
+ ^- Called when the node state is switched by advtrains, after the node replacement has commenced.
+
+ Turnout switching can happen programmatically via advtrains.setstate(pos, state), via user right_click or via the interlocking system.
+ In no other situation is it permissible to exchange track nodes in-place, unless both at_conns and at_conn_map stay identical.
+
+ Note that the fields node_state, node_next_state and node_state_map completely replace the getstate/setstate functions.
+ There must be a one-to-one mapping between states and node names and no function can be defined for state switching.
+ This principle enables the seamless working of the interlocking autorouter and reduces failure points.
+ The node_state_* system can also be used as drop-in replacement for the passive-API-enabled nodes (andrews-cross, mesecon_switch etc.)
+ The advtrains API functions advtrains.getstate() and advtrains.setstate() remain the programmatic access points, but will now utilize the new state system.
+
+
+ trackworker_next_rot = <nodename of next rotation step>,
+ ^- if set, right-click with trackworker will set this node
+ trackworker_rot_incr_param2 = true
+ ^- if set, trackworker will increase node param2 on rightclick
+
+ trackworker_next_var = <nodename of next variant>
+ ^- if set, left-click with trackworker will set this node
+ }
+ })
+
+]]--
+
+-- This file provides some utilities to register tracks, but tries to not get into the way too much
+
+
+function advtrains.track_can_dig_callback(pos, player)
+ local ok, reason = advtrains.can_dig_or_modify_track(pos)
+ if not ok and player then
+ minetest.chat_send_player(player:get_player_name(), S("This track can not be removed!") .. " " .. reason)
+ end
+ return ok
+end
+
+function advtrains.track_update_callback(pos)
+ advtrains.ndb.update(pos)
+end
+
+function advtrains.state_node_on_rightclick_callback(pos, node, player)
+ if advtrains.check_turnout_signal_protection(pos, player:get_player_name()) then
+ local ndef = minetest.registered_nodes[node.name]
+ if ndef and ndef.advtrains and ndef.advtrains.node_next_state then
+ advtrains.setstate(pos, ndef.advtrains.node_next_state, node)
+ advtrains.log("Switch", player:get_player_name(), pos)
+ end
+ end
+end
+
+-- advtrains.register_node_4rot(name, nodedef)
+-- Registers four rotations for the node defined by nodedef (0°, 30°, 45° and 60°; the 4 90°-steps are already handled by the param2, resulting in 16 directions total).
+-- You must provide the definition for the base node, and certain fields are altered automatically for the 3 additional rotations:
+-- name: appends the suffix "_30", "_45" or "_60"
+-- description: appends the rotation (human-readable) in parenthesis
+-- tiles_prefix: if defined, "tiles" field will be set as prefix..rotationExtension..".png"
+-- mesh_prefix, mesh_suffix: if defined, "mesh" field will be set as prefix..rotationExtension..suffix
+-- at_conns: are rotated according to the node rotation
+-- node_state_map, trackworker_next_var: appends the suffix appropriately.
+-- groups: applies save_in_at_nodedb and not_blocking_trains groups if not already present
+-- The nodes are registered in the trackworker to be rotated with right-click.
+-- definition_mangling_function is an optional parameter. For each of the 4 rotations, it gets passed the modified node definition and may perform final modifications to it.
+-- signature: function definition_mangling_function(name, nodedef, rotationIndex, rotationSuffix)
+-- Example usage: define the setstate function of turnouts (if that is not done via the "automatic" way of state_node_map)
+local rotations = {
+ {i = 0, s = "", h = " (0)", n = "_30"},
+ {i = 1, s = "_30", h = " (30)", n = "_45"},
+ {i = 2, s = "_45", h = " (45)", n = "_60"},
+ {i = 3, s = "_60", h = " (60)", n = ""},
+}
+function advtrains.register_node_4rot(ori_name, ori_ndef, definition_mangling_function)
+ for _, rot in ipairs(rotations) do
+ local ndef = table.copy(ori_ndef)
+ if ori_ndef.advtrains then
+ -- make sure advtrains table is deep-copied because we may need to replace node_state_map
+ ndef.advtrains = table.copy(ori_ndef.advtrains)
+ else
+ ndef.advtrains = {} -- we need the table later for trackworker
+ end
+ -- Perform the name mangling
+ local suffix = rot.s
+ local name = ori_name..suffix
+ ndef.description = ori_ndef.description .. rot.h
+ if ori_ndef.tiles_prefix then
+ ndef.tiles = { ori_ndef.tiles_prefix .. suffix .. ".png" }
+ end
+ if ori_ndef.mesh_prefix then
+ ndef.mesh = ori_ndef.mesh_prefix .. suffix .. ori_ndef.mesh_suffix
+ end
+ -- rotate connections
+ if ori_ndef.at_conns then
+ ndef.at_conns = advtrains.rotate_conn_by(ori_ndef.at_conns, rot.i)
+ end
+ -- update node state map if present
+ if ori_ndef.advtrains then
+ if ori_ndef.advtrains.node_state_map then
+ local new_nsm = {}
+ for state, nname in pairs(ori_ndef.advtrains.node_state_map) do
+ new_nsm[state] = nname .. suffix
+ end
+ ndef.advtrains.node_state_map = new_nsm
+ end
+ if ori_ndef.advtrains.trackworker_next_var then
+ ndef.advtrains.trackworker_next_var = ori_ndef.advtrains.trackworker_next_var .. suffix
+ end
+ -- apply trackworker rot field
+ ndef.advtrains.trackworker_next_rot = ori_name .. rot.n
+ ndef.advtrains.trackworker_rot_incr_param2 = (rot.n=="")
+ end
+ -- apply groups
+ ndef.groups.save_in_at_nodedb = 1
+ ndef.groups.not_blocking_trains = 1
+
+ -- give the definition mangling function an option to do some adjustments
+ if definition_mangling_function then
+ definition_mangling_function(name, ndef, rot.i, suffix)
+ end
+
+ -- register node
+ minetest.register_node(":"..name, ndef)
+
+ -- if this has the track_place_group set, register as a candidate for the track_place_group
+ if ndef.advtrains.track_place_group then
+ advtrains.trackplacer.register_candidate(ndef.advtrains.track_place_group, name, ndef, ndef.advtrains.track_place_single, true)
+ end
+ end
+end
+
+-- track-related helper functions
+
+function advtrains.is_track(nodename)
+ if not minetest.registered_nodes[nodename] then
+ return false
+ end
+ local nodedef=minetest.registered_nodes[nodename]
+ if nodedef and nodedef.groups.advtrains_track then
+ return true
+ end
+ return false
+end
+
+-- returns the connection tables of the track with given node details
+-- returns: conns table, railheight, conn_map table
+function advtrains.get_track_connections(name, param2)
+ local nodedef=minetest.registered_nodes[name]
+ if not nodedef then atprint(" get_track_connections couldn't find nodedef for nodename "..(name or "nil")) return nil end
+ local noderot=param2
+ if not param2 then noderot=0 end
+ if noderot > 3 then atprint(" get_track_connections: rail has invaild param2 of "..noderot) noderot=0 end
+
+ if not nodedef.at_conns then
+ return nil
+ end
+ --atdebug("Track connections of ",name,param2,":",nodedef.at_conns)
+ return advtrains.rotate_conn_by(nodedef.at_conns, noderot*AT_CMAX/4), (nodedef.at_rail_y or 0), nodedef.at_conn_map
+end
+
+-- Function called when a track is about to be dug or modified by the trackworker
+-- Returns either true (ok) or false,"translated string describing reason why it isn't allowed"
+-- Impl Note: possibly duplicate code in "self contained TCB" - see interlocking/tcb_ts_ui.lua!
+function advtrains.can_dig_or_modify_track(pos)
+ if advtrains.get_train_at_pos(pos) then
+ return false, S("Position is occupied by a train.")
+ end
+ -- interlocking: tcb, signal IP a.s.o.
+ if advtrains.interlocking then
+ -- TCB?
+ if advtrains.interlocking.db.get_tcb(pos) then
+ return false, S("There's a Track Circuit Break here.")
+ end
+ -- signal ip?
+ if advtrains.interlocking.db.is_ip_at(pos, true) then -- is_ip_at with purge parameter
+ return false, S("There's a Signal Influence Point here.")
+ end
+ end
+ return true
+end
diff --git a/advtrains/trainhud.lua b/advtrains/trainhud.lua
new file mode 100644
index 0000000..eeebff0
--- /dev/null
+++ b/advtrains/trainhud.lua
@@ -0,0 +1,322 @@
+--trainhud.lua: holds all the code for train controlling
+
+-- Get current translator
+local S = advtrains.translate
+
+local T = advtrains.texture
+
+advtrains.hud = {}
+advtrains.hhud = {}
+
+minetest.register_on_leaveplayer(function(player)
+advtrains.hud[player:get_player_name()] = nil
+advtrains.hhud[player:get_player_name()] = nil
+end)
+
+local hud_type_key = minetest.features.hud_def_type_field and "type" or "hud_elem_type"
+
+local mletter={[1]="F", [-1]="R", [0]="N"}
+
+function advtrains.on_control_change(pc, train, flip)
+ local maxspeed = train.max_speed or 10
+ if pc.sneak then
+ if pc.up then
+ train.tarvelocity = maxspeed
+ end
+ if pc.down then
+ train.tarvelocity = 0
+ end
+ if pc.left then
+ train.tarvelocity = 4
+ end
+ if pc.right then
+ train.tarvelocity = 8
+ end
+ --[[if pc.jump then
+ train.brake = true
+ --0: released, 1: brake and pressed, 2: released and brake, 3: pressed and brake
+ if not train.brake_hold_state or train.brake_hold_state==0 then
+ train.brake_hold_state = 1
+ elseif train.brake_hold_state==2 then
+ train.brake_hold_state = 3
+ end
+ elseif train.brake_hold_state==1 then
+ train.brake_hold_state = 2
+ elseif train.brake_hold_state==3 then
+ train.brake = false
+ train.brake_hold_state = 0
+ end]]
+ --shift+use:see wagons.lua
+ else
+ local act=false
+ if pc.jump then
+ train.ctrl_user = 1
+ act=true
+ end
+ if train.ars_disable and pc.up then
+ -- up clears ars disable flag in any situation
+ train.ars_disable = nil
+ end
+ -- If atc command set, only "Jump" key can clear command. To prevent accidental control.
+ if train.tarvelocity or train.atc_command then
+ return
+ end
+ if pc.up then
+ train.ctrl_user=4
+ act=true
+ end
+ if pc.down then
+ if train.velocity>0 then
+ if pc.jump then
+ train.ctrl_user = 0
+ else
+ train.ctrl_user = 2
+ end
+ act=true
+ else
+ advtrains.invert_train(train.id)
+ advtrains.atc.train_reset_command(train)
+ end
+ end
+ if pc.left then
+ if train.door_open ~= 0 then
+ train.door_open = 0
+ else
+ train.door_open = -1
+ end
+ end
+ if pc.right then
+ if train.door_open ~= 0 then
+ train.door_open = 0
+ else
+ train.door_open = 1
+ end
+ end
+ if not act then
+ train.ctrl_user = nil
+ end
+ end
+end
+function advtrains.update_driver_hud(pname, train, flip)
+ local inside=train.text_inside or ""
+ local ft, ht = advtrains.hud_train_format(train, flip)
+ advtrains.set_trainhud(pname, inside.."\n"..ft, ht)
+end
+function advtrains.clear_driver_hud(pname)
+ advtrains.set_trainhud(pname, "")
+end
+
+function advtrains.set_trainhud(name, text, driver)
+ local hud = advtrains.hud[name]
+ local player=minetest.get_player_by_name(name)
+ if not player then
+ return
+ end
+ local drivertext = driver or ""
+ local driverhud = {
+ [hud_type_key] = "image",
+ name = "ADVTRAINS_DRIVER",
+ position = {x=0.5, y=1},
+ offset = {x=0,y=-170},
+ text = drivertext,
+ alignment = {x=0,y=-1},
+ scale = {x=1,y=1},
+ }
+ if not hud then
+ hud = {}
+ advtrains.hud[name] = hud
+ hud.id = player:hud_add({
+ [hud_type_key] = "text",
+ name = "ADVTRAINS",
+ number = 0xFFFFFF,
+ position = {x=0.5, y=1},
+ offset = {x=0, y=-300},
+ text = text,
+ scale = {x=200, y=60},
+ alignment = {x=0, y=-1},
+ })
+ hud.driver = player:hud_add(driverhud)
+ hud.oldText = text
+ hud.oldDriver = drivertext
+ else
+ if hud.oldText ~= text then
+ player:hud_change(hud.id, "text", text)
+ hud.oldText=text
+ end
+ if hud.driver then
+ if hud.oldDriver ~= drivertext then
+ player:hud_change(hud.driver, "text", drivertext)
+ hud.oldDriver = drivertext
+ end
+ elseif driver then
+ hud.driver = player:hud_add(driverhud)
+ hud.oldDriver = drivertext
+ end
+ end
+end
+
+function advtrains.set_help_hud(name, text)
+ local hud = advtrains.hhud[name]
+ local player=minetest.get_player_by_name(name)
+ if not player then
+ return
+ end
+ if not hud then
+ hud = {}
+ advtrains.hhud[name] = hud
+ hud.id = player:hud_add({
+ [hud_type_key] = "text",
+ name = "ADVTRAINS_HELP",
+ number = 0xFFFFFF,
+ position = {x=1, y=0.3},
+ offset = {x=0, y=0},
+ text = text,
+ scale = {x=200, y=60},
+ alignment = {x=1, y=0},
+ })
+ hud.oldText=text
+ return
+ elseif hud.oldText ~= text then
+ player:hud_change(hud.id, "text", text)
+ hud.oldText=text
+ end
+end
+
+--train.lever:
+--Speed control lever in train, for new train control system.
+--[[
+Value Disp Control Meaning
+0 BB S+Space Emergency Brake
+1 B Space Normal Brake
+2 - S Roll
+3 o <none> Stay at speed
+4 + W Accelerate
+]]
+
+function advtrains.hud_train_format(train, flip)
+ if not train then return "","" end
+ local sformat = string.format -- this appears to be faster than (...):format
+
+ local max = train.max_speed or 10
+ local res = train.speed_restriction
+ local vel = advtrains.abs_ceil(train.velocity)
+ local vel_kmh=advtrains.abs_ceil(advtrains.ms_to_kmh(train.velocity))
+
+ local tlev=train.lever or 3
+ if train.velocity==0 and not train.active_control then tlev=1 end
+ if train.hud_lzb_effect_tmr then
+ tlev=1
+ end
+
+ local hud = T.combine(440, 110, "black")
+ local st = {}
+ if train.debug then st = {train.debug} end
+
+ -- lever
+ hud:add_multicolor_fill_topdown(275, 10, 5, 90, 1, "cyan", 1, "white", 2, "orange", 1, "red")
+ hud:add_lever_topdown(280, 10, 30, 90, 18, 6, (4-tlev)/4, "gray", "darkslategray")
+ -- reverser
+ hud:add(245, 10, T"advtrains_hud_arrow.png":transform"FY":multiply(flip and "gray" or "cyan"))
+ hud:add(245, 85, T"advtrains_hud_arrow.png":multiply(flip and "orange" or "gray"))
+ hud:add_lever_topdown(240, 30, 25, 50, 15, 5, flip and 1 or 0, "gray", "darkslategray")
+ -- train control/safety indication
+ hud:add(10, 10, T"advtrains_hud_atc.png":resize(30, 30):multiply((train.tarvelocity or train.atc_command) and "cyan" or "darkslategray"))
+ hud:add(50, 10, T"advtrains_hud_lzb.png":resize(30, 30):multiply(train.hud_lzb_effect_tmr and "red" or "darkslategray"))
+ hud:add(90, 10, T"advtrains_hud_shunt.png":resize(30, 30):multiply(train.is_shunt and "orange" or "darkslategray"))
+ -- door
+ hud:add_fill(187, 10, 26, 30, "white"):add_fill(189, 12, 22, 11, "black")
+ hud:add_fill(170, 10, 15, 30, train.door_open==-1 and "white" or "darkslategray"):add_fill(172, 12, 11, 11, "black")
+ hud:add_fill(215, 10, 15, 30, train.door_open==1 and "white" or "darkslategray"):add_fill(217, 12, 11, 11, "black")
+ -- speed indication(s)
+ hud:add_n7seg(320, 10, 110, 90, vel, 2, "red")
+ hud:add_segmentbar_leftright(10, 65, 217, 20, 3, 20, max, 20, "darkslategray", 0, vel, "white")
+ if res and res > 0 then
+ hud:add_fill(7+res*11, 60, 3, 30, "red")
+ end
+ if train.tarvelocity then
+ hud:add(1+train.tarvelocity*11, 85, T"advtrains_hud_arrow.png":transform"FY":multiply"cyan")
+ end
+ local lzb = train.lzb
+ local lzbdisp = {c = "darkslategray", d = 888}
+ if lzb and lzb.checkpoints and lzb.checkpoints[1] then
+ local cp = lzb.checkpoints[1]
+ if advtrains.interlocking and cp.udata and cp.udata.signal_pos then
+ local sigd = advtrains.interlocking.db.get_sigd_for_signal(cp.udata.signal_pos)
+ if sigd then
+ local tcbs = advtrains.interlocking.db.get_tcbs(sigd) or {}
+ if tcbs.route_rsn then
+ table.insert(st, ("%s: %s"):format(minetest.pos_to_string(sigd.p), tcbs.route_rsn))
+ end
+ end
+ end
+ local spd = cp.speed
+ local c, arrow
+ if not spd or spd == -1 then
+ c = "lime"
+ elseif spd == 0 then
+ c = "red"
+ elseif not res or spd <= res then
+ c = "orange"
+ arrow = true
+ elseif spd <= max then
+ c = "yellow"
+ arrow = true
+ else
+ c = "cyan"
+ arrow = true
+ end
+ if arrow then
+ hud:add(1+spd*11, 50, T"advtrains_hud_arrow.png":multiply"red")
+ end
+ local dist = math.floor(((cp.index or train.index)-train.index))
+ dist = math.max(0, math.min(999, dist))
+ lzbdisp = {c = c, d = dist}
+ end
+ hud:add_fill(130, 10, 30, 5, lzbdisp.c)
+ hud:add_fill(130, 35, 30, 5, lzbdisp.c)
+ hud:add_n7seg(131, 18, 28, 14, lzbdisp.d, 3, lzbdisp.c)
+
+ if res and res == 0 then
+ table.insert(st, S("OVERRUN RED SIGNAL! Examine situation and reverse train to move again."))
+ end
+
+ if train.atc_command then
+ local delay_str = ""
+ if train.atc_delay and train.atc_delay >= 0 then
+ delay_str = advtrains.abs_ceil(train.atc_delay).."s "
+ end
+ if train.atc_wait_finish then
+ delay_str = delay_str.."[W] "
+ end
+ if train.atc_wait_autocouple then
+ delay_str = delay_str.."[Cpl] "
+ end
+ if train.atc_wait_signal then
+ delay_str = delay_str.."[G] "
+ end
+ table.insert(st, ("ATC: %s%s"):format(delay_str, train.atc_command or ""))
+ end
+
+ return table.concat(st,"\n"), tostring(hud)
+end
+
+local _, texture = advtrains.hud_train_format { -- dummy train object to demonstrate the train hud
+ max_speed = 15, speed_restriction = 15, velocity = 15, tarvelocity = 12,
+ active_control = true, lever = 3, ctrl = {lzb = true}, is_shunt = true,
+ door_open = 1, lzb = {checkpoints = {{speed=6, index=125.7}}}, index = 100,
+}
+
+minetest.register_node("advtrains:hud_demo",{
+ description = "Train HUD demonstration",
+ tiles = {texture},
+ groups = {cracky = 3, not_in_creative_inventory = 1}
+})
+
+minetest.register_craft {
+ output = "advtrains:hud_demo",
+ recipe = {
+ {"default:paper", "default:paper", "default:paper"},
+ {"default:paper", "advtrains:trackworker", "default:paper"},
+ {"default:paper", "default:paper", "default:paper"},
+ }
+}
diff --git a/advtrains/trainlogic.lua b/advtrains/trainlogic.lua
new file mode 100644
index 0000000..559c029
--- /dev/null
+++ b/advtrains/trainlogic.lua
@@ -0,0 +1,1363 @@
+--trainlogic.lua
+--controls train entities stuff about connecting/disconnecting/colliding trains and other things
+
+-- Get current translator
+local S = advtrains.translate
+
+local setting_overrun_mode = minetest.settings:get("advtrains_overrun_mode")
+
+local benchmark=false
+local bm={}
+local bmlt=0
+local bmsteps=0
+local bmstepint=200
+atprintbm=function(action, ta)
+ if not benchmark then return end
+ local t=(os.clock()-ta)*1000
+ if not bm[action] then
+ bm[action]=t
+ else
+ bm[action]=bm[action]+t
+ end
+ bmlt=bmlt+t
+end
+function endstep()
+ if not benchmark then return end
+ bmsteps=bmsteps-1
+ if bmsteps<=0 then
+ bmsteps=bmstepint
+ for key, value in pairs(bm) do
+ minetest.chat_send_all(key.." "..(value/bmstepint).." ms avg.")
+ end
+ minetest.chat_send_all("Total time consumed by all advtrains actions per step: "..(bmlt/bmstepint).." ms avg.")
+ bm={}
+ bmlt=0
+ end
+end
+
+--acceleration for lever modes (trainhud.lua), per wagon
+local t_accel_all={
+ [0] = -10,
+ [1] = -3,
+ [11] = -2, -- calculation base for LZB
+ [2] = -0.5,
+ [4] = 0.5,
+}
+--acceleration per engine
+local t_accel_eng={
+ [0] = 0,
+ [1] = 0,
+ [11] = 0,
+ [2] = 0,
+ [4] = 1.5,
+}
+
+local VLEVER_EMERG = 0
+local VLEVER_BRAKE = 1
+local VLEVER_LZBCALC = 11
+local VLEVER_ROLL = 2
+local VLEVER_HOLD = 3
+local VLEVER_ACCEL = 4
+
+-- How far in front of a whole index with LZB 0 restriction the train should come to a halt
+-- value must be between 0 and 0.5, exclusively
+local LZB_ZERO_APPROACH_DIST = 0.1
+-- Speed the train temporarily approaches the stop point with
+local LZB_ZERO_APPROACH_SPEED = 0.2
+
+
+
+tp_player_tmr = 0
+
+advtrains.mainloop_trainlogic=function(dtime, stepno)
+ --build a table of all players indexed by pts. used by damage and door system.
+ advtrains.playersbypts={}
+ for _, player in pairs(minetest.get_connected_players()) do
+ if not advtrains.player_to_train_mapping[player:get_player_name()] then
+ --players in train are not subject to damage
+ local ptspos=minetest.pos_to_string(vector.round(player:get_pos()))
+ advtrains.playersbypts[ptspos]=player
+ end
+ end
+
+ if tp_player_tmr<=0 then
+ -- teleport players to their train every 2 seconds
+ for _, player in pairs(minetest.get_connected_players()) do
+ advtrains.tp_player_to_train(player)
+ end
+ tp_player_tmr = 2
+ else
+ tp_player_tmr = tp_player_tmr - dtime
+ end
+ --regular train step
+ --[[ structure:
+ 1. make trains calculate their occupation windows when needed (a)
+ 2. when occupation tells us so, restore the occupation tables (a)
+ 4. make trains move and update their new occupation windows and write changes
+ to occupation tables (b)
+ 5. make trains do other stuff (c)
+ ]]--
+ local t=os.clock()
+
+ for k,v in pairs(advtrains.trains) do
+ advtrains.atprint_context_tid=k
+ --atprint("=== Step",stepno,"===")
+ advtrains.train_ensure_init(k, v)
+ end
+
+ advtrains.lock_path_inval = true
+
+ for k,v in pairs(advtrains.trains) do
+ advtrains.atprint_context_tid=k
+ advtrains.train_step_b(k, v, dtime)
+ end
+
+ for k,v in pairs(advtrains.trains) do
+ advtrains.atprint_context_tid=k
+ advtrains.train_step_c(k, v, dtime)
+ end
+
+ advtrains.lock_path_inval = false
+
+ advtrains.atprint_context_tid=nil
+
+ atprintbm("trainsteps", t)
+ endstep()
+end
+
+function advtrains.tp_player_to_train(player)
+ local pname = player:get_player_name()
+ local id=advtrains.player_to_train_mapping[pname]
+ if id then
+ local train=advtrains.trains[id]
+ if not train then advtrains.player_to_train_mapping[pname]=nil return end
+ --set the player to the train position.
+ --minetest will emerge the area and load the objects, which then will call reattach_all().
+ --because player is in mapping, it will not be subject to dying.
+ player:set_pos(train.last_pos)
+ end
+end
+minetest.register_on_joinplayer(function(player)
+ advtrains.hud[player:get_player_name()] = nil
+ advtrains.hhud[player:get_player_name()] = nil
+ --independent of this, cause all wagons of the train which are loaded to reattach their players
+ --needed because already loaded wagons won't call reattach_all()
+ local pname = player:get_player_name()
+ local id=advtrains.player_to_train_mapping[pname]
+ if id then
+ for _, wagon in advtrains.wagon_entity_pairs_in_train(id) do
+ wagon:reattach_all()
+ end
+ end
+end)
+
+
+minetest.register_on_dieplayer(function(player)
+ local pname=player:get_player_name()
+ local id=advtrains.player_to_train_mapping[pname]
+ if id then
+ local train=advtrains.trains[id]
+ if not train then advtrains.player_to_train_mapping[pname]=nil return end
+ for _, wagon in advtrains.wagon_entity_pairs_in_train(id) do
+ --when player dies, detach him from the train
+ --call get_off_plr on every wagon since we don't know which one he's on.
+ wagon:get_off_plr(pname)
+ end
+ -- just in case no wagon felt responsible for this player: clear train mapping
+ advtrains.player_to_train_mapping[pname] = nil
+ end
+end)
+
+--[[
+
+Zone diagram of a train (copy from occupation.lua!):
+ |___| |___| --> Direction of travel
+ oo oo+oo oo
+=|=======|===|===========|===|=======|===================|========|===
+ |SafetyB|CpB| Train |CpF|SafetyF| Brake |Aware |
+[1] [2] [3] [4] [5] [6] [7] [8]
+This mapping from indices in occwindows to zone ids is contained in WINDOW_ZONE_IDS
+
+
+The occupation system has been abandoned. The constants will still be used
+to determine the couple distance
+(because of the reverse lookup, the couple system simplifies a lot...)
+
+]]--
+-- unless otherwise stated, in meters.
+local SAFETY_ZONE = 10
+local COUPLE_ZONE = 2 --value in index positions!
+local BRAKE_SPACE = 10
+local AWARE_ZONE = 10
+local WINDOW_ZONE_IDS = {
+ 2, -- 1 - SafetyB
+ 4, -- 2 - CpB
+ 1, -- 3 - Train
+ 5, -- 4 - CpF
+ 3, -- 5 - SafetyF
+ 6, -- 6 - Brake
+ 7, -- 7 - Aware
+}
+
+
+-- If a variable does not exist in the table, it is assigned the default value
+local function assertdef(tbl, var, def)
+ if not tbl[var] then
+ tbl[var] = def
+ end
+end
+
+function advtrains.get_acceleration(train, lever)
+ local acc_all = t_accel_all[lever]
+ if not acc_all then return 0 end
+
+ local acc_eng = t_accel_eng[lever]
+ local nwagons = #train.trainparts
+ if nwagons == 0 then
+ -- empty train! avoid division through zero
+ return -1
+ end
+ local acc = acc_all + (acc_eng*train.locomotives_in_train)/nwagons
+ return acc
+end
+
+-- Small local util function to recalculate train's end index
+local function recalc_end_index(train)
+ train.end_index = advtrains.path_get_index_by_offset(train, train.index, -train.trainlen)
+end
+
+-- Occupation Callback system
+-- see occupation.lua
+-- signature is advtrains.te_register_on_<?>(function(id, train) ... end)
+
+local function mkcallback(name)
+ local callt = {}
+ advtrains["te_register_on_"..name] = function(func)
+ assertt(func, "function")
+ table.insert(callt, func)
+ end
+ return callt, function(id, train, param1, param2, param3)
+ for _,f in ipairs(callt) do
+ f(id, train, param1, param2, param3)
+ end
+ end
+end
+
+local callbacks_new_path, run_callbacks_new_path = mkcallback("new_path")
+local callbacks_invahead
+callbacks_invahead, advtrains.run_callbacks_invahead = mkcallback("invalidate_ahead") -- (id, train, start_idx)
+local callbacks_update, run_callbacks_update = mkcallback("update")
+local callbacks_create, run_callbacks_create = mkcallback("create")
+local callbacks_remove, run_callbacks_remove = mkcallback("remove")
+
+-- required to call from couple.lua
+function advtrains.update_train_start_and_end(train)
+ recalc_end_index(train)
+ run_callbacks_update(train.id, train)
+end
+
+-- train_ensure_init: responsible for creating a state that we can work on, after one of the following events has happened:
+-- - the train's path got cleared
+-- - save files were loaded
+-- Additionally, this gets called outside the step cycle to initialize and/or remove a train, then occ_write_mode is set.
+function advtrains.train_ensure_init(id, train)
+ if not train then
+ atwarn("train_ensure_init: Called with id =",id,"but a nil train!")
+ atwarn(debug.traceback())
+ return nil
+ end
+
+ if not train.staticdata then
+ train.staticdata = {}
+ end
+
+ train.dirty = true
+ if train.no_step then
+ --atprint("in ensure_init: no_step set, train step ignored!")
+ return nil
+ end
+
+ assertdef(train, "velocity", 0)
+ --assertdef(train, "tarvelocity", 0)
+ assertdef(train, "acceleration", 0)
+ if train.id ~= id then
+ train.id = id
+ end
+ assertdef(train, "path_ori_cp", {})
+
+ if not train.max_speed then
+ --atprint("in ensure_init: missing properties, updating!")
+ advtrains.update_trainpart_properties(id)
+ end
+
+ --restore path
+ if not train.path then
+ --atprint("in ensure_init: Needs restoring path...")
+ if not train.last_pos then
+ atlog("Train",id,": Restoring path failed, no last_pos set! Train will be disabled. You can try to fix the issue in the save file.")
+ train.no_step = true
+ return nil
+ end
+ if not train.last_connid then
+ atwarn("Train",id,": Restoring path: no last_connid set! Will assume 1")
+ train.last_connid = 1
+ --[[
+ Why this fix was necessary:
+ Issue: Migration problems on Grand Theft Auto Minetest
+ 1. Run of this code, warning printed.
+ 2. path_create failed with result==nil (there was an unloaded node, wait_for_path set)
+ 3. in consequence, the supposed call to path_setrestore does not happen
+ 4. train.last_connid is still unset
+ 5. next step, warning is printed again
+ Result: log flood.
+ ]]
+ end
+
+ local result = advtrains.path_create(train, train.last_pos, train.last_connid or 1, train.last_frac or 0)
+
+ --atprint("in ensure_init: path_create result ",result)
+
+ if result==false then
+ atlog("Train",id,": Restoring path failed, node at",train.last_pos,"is gone! Train will be disabled. You can try to place a rail at this position and restart the server.")
+ train.no_step = true
+ return nil
+ elseif result==nil then
+ if not train.wait_for_path then
+ atlog("Train",id,": Can't initialize: Waiting for the (yet unloaded) node at",train.last_pos," to be loaded.")
+ end
+ train.wait_for_path = true
+ return false
+ end
+ -- by now, we should have a working initial path
+ train.wait_for_path = false
+
+ advtrains.update_trainpart_properties(id)
+ recalc_end_index(train)
+
+ --atdebug("Train",id,": Successfully restored path at",train.last_pos," connid",train.last_connid," frac",train.last_frac)
+
+ -- run on_new_path callbacks
+ run_callbacks_new_path(id, train)
+ end
+
+ train.dirty = false -- TODO einbauen!
+ return true
+end
+
+local function v_target_apply(v_targets, lever, vel)
+ v_targets[lever] = v_targets[lever] and math.min(v_targets[lever], vel) or vel
+end
+
+function advtrains.train_step_b(id, train, dtime)
+ if train.no_step or train.wait_for_path or not train.path then return end
+
+ -- in this code, we check variables such as path_trk_? and path_dist. We need to ensure that the path is known for the whole 'Train' zone
+ advtrains.path_get(train, atfloor(train.index + 2))
+ advtrains.path_get(train, atfloor(train.end_index - 1))
+
+ -- run pre-move hooks
+ -- TODO: if more pre-move hooks are added, make a separate callback hook
+ advtrains.lzb_look_ahead(id, train)
+
+ --[[ again, new velocity control:
+ There are two heterogenous means of control:
+ -> set a fixed acceleration and ignore speed (user)
+ -> steer towards a target speed, distance doesn't matter
+ -> needs to specify the maximum acceleration/deceleration values they are willing to accelerate/brake with
+ -> Reach a target speed after a certain distance (LZB, handled specially)
+
+ ]]--
+
+ --- 3. handle velocity influences ---
+
+ local v0 = train.velocity
+ local sit_v_cap = train.max_speed -- Maximum speed in current situation (multiple limit factors)
+ -- The desired speed change issued by the active control (user or atc)
+ local ctrl_v_tar -- desired speed which should not be crossed by braking or accelerating
+ local ctrl_accelerating = false -- whether the train should accelerate
+ local ctrl_braking = false -- whether the train should brake
+ local ctrl_lever -- the lever value to use to calculate the acceleration
+ -- the final speed change after applying LZB
+ local v_cap -- absolute maximum speed
+ local v_tar -- desired speed which should not be crossed by braking or accelerating
+ local accelerating = false-- whether the train should accelerate
+ local braking = false -- whether the train should brake
+ local lever -- the lever value to use to calculate the acceleration
+ local train_moves = (v0 > 0)
+
+ if train.recently_collided_with_env then
+ if not train_moves then
+ train.recently_collided_with_env=nil--reset status when stopped
+ end
+ --atprint("in train_step_b: applying collided_with_env")
+ sit_v_cap = 0
+ elseif train.locomotives_in_train==0 then
+ --atprint("in train_step_b: applying no_locomotives")
+ sit_v_cap = 0
+ -- interlocking speed restriction
+ elseif train.speed_restriction then
+ --atprint("in train_step_b: applying interlocking speed restriction",train.speed_restriction)
+ sit_v_cap = math.min(sit_v_cap or math.huge, train.speed_restriction)
+ end
+
+ --apply off-track handling:
+ local front_off_track = train.index>train.path_trk_f
+ local back_off_track=train.end_index<train.path_trk_b
+ train.off_track = front_off_track or back_off_track
+
+ if back_off_track and (not sit_v_cap or sit_v_cap > 1) then
+ --atprint("in train_step_b: applying back_off_track")
+ sit_v_cap = 1
+ elseif front_off_track then
+ --atprint("in train_step_b: applying front_off_track")
+ sit_v_cap = 0
+ end
+
+
+ --interpret ATC command and apply auto-lever control when not actively controlled
+ local userc = train.ctrl_user
+ if userc then
+ --atprint("in train_step_b: ctrl_user active",userc)
+ advtrains.atc.train_reset_command(train)
+
+ if userc >= VLEVER_ACCEL then
+ ctrl_accelerating = true
+ else
+ ctrl_braking = true
+ end
+ ctrl_lever = userc
+ else
+ if train.atc_command then
+ if (not train.atc_delay or train.atc_delay<=0)
+ and not train.atc_wait_finish
+ and not train.atc_wait_autocouple
+ and not train.atc_wait_signal then
+ advtrains.atc.execute_atc_command(id, train)
+ elseif train.atc_delay and train.atc_delay > 0 then
+ train.atc_delay=train.atc_delay-dtime
+ end
+ elseif train.atc_delay then
+ train.atc_delay = nil
+ end
+
+ local braketar = train.atc_brake_target
+ local emerg = false -- atc_brake_target==-1 means emergency brake (BB command)
+ if braketar == -1 then
+ braketar = 0
+ emerg = true
+ end
+ --atprint("in train_step_b: ATC: brake state braketar=",braketar,"emerg=",emerg)
+ if braketar and braketar>=v0 then
+ --atprint("in train_step_b: ATC: brake target cleared")
+ train.atc_brake_target=nil
+ braketar = nil
+ end
+ --if train.tarvelocity and train.velocity==train.tarvelocity then
+ -- train.tarvelocity = nil
+ --end
+ if train.atc_wait_finish then
+ if not train.atc_brake_target and (not train.tarvelocity or train.velocity==train.tarvelocity) then
+ train.atc_wait_finish=nil
+ end
+ end
+ -- clear atc_wait_signal immediately when the next LZB checkpoint is not a "stop"
+ -- (but make sure lzb is initialized, otherwise wait for it)
+ if train.atc_wait_signal and train.lzb then
+ local first_ckp = train.lzb.checkpoints and train.lzb.checkpoints[1]
+ -- no checkpoint exists, or it has a speed of either nil or >0
+ if not first_ckp or first_ckp.speed ~= 0 then
+ train.atc_wait_signal = nil
+ end
+ end
+
+ if train.tarvelocity and train.tarvelocity>v0 then
+ --atprint("in train_step_b: applying ATC ACCEL", train.tarvelocity)
+ ctrl_accelerating = true
+ ctrl_lever = VLEVER_ACCEL
+ elseif train.tarvelocity and train.tarvelocity<v0 then
+ ctrl_braking = true
+
+ if (braketar and braketar<v0) then
+ if emerg then
+ --atprint("in train_step_b: applying ATC EMERG", train.tarvelocity)
+ ctrl_lever = VLEVER_EMERG
+ else
+ --atprint("in train_step_b: applying ATC BRAKE", train.tarvelocity)
+ ctrl_v_tar = braketar
+ ctrl_lever = VLEVER_BRAKE
+ end
+ else
+ --atprint("in train_step_b: applying ATC ROLL", train.tarvelocity)
+ ctrl_v_tar = train.tarvelocity
+ ctrl_lever = VLEVER_ROLL
+ end
+ end
+ end
+
+ --- 2b. look at v_target, determine the effective v_target and desired acceleration ---
+ --atprint("in train_step_b: Resulting control before LZB: accelerating",ctrl_accelerating,"braking",ctrl_braking,"lever", ctrl_lever, "target", ctrl_v_tar)
+ --train.debug = dump({tv_target,tv_lever})
+
+ --atprint("in train_step_b: Current index",train.index,"end",train.end_index,"vel",v0)
+ --- 3a. calculate the acceleration required to reach the speed restriction in path_speed (LZB) ---
+ -- Iterates over the path nodes we WOULD pass if we were continuing with the current speed
+ -- and determines the MINIMUM of path_speed in this range.
+ -- Then, determines acceleration so that we can reach this 'overridden' target speed in this step (but short-circuited)
+ local lzb_next_zero_barrier -- if defined, train should not pass this point as it's a 0-LZB
+ local new_index_curr_tv -- pre-calculated new train index in lzb check
+ local lzb_v_cap -- the maximum speed that LZB dictates
+
+ local dst_curr_v = v0 * dtime
+ new_index_curr_tv = advtrains.path_get_index_by_offset(train, train.index, dst_curr_v)
+ local i = atfloor(train.index)
+ local psp
+ while true do
+ psp = train.path_speed[i]
+ if psp then
+ lzb_v_cap = lzb_v_cap and math.min(lzb_v_cap, psp) or psp
+ if psp == 0 and not lzb_next_zero_barrier then
+ --atprint("in train_step_b: Found zero barrier: ",i)
+ lzb_next_zero_barrier = i - LZB_ZERO_APPROACH_DIST
+ end
+ end
+ if i > new_index_curr_tv then
+ break
+ end
+ i = i + 1
+ end
+
+ if lzb_next_zero_barrier and train.index < lzb_next_zero_barrier then
+ lzb_v_cap = LZB_ZERO_APPROACH_SPEED
+ end
+
+ --atprint("in train_step_b: LZB calculation yields newindex=",new_index_curr_tv,"lzbtarget=",lzb_v_cap,"zero_barr=",lzb_next_zero_barrier,"")
+
+ -- LZB HUD: decrement timer and delete when 0
+ if train.hud_lzb_effect_tmr then
+ if train.hud_lzb_effect_tmr <=0 then
+ train.hud_lzb_effect_tmr = nil
+ else
+ train.hud_lzb_effect_tmr = train.hud_lzb_effect_tmr - 1
+ end
+ end
+
+ -- We now need to bring ctrl_*, sit_v_cap and lzb_v_cap together to determine the final controls.
+ local v_cap = sit_v_cap -- always defined, by default train.max_speed
+ if lzb_v_cap and lzb_v_cap < v_cap then
+ v_cap = lzb_v_cap
+ lever = VLEVER_BRAKE -- actually irrelevant, acceleration is not considered anyway unless v_tar is also set.
+ -- display LZB control override in the HUD
+ if lzb_v_cap <= v0 then
+ train.hud_lzb_effect_tmr = 1
+ -- This is to signal the HUD that LZB is active. This works as a timer to avoid HUD blinking
+ end
+ end
+
+ v_tar = ctrl_v_tar
+ -- if v_cap is smaller than the current speed, we need to brake in all cases.
+ if v_cap < v0 then
+ braking = true
+ lever = VLEVER_BRAKE
+ -- set v_tar to v_cap to not slow down any further than required.
+ -- unless control wants us to brake too, then we use control's v_tar.
+ if not ctrl_v_tar or ctrl_v_tar > v_cap then
+ v_tar = v_cap
+ end
+ else -- else, use what the ctrl says
+ braking = ctrl_braking
+ accelerating = ctrl_accelerating and not braking
+ lever = ctrl_lever
+ end
+ train.lever = lever
+
+ --atprint("in train_step_b: final control: accelerating",accelerating,"braking",braking,"lever", lever, "target", v_tar)
+
+ -- reset train acceleration when holding speed
+ if not braking and not accelerating then
+ train.acceleration = 0
+ end
+
+ --- 3b. if braking, modify the velocity BEFORE the movement
+ if braking then
+ local dv = advtrains.get_acceleration(train, lever) * dtime
+ local v1 = v0 + dv
+ if v_tar and v1 < v_tar then
+ --atprint("in train_step_b: Braking: Hit v_tar!")
+ v1 = v_tar
+ end
+ if v1 > v_cap then
+ --atprint("in train_step_b: Braking: Hit v_cap!")
+ v1 = v_cap
+ end
+ if v1 < 0 then
+ --atprint("in train_step_b: Braking: Hit 0!")
+ v1 = 0
+ end
+
+ train.acceleration = (v1 - v0) / dtime
+ train.velocity = v1
+ --atprint("in train_step_b: Braking: New velocity",v1," (yields acceleration",train.acceleration,")")
+ -- make saved new_index_curr_tv invalid because speed has changed
+ new_index_curr_tv = nil
+ end
+
+ --- 4. move train ---
+ -- if we have calculated the new end index before, don't do that again
+ if not new_index_curr_tv then
+ local dst_curr_v = train.velocity * dtime
+ new_index_curr_tv = advtrains.path_get_index_by_offset(train, train.index, dst_curr_v)
+ --atprint("in train_step_b: movement calculation (re)done, yields newindex=",new_index_curr_tv)
+ else
+ --atprint("in train_step_b: movement calculation reusing from LZB newindex=",new_index_curr_tv)
+ end
+
+ -- if the zeroappr mechanism has hit, go no further than zeroappr index
+ if lzb_next_zero_barrier and new_index_curr_tv > lzb_next_zero_barrier then
+ --atprint("in train_step_b: Zero barrier hit, clipping to newidx_tv=",new_index_curr_tv, "zb_idx=",lzb_next_zero_barrier)
+ new_index_curr_tv = lzb_next_zero_barrier
+ end
+
+ -- New same-track collision system - check for any other trains within the range we're going to move
+ -- do the checks if we either are moving or about to start moving
+ if new_index_curr_tv > train.index or accelerating then -- only if train is actually advancing
+ -- Note: duplicate code from path_project() because of subtle differences: no frac processing and scanning all occupations
+ --[[train.debug = ""
+ local atdebug = function(t, ...)
+ local text=advtrains.print_concat_table({t, ...})
+ train.debug = train.debug..text.."\n"
+ end]]
+ local base_idx = atfloor(new_index_curr_tv + 1)
+ local base_pos = advtrains.path_get(train, base_idx)
+ local base_cn = train.path_cn[base_idx]
+ --atdebug(id,"Begin Checking for on-track collisions new_idx=",new_index_curr_tv,"base_idx=",base_idx,"base_pos=",base_pos,"base_cn=",base_cn)
+ -- query occupation
+ local occ = advtrains.occ.reverse_lookup_sel(base_pos, "close_proximity")
+ -- iterate other trains
+ for otid, ob_idx in pairs(occ) do
+ if otid ~= id then
+ --atdebug(id,"Found other train",otid," with matching index ",ob_idx)
+ -- Phase 1 - determine if trains are facing and which is the relefant stpo index
+ local otrn = advtrains.trains[otid]
+
+ -- retrieve other train's cn and cp
+ local ocn = otrn.path_cn[ob_idx]
+ local ocp = otrn.path_cp[ob_idx]
+
+ local target_is_inside, ref_index, facing, same_dir
+
+ if base_cn == ocn then
+ -- same direction
+ ref_index = otrn.end_index
+ same_dir = true
+ target_is_inside = (ob_idx >= ref_index)
+ --atdebug("Same direction: ref_index",ref_index,"inside=",target_is_inside)
+ elseif base_cn == ocp then
+ -- facing trains - subtract index frac
+ ref_index = otrn.index
+ same_dir = false
+ target_is_inside = (ob_idx <= ref_index)
+ --atdebug("Facing direction: ref_index",ref_index,"inside=",target_is_inside)
+ end
+
+ -- Phase 2 - project ref_index back onto our path and check again (necessary because there might be a turnout on the way and we are driving into the flank
+ if target_is_inside then
+ local our_index = advtrains.path_project(otrn, ref_index, id, "before_end")
+ --atdebug("Backprojected our_index",our_index)
+ if our_index and our_index <= new_index_curr_tv
+ and our_index >= train.index then --FIX: If train was already past the collision point in the previous step, there is no collision! Fixes bug with split_at_index
+ -- ON_TRACK COLLISION IS HAPPENING
+ -- the actual collision is handled in train_step_c, so set appropriate signal variables
+ train.ontrack_collision_info = {
+ otid = otid,
+ same_dir = same_dir,
+ }
+ -- clip newindex
+ --atdebug("-- Collision detected!")
+ new_index_curr_tv = our_index
+ end
+ end
+ end
+ end
+ end
+
+ -- ## Movement happens here ##
+ train.index = new_index_curr_tv
+
+ recalc_end_index(train)
+ --atprint("in train_step_b: New index",train.index,"end",train.end_index,"vel",train.velocity)
+
+ --- 4a. if accelerating, modify the velocity AFTER the movement
+ if accelerating then
+ local dv = advtrains.get_acceleration(train, lever) * dtime
+ local v1 = v0 + dv
+ if v_tar and v1 > v_tar then
+ --atprint("in train_step_b: Accelerating: Hit v_tar!")
+ v1 = v_tar
+ end
+ if v1 > v_cap then
+ --atprint("in train_step_b: Accelerating: Hit v_cap!")
+ v1 = v_cap
+ end
+
+ train.acceleration = (v1 - v0) / dtime
+ train.velocity = v1
+ --atprint("in train_step_b: Accelerating: New velocity",v1," (yields acceleration",train.acceleration,")")
+ end
+end
+
+function advtrains.train_step_c(id, train, dtime)
+ if train.no_step or train.wait_for_path or not train.path then return end
+
+ -- all location/extent-critical actions have been done.
+ -- calculate the new occupation window
+ run_callbacks_update(id, train)
+
+ -- Return if something(TM) damaged the path
+ if train.no_step or train.wait_for_path or not train.path then return end
+
+ advtrains.path_clear_unused(train)
+
+ advtrains.path_setrestore(train)
+
+ -- less important stuff
+
+ train.check_trainpartload=(train.check_trainpartload or 0)-dtime
+ if train.check_trainpartload<=0 then
+ advtrains.spawn_wagons(id)
+ train.check_trainpartload=2
+ end
+
+ local train_moves=(train.velocity~=0)
+ local very_short_train = train.trainlen < 3
+
+ --- On-track collision handling - detected in train_step_b, but handled here so all other train movements have already happened.
+ if train.ontrack_collision_info then
+ train.velocity = 0
+ train.acceleration = 0
+ --advtrains.atc.train_reset_command(train) will occur in couple_initiate_with if required
+
+ local otrn = advtrains.trains[train.ontrack_collision_info.otid]
+
+ if otrn.velocity == 0 then -- other train must be standing, else don't initiate coupling
+ advtrains.couple_initiate_with(train, otrn, not train.ontrack_collision_info.same_dir)
+ else
+ -- other collision - stop any ATC control
+ advtrains.atc.train_reset_command(train)
+ end
+
+ train.ontrack_collision_info = nil
+ train.couples_up_to_date = true
+ end
+
+ -- handle couples if on_track collision handling did not fire
+ if train_moves then
+ train.couples_up_to_date = nil
+ elseif not train.couples_up_to_date then
+ if not very_short_train then -- old coupling system is buggy for short trains
+ advtrains.train_check_couples(train) -- no guarantee for train order here
+ end
+ train.couples_up_to_date = true
+ end
+
+ --- 8. check for collisions with other trains and damage players ---
+ if train_moves then
+ -- Note: this code handles collisions with trains that are not on the same path as the current train
+ -- The same-track collisions and coupling handling is found in couple.lua and handled from train_step_b() and code 2 blocks above.
+ local collided = false
+ local coll_grace=2
+ local collindex = advtrains.path_get_index_by_offset(train, train.index, -coll_grace)
+ local collpos = advtrains.path_get(train, atround(collindex))
+ if collpos then
+ local rcollpos=advtrains.round_vector_floor_y(collpos)
+ local is_loaded_area = advtrains.is_node_loaded(rcollpos)
+ for x=-train.extent_h,train.extent_h do
+ for z=-train.extent_h,train.extent_h do
+ local testpos=vector.add(rcollpos, {x=x, y=0, z=z})
+ --- 8a Check collision ---
+ if not collided then
+ if not very_short_train then -- position collision system is buggy for short trains
+ local col_tr = advtrains.occ.check_collision(testpos, id)
+ if col_tr then
+ train.velocity = 0
+ train.acceleration = 0
+ advtrains.atc.train_reset_command(train)
+ collided = true
+ end
+ end
+
+ --- 8b damage players ---
+ if is_loaded_area and train.velocity > 3 and (setting_overrun_mode=="drop" or setting_overrun_mode=="normal") then
+ local testpts = minetest.pos_to_string(testpos)
+ local player=advtrains.playersbypts[testpts]
+ if player and player:get_hp()>0 and advtrains.is_damage_enabled(player:get_player_name()) then
+ --atdebug("damage found",player:get_player_name())
+ if setting_overrun_mode=="drop" then
+ --instantly kill player
+ --drop inventory contents first, to not to spawn bones
+ local player_inv=player:get_inventory()
+ for i=1,player_inv:get_size("main") do
+ minetest.add_item(testpos, player_inv:get_stack("main", i))
+ end
+ for i=1,player_inv:get_size("craft") do
+ minetest.add_item(testpos, player_inv:get_stack("craft", i))
+ end
+ -- empty lists main and craft
+ player_inv:set_list("main", {})
+ player_inv:set_list("craft", {})
+ end
+ player:set_hp(0)
+ end
+ end
+ end
+ end
+ end
+ --- 8c damage other objects ---
+ if is_loaded_area then
+ local objs = minetest.get_objects_inside_radius(rcollpos, 2)
+ for _,obj in ipairs(objs) do
+ if not obj:is_player() then
+ local armor = obj:get_armor_groups()
+ local luaentity = obj:get_luaentity()
+ if armor.fleshy and armor.fleshy > 0 and luaentity and luaentity.name ~= "signs_lib:text" then
+ obj:punch(obj, 1, { full_punch_interval = 1.0, damage_groups = {fleshy = 1000}, }, nil)
+ end
+ end
+ end
+ end
+ end
+ end
+end
+
+-- Default occupation callbacks for node callbacks
+-- (remember, train.end_index is set separately because callbacks are
+-- asserted to rely on this)
+
+local function mknodecallback(name)
+ local callt = {}
+ advtrains["tnc_register_on_"..name] = function(func, prio)
+ assertt(func, "function")
+ if prio then
+ table.insert(callt, 1, func)
+ else
+ table.insert(callt, func)
+ end
+ end
+ return callt, function(pos, id, train, index, paramx1, paramx2, paramx3)
+ for _,f in ipairs(callt) do
+ f(pos, id, train, index, paramx1, paramx2, paramx3)
+ end
+ end
+end
+
+-- enter/leave-node callbacks
+-- signature is advtrains.tnc_register_on_enter/leave(function(pos, id, train, index) ... end)
+local callbacks_enter_node, run_callbacks_enter_node = mknodecallback("enter")
+local callbacks_leave_node, run_callbacks_leave_node = mknodecallback("leave")
+
+-- Node callback for approaching
+-- Might be called multiple times, whenever path is recalculated. Also called for the first node the train is standing on, then has_entered is true.
+-- signature is function(pos, id, train, index, has_entered, lzbdata)
+-- has_entered: Provided for legacy reasons. Always false. (used to signify that the enter callback has already been called, at a time where enter was still called at .5 index)
+-- lzbdata: arbitrary data (shared between all callbacks), deleted when LZB is restarted.
+-- These callbacks are called in order of distance as train progresses along tracks, so lzbdata can be used to
+-- keep track of a train's state once it passes this point
+local callbacks_approach_node, run_callbacks_approach_node = mknodecallback("approach")
+
+
+local function tnc_call_enter_callback(pos, train_id, train, index)
+ --atdebug("tnc enter",pos,train_id)
+ local node = advtrains.ndb.get_node(pos) --this spares the check if node is nil, it has a name in any case
+ local mregnode=minetest.registered_nodes[node.name]
+ if mregnode and mregnode.advtrains and mregnode.advtrains.on_train_enter then
+ mregnode.advtrains.on_train_enter(pos, train_id, train, index)
+ end
+
+ -- call other registered callbacks
+ run_callbacks_enter_node(pos, train_id, train, index)
+
+ -- check for split points
+ if mregnode and mregnode.at_conn_map then
+ -- If this node has >2 conns (and a connmap), remember the connection where we came from to handle split points
+ --atdebug("Train",train_id,"at",pos,"saving turnout origin CP",train.path_cp[index],"for path item",index)
+ train.path_ori_cp[advtrains.encode_pos(pos)] = train.path_cp[index]
+ end
+end
+local function tnc_call_leave_callback(pos, train_id, train, index)
+ --atdebug("tnc leave",pos,train_id)
+ local node = advtrains.ndb.get_node(pos) --this spares the check if node is nil, it has a name in any case
+ local mregnode=minetest.registered_nodes[node.name]
+ if mregnode and mregnode.advtrains and mregnode.advtrains.on_train_leave then
+ mregnode.advtrains.on_train_leave(pos, train_id, train, index)
+ end
+
+ -- call other registered callbacks
+ run_callbacks_leave_node(pos, train_id, train, index)
+
+ -- split points do not matter anymore. clear them
+ if mregnode and mregnode.at_conn_map then
+ -- If this node has >2 conns (and a connmap), remember the connection where we came from to handle split points
+ --atdebug("Train",train_id,"at",pos,"removing turnout origin CP for path item",index," because train has left it")
+ train.path_ori_cp[advtrains.encode_pos(pos)] = nil
+ end
+end
+
+function advtrains.tnc_call_approach_callback(pos, train_id, train, index, lzbdata)
+ --atdebug("tnc approach",pos,train_id, lzbdata)
+ local has_entered = false -- 2024-11-25: has_entered is now always false, because enter point = LZB hit point!
+
+ local node = advtrains.ndb.get_node(pos) --this spares the check if node is nil, it has a name in any case
+ local mregnode=minetest.registered_nodes[node.name]
+ if mregnode and mregnode.advtrains and mregnode.advtrains.on_train_approach then
+ mregnode.advtrains.on_train_approach(pos, train_id, train, index, has_entered, lzbdata)
+ end
+
+ -- call other registered callbacks
+ run_callbacks_approach_node(pos, train_id, train, index, has_entered, lzbdata)
+end
+
+-- === te callback definition for tnc node callbacks ===
+-- Change 2024-11-25: Enter node happens when index surpasses whole number (i.e. at center of rail)
+-- Instead of atround (prev behavior) nouw use floor and ceil (note this also fixes issues where index was exactly on .0)
+local atceil = math.ceil
+
+advtrains.te_register_on_new_path(function(id, train)
+ train.tnc = {
+ old_index = atfloor(train.index),
+ old_end_index = atceil(train.end_index),
+ }
+ --atdebug(id,"tnc init",train.index,train.end_index)
+end)
+
+advtrains.te_register_on_update(function(id, train)
+ local new_index = atfloor(train.index)
+ local new_end_index = atceil(train.end_index)
+ local old_index = train.tnc.old_index
+ local old_end_index = train.tnc.old_end_index
+ while old_index < new_index do
+ old_index = old_index + 1
+ local pos = advtrains.round_vector_floor_y(advtrains.path_get(train,old_index))
+ tnc_call_enter_callback(pos, id, train, old_index)
+ end
+ while old_end_index < new_end_index do
+ local pos = advtrains.round_vector_floor_y(advtrains.path_get(train,old_end_index))
+ tnc_call_leave_callback(pos, id, train, old_end_index)
+ old_end_index = old_end_index + 1
+ end
+ train.tnc.old_index = new_index
+ train.tnc.old_end_index = new_end_index
+end)
+
+advtrains.te_register_on_create(function(id, train)
+ local index = atfloor(train.index)
+ local end_index = atceil(train.end_index)
+ while end_index <= index do
+ local pos = advtrains.round_vector_floor_y(advtrains.path_get(train,end_index))
+ tnc_call_enter_callback(pos, id, train, end_index)
+ end_index = end_index + 1
+ end
+ --atdebug(id,"tnc create",train.index,train.end_index)
+end)
+
+advtrains.te_register_on_remove(function(id, train)
+ local index = atfloor(train.index)
+ local end_index = atceil(train.end_index)
+ while end_index <= index do
+ local pos = advtrains.round_vector_floor_y(advtrains.path_get(train,end_index))
+ tnc_call_leave_callback(pos, id, train, end_index)
+ end_index = end_index + 1
+ end
+ --atdebug(id,"tnc remove",train.index,train.end_index)
+end)
+
+--returns new id
+function advtrains.create_new_train_at(pos, connid, ioff, trainparts)
+ local new_id=advtrains.random_id()
+ while advtrains.trains[new_id] do new_id=advtrains.random_id() end--ensure uniqueness
+
+ local t={}
+ t.id = new_id
+
+ t.last_pos=pos
+ t.last_connid=connid
+ t.last_frac=ioff
+
+ --t.tarvelocity=0
+ t.velocity=0
+ t.trainparts=trainparts
+
+ advtrains.trains[new_id] = t
+ --atdebug("Created new train:",t)
+
+ if not advtrains.train_ensure_init(new_id, advtrains.trains[new_id]) then
+ atwarn("create_new_train_at",pos,connid,"failed! This might lead to temporary bugs.")
+ return
+ end
+
+ run_callbacks_create(new_id, advtrains.trains[new_id])
+
+ return new_id
+end
+
+function advtrains.remove_train(id)
+ local train = advtrains.trains[id]
+
+ if not advtrains.train_ensure_init(id, train) then
+ atwarn("remove_train",id,"failed! This might lead to temporary bugs.")
+ return
+ end
+
+ run_callbacks_remove(id, train)
+
+ advtrains.path_invalidate(train, true)
+ advtrains.couple_invalidate(train)
+
+ local tp = train.trainparts
+ --atdebug("Removing train",id,"leftover trainparts:",tp)
+
+ advtrains.trains[id] = nil
+
+ return tp
+
+end
+
+
+function advtrains.add_wagon_to_train(wagon_id, train_id, index)
+ local train=advtrains.trains[train_id]
+
+ if not advtrains.train_ensure_init(train_id, train) then
+ atwarn("Train",train_id,"is not initialized! Operation aborted!")
+ return
+ end
+
+ if index then
+ table.insert(train.trainparts, index, wagon_id)
+ else
+ table.insert(train.trainparts, wagon_id)
+ end
+
+ advtrains.update_trainpart_properties(train_id)
+ recalc_end_index(train)
+ run_callbacks_update(train_id, train)
+end
+
+-- Note: safe_decouple_wagon() has been moved to wagons.lua
+
+-- this function sets wagon's pos_in_train(parts) properties and train's max_speed (and more)
+function advtrains.update_trainpart_properties(train_id, invert_flipstate)
+ local train=advtrains.trains[train_id]
+ --FIX: deep-copy the table!!!
+ train.max_speed=20
+ train.extent_h = 0;
+ train.door_operation_time = 1
+
+ local rel_pos=0
+ local count_l=0
+ local shift_dcpl_lock=false
+ for i, w_id in ipairs(train.trainparts) do
+
+ local data = advtrains.wagons[w_id]
+
+ -- 1st: update wagon data (pos_in_train a.s.o)
+ if data then
+ local wagon = advtrains.wagon_prototypes[data.type or data.entity_name]
+ if not wagon then
+ local ent = advtrains.wagon_objects[w_id]
+ local pdesc
+ if ent and ent:get_pos() then
+ pdesc = "at " .. minetest.pos_to_string(ent:get_pos())
+ elseif train.last_pos then
+ pdesc = "near " .. minetest.pos_to_string(train.last_pos)
+ else
+ pdesc = "at an unknown location"
+ end
+ atwarn(string.format("Wagon %q %s could not be found. Please check that all required modules are loaded!", data.type, pdesc))
+ wagon = advtrains.wagon_prototypes["advtrains:wagon_placeholder"]
+
+ end
+ rel_pos=rel_pos+wagon.wagon_span
+ data.train_id=train_id
+ data.pos_in_train=rel_pos
+ data.pos_in_trainparts=i
+ if wagon.is_locomotive then
+ count_l=count_l+1
+ end
+ if invert_flipstate then
+ data.wagon_flipped = not data.wagon_flipped
+ shift_dcpl_lock, data.dcpl_lock = data.dcpl_lock, shift_dcpl_lock
+ end
+ rel_pos=rel_pos+wagon.wagon_span
+
+ train.max_speed=math.min(train.max_speed, wagon.max_speed)
+ train.extent_h = math.max(train.extent_h, wagon.extent_h or 1);
+ train.door_operation_time = math.max(train.door_operation_time, wagon.door_operation_time or 2)
+ end
+ end
+ train.trainlen = rel_pos
+ train.locomotives_in_train = count_l
+end
+
+
+local ablkrng = advtrains.wagon_load_range
+-- This function checks whether entities need to be spawned for certain wagons, and spawns them.
+-- Called from train_step_*(), not required to check init.
+function advtrains.spawn_wagons(train_id)
+ local train = advtrains.trains[train_id]
+
+ for i = 1, #train.trainparts do
+ local w_id = train.trainparts[i]
+ local data = advtrains.wagons[w_id]
+ if data then
+ if data.train_id ~= train_id then
+ atwarn("Train",train_id,"Wagon #",i,": Saved train ID",data.train_id,"did not match!")
+ data.train_id = train_id
+ end
+ if not advtrains.wagon_objects[w_id] or not advtrains.wagon_objects[w_id]:get_yaw() then
+ -- eventually need to spawn new object. check if position is loaded.
+ local index = advtrains.path_get_index_by_offset(train, train.index, -data.pos_in_train)
+ local pos = advtrains.path_get(train, atfloor(index))
+
+ if advtrains.position_in_range(pos, ablkrng) then
+ --atdebug("wagon",w_id,"spawning")
+ local wt = advtrains.get_wagon_prototype(data)
+ local wobj = minetest.add_entity(pos, wt)
+ if not wobj then
+ atwarn("Failed to spawn wagon", w_id, "of type", wt)
+ else
+ local wagon = wobj:get_luaentity()
+ if not wagon then
+ atwarn("Wagon", w_id, "of type", wt, "spawned with nil luaentity")
+ else
+ wagon:set_id(w_id)
+ end
+ end
+ end
+ end
+ else
+ atwarn("Train",train_id,"Wagon #",1,": A wagon with id",w_id,"does not exist! Wagon will be removed from train.")
+ table.remove(train.trainparts, i)
+ i = i - 1
+ end
+ end
+end
+
+function advtrains.split_train_at_index(train, index)
+ -- this function splits a train at index, creating a new train from the back part of the train.
+ --atdebug("split_train_at_index invoked on",train.id,"index",index)
+
+ local train_id=train.id
+ if index > #train.trainparts then
+ -- index specified too long
+ return
+ end
+ local w_id = train.trainparts[index]
+ local data = advtrains.wagons[w_id]
+ local _, wagon = advtrains.get_wagon_prototype(data)
+ if not advtrains.train_ensure_init(train_id, train) then
+ atwarn("Train",train_id,"is not initialized! Operation aborted!")
+ return
+ end
+
+ -- make sure that the train is fully on track before splitting. May cause problems otherwise
+ if train.index > train.path_trk_f or train.end_index < train.path_trk_b then
+ atwarn("Train",train_id,": cannot split train because it is off track!")
+ return
+ end
+
+ local p_index=advtrains.path_get_index_by_offset(train, train.index, - data.pos_in_train + wagon.wagon_span)
+ local pos, connid, frac = advtrains.path_getrestore(train, p_index)
+ --atdebug("new train position p_index",p_index,"pos",pos,"connid",connid,"frac",frac)
+ local tp = {}
+ for k,v in ipairs(train.trainparts) do
+ if k >= index then
+ table.insert(tp, v)
+ train.trainparts[k] = nil
+ end
+ end
+ advtrains.update_trainpart_properties(train_id)
+ recalc_end_index(train)
+ --atdebug("old train index",train.index,"end_index",train.end_index)
+ run_callbacks_update(train_id, train)
+
+ --create subtrain
+ local newtrain_id=advtrains.create_new_train_at(pos, connid, frac, tp)
+ local newtrain=advtrains.trains[newtrain_id]
+ --atdebug("new train created with ID",newtrain_id,"index",newtrain.index,"end_index",newtrain.end_index)
+
+ newtrain.velocity=train.velocity
+ -- copy various properties from the old to the new train
+ newtrain.door_open = train.door_open
+ newtrain.text_outside = train.text_outside
+ newtrain.text_inside = train.text_inside
+ newtrain.line = train.line
+ newtrain.routingcode = train.routingcode
+ newtrain.speed_restriction = train.speed_restriction
+ newtrain.speed_restrictions_t = table.copy(train.speed_restrictions_t or {main=train.speed_restriction})
+ newtrain.is_shunt = train.is_shunt
+ newtrain.points_split = advtrains.merge_tables(train.points_split)
+ newtrain.autocouple = train.autocouple
+
+ advtrains.te_run_callbacks_on_decouple(train, newtrain, index)
+
+ return newtrain_id -- return new train ID, so new train can be manipulated
+
+end
+
+function advtrains.invert_train(train_id)
+ local train=advtrains.trains[train_id]
+
+ if not advtrains.train_ensure_init(train_id, train) then
+ atwarn("Train",train_id,"is not initialized! Operation aborted!")
+ return
+ end
+
+ -- Before flipping the train, we must check if there are any points on the path
+ -- which will become split on rotating, and store their cn (which will become the cp)
+ local ori_cp_after_flip = {}
+ for index = atround(train.end_index),atround(train.index) do
+ local pos = advtrains.path_get(train, index)
+ local ok, conns, railheight, connmap = advtrains.get_rail_info_at(pos)
+ if ok and connmap then
+ --atdebug("Reversing Train",train.id," ori_cp Checks: at",pos,"saving turnout origin CP",train.path_cn[index],"for path item",index)
+ ori_cp_after_flip[advtrains.encode_pos(pos)] = train.path_cn[index]
+ end
+ end
+
+ -- Actual rotation happens here! This sets the path restore position to the end of the train, inverting the connid.
+ advtrains.path_setrestore(train, true)
+
+ -- clear the origin cp list because it is now invalid, and replace it by what we built prior.
+ train.path_ori_cp = ori_cp_after_flip
+
+ -- rotate some other stuff
+ if train.door_open then
+ train.door_open = - train.door_open
+ end
+ if train.atc_command then
+ train.atc_arrow = not train.atc_arrow
+ end
+
+ advtrains.path_invalidate(train, true)
+ advtrains.couple_invalidate(train)
+
+ local old_trainparts=train.trainparts
+ train.trainparts={}
+ for k,v in ipairs(old_trainparts) do
+ table.insert(train.trainparts, 1, v)--notice insertion at first place
+ end
+ advtrains.update_trainpart_properties(train_id, true)
+
+ -- recalculate path
+
+ -- If interlocking present, check whether this train is in a section and then set as shunt move after reversion
+ if advtrains.interlocking and train.il_sections and #train.il_sections > 0 then
+ train.is_shunt = true
+ advtrains.speed.set_restriction(train, "main", advtrains.SHUNT_SPEED_MAX)
+ else
+ train.is_shunt = false
+ advtrains.speed.set_restriction(train, "main", -1)
+ end
+end
+
+-- returns: train id, index of one of the trains that stand at this position.
+function advtrains.get_train_at_pos(pos)
+ local t = advtrains.occ.get_trains_at(pos)
+ for tid,idx in pairs(t) do
+ return tid, idx
+ end
+end
+
+
+-- ehm... I never adapted this function to the new path system ?!
+function advtrains.invalidate_all_paths(pos)
+ local tab
+ if pos then
+ -- if position given, check occupation system
+ tab = advtrains.occ.reverse_lookup_quick(pos)
+ else
+ tab = advtrains.trains
+ end
+
+ for id, _ in pairs(tab) do
+ advtrains.invalidate_path(id)
+ end
+end
+
+-- Calls invalidate_path_ahead on all trains occupying (having paths over) this node
+-- Can be called during train step.
+function advtrains.invalidate_all_paths_ahead(pos)
+ local tab = advtrains.occ.reverse_lookup_sel(pos, "first_ahead")
+
+ for id,index in pairs(tab) do
+ local train = advtrains.trains[id]
+ advtrains.path_invalidate_ahead(train, index, true)
+ end
+end
+
+function advtrains.invalidate_path(id)
+ --atdebug("Path invalidate:",id)
+ local v=advtrains.trains[id]
+ if not v then return end
+ advtrains.path_invalidate(v)
+ advtrains.couple_invalidate(v)
+ v.dirty = true
+end
+
+--not blocking trains group
+
+if minetest.settings:get_bool("advtrains_forgiving_collision") then
+ function advtrains.train_collides(node)
+ if node and minetest.registered_nodes[node.name] then
+ local ndef = minetest.registered_nodes[node.name]
+ -- if the node is drawtype normal (that is a full cube) then it does collide
+ if ndef.drawtype == "normal" then
+ -- except if it is not_blocking_trains
+ if ndef.groups.not_blocking_trains and ndef.groups.not_blocking_trains ~= 0 then
+ return false
+ end
+ return true
+ end
+ end
+ return false
+ end
+else
+ function advtrains.train_collides(node)
+ if node and minetest.registered_nodes[node.name] and minetest.registered_nodes[node.name].walkable then
+ if not minetest.registered_nodes[node.name].groups.not_blocking_trains then
+ return true
+ end
+ end
+ return false
+ end
+
+ local nonblocknodes={
+ "default:fence_wood",
+ "default:fence_acacia_wood",
+ "default:fence_aspen_wood",
+ "default:fence_pine_wood",
+ "default:fence_junglewood",
+ "default:torch",
+ "bones:bones",
+
+ "default:sign_wall",
+ "signs:sign_wall",
+ "signs:sign_wall_blue",
+ "signs:sign_wall_brown",
+ "signs:sign_wall_orange",
+ "signs:sign_wall_green",
+ "signs:sign_yard",
+ "signs:sign_wall_white_black",
+ "signs:sign_wall_red",
+ "signs:sign_wall_white_red",
+ "signs:sign_wall_yellow",
+ "signs:sign_post",
+ "signs:sign_hanging",
+
+ }
+ minetest.after(0, function()
+ for _,name in ipairs(nonblocknodes) do
+ if minetest.registered_nodes[name] then
+ minetest.registered_nodes[name].groups.not_blocking_trains=1
+ end
+ end
+ end)
+end
diff --git a/advtrains/wagonprop_tool.lua b/advtrains/wagonprop_tool.lua
new file mode 100644
index 0000000..95feae9
--- /dev/null
+++ b/advtrains/wagonprop_tool.lua
@@ -0,0 +1,47 @@
+
+-- Get current translator
+local S = advtrains.translate
+
+minetest.register_craftitem("advtrains:wagon_prop_tool",{ --craftitem because it does nothing on its own
+ description = S("Wagon Properties Tool") .. "\n" .. S("Punch a wagon to view and edit the Wagon Properties"),
+ short_description = S("Wagon Properties Tool"),
+ groups = {},
+ inventory_image = "advtrains_wagon_prop_tool.png",
+ wield_image = "advtrains_wagon_prop_tool.png",
+ stack_max = 1,
+ on_use = function(itemstack, user, pointed_thing)
+ local pname = user:get_player_name()
+ if not pname or pname == "" then
+ return
+ end
+
+ --sanity checks in case of clicking the wrong entity/node/nothing
+ if pointed_thing.type ~= "object" then return end --not an entity
+ local object = pointed_thing.ref:get_luaentity()
+ if not object.id then return end --entity doesn't have an id field
+
+ local wagon = advtrains.wagons[object.id] --check if wagon exists in advtrains
+ if not wagon then --not a wagon
+ return
+ end --end sanity checks
+
+ --whitelist protection check
+ if not advtrains.check_driving_couple_protection(pname,wagon.owner,wagon.whitelist) then
+ minetest.chat_send_player(pname, S("Insufficient privileges to use this!"))
+ return
+ end
+ object:show_wagon_properties(pname)
+ return itemstack
+ end,
+})
+
+if minetest.get_modpath("default") then --register recipe
+ minetest.register_craft({
+ output = "advtrains:wagon_prop_tool",
+ recipe = {
+ {"advtrains:dtrack_placer","dye:black","default:paper"},
+ {"screwdriver:screwdriver","default:paper","default:paper"},
+ {"","","group:wood"},
+ }
+ })
+end
diff --git a/advtrains/wagons.lua b/advtrains/wagons.lua
new file mode 100644
index 0000000..5ff7946
--- /dev/null
+++ b/advtrains/wagons.lua
@@ -0,0 +1,1607 @@
+-- wagon.lua
+-- Holds all logic related to wagons
+-- From now on, wagons are, just like trains, just entries in a table
+-- All data that is static is stored in the entity prototype (self).
+-- A copy of the entity prototype is always available inside wagon_prototypes
+-- All dynamic data is stored in the (new) wagons table
+-- An entity is ONLY spawned by update_trainpart_properties when it finds it useful.
+-- Only data that are only important to the entity itself are stored in the luaentity
+
+-- Get current translator
+local S = advtrains.translate
+
+-- TP delay when getting off wagon
+local GETOFF_TP_DELAY = 0.5
+
+local IGNORE_WORLD = advtrains.IGNORE_WORLD
+
+advtrains.wagons = {}
+advtrains.wagon_alias = {}
+advtrains.wagon_prototypes = setmetatable({}, {
+ __index = function(t, k)
+ local _, proto = advtrains.resolve_wagon_alias(k)
+ return proto
+ end
+})
+advtrains.wagon_objects = {}
+
+local unload_wgn_range = advtrains.wagon_load_range + 32
+function advtrains.wagon_outside_range(pos) -- returns true if the object is outside of unload_wgn_range of any player
+ return not advtrains.position_in_range(pos, unload_wgn_range)
+end
+
+local setting_show_ids = minetest.settings:get_bool("advtrains_show_ids")
+
+--
+function advtrains.create_wagon(wtype, owner)
+ local new_id=advtrains.random_id()
+ while advtrains.wagons[new_id] do new_id=advtrains.random_id() end
+ local wgn = {}
+ wgn.type = wtype
+ wgn.seatp = {}
+ wgn.owner = owner
+ wgn.id = new_id
+ ---wgn.train_id = train_id --- will get this via update_trainpart_properties
+ wgn.fc = {}
+ wgn.fcind = 1
+ advtrains.wagons[new_id] = wgn
+ --atdebug("Created new wagon:",wgn)
+ return new_id
+end
+
+local function make_inv_name(uid)
+ return "detached:advtrains_wgn_"..uid
+end
+
+
+local wagon={
+ collisionbox = {-0.5,-0.5,-0.5, 0.5,0.5,0.5},
+ --physical = true,
+ visual = "mesh",
+ mesh = "wagon.b3d",
+ visual_size = {x=1, y=1},
+ textures = {"black.png"},
+ is_wagon=true,
+ wagon_span=1,--how many index units of space does this wagon consume
+ wagon_width=3, -- Wagon width in meters
+ has_inventory=false,
+ static_save=false,
+}
+
+
+function wagon:train()
+ local data = advtrains.wagons[self.id]
+ return advtrains.trains[data.train_id]
+end
+
+
+function wagon:on_activate(sd_uid, dtime_s)
+ if sd_uid~="" then
+ --destroy when loaded from static block.
+ self.object:remove()
+ return
+ end
+ self.object:set_armor_groups({immortal=1})
+end
+
+local function invcallback(id, pname, rtallow, rtfail)
+ local data = advtrains.wagons[id]
+ if data and advtrains.check_driving_couple_protection(pname, data.owner, data.whitelist) then
+ return rtallow
+ end
+ return rtfail
+end
+
+function wagon:set_id(wid)
+ self.id = wid
+ self.initialized = true
+
+ local data = advtrains.wagons[self.id]
+ advtrains.wagon_objects[self.id] = self.object
+
+ --atdebug("Created wagon entity:",self.name," w_id",wid," t_id",data.train_id)
+
+ if self.has_inventory then
+ --to be used later
+ local inv=minetest.get_inventory({type="detached", name="advtrains_wgn_"..self.id})
+ -- create inventory, if not yet created
+ if not inv then
+ inv=minetest.create_detached_inventory("advtrains_wgn_"..self.id, {
+ allow_move = function(inv, from_list, from_index, to_list, to_index, count, player)
+ return invcallback(wid, player:get_player_name(), count, 0)
+ end,
+ allow_put = function(inv, listname, index, stack, player)
+ return invcallback(wid, player:get_player_name(), stack:get_count(), 0)
+ end,
+ allow_take = function(inv, listname, index, stack, player)
+ return invcallback(wid, player:get_player_name(), stack:get_count(), 0)
+ end
+ })
+ if data.ser_inv then
+ advtrains.deserialize_inventory(data.ser_inv, inv)
+ end
+ if self.inventory_list_sizes then
+ for lst, siz in pairs(self.inventory_list_sizes) do
+ inv:set_size(lst, siz)
+ end
+ end
+ end
+ end
+ self.door_anim_timer=0
+ self.door_state=0
+
+ minetest.after(0.2, function() self:reattach_all() end)
+
+
+
+ if self.set_textures then
+ self:set_textures(data)
+ end
+
+ if self.custom_on_activate then
+ self:custom_on_activate()
+ end
+end
+
+function wagon:get_staticdata()
+ return "STATIC"
+end
+
+function wagon:ensure_init()
+ -- Note: A wagon entity won't exist when there's no train, because the train is
+ -- the thing that actually creates the entity
+ -- Train not being set just means that this will happen as soon as the train calls update_trainpart_properties.
+ if self.initialized and self.id then
+ local data = advtrains.wagons[self.id]
+ if data and data.train_id and self:train() then
+ if self.noninitticks then self.noninitticks=nil end
+ return true
+ end
+ end
+ if not self.noninitticks then
+ atwarn("Wagon",self.id,"Uninitialized init=",self.initialized)
+ self.noninitticks=0
+ end
+ self.noninitticks=self.noninitticks+1
+ if self.noninitticks>20 then
+ atwarn("Wagon",self.id,S("Uninitialized, removing"))
+ self:destroy()
+ else
+ self.object:set_velocity({x=0,y=0,z=0})
+ end
+ return false
+end
+
+function wagon:train()
+ local data = advtrains.wagons[self.id]
+ return advtrains.trains[data.train_id]
+end
+
+-- Remove the wagon
+function wagon:on_punch(puncher, time_from_last_punch, tool_capabilities, direction)
+ if not self:ensure_init() then return end
+
+ local data = advtrains.wagons[self.id]
+
+ if not puncher or not puncher:is_player() then
+ return
+ end
+ if data.owner and puncher:get_player_name()~=data.owner and (not minetest.check_player_privs(puncher, {train_admin = true })) then
+ minetest.chat_send_player(puncher:get_player_name(), S("This wagon is owned by @1, you can't destroy it.", data.owner));
+ return
+ end
+
+ if self.custom_may_destroy then
+ if not self.custom_may_destroy(self, puncher, time_from_last_punch, tool_capabilities, direction) then
+ return
+ end
+ end
+ local itemstack = puncher:get_wielded_item()
+ -- WARNING: This part of the API is guaranteed to change! DO NOT USE!
+ if self.set_livery and itemstack:get_name() == "bike:painter" then
+ self:set_livery(puncher, itemstack, data)
+ return
+ end
+ -- check whether wagon has an inventory. Is is empty?
+ if self.has_inventory then
+ local inv=minetest.get_inventory({type="detached", name="advtrains_wgn_"..self.id})
+ if not inv then -- inventory is not initialized when wagon was never loaded - should never happen
+ atwarn(S("Destroying wagon with inventory, but inventory is not found? Shouldn't happen!"))
+ return
+ end
+ for listname, _ in pairs(inv:get_lists()) do
+ if not inv:is_empty(listname) then
+ minetest.chat_send_player(puncher:get_player_name(), S("The wagon's inventory is not empty."));
+ return
+ end
+ end
+ end
+
+ if #(self:train().trainparts)>1 then
+ minetest.chat_send_player(puncher:get_player_name(), S("Wagon needs to be decoupled from other wagons in order to destroy it."));
+ return
+ end
+
+ local pc=puncher:get_player_control()
+ if not pc.sneak then
+ minetest.chat_send_player(puncher:get_player_name(), S("Warning: If you destroy this wagon, you only get some steel back! If you are sure, hold Sneak and left-click the wagon."))
+ return
+ end
+
+
+ if not self:destroy() then return end
+
+ local inv = puncher:get_inventory()
+ for _,item in ipairs(self.drops or {self.name}) do
+ inv:add_item("main", item)
+ end
+end
+function wagon:destroy()
+ --some rules:
+ -- you get only some items back
+ -- single left-click shows warning
+ -- shift leftclick destroys
+ -- not when a driver is inside
+ if self.id then
+ local data = advtrains.wagons[self.id]
+ if not data then
+ atwarn(" wagon:destroy(): data is not set!")
+ return
+ end
+
+ if self.custom_on_destroy then
+ self.custom_on_destroy(self)
+ end
+
+ for seat,_ in pairs(data.seatp) do
+ self:get_off(seat)
+ end
+
+ if data.train_id and self:train() then
+ advtrains.remove_train(data.train_id)
+ advtrains.wagons[self.id]=nil
+ if self.discouple then self.discouple.object:remove() end--will have no effect on unloaded objects
+ end
+ end
+ --atdebug("[wagon ", self.id, "]: destroying")
+
+ self.object:remove()
+ return true
+end
+
+function wagon:is_driver_stand(seat)
+ if self.seat_groups then
+ return (seat.driving_ctrl_access or self.seat_groups[seat.group].driving_ctrl_access)
+ else
+ return seat.driving_ctrl_access
+ end
+
+end
+
+function wagon:on_step(dtime)
+ if not self:ensure_init() then return end
+
+ if advtrains.is_no_action() then
+ self.object:remove()
+ return
+ end
+
+ local t=os.clock()
+ local pos = self.object:get_pos()
+ local data = advtrains.wagons[self.id]
+
+ if not pos then
+ --atdebug("["..self.id.."][fatal] missing position (object:get_pos() returned nil)")
+ return
+ end
+
+ if not data.seatp then
+ data.seatp={}
+ end
+ if not self.seatpc then
+ self.seatpc={}
+ end
+
+ local train=self:train()
+
+ local is_in_loaded_area = advtrains.is_node_loaded(pos)
+
+ --custom on_step function
+ if self.custom_on_step then
+ self:custom_on_step(dtime, data, train)
+ end
+
+ --driver control
+ for seatno, seat in ipairs(self.seats) do
+ local pname=data.seatp[seatno]
+ local driver=pname and minetest.get_player_by_name(pname)
+ local has_driverstand = pname and advtrains.check_driving_couple_protection(pname, data.owner, data.whitelist)
+ has_driverstand = has_driverstand and self:is_driver_stand(seat)
+ if has_driverstand and driver then
+ advtrains.update_driver_hud(driver:get_player_name(), self:train(), data.wagon_flipped)
+ elseif driver then
+ --only show the inside text
+ local inside=self:train().text_inside or ""
+ advtrains.set_trainhud(driver:get_player_name(), inside)
+ end
+ if driver and driver:get_player_control_bits()~=self.seatpc[seatno] then
+ local pc=driver:get_player_control()
+ self.seatpc[seatno]=driver:get_player_control_bits()
+
+ if has_driverstand then
+ --regular driver stand controls
+ advtrains.on_control_change(pc, self:train(), data.wagon_flipped)
+ --bordcom
+ if pc.sneak and pc.jump then
+ self:show_bordcom(data.seatp[seatno])
+ end
+ --sound horn when required
+ if self.horn_sound and pc.aux1 and not pc.sneak and not self.horn_handle then
+ self.horn_handle = minetest.sound_play(self.horn_sound, {
+ object = self.object,
+ gain = 1.0, -- default
+ max_hear_distance = 128, -- default, uses an euclidean metric
+ loop = true,
+ })
+ elseif not pc.aux1 and self.horn_handle then
+ minetest.sound_stop(self.horn_handle)
+ self.horn_handle = nil
+ end
+ else
+ -- If on a passenger seat and doors are open, get off when W or D pressed.
+ local pass = data.seatp[seatno] and minetest.get_player_by_name(data.seatp[seatno])
+ if pass and self:train().door_open~=0 then
+ local pc=pass:get_player_control()
+ if pc.up or pc.down then
+ self:get_off(seatno)
+ end
+ end
+ end
+ if pc.aux1 and pc.sneak then
+ self:get_off(seatno)
+ end
+ end
+ end
+
+ --check infotext
+ local outside=train.text_outside or ""
+ if setting_show_ids then
+ outside = outside .. "\nT:" .. data.train_id .. " W:" .. self.id .. " O:" .. data.owner
+ end
+
+
+ --show off-track information in outside text instead of notifying the whole server about this
+ if train.off_track then
+ outside = outside .."\n"..S("!!! Train off track !!!")
+ end
+
+ -- liquid container: display liquid contents in infotext
+ if self.techage_liquid_capacity then
+ if data.techage_liquid and data.techage_liquid.name then
+ outside = outside .."\n"..S("Liquid: ")..data.techage_liquid.name..", "..data.techage_liquid.amount..S(" units")
+ else
+ outside = outside .."\n"..S("Liquid: empty")
+ end
+ end
+
+ if self.infotext_cache~=outside then
+ self.object:set_properties({infotext=outside})
+ self.infotext_cache=outside
+ end
+
+ local fct=data.wagon_flipped and -1 or 1
+
+ --door animation
+ if self.doors then
+ if (self.door_anim_timer or 0)<=0 then
+ local dstate = (train.door_open or 0) * fct
+ if dstate ~= self.door_state then
+ local at
+ --meaning of the train.door_open field:
+ -- -1: left doors (rel. to train orientation)
+ -- 0: closed
+ -- 1: right doors
+ --this code produces the following behavior:
+ -- if changed from 0 to +-1, play open anim. if changed from +-1 to 0, play close.
+ -- if changed from +-1 to -+1, first close and set 0, then it will detect state change again and run open.
+ if self.door_state == 0 then
+ if self.doors.open.sound then minetest.sound_play(self.doors.open.sound, {object = self.object}) end
+ at=self.doors.open[dstate]
+ self.object:set_animation(at.frames, at.speed or 15, at.blend or 0, false)
+ self.door_state = dstate
+ else
+ if self.doors.close.sound then minetest.sound_play(self.doors.close.sound, {object = self.object}) end
+ at=self.doors.close[self.door_state or 1]--in case it has not been set yet
+ self.object:set_animation(at.frames, at.speed or 15, at.blend or 0, false)
+ self.door_state = 0
+ end
+ self.door_anim_timer = at.time
+ end
+ else
+ self.door_anim_timer = (self.door_anim_timer or 0) - dtime
+ end
+ end
+
+ --for path to be available. if not, skip step
+ if not train.path or train.no_step then
+ self.object:set_velocity({x=0, y=0, z=0})
+ self.object:set_acceleration({x=0, y=0, z=0})
+ return
+ end
+ if not data.pos_in_train then
+ return
+ end
+
+ -- Calculate new position, yaw and direction vector
+ -- note: "index" is needed to be the center index, required by door code
+ local index = advtrains.path_get_index_by_offset(train, train.index, -data.pos_in_train)
+ local pos, yaw, npos, npos2, vdir
+
+ -- use new position logic?
+ if self.wheel_positions then
+ -- request two positions, calculate difference and yaw from this
+ -- depending on flipstate, need to invert wheel pos indices -> wheelpos * fct
+ local index1 = advtrains.path_get_index_by_offset(train, index, self.wheel_positions[1] * fct)
+ local index2 = advtrains.path_get_index_by_offset(train, index, self.wheel_positions[2] * fct)
+ local pos1 = advtrains.path_get_interpolated(train, index1)
+ local pos2 = advtrains.path_get_interpolated(train, index2)
+ npos = advtrains.path_get(train, atfloor(index)) -- need npos just for node loaded check
+ -- calculate center of 2 positions and vdir vector
+ -- if wheel positions are asymmetric, needs to weight by the difference!
+ local fact = self.wheel_positions[1] / (self.wheel_positions[1]-self.wheel_positions[2])
+ pos = {x=pos1.x-(pos1.x-pos2.x)*fact, y=pos1.y-(pos1.y-pos2.y)*fact, z=pos1.z-(pos1.z-pos2.z)*fact}
+ if data.wagon_flipped then
+ vdir = vector.normalize(vector.subtract(pos2, pos1))
+ else
+ vdir = vector.normalize(vector.subtract(pos1, pos2))
+ end
+ yaw = math.atan2(-vdir.x, vdir.z)
+ else
+ --old position logic (for small wagons): use center index and just get position
+ pos, yaw, npos, npos2 = advtrains.path_get_interpolated(train, index)
+ vdir = vector.normalize(vector.subtract(npos2, npos))
+ end
+
+ --automatic get_on
+ --needs to know index and path
+ if train.velocity==0 and self.door_entry and train.door_open and train.door_open~=0 then
+ --using the mapping created by the trainlogic globalstep
+ local platform_offset = math.floor(self.wagon_width / 2)
+ for i, ino in ipairs(self.door_entry) do
+ --fct is the flipstate flag from door animation above
+ local aci = advtrains.path_get_index_by_offset(train, index, ino*fct)
+ local ix1, ix2 = advtrains.path_get_adjacent(train, aci)
+ -- the two wanted positions are ix1 and ix2 + (2nd-1st rotated by 90deg)
+ -- (x z) rotated by 90deg is (-z x) (http://stackoverflow.com/a/4780141)
+ local add = {
+ x = atround((ix2.z-ix1.z)*train.door_open),
+ y = 0,
+ z = atround((ix1.x-ix2.x)*train.door_open)
+ }
+ for offset = (platform_offset == 0 and 0 or 1), platform_offset do
+ local scaled_add = vector.multiply(add, offset)
+ local pts1=vector.add(ix1, scaled_add)
+ local pts2=vector.add(ix2, scaled_add)
+ if minetest.get_item_group(minetest.get_node(pts1).name, "platform")>0 then
+ local ckpts={
+ pts1,
+ pts2,
+ vector.add(pts1, {x=0, y=1, z=0}),
+ vector.add(pts2, {x=0, y=1, z=0}),
+ }
+ for _,ckpos in ipairs(ckpts) do
+ local cpp=minetest.pos_to_string(ckpos)
+ if advtrains.playersbypts[cpp] then
+ self:on_rightclick(advtrains.playersbypts[cpp])
+ end
+ end
+ end
+ end
+ end
+ end
+
+ --checking for environment collisions(a 3x3 cube around the center)
+ if not IGNORE_WORLD and is_in_loaded_area and not train.recently_collided_with_env then
+ local collides=false
+ local exh = self.extent_h or 1
+ local exv = self.extent_v or 2
+ for x=-exh,exh do
+ for y=0,exv do
+ for z=-exh,exh do
+ local node=minetest.get_node_or_nil(vector.add(npos, {x=x, y=y, z=z}))
+ if (advtrains.train_collides(node)) then
+ collides=true
+ end
+ end
+ end
+ end
+ if collides then
+ -- screw collision mercy
+ train.recently_collided_with_env=true
+ train.velocity=0
+ advtrains.atc.train_reset_command(train)
+ end
+ end
+
+ -- Spawn discouple object when train stands, in all other cases remove it.
+ -- FIX: Need to do this after the yaw calculation
+ if train.velocity==0 and is_in_loaded_area and data.pos_in_trainparts and data.pos_in_trainparts>1 then
+ if not self.discouple or not self.discouple.object:get_yaw() then
+ atprint(self.id,"trying to spawn discouple")
+ local dcpl_pos = vector.add(pos, {y=0, x=-math.sin(yaw)*self.wagon_span, z=math.cos(yaw)*self.wagon_span})
+ local object=minetest.add_entity(dcpl_pos, "advtrains:discouple")
+ if object then
+ local le=object:get_luaentity()
+ le.wagon=self
+ --box is hidden when attached, so unuseful.
+ --object:set_attach(self.object, "", {x=0, y=0, z=self.wagon_span*10}, {x=0, y=0, z=0})
+ self.discouple=le
+ end
+ end
+ else
+ if self.discouple and self.discouple.object:get_yaw() then
+ self.discouple.object:remove()
+ atprint(self.id," removing discouple")
+ end
+ end
+
+ -- object yaw (corrected by flipstate)
+ local oyaw = yaw
+ if data.wagon_flipped then
+ oyaw = yaw + math.pi
+ end
+
+ --FIX: use index of the wagon, not of the train.
+ local velocity = train.velocity * advtrains.global_slowdown
+ local acceleration = (train.acceleration or 0) * (advtrains.global_slowdown*advtrains.global_slowdown)
+ local velocityvec = vector.multiply(vdir, velocity)
+ local accelerationvec = vector.multiply(vdir, acceleration)
+
+ -- this timer runs off every 2 seconds.
+ self.updatepct_timer=(self.updatepct_timer or 0)-dtime
+ local updatepct_timer_elapsed = self.updatepct_timer<=0
+
+ if updatepct_timer_elapsed then
+ --restart timer
+ self.updatepct_timer=2
+ -- perform checks that are not frequently needed
+
+ -- unload entity if out of range (because relevant pr won't be merged in engine)
+ -- This is a WORKAROUND!
+ local players_in = false
+ for sno,pname in pairs(data.seatp) do
+ if minetest.get_player_by_name(pname) then
+ -- Fix: If the RTT is too high, a wagon might be recognized out of range even if a player sits in it
+ -- (client updates position not fast enough)
+ players_in = true
+ break
+ end
+ end
+ if not players_in then
+ if advtrains.wagon_outside_range(pos) then
+ --atdebug("wagon",self.id,"unloading (too far away)")
+ -- Workaround until minetest engine deletes attached sounds
+ if self.sound_loop_handle then
+ minetest.sound_stop(self.sound_loop_handle)
+ end
+ self.object:remove()
+ end
+ end
+ end
+
+ if not self.old_velocity_vector
+ or not vector.equals(velocityvec, self.old_velocity_vector)
+ or not self.old_acceleration_vector
+ or not vector.equals(accelerationvec, self.old_acceleration_vector)
+ or self.old_yaw~=oyaw
+ or updatepct_timer_elapsed then--only send update packet if something changed
+
+ self.object:set_pos(pos)
+ self.object:set_velocity(velocityvec)
+ self.object:set_acceleration(accelerationvec)
+
+ if #self.seats > 0 and self.old_yaw ~= oyaw then
+ if not self.player_yaw then
+ self.player_yaw = {}
+ end
+ if not self.old_yaw then
+ self.old_yaw=oyaw
+ end
+ for _,name in pairs(data.seatp) do
+ local p = minetest.get_player_by_name(name)
+ if p then
+ if not self.turning then
+ -- save player looking direction offset
+ self.player_yaw[name] = p:get_look_horizontal()-self.old_yaw
+ end
+ -- set player looking direction using calculated offset
+ p:set_look_horizontal((self.player_yaw[name] or 0)+oyaw)
+ end
+ end
+ self.turning = true
+ elseif self.old_yaw == oyaw then
+ -- train is no longer turning
+ self.turning = false
+ end
+
+ if self.object.set_rotation then
+ local pitch = math.atan2(vdir.y, math.hypot(vdir.x, vdir.z))
+ if data.wagon_flipped then
+ pitch = -pitch
+ end
+ self.object:set_rotation({x=pitch, y=oyaw, z=0})
+ else
+ self.object:set_yaw(oyaw)
+ end
+
+ if self.update_animation then
+ self:update_animation(train.velocity, self.old_velocity)
+ end
+ if self.custom_on_velocity_change then
+ self:custom_on_velocity_change(train.velocity, self.old_velocity or 0, dtime)
+ end
+ -- remove discouple object, because it will be in a wrong location
+ if not updatepct_timer_elapsed and self.discouple then
+ self.discouple.object:remove()
+ end
+ end
+
+
+ self.old_velocity_vector=velocityvec
+ self.old_velocity = train.velocity
+ self.old_acceleration_vector=accelerationvec
+ self.old_yaw=oyaw
+ atprintbm("wagon step", t)
+end
+
+function wagon:on_rightclick(clicker)
+ if not self:ensure_init() then return end
+ if not clicker or not clicker:is_player() then
+ return
+ end
+
+ local data = advtrains.wagons[self.id]
+
+ local pname=clicker:get_player_name()
+ local no=self:get_seatno(pname)
+ if no then
+ if self.seat_groups then
+ local poss={}
+ local sgr=self.seats[no].group
+ for _,access in ipairs(self.seat_groups[sgr].access_to) do
+ if self:check_seat_group_access(pname, access) then
+ poss[#poss+1]={name=self.seat_groups[access].name, key="sgr_"..access}
+ end
+ end
+ if self.has_inventory and self.get_inventory_formspec and advtrains.check_driving_couple_protection(pname, data.owner, data.whitelist) then
+ poss[#poss+1]={name=S("Show Inventory"), key="inv"}
+ end
+ if self.seat_groups[sgr].driving_ctrl_access and advtrains.check_driving_couple_protection(pname, data.owner, data.whitelist) then
+ poss[#poss+1]={name=S("Onboard Computer"), key="bordcom"}
+ end
+ if data.owner==pname then
+ poss[#poss+1]={name=S("Wagon properties"), key="prop"}
+ end
+ if not self.seat_groups[sgr].require_doors_open or self:train().door_open~=0 then
+ poss[#poss+1]={name=S("Get off"), key="off"}
+ else
+ if clicker:get_player_control().sneak then
+ poss[#poss+1]={name=S("Get off (forced)"), key="off"}
+ else
+ poss[#poss+1]={name=S("(Doors closed)"), key="dcwarn"}
+ end
+ end
+ if #poss==0 then
+ --can't do anything.
+ elseif #poss==1 then
+ self:seating_from_key_helper(pname, {[poss[1].key]=true}, no)
+ else
+ local form = "size[5,"..1+(#poss).."]"
+ for pos,ent in ipairs(poss) do
+ form = form.. "button_exit[0.5,"..(pos-0.5)..";4,1;"..ent.key..";"..ent.name.."]"
+ end
+ minetest.show_formspec(pname, "advtrains_seating_"..self.id, form)
+ end
+ else
+ self:get_off(no)
+ end
+ else
+ --do not attach if already on a train
+ if advtrains.player_to_train_mapping[pname] then return end
+ if self.seat_groups then
+ if #self.seats==0 then
+ if self.has_inventory and self.get_inventory_formspec and advtrains.check_driving_couple_protection(pname, data.owner, data.whitelist) then
+ minetest.show_formspec(pname, "advtrains_inv_"..self.id, self:get_inventory_formspec(pname, make_inv_name(self.id)))
+ end
+ return
+ end
+
+ local doors_open = self:train().door_open~=0 or clicker:get_player_control().sneak
+ local allow, rsn=false, S("This wagon has no seats.")
+ for _,sgr in ipairs(self.assign_to_seat_group) do
+ allow, rsn = self:check_seat_group_access(pname, sgr)
+ if allow then
+ for seatid, seatdef in ipairs(self.seats) do
+ if seatdef.group==sgr then
+ if (not self.seat_groups[sgr].require_doors_open or doors_open) then
+ if not data.seatp[seatid] then
+ self:get_on(clicker, seatid)
+ return
+ else
+ rsn=S("This wagon is full.")
+ end
+ else
+ rsn=S("Doors are closed! (Try holding sneak key!)")
+ end
+ end
+ end
+ end
+ end
+ minetest.chat_send_player(pname, rsn or S("You can't get on this wagon."))
+ else
+ self:show_get_on_form(pname)
+ end
+ end
+end
+
+function wagon:get_on(clicker, seatno)
+
+ local data = advtrains.wagons[self.id]
+
+ if not data.seatp then data.seatp={}end
+ if not self.seatpc then self.seatpc={}end--player controls in driver stands
+
+ if not self.seats[seatno] then return end
+ local oldno=self:get_seatno(clicker:get_player_name())
+ if oldno then
+ atprint("get_on: clearing oldno",seatno)
+ advtrains.player_to_train_mapping[clicker:get_player_name()]=nil
+ advtrains.clear_driver_hud(clicker:get_player_name())
+ data.seatp[oldno]=nil
+ end
+ if data.seatp[seatno] and data.seatp[seatno]~=clicker:get_player_name() then
+ atprint("get_on: throwing off",data.seatp[seatno],"from seat",seatno)
+ self:get_off(seatno)
+ end
+ atprint("get_on: attaching",clicker:get_player_name())
+ data.seatp[seatno] = clicker:get_player_name()
+ self.seatpc[seatno] = clicker:get_player_control_bits()
+ advtrains.player_to_train_mapping[clicker:get_player_name()]=data.train_id
+ clicker:set_attach(self.object, "", self.seats[seatno].attach_offset, {x=0,y=0,z=0})
+ clicker:set_eye_offset(self.seats[seatno].view_offset, self.seats[seatno].view_offset)
+end
+function wagon:get_off_plr(pname)
+ local no=self:get_seatno(pname)
+ if no then
+ self:get_off(no)
+ end
+end
+function wagon:get_seatno(pname)
+
+ local data = advtrains.wagons[self.id]
+
+ for no, cont in pairs(data.seatp) do
+ if cont==pname then
+ return no
+ end
+ end
+ return nil
+end
+function wagon:get_off(seatno)
+
+ local data = advtrains.wagons[self.id]
+
+ if not data.seatp[seatno] then return end
+ local pname = data.seatp[seatno]
+ local clicker = minetest.get_player_by_name(pname)
+ advtrains.player_to_train_mapping[pname]=nil
+ advtrains.clear_driver_hud(pname)
+ data.seatp[seatno]=nil
+ self.seatpc[seatno]=nil
+ if clicker then
+ atprint("get_off: detaching",clicker:get_player_name())
+ clicker:set_detach()
+ clicker:set_eye_offset({x=0,y=0,z=0}, {x=0,y=0,z=0})
+ local train=self:train()
+ --code as in step - automatic get on
+ if self.door_entry and train.door_open and train.door_open~=0 and train.velocity==0 and train.index and train.path then
+ local index = advtrains.path_get_index_by_offset(train, train.index, -data.pos_in_train)
+ for i, ino in ipairs(self.door_entry) do
+ --atdebug("using door-based",i,ino)
+ local fct=data.wagon_flipped and -1 or 1
+ local aci = advtrains.path_get_index_by_offset(train, index, ino*fct)
+ local ix1, ix2 = advtrains.path_get_adjacent(train, aci)
+ local d = train.door_open
+ if self.wagon_width then
+ d = d * math.floor(self.wagon_width/2)
+ end
+ -- the two wanted positions are ix1 and ix2 + (2nd-1st rotated by 90deg)
+ -- (x z) rotated by 90deg is (-z x) (http://stackoverflow.com/a/4780141)
+ local add = { x = (ix2.z-ix1.z)*d, y = 0, z = (ix1.x-ix2.x)*d }
+ local oadd = { x = (ix2.z-ix1.z)*(d+train.door_open), y = 1, z = (ix1.x-ix2.x)*(d+train.door_open)}
+ local platpos=vector.round(vector.add(ix1, add))
+ local offpos=vector.round(vector.add(ix1, oadd))
+
+ --atdebug("platpos:", platpos, "offpos:", offpos)
+ if minetest.get_item_group(minetest.get_node(platpos).name, "platform")>0 then
+ minetest.after(GETOFF_TP_DELAY, function() clicker:set_pos(offpos) end)
+ --atdebug("tp",offpos)
+ return
+ end
+ --atdebug("nope")
+ end
+ end
+ --if not door_entry, or paths missing, fall back to old method
+ --atdebug("using fallback")
+ local objpos=advtrains.round_vector_floor_y(self.object:get_pos())
+ local yaw=self.object:get_yaw()
+ local isx=(yaw < math.pi/4) or (yaw > 3*math.pi/4 and yaw < 5*math.pi/4) or (yaw > 7*math.pi/4)
+ local offp
+ --abuse helper function
+ for _,r in ipairs({-1, 1}) do
+ --atdebug("offset",r)
+ local p=vector.add({x=isx and r or 0, y=0, z=not isx and r or 0}, objpos)
+ offp=vector.add({x=isx and r*2 or 0, y=1, z=not isx and r*2 or 0}, objpos)
+ --atdebug("platpos:", p, "offpos:", offp)
+ if minetest.get_item_group(minetest.get_node(p).name, "platform")>0 then
+ minetest.after(GETOFF_TP_DELAY, function() clicker:set_pos(offp) end)
+ --atdebug("tp",offp)
+ return
+ end
+ end
+ --atdebug("nope")
+
+ end
+end
+function wagon:show_get_on_form(pname)
+ if not self.initialized then return end
+
+ local data = advtrains.wagons[self.id]
+ if #self.seats==0 then
+ if self.has_inventory and self.get_inventory_formspec and advtrains.check_driving_couple_protection(pname, data.owner, data.whitelist) then
+ minetest.show_formspec(pname, "advtrains_inv_"..self.id, self:get_inventory_formspec(pname, make_inv_name(self.id)))
+ end
+ return
+ end
+ local form, comma="size[5,8]label[0.5,0.5;"..S("Select seat:").."]textlist[0.5,1;4,6;seat;", ""
+ for seatno, seattbl in ipairs(self.seats) do
+ local addtext, colorcode="", ""
+ if data.seatp and data.seatp[seatno] then
+ colorcode="#FF0000"
+ addtext=" ("..data.seatp[seatno]..")"
+ end
+ form=form..comma..colorcode..seattbl.name..addtext
+ comma=","
+ end
+ form=form..";0,false]"
+ if self.has_inventory and self.get_inventory_formspec then
+ form=form.."button_exit[1,7;3,1;inv;"..S("Show Inventory").."]"
+ end
+ minetest.show_formspec(pname, "advtrains_geton_"..self.id, form)
+end
+function wagon:show_wagon_properties(pname)
+ --[[
+ fields:
+ field: driving/couple whitelist
+ button: save
+ ]]
+ local data = advtrains.wagons[self.id]
+ local form="size[5,5]"
+ form=form.."label[0.2,0;"..S("This Wagon ID")..": "..self.id.." ("..data.owner..")]"
+ form = form.."field[0.5,1;4.5,1;whitelist;"..S("Allow these players to access your wagon:")..";"..minetest.formspec_escape(data.whitelist or "").."]"
+ form = form.."field[0.5,2;4.5,1;roadnumber;"..S("Wagon road number:")..";"..minetest.formspec_escape(data.roadnumber or "").."]"
+ local fc = ""
+ if data.fc then
+ fc = table.concat(data.fc, "!")
+ end
+ form = form.. "field[0.5,3;4.5,1;fc;"..S("Freight Code:")..";"..fc.."]"
+ if data.fc then
+ if not data.fcind then data.fcind = 1 end
+ if data.fcind > 1 then
+ form=form.."button[0.5,3.5;1,1;fcp;"..S("Prev FC").."]"
+ end
+ form=form.."label[1.5,3.5;"..S("Current FC: ").."]"
+
+ local cur = data.fc[data.fcind] or ""
+ form=form.."label[1.5,3.75;"..minetest.formspec_escape(cur).."]"
+ form=form.."button[3.5,3.5;1,1;fcn;"..S("Next FC:").."]"
+ end
+ form=form.."button_exit[0.5,4.5;4,1;save;"..S("Save wagon properties").."]"
+ minetest.show_formspec(pname, "advtrains_prop_"..self.id, form)
+end
+
+--BordCom
+local function checkcouple(ent)
+ if not ent or not ent:get_yaw() then
+ return nil
+ end
+ local le = ent:get_luaentity()
+ if not le or not le.is_couple then
+ return nil
+ end
+ return le
+end
+local function checklock(pname, own1, own2, wl1, wl2)
+ return advtrains.check_driving_couple_protection(pname, own1, wl1)
+ or advtrains.check_driving_couple_protection(pname, own2, wl2)
+end
+
+local function split(str, sep)
+ local fields = {}
+ local pattern = string.format("([^%s]+)", sep)
+ str:gsub(pattern, function(c) fields[#fields+1] = c end)
+ return fields
+end
+
+function wagon.set_fc(data, fcstr)
+ data.fc = split(fcstr, "!")
+ if not data.fcind then
+ data.fcind = 1
+ elseif data.fcind > #data.fc then
+ data.fcind = #data.fc
+ end
+end
+
+function wagon.prev_fc(data)
+ if data.fcind > 1 then
+ data.fcind = data.fcind -1
+ end
+ if data.fcind == 1 and data.fcrev then
+ data.fcrev = nil
+ end
+end
+
+function wagon.next_fc(data)
+ if not data.fc then return end
+ if data.fcrev then
+ wagon.prev_fc(data)
+ return
+ end
+ if data.fcind < #data.fc then
+ data.fcind = data.fcind + 1
+ else
+ data.fcind = 1
+ end
+ if data.fcind == #data.fc and data.fc[data.fcind] == "?" then
+ data.fcrev = true
+ wagon.prev_fc(data)
+ return
+ end
+end
+
+function advtrains.get_cur_fc(data)
+ if not ( data.fc and data.fcind ) then
+ return ""
+ end
+ return data.fc[data.fcind] or ""
+end
+
+function advtrains.step_fc(data)
+ wagon.next_fc(data)
+end
+
+
+
+
+
+function wagon:show_bordcom(pname)
+ if not self:train() then return end
+ local train = self:train()
+ local data = advtrains.wagons[self.id]
+ local linhei
+
+ local form = "size[11,9]label[0.5,0;AdvTrains Boardcom v0.1]"
+ form=form.."textarea[7.5,0.05;10,1;;"..S("Train ID")..": "..(minetest.formspec_escape(train.id or ""))..";]"
+ form=form.."textarea[0.5,1.5;7,1;text_outside;"..S("Text displayed outside on train")..";"..(minetest.formspec_escape(train.text_outside or "")).."]"
+ form=form.."textarea[0.5,3;7,1;text_inside;"..S("Text displayed inside train")..";"..(minetest.formspec_escape(train.text_inside or "")).."]"
+ form=form.."field[7.5,1.75;3,1;line;"..S("Line")..";"..(minetest.formspec_escape(train.line or "")).."]"
+ form=form.."field[7.5,3.25;3,1;routingcode;"..S("Routingcode")..";"..(minetest.formspec_escape(train.routingcode or "")).."]"
+ --row 5 : train overview and autocoupling
+ if train.velocity==0 then
+ form=form.."label[0.5,4;"..S("Train overview /coupling control:").."])"
+ linhei=5
+ local pre_own, pre_wl, owns_any = nil, nil, minetest.check_player_privs(pname, "train_admin")
+ for i, tpid in ipairs(train.trainparts) do
+ local ent = advtrains.wagons[tpid]
+ if ent then
+ local roadnumber = ent.roadnumber or ""
+ form = form.. string.format("button[%d,%d;%d,%d;%s;%s]", i, linhei, 1, 0.2, "wgprp"..i, roadnumber)
+ local ename = ent.type
+ form = form.. "item_image["..i..","..(linhei+0.5)..";1,1;"..ename.."]"
+ if i~=1 then
+ if checklock(pname, ent.owner, pre_own, ent.whitelist, pre_wl) then
+ form = form.. "image_button["..(i-0.5)..","..(linhei+1.5)..";1,1;advtrains_discouple.png;dcpl_"..i..";]"
+ end
+ end
+ if i == data.pos_in_trainparts then
+ form = form.. "box["..(i-0.1)..","..(linhei+0.4)..";1,1;green]"
+ end
+ pre_own = ent.owner
+ pre_wl = ent.whitelist
+ owns_any = owns_any or (not ent.owner or ent.owner==pname)
+ end
+ end
+
+ if train.movedir==1 then
+ form = form.. "label["..(#train.trainparts+1)..","..(linhei)..";-->]"
+ else
+ form = form.. "label[0.5,"..(linhei)..";<--]"
+ end
+ --check cpl_eid_front and _back of train
+ local couple_front = checkcouple(train.cpl_front)
+ local couple_back = checkcouple(train.cpl_back)
+ if couple_front then
+ form = form.. "image_button[0.5,"..(linhei+1)..";1,1;advtrains_couple.png;cpl_f;]"
+ end
+ if couple_back then
+ form = form.. "image_button["..(#train.trainparts+0.5)..","..(linhei+1)..";1,1;advtrains_couple.png;cpl_b;]"
+ end
+
+ else
+ form=form.."label[0.5,4.5;"..S("Train overview / coupling control is only shown when the train stands.").."]"
+ end
+ form = form.. "button[0.5,8;3,1;save;"..S("Save").."]"
+
+ -- Interlocking functionality: If the interlocking module is loaded, you can set the signal aspect
+ -- from inside the train
+ if advtrains.interlocking and train.lzb and #train.lzb.checkpoints > 0 then
+ local i=1
+ while train.lzb.checkpoints[i] do
+ local oci = train.lzb.checkpoints[i]
+ if oci.udata and oci.udata.signal_pos then
+ if advtrains.interlocking.db.get_sigd_for_signal(oci.udata.signal_pos) then
+ form = form.. "button[4.5,8;5,1;ilrs;"..S("Remote Routesetting").."]"
+ break
+ end
+ end
+ i=i+1
+ end
+ if train.ars_disable then
+ form = form.. "button[4.5,7;5,1;ilarsenable;"..S("Clear 'Disable ARS' flag").."]"
+ end
+ end
+
+ minetest.show_formspec(pname, "advtrains_bordcom_"..self.id, form)
+end
+function wagon:handle_bordcom_fields(pname, formname, fields)
+ local data = advtrains.wagons[self.id]
+
+ local seatno=self:get_seatno(pname)
+ if not seatno or not self.seat_groups[self.seats[seatno].group].driving_ctrl_access or not advtrains.check_driving_couple_protection(pname, data.owner, data.whitelist) then
+ return
+ end
+ local train = self:train()
+ if not train then return end
+ if fields.text_outside then
+ if fields.text_outside~="" then
+ train.text_outside=fields.text_outside
+ else
+ train.text_outside=nil
+ end
+ end
+ if fields.text_inside then
+ if fields.text_inside~="" then
+ train.text_inside=fields.text_inside
+ else
+ train.text_inside=nil
+ end
+ end
+ if fields.line then
+ if fields.line~="" then
+ if fields.line ~= train.line then
+ train.line=fields.line
+ minetest.after(0, advtrains.invalidate_path, train.id)
+ end
+ else
+ train.line=nil
+ end
+ end
+ if fields.routingcode then
+ if fields.routingcode~="" then
+ if fields.routingcode ~= train.routingcode then
+ train.routingcode=fields.routingcode
+ minetest.after(0, advtrains.invalidate_path, train.id)
+ end
+ else
+ train.routingcode=nil
+ end
+ end
+ for i, tpid in ipairs(train.trainparts) do
+ if fields["dcpl_"..i] then
+ advtrains.safe_decouple_wagon(tpid, pname)
+ elseif fields["wgprp"..i] and data.owner==pname then
+ local wagon = advtrains.get_wagon_entity(tpid)
+ if wagon then
+ wagon:show_wagon_properties(pname)
+ return
+ end
+ end
+ end
+ --check cpl_eid_front and _back of train
+ local couple_front = checkcouple(train.cpl_front)
+ local couple_back = checkcouple(train.cpl_back)
+
+ if fields.cpl_f and couple_front then
+ couple_front:on_rightclick(pname)
+ end
+ if fields.cpl_b and couple_back then
+ couple_back:on_rightclick(pname)
+ end
+
+ -- Interlocking functionality: If the interlocking module is loaded, you can set the signal aspect
+ -- from inside the train
+ if advtrains.interlocking then
+ if fields.ilrs and train.lzb and #train.lzb.checkpoints > 0 then
+ local i=1
+ while train.lzb.checkpoints[i] do
+ local oci = train.lzb.checkpoints[i]
+ if oci.udata and oci.udata.signal_pos then
+ local sigd = advtrains.interlocking.db.get_sigd_for_signal(oci.udata.signal_pos)
+ if sigd then
+ advtrains.interlocking.show_signalling_form(sigd, pname)
+ return
+ end
+ end
+ i=i+1
+ end
+ end
+ if fields.ilarsenable then
+ advtrains.interlocking.ars_set_disable(train, false)
+ end
+ end
+
+
+ if not fields.quit then
+ self:show_bordcom(pname)
+ end
+end
+
+minetest.register_on_player_receive_fields(function(player, formname, fields)
+ local uid=string.match(formname, "^advtrains_geton_(.+)$")
+ if uid then
+ local wagon = advtrains.get_wagon_entity(uid)
+ if wagon then
+ local data = advtrains.wagons[wagon.id]
+ if fields.inv then
+ if wagon.has_inventory and wagon.get_inventory_formspec then
+ minetest.show_formspec(player:get_player_name(), "advtrains_inv_"..uid, wagon:get_inventory_formspec(player:get_player_name(), make_inv_name(uid)))
+ end
+ elseif fields.seat then
+ local val=minetest.explode_textlist_event(fields.seat)
+ if val and val.type~="INV" and not data.seatp[player:get_player_name()] then
+ --get on
+ wagon:get_on(player, val.index)
+ --will work with the new close_formspec functionality. close exactly this formspec.
+ minetest.show_formspec(player:get_player_name(), formname, "")
+ end
+ end
+ end
+ return true
+ end
+
+ uid=string.match(formname, "^advtrains_seating_(.+)$")
+ if uid then
+ local wagon = advtrains.get_wagon_entity(uid)
+ if wagon then
+ local pname=player:get_player_name()
+ local no=wagon:get_seatno(pname)
+ if no then
+ if wagon.seat_groups then
+ wagon:seating_from_key_helper(pname, fields, no)
+ end
+ end
+ end
+ return true
+ end
+
+ uid=string.match(formname, "^advtrains_prop_(.+)$")
+ if uid then
+ local pname=player:get_player_name()
+ local data = advtrains.wagons[uid]
+ if not data then
+ return true
+ elseif pname~=data.owner and not minetest.check_player_privs(pname, {train_admin = true}) then
+ return true
+ end
+ if fields.save or not fields.quit then
+ if fields.whitelist then
+ data.whitelist = fields.whitelist
+ end
+ if fields.roadnumber then
+ data.roadnumber = fields.roadnumber
+ end
+ if fields.fc then
+ wagon.set_fc(data, fields.fc)
+ end
+ if fields.fcp then
+ wagon.prev_fc(data)
+ wagon.show_wagon_properties({id=uid}, pname)
+ end
+ if fields.fcn then
+ advtrains.step_fc(data)
+ wagon.show_wagon_properties({id=uid}, pname)
+ end
+ end
+ return true
+ end
+ uid=string.match(formname, "^advtrains_bordcom_(.+)$")
+ if uid then
+ local wagon = advtrains.get_wagon_entity(uid)
+ if wagon then
+ wagon:handle_bordcom_fields(player:get_player_name(), formname, fields)
+ end
+ return true
+ end
+
+ uid=string.match(formname, "^advtrains_inv_(.+)$")
+ if uid then
+ local pname=player:get_player_name()
+ local data = advtrains.wagons[uid]
+ if fields.prop and data.owner==pname then
+ local wagon = advtrains.get_wagon_entity(uid)
+ if wagon then
+ wagon:show_wagon_properties(pname)
+ --wagon:handle_bordcom_fields(player:get_player_name(), formname, fields)
+ end
+ end
+ return true
+ end
+end)
+
+function wagon:seating_from_key_helper(pname, fields, no)
+ local data = advtrains.wagons[self.id]
+ local sgr=self.seats[no].group
+ for _,access in ipairs(self.seat_groups[sgr].access_to) do
+ if fields["sgr_"..access] and self:check_seat_group_access(pname, access) then
+ for seatid, seatdef in ipairs(self.seats) do
+ if seatdef.group==access and not data.seatp[seatid] then
+ self:get_on(minetest.get_player_by_name(pname), seatid)
+ return
+ end
+ end
+ end
+ end
+ if fields.inv and self.has_inventory and self.get_inventory_formspec then
+ minetest.close_formspec(pname, "advtrains_seating_"..self.id)
+ minetest.show_formspec(pname, "advtrains_inv_"..self.id, self:get_inventory_formspec(pname, make_inv_name(self.id)))
+ end
+ if fields.prop and data.owner==pname then
+ minetest.close_formspec(pname, "advtrains_seating_"..self.id)
+ self:show_wagon_properties(pname)
+ end
+ if fields.bordcom and self.seat_groups[sgr].driving_ctrl_access and advtrains.check_driving_couple_protection(pname, data.owner, data.whitelist) then
+ minetest.close_formspec(pname, "advtrains_seating_"..self.id)
+ self:show_bordcom(pname)
+ end
+ if fields.dcwarn then
+ minetest.chat_send_player(pname, S("Doors are closed. Use Sneak+rightclick to ignore the closed doors and get off."))
+ end
+ if fields.off then
+ self:get_off(no)
+ end
+end
+function wagon:check_seat_group_access(pname, sgr)
+ local data = advtrains.wagons[self.id]
+ if self.seat_groups[sgr].driving_ctrl_access and not (advtrains.check_driving_couple_protection(pname, data.owner, data.whitelist)) then
+ return false, S("You are not allowed to access the driver stand.")
+ end
+ if self.seat_groups[sgr].driving_ctrl_access then
+ advtrains.log("Drive", pname, self.object:get_pos(), self:train().text_outside)
+ end
+ return true
+end
+function wagon:reattach_all()
+ local data = advtrains.wagons[self.id]
+ if not data.seatp then data.seatp={} end
+ for seatno, pname in pairs(data.seatp) do
+ local p=minetest.get_player_by_name(pname)
+ if p then
+ self:get_on(p ,seatno)
+ end
+ end
+end
+
+function advtrains.safe_decouple_wagon(w_id, pname, try_run)
+ if not minetest.check_player_privs(pname, "train_operator") then
+ minetest.chat_send_player(pname, S("Missing train_operator privilege"))
+ return false
+ end
+ local data = advtrains.wagons[w_id]
+
+ local dpt = data.pos_in_trainparts
+ if not dpt or dpt <= 1 then
+ return false
+ end
+ local train = advtrains.trains[data.train_id]
+ local owid = train.trainparts[dpt-1]
+ local owdata = advtrains.wagons[owid]
+
+ if not owdata then
+ return
+ end
+
+ if not checklock(pname, data.owner, owdata.owner, data.whitelist, owdata.whitelist) then
+ minetest.chat_send_player(pname, S("Not allowed to do this."))
+ return false
+ end
+
+ if try_run then
+ return true
+ end
+
+ advtrains.log("Discouple", pname, train.last_pos, train.text_outside)
+ advtrains.split_train_at_wagon(w_id)
+ return true
+end
+
+
+
+function advtrains.get_wagon_prototype(data)
+ local wt = data.type
+ if not wt then
+ -- LEGACY: Field was called "entity_name" in previous versions
+ wt = data.entity_name
+ data.type = data.entity_name
+ data.entity_name = nil
+ end
+ local rt, proto = advtrains.resolve_wagon_alias(wt)
+ if not rt then
+ --atwarn(S("Unable to load wagon type"),wt,S(", using placeholder"))
+ rt = "advtrains:wagon_placeholder"
+ proto = advtrains.wagon_prototypes[rt]
+ end
+ return rt, proto
+end
+
+function advtrains.register_wagon_alias(src, dst)
+ advtrains.wagon_alias[src] = dst
+end
+
+local function recursive_resolve_alias(name, seen)
+ local prototype = rawget(advtrains.wagon_prototypes, name)
+ if prototype then
+ return name, prototype
+ end
+ local resolved = advtrains.wagon_alias[name]
+ if resolved and not seen[resolved] then
+ seen[name] = true
+ return recursive_resolve_alias(resolved, seen)
+ end
+end
+
+function advtrains.resolve_wagon_alias(name)
+ return recursive_resolve_alias(name, {})
+end
+
+function advtrains.standard_inventory_formspec(self, pname, invname)
+ --[[minetest.chat_send_player(pname, string.format("self=%s, pname=%s, invname=%s", self, pname, invname))
+ for k,v in pairs(self) do
+ minetest.chat_send_player(pname, string.format("%s=%s", k,v))
+ end
+ minetest.chat_send_player(pname, string.format("***%s***", self.object:get_pos()))--]]
+ local data = advtrains.wagons[self.id]
+ local r = "size[8,11]"..
+ "list["..invname..";box;0,0;8,3;]"
+ if data.owner==pname then
+ r = r .. "button_exit[0,9;4,1;prop;"..S("Wagon properties").."]"
+ end
+ r = r .. "list[current_player;main;0,5;8,4;]"..
+ "listring[]"
+ return r
+end
+
+function advtrains.register_wagon(sysname_p, prototype, desc, inv_img, nincreative)
+ local sysname = sysname_p
+ if not string.match(sysname, ":") then
+ sysname = "advtrains:"..sysname_p
+ end
+ setmetatable(prototype, {__index=wagon})
+ minetest.register_entity(":"..sysname,prototype)
+ advtrains.wagon_prototypes[sysname] = prototype
+
+ --group classification to make recipe searching easier
+ local wagon_groups = { not_in_creative_inventory = nincreative and 1 or 0}
+ if prototype.is_locomotive then wagon_groups['at_loco'] = 1 end
+ if prototype.seat_groups then
+ wagon_groups['at_rideable'] = 1
+ for seats, seat in pairs(prototype.seat_groups) do
+ if seat.driving_ctrl_access then
+ wagon_groups['at_control'] = 1
+ else
+ wagon_groups['at_pax'] = 1
+ end
+ end
+ end
+ if prototype.has_inventory then wagon_groups['at_freight'] = 1 end
+
+ minetest.register_craftitem(":"..sysname, {
+ description = desc,
+ inventory_image = inv_img,
+ wield_image = inv_img,
+ stack_max = 1,
+
+ groups = wagon_groups,
+
+ on_place = function(itemstack, placer, pointed_thing)
+ if pointed_thing.type ~= "node" then
+ return
+ end
+
+ local pos = pointed_thing.under
+ local node = minetest.get_node(pos)
+ local pointed_def = minetest.registered_nodes[node.name]
+ if pointed_def and pointed_def.on_rightclick then
+ local controls = placer:get_player_control()
+ if not controls.sneak then
+ return pointed_def.on_rightclick(pos, node, placer, itemstack, pointed_thing)
+ end
+ end
+
+ local pname = placer:get_player_name()
+
+ if node.name == "ignore" then atprint("[advtrains]Ignore at placer position") return itemstack end
+ local nodename=node.name
+ if(not advtrains.is_track(nodename)) then
+ atprint("no track here, not placing.")
+ return itemstack
+ end
+ if not minetest.check_player_privs(placer, {train_operator = true }) then
+ minetest.chat_send_player(pname, S("You don't have the train_operator privilege."))
+ return itemstack
+ end
+ if not minetest.check_player_privs(placer, {train_admin = true }) and minetest.is_protected(pos, placer:get_player_name()) then
+ return itemstack
+ end
+ local tconns=advtrains.get_track_connections(node.name, node.param2)
+ local yaw = placer:get_look_horizontal()
+ local plconnid = advtrains.yawToClosestConn(yaw, tconns)
+
+ local prevpos = advtrains.get_adjacent_rail(pos, tconns, plconnid)
+ if not prevpos then
+ minetest.chat_send_player(pname, S("The track you are trying to place the wagon on is not long enough!"))
+ return
+ end
+
+ local wid = advtrains.create_wagon(sysname, pname)
+
+ local id=advtrains.create_new_train_at(pos, plconnid, 0, {wid})
+
+ if not advtrains.is_creative(pname) then
+ itemstack:take_item()
+ end
+ return itemstack
+ end,
+ })
+end
+
+-- Placeholder wagon. Will be spawned whenever a mod is missing
+advtrains.register_wagon("advtrains:wagon_placeholder", {
+ visual="sprite",
+ textures = {"advtrains_wagon_placeholder.png"},
+ collisionbox = {-0.3,-0.3,-0.3, 0.3,0.3,0.3},
+ visual_size = {x=0.7, y=0.7},
+ initial_sprite_basepos = {x=0, y=0},
+ max_speed = 5,
+ seats = {
+ },
+ seat_groups = {
+ },
+ assign_to_seat_group = {},
+ wagon_span=1,
+ drops={},
+}, S("Wagon placeholder"), "advtrains_wagon_placeholder.png", true)
+
+
+
+-- Helper function to retrieve the wagon at a certain position in a train, given its train ID and the desired index within that train's path
+--
+-- Returns: wagon_num, wagon_id, wagon_data, offset_from_center
+-- wagon_num: The n'th wagon in the train (index into "trainparts" table)
+-- wagon_id: The wagon ID. Obtain wagon data from advtrains.wagons[wagon_id], and subsequently the wagon prototype via advtrains.get_wagon_prototype(data)
+-- offset_from_center: The offset (an absolute distance value) from the center point of the wagon. Positive is towards the end of the train, negative towards the start. (note that this is inverse to the counting direction of the index!)
+--
+--[[ To get the wagon standing at a certain world position, you first need to retrieve the index via the occupation table, as follows:
+ local trains = advtrains.occ.get_trains_at(pos)
+ for train_id, index in pairs(trains) do
+ local wagon_num, wagon_id, wagon_data, offset_from_center = advtrains.get_wagon_at_index(train_id, index)
+ if wagon_num then
+ ...
+ end
+ end
+]]--
+function advtrains.get_wagon_at_index(train_id, w_index)
+ local train = advtrains.trains[train_id]
+ if not train then error("Passed train id "..train_id.." doesnt exist") end
+ -- ensure init - always required
+ advtrains.train_ensure_init(train_id, train)
+ -- Use path dist to determine the offset from the start of the train
+ local dstart = advtrains.path_get_path_dist_fractional(train, train.index)
+ local dtarget = advtrains.path_get_path_dist_fractional(train, w_index)
+ local dist_from_start = dstart - dtarget -- NOTE: dist_from_start is supposed to be positive, but dtarget will be smaller than dstart
+ -- if dist_from_start is <0, we are outside of train
+ if dist_from_start < 0 then
+ return nil
+ end
+ -- scan over wagons to see if dist_from_start falls into its window
+ local start_pos = 0
+ local center_pos
+ local end_pos
+ local i = 1
+ while train.trainparts[i] do
+ local w_id = train.trainparts[i]
+ -- get wagon prototype to retrieve wagon span
+ local wdata = advtrains.wagons[w_id]
+ if wdata then
+ local wtype, wproto = advtrains.get_wagon_prototype(wdata)
+ local wagon_span = wproto.wagon_span
+ -- determine center and end pos
+ center_pos = start_pos + wagon_span
+ end_pos = center_pos + wagon_span
+ if start_pos <= dist_from_start and dist_from_start < end_pos then
+ -- Found the correct wagon in the train!
+ local offset_from_center = dist_from_start - center_pos
+ return i, w_id, wdata, offset_from_center
+ end
+ -- go on
+ start_pos = end_pos
+ else
+ error("Wagon "..w_id.." from train "..train_id.." doesnt exist!")
+ end
+ i = i + 1
+ end
+ -- nothing found, dist must be further back
+ return nil
+end
+
+function advtrains.get_wagon_entity(wagon_id)
+ if not advtrains.wagons[wagon_id] then return end
+ local object = advtrains.wagon_objects[wagon_id]
+ if object then
+ return object:get_luaentity()
+ end
+end
+
+function advtrains.next_wagon_entity_in_train(train, i)
+ local wagon_id = train.trainparts[i + 1]
+ if wagon_id then
+ local wagon = advtrains.get_wagon_entity(wagon_id)
+ if wagon then
+ return i + 1, wagon
+ end
+ end
+end
+
+function advtrains.wagon_entity_pairs_in_train(train_id)
+ local train = advtrains.trains[train_id]
+ if not train then return function() end end
+ return advtrains.next_wagon_entity_in_train, train, 0
+end
+
+minetest.register_chatcommand("at_chown", {
+ params = "<wagon_id> <player_name>",
+ description = "Change the owner of an advtrains wagon",
+ privs = {train_admin=true},
+ func = function(name, param)
+ local params = string.split(param," ")
+ local wid = params[1]
+ local new_owner = params[2]
+ if not wid then return false end --no params added
+ --player name checks
+ if not new_owner then return false, S("Please specify a player name to transfer ownership to.") end --no player name argument
+ if not core.player_exists(new_owner) then return false, S("That player does not exist!") end --is a valid player
+ --wagon id checks
+ if not wid:match("%d%d%d%d%d%d") then return false, S("Not a valid wagon id.") end -- invalid wagon id
+ local w_data = advtrains.wagons[wid]
+ if not w_data then return false, S("That wagon does not exist!") end
+ -- actually chown the wagon
+ local curr_owner = w_data.owner
+ w_data.owner = new_owner
+ advtrains.wagons[wid] = w_data
+ advtrains.log("Chown", name, core.get_player_by_name(name):get_pos(), "wid="..wid..", from="..curr_owner..", to="..new_owner)
+
+ if name ~= new_owner then
+ core.chat_send_player(new_owner, S("You have been given ownership of wagon @1", wid))
+ end
+ return true, S("Wagon @1 ownership changed from @2 to @3", wid, curr_owner, new_owner)
+ end
+})