more mods

This commit is contained in:
2026-09-12 07:03:41 -06:00
parent cc0fa41e3b
commit bac6ac94a3
1742 changed files with 115814 additions and 1 deletions
+10
View File
@@ -0,0 +1,10 @@
## Buggy
This mod adds a buggy automobile to Minetest.
## Licenses
- Code: see [LICENSE](/LICENSE)
- Media: see [license_media.txt](/license_media.txt)
## Screenshot
![buggy](/automobiles_buggy/screenshot.jpg)
@@ -0,0 +1,81 @@
local S = buggy.S
--
-- items
--
-- body
minetest.register_craftitem("automobiles_buggy:buggy_body",{
description = S("Buggy Body"),
inventory_image = "automobiles_buggy_body.png",
})
-- wheel
minetest.register_craftitem("automobiles_buggy:wheel",{
description = S("Buggy Wheel"),
inventory_image = "automobiles_buggy_wheel_icon.png",
})
-- buggy
minetest.register_tool("automobiles_buggy:buggy", {
description = S("Buggy"),
inventory_image = "automobiles_buggy.png",
liquids_pointable = false,
stack_max = 1,
on_place = function(itemstack, placer, pointed_thing)
if pointed_thing.type ~= "node" then
return
end
local stack_meta = itemstack:get_meta()
local staticdata = stack_meta:get_string("staticdata")
local pointed_pos = pointed_thing.above
--pointed_pos.y=pointed_pos.y+0.2
local car = minetest.add_entity(pointed_pos, "automobiles_buggy:buggy", staticdata)
if car and placer then
local ent = car:get_luaentity()
local owner = placer:get_player_name()
if ent then
ent.owner = owner
ent.hp = 50 --reset hp
car:set_yaw(placer:get_look_horizontal())
itemstack:take_item()
ent.object:set_acceleration({x=0,y=-automobiles_lib.gravity,z=0})
automobiles_lib.setText(ent, S("Buggy"))
automobiles_lib.create_inventory(ent, ent._trunk_slots, owner)
end
end
return itemstack
end,
})
--
-- crafting
--
if minetest.get_modpath("default") then
minetest.register_craft({
output = "automobiles_buggy:buggy",
recipe = {
{"automobiles_buggy:wheel", "automobiles_lib:engine", "automobiles_buggy:wheel"},
{"automobiles_buggy:wheel","automobiles_buggy:buggy_body", "automobiles_buggy:wheel"},
}
})
minetest.register_craft({
output = "automobiles_buggy:buggy_body",
recipe = {
{"default:glass" ,"","default:steel_ingot"},
{"default:steel_ingot","","default:steel_ingot"},
{"default:steel_ingot","default:steel_ingot", "default:steel_ingot"},
}
})
minetest.register_craft({
output = "automobiles_buggy:wheel",
recipe = {
{"default:steel_ingot", "default:tin_ingot", "default:steel_ingot"},
{"default:tin_ingot","default:steelblock", "default:tin_ingot"},
{"default:steel_ingot", "default:tin_ingot", "default:steel_ingot"},
}
})
end
+278
View File
@@ -0,0 +1,278 @@
--
-- entity
--
minetest.register_entity('automobiles_buggy:front_suspension',{
initial_properties = {
physical = true,
collide_with_objects=true,
collisionbox = {-0.5, 0, -0.5, 0.5, 1, 0.5},
pointable=false,
visual = "mesh",
mesh = "automobiles_buggy_f_suspension.b3d",
textures = {"automobiles_black.png",},
},
on_activate = function(self,std)
self.sdata = minetest.deserialize(std) or {}
if self.sdata.remove then self.object:remove() end
end,
get_staticdata=function(self)
self.sdata.remove=true
return minetest.serialize(self.sdata)
end,
--[[on_step = function(self, dtime, moveresult)
minetest.chat_send_all(dump(moveresult))
end,]]--
})
minetest.register_entity('automobiles_buggy:rear_suspension',{
initial_properties = {
physical = true,
collide_with_objects=true,
pointable=false,
visual = "mesh",
mesh = "automobiles_buggy_r_suspension.b3d",
textures = {"automobiles_black.png",},
},
on_activate = function(self,std)
self.sdata = minetest.deserialize(std) or {}
if self.sdata.remove then self.object:remove() end
end,
get_staticdata=function(self)
self.sdata.remove=true
return minetest.serialize(self.sdata)
end,
})
minetest.register_entity('automobiles_buggy:f_lights',{
initial_properties = {
physical = false,
collide_with_objects=false,
pointable=false,
glow = 0,
visual = "mesh",
mesh = "automobiles_buggy_f_lights.b3d",
textures = {"automobiles_grey.png",},
},
on_activate = function(self,std)
self.sdata = minetest.deserialize(std) or {}
if self.sdata.remove then self.object:remove() end
end,
get_staticdata=function(self)
self.sdata.remove=true
return minetest.serialize(self.sdata)
end,
})
minetest.register_entity('automobiles_buggy:r_lights',{
initial_properties = {
physical = false,
collide_with_objects=false,
pointable=false,
glow = 0,
visual = "mesh",
mesh = "automobiles_buggy_r_lights.b3d",
textures = {"automobiles_rear_lights_off.png",},
},
on_activate = function(self,std)
self.sdata = minetest.deserialize(std) or {}
if self.sdata.remove then self.object:remove() end
end,
get_staticdata=function(self)
self.sdata.remove=true
return minetest.serialize(self.sdata)
end,
})
minetest.register_entity('automobiles_buggy:f_wheel',{
initial_properties = {
physical = false,
collide_with_objects=false,
pointable=false,
visual = "mesh",
mesh = "automobiles_buggy_f_wheel.b3d",
backface_culling = false,
textures = {"automobiles_black.png", "automobiles_metal.png", "automobiles_buggy_wheel.png"},
},
on_activate = function(self,std)
self.sdata = minetest.deserialize(std) or {}
if self.sdata.remove then self.object:remove() end
end,
get_staticdata=function(self)
self.sdata.remove=true
return minetest.serialize(self.sdata)
end,
})
minetest.register_entity('automobiles_buggy:r_wheel',{
initial_properties = {
physical = false,
collide_with_objects=false,
pointable=false,
visual = "mesh",
mesh = "automobiles_buggy_r_wheel.b3d",
backface_culling = false,
textures = {"automobiles_black.png", "automobiles_metal.png", "automobiles_buggy_wheel.png"},
},
on_activate = function(self,std)
self.sdata = minetest.deserialize(std) or {}
if self.sdata.remove then self.object:remove() end
end,
get_staticdata=function(self)
self.sdata.remove=true
return minetest.serialize(self.sdata)
end,
})
minetest.register_entity('automobiles_buggy:rag',{
initial_properties = {
physical = false,
collide_with_objects=false,
pointable=false,
visual = "mesh",
mesh = "automobiles_buggy_rag.b3d",
backface_culling = false,
textures = {"automobiles_black.png", "automobiles_buggy_rag_window.png"},
},
on_activate = function(self,std)
self.sdata = minetest.deserialize(std) or {}
if self.sdata.remove then self.object:remove() end
end,
get_staticdata=function(self)
self.sdata.remove=true
return minetest.serialize(self.sdata)
end,
})
minetest.register_entity("automobiles_buggy:buggy", {
initial_properties = {
physical = true,
collide_with_objects = true,
collisionbox = {-0.1, -0.45, -0.1, 0.1, 1, 0.1},
selectionbox = {-1.5, 0.0, -1.5, 1.5, 2, 1.5},
stepheight = 0.7 + automobiles_lib.extra_stepheight,
visual = "mesh",
mesh = "automobiles_buggy_body.b3d",
textures = {
"automobiles_black.png", --bancos
"automobiles_painting.png", --carroceria
"automobiles_black.png", --banco traseiro
"automobiles_black.png", --chssis
"automobiles_metal.png", --frontlights
"automobiles_black.png", --interior
"automobiles_metal.png", --engine
"automobiles_buggy_fuel.png", --panel
"automobiles_metal.png", --windshield
"automobiles_buggy_windshield.png", --windshield
"automobiles_metal.png", --engine protection
"automobiles_metal.png", --front protection
"automobiles_metal.png", --driver protection
"automobiles_black.png", -- engine details
"automobiles_metal.png", "automobiles_black.png", --volante
},
},
textures = {},
driver_name = nil,
sound_handle = nil,
owner = "",
static_save = true,
infotext = "A very nice buggy!",
hp = 50,
buoyancy = 2,
physics = automobiles_lib.physics,
lastvelocity = vector.new(),
time_total = 0,
_passenger = nil,
_color = "#ff8b0e",
_steering_angle = 0,
_engine_running = false,
_last_checkpoint = "",
_total_laps = -1,
_race_id = "",
_energy = 1,
_last_time_collision_snd = 0,
_last_time_drift_snd = 0,
_last_time_command = 0,
_roll = math.rad(0),
_pitch = 0,
_longit_speed = 0,
_show_rag = true,
_show_lights = false,
_light_old_pos = nil,
_last_ground_check = 0,
_last_light_move = 0,
_last_engine_sound_update = 0,
_inv = nil,
_inv_id = "",
_change_color = automobiles_lib.paint,
_intensity = 4,
_trunk_slots = 8,
_engine_sound = "buggy_engine",
_max_fuel = 10,
_formspec_function = buggy.driver_formspec,
_vehicle_name = "Buggy",
_drive_wheel_pos = {x=-4.26,y=6.01,z=16},
_drive_wheel_angle = 15,
_rag_extended_ent = 'automobiles_buggy:rag',
_seat_pos = {{x=-4.25,y=0.48,z=9.5},{x=4.25,y=0.48,z=9.5}},
_front_suspension_ent = 'automobiles_buggy:front_suspension',
_front_suspension_pos = {x=0,y=-0.7,z=23},
_front_wheel_ent = 'automobiles_buggy:f_wheel',
_front_wheel_xpos = 8,
_front_wheel_frames = {x = 1, y = 13},
_rear_suspension_ent = 'automobiles_buggy:rear_suspension',
_rear_suspension_pos = {x=0,y=0,z=0},
_rear_wheel_ent = 'automobiles_buggy:r_wheel',
_rear_wheel_xpos = 8,
_rear_wheel_frames = {x = 1, y = 13},
_fuel_gauge_pos = {x=0,y=4.65,z=15.17},
_front_lights = 'automobiles_buggy:f_lights',
_rear_lights = 'automobiles_buggy:r_lights',
_LONGIT_DRAG_FACTOR = 0.12*0.12,
_LATER_DRAG_FACTOR = 6.0,
_max_acc_factor = 5,
_max_speed = 15,
_min_later_speed = 4.0,
_consumption_divisor = 60000,
get_staticdata = automobiles_lib.get_staticdata,
on_deactivate = function(self)
automobiles_lib.save_inventory(self)
end,
on_activate = automobiles_lib.on_activate,
on_step = automobiles_lib.on_step,
on_punch = automobiles_lib.on_punch,
on_rightclick = automobiles_lib.on_rightclick,
})
@@ -0,0 +1,79 @@
local S = buggy.S
function buggy.driver_formspec(name)
local player = minetest.get_player_by_name(name)
local vehicle_obj = automobiles_lib.getCarFromPlayer(player)
if vehicle_obj == nil then
return
end
local ent = vehicle_obj:get_luaentity()
local yaw = "false"
local one_hand = "false"
if ent._yaw_by_mouse then yaw = "true" end
if ent._one_hand then one_hand = "true" end
local basic_form = table.concat({
"formspec_version[3]",
"size[6,7]",
}, "")
basic_form = basic_form.."button[1,1.0;4,1;go_out;" .. S("Go Offboard") .. "]"
basic_form = basic_form.."button[1,2.5;4,1;top;" .. S("Close/Open Rag") .. "]"
basic_form = basic_form.."button[1,4.0;4,1;lights;" .. S("Lights") .. "]"
basic_form = basic_form.."checkbox[1,5.5;yaw;" .. S("Direction by mouse") .. ";"..yaw.."]"
basic_form = basic_form.."checkbox[1,6.2;one_hand;" .. S("One Hand Driving\n(open menu using AUX)") .. ";"..one_hand.."]"
minetest.show_formspec(name, "buggy:driver_main", basic_form)
end
minetest.register_on_player_receive_fields(function(player, formname, fields)
if formname == "buggy:driver_main" then
local name = player:get_player_name()
local car_obj = automobiles_lib.getCarFromPlayer(player)
if car_obj then
local ent = car_obj:get_luaentity()
if ent then
if fields.top then
if ent._show_rag == true then
ent._show_rag = false
else
ent._show_rag = true
end
end
if fields.go_out then
if ent._passenger then --any pax?
local pax_obj = minetest.get_player_by_name(ent._passenger)
automobiles_lib.dettach_pax(ent, pax_obj)
end
automobiles_lib.dettach_driver(ent, player)
end
if fields.lights then
if ent._show_lights == true then
ent._show_lights = false
else
ent._show_lights = true
end
end
if fields.yaw then
if ent._yaw_by_mouse == true then
ent._yaw_by_mouse = false
else
ent._yaw_by_mouse = true
end
end
if fields.one_hand then
if ent._one_hand == true then
ent._one_hand = false
else
ent._one_hand = true
core.chat_send_player(name,core.colorize('#00ff00', S(" >>> Use AUX or key \"E\" to open the menu")))
end
end
end
end
minetest.close_formspec(name, "buggy:driver_main")
end
end)
+27
View File
@@ -0,0 +1,27 @@
--
-- constants
--
buggy={}
buggy.gravity = automobiles_lib.gravity
buggy.S = nil
if(minetest.get_translator ~= nil) then
buggy.S = minetest.get_translator(minetest.get_current_modname())
else
buggy.S = function ( s ) return s end
end
local S = buggy.S
dofile(minetest.get_modpath("automobiles_lib") .. DIR_DELIM .. "custom_physics.lua")
dofile(minetest.get_modpath("automobiles_lib") .. DIR_DELIM .. "control.lua")
dofile(minetest.get_modpath("automobiles_lib") .. DIR_DELIM .. "fuel_management.lua")
dofile(minetest.get_modpath("automobiles_lib") .. DIR_DELIM .. "ground_detection.lua")
dofile(minetest.get_modpath("automobiles_buggy") .. DIR_DELIM .. "buggy_forms.lua")
dofile(minetest.get_modpath("automobiles_buggy") .. DIR_DELIM .. "buggy_entities.lua")
dofile(minetest.get_modpath("automobiles_buggy") .. DIR_DELIM .. "buggy_crafts.lua")
@@ -0,0 +1,9 @@
# textdomain: automobiles_buggy
### buggy_crafts.lua ###
Buggy Body=Buggy Karrosserie
Buggy Wheel=Buggy Rad
Buggy=Buggy
Go Offboard=Aussteigen
Close/Open Rag=Öffne/Schließe Sonnendach
Lights=Lichter
Direction by mouse=Lenke mit Maus
@@ -0,0 +1,9 @@
# textdomain: automobiles_buggy
### buggy_crafts.lua ###
Buggy Body=Korpo de Buggy
Buggy Wheel=Rado de Buggy
Buggy=Buggy
Go Offboard=
Close/Open Rag=
Lights=
Direction by mouse=
@@ -0,0 +1,9 @@
# textdomain: automobiles_buggy
### buggy_crafts.lua ###
Buggy Body=
Buggy Wheel=
Buggy=
Go Offboard=
Close/Open Rag=
Lights=
Direction by mouse=
+5
View File
@@ -0,0 +1,5 @@
name=automobiles_buggy
title=Buggy
description=A buggy
author=apercy
depends=automobiles_lib
@@ -0,0 +1,495 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Script to generate Minetest translation template files and update
# translation files.
#
# Copyright (C) 2019 Joachim Stolberg, 2020 FaceDeer, 2020 Louis Royer,
# 2023 Wuzzy.
# License: LGPLv2.1 or later (see LICENSE file for details)
import os, fnmatch, re, shutil, errno
from sys import argv as _argv
from sys import stderr as _stderr
# Running params
params = {"recursive": False,
"help": False,
"verbose": False,
"folders": [],
"old-file": False,
"break-long-lines": False,
"print-source": False,
"truncate-unused": False,
}
# Available CLI options
options = {"recursive": ['--recursive', '-r'],
"help": ['--help', '-h'],
"verbose": ['--verbose', '-v'],
"old-file": ['--old-file', '-o'],
"break-long-lines": ['--break-long-lines', '-b'],
"print-source": ['--print-source', '-p'],
"truncate-unused": ['--truncate-unused', '-t'],
}
# Strings longer than this will have extra space added between
# them in the translation files to make it easier to distinguish their
# beginnings and endings at a glance
doublespace_threshold = 80
# These symbols mark comment lines showing the source file name.
# A comment may look like "##[ init.lua ]##".
symbol_source_prefix = "##["
symbol_source_suffix = "]##"
# comment to mark the section of old/unused strings
comment_unused = "##### not used anymore #####"
def set_params_folders(tab: list):
'''Initialize params["folders"] from CLI arguments.'''
# Discarding argument 0 (tool name)
for param in tab[1:]:
stop_param = False
for option in options:
if param in options[option]:
stop_param = True
break
if not stop_param:
params["folders"].append(os.path.abspath(param))
def set_params(tab: list):
'''Initialize params from CLI arguments.'''
for option in options:
for option_name in options[option]:
if option_name in tab:
params[option] = True
break
def print_help(name):
'''Prints some help message.'''
print(f'''SYNOPSIS
{name} [OPTIONS] [PATHS...]
DESCRIPTION
{', '.join(options["help"])}
prints this help message
{', '.join(options["recursive"])}
run on all subfolders of paths given
{', '.join(options["old-file"])}
create *.old files
{', '.join(options["break-long-lines"])}
add extra line breaks before and after long strings
{', '.join(options["print-source"])}
add comments denoting the source file
{', '.join(options["verbose"])}
add output information
{', '.join(options["truncate-unused"])}
delete unused strings from files
''')
def main():
'''Main function'''
set_params(_argv)
set_params_folders(_argv)
if params["help"]:
print_help(_argv[0])
else:
# Add recursivity message
print("Running ", end='')
if params["recursive"]:
print("recursively ", end='')
# Running
if len(params["folders"]) >= 2:
print("on folder list:", params["folders"])
for f in params["folders"]:
if params["recursive"]:
run_all_subfolders(f)
else:
update_folder(f)
elif len(params["folders"]) == 1:
print("on folder", params["folders"][0])
if params["recursive"]:
run_all_subfolders(params["folders"][0])
else:
update_folder(params["folders"][0])
else:
print("on folder", os.path.abspath("./"))
if params["recursive"]:
run_all_subfolders(os.path.abspath("./"))
else:
update_folder(os.path.abspath("./"))
# Group 2 will be the string, groups 1 and 3 will be the delimiters (" or ')
# See https://stackoverflow.com/questions/46967465/regex-match-text-in-either-single-or-double-quote
pattern_lua_quoted = re.compile(
r'(?:^|[\.=,{\(\s])' # Look for beginning of file or anything that isn't a function identifier
r'N?F?S\s*\(\s*' # Matches S, FS, NS or NFS function call
r'(["\'])((?:\\\1|(?:(?!\1)).)*)(\1)' # Quoted string
r'[\s,\)]', # End of call or argument
re.DOTALL)
# Handles the [[ ... ]] string delimiters
pattern_lua_bracketed = re.compile(
r'(?:^|[\.=,{\(\s])' # Same as for pattern_lua_quoted
r'N?F?S\s*\(\s*' # Same as for pattern_lua_quoted
r'\[\[(.*?)\]\]' # [[ ... ]] string delimiters
r'[\s,\)]', # Same as for pattern_lua_quoted
re.DOTALL)
# Handles "concatenation" .. " of strings"
pattern_concat = re.compile(r'["\'][\s]*\.\.[\s]*["\']', re.DOTALL)
# Handles a translation line in *.tr file.
# Group 1 is the source string left of the equals sign.
# Group 2 is the translated string, right of the equals sign.
pattern_tr = re.compile(
r'(.*)' # Source string
# the separating equals sign, if NOT preceded by @, unless
# that @ is preceded by another @
r'(?:(?<!(?<!@)@)=)'
r'(.*)' # Translation string
)
pattern_name = re.compile(r'^name[ ]*=[ ]*([^ \n]*)')
pattern_tr_filename = re.compile(r'\.tr$')
# Matches bad use of @ signs in Lua string
pattern_bad_luastring = re.compile(
r'^@$|' # single @, OR
r'[^@]@$|' # trailing unescaped @, OR
r'(?<!@)@(?=[^@1-9])' # an @ that is not escaped or part of a placeholder
)
# Attempt to read the mod's name from the mod.conf file or folder name. Returns None on failure
def get_modname(folder):
try:
with open(os.path.join(folder, "mod.conf"), "r", encoding='utf-8') as mod_conf:
for line in mod_conf:
match = pattern_name.match(line)
if match:
return match.group(1)
except FileNotFoundError:
if not os.path.isfile(os.path.join(folder, "modpack.txt")):
folder_name = os.path.basename(folder)
# Special case when run in Minetest's builtin directory
if folder_name == "builtin":
return "__builtin"
else:
return folder_name
else:
return None
return None
# If there are already .tr files in /locale, returns a list of their names
def get_existing_tr_files(folder):
out = []
for root, dirs, files in os.walk(os.path.join(folder, 'locale/')):
for name in files:
if pattern_tr_filename.search(name):
out.append(name)
return out
# from https://stackoverflow.com/questions/600268/mkdir-p-functionality-in-python/600612#600612
# Creates a directory if it doesn't exist, silently does
# nothing if it already exists
def mkdir_p(path):
try:
os.makedirs(path)
except OSError as exc: # Python >2.5
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else: raise
# Converts the template dictionary to a text to be written as a file
# dKeyStrings is a dictionary of localized string to source file sets
# dOld is a dictionary of existing translations and comments from
# the previous version of this text
def strings_to_text(dkeyStrings, dOld, mod_name, header_comments, textdomain):
# if textdomain is specified, insert it at the top
if textdomain != None:
lOut = [textdomain] # argument is full textdomain line
# otherwise, use mod name as textdomain automatically
else:
lOut = [f"# textdomain: {mod_name}"]
if header_comments is not None:
lOut.append(header_comments)
dGroupedBySource = {}
for key in dkeyStrings:
sourceList = list(dkeyStrings[key])
sourceString = "\n".join(sourceList)
listForSource = dGroupedBySource.get(sourceString, [])
listForSource.append(key)
dGroupedBySource[sourceString] = listForSource
lSourceKeys = list(dGroupedBySource.keys())
lSourceKeys.sort()
for source in lSourceKeys:
localizedStrings = dGroupedBySource[source]
if params["print-source"]:
if lOut[-1] != "":
lOut.append("")
lOut.append(source)
for localizedString in localizedStrings:
val = dOld.get(localizedString, {})
translation = val.get("translation", "")
comment = val.get("comment")
if params["break-long-lines"] and len(localizedString) > doublespace_threshold and not lOut[-1] == "":
lOut.append("")
if comment != None and comment != "" and not comment.startswith("# textdomain:"):
lOut.append(comment)
lOut.append(f"{localizedString}={translation}")
if params["break-long-lines"] and len(localizedString) > doublespace_threshold:
lOut.append("")
unusedExist = False
if not params["truncate-unused"]:
for key in dOld:
if key not in dkeyStrings:
val = dOld[key]
translation = val.get("translation")
comment = val.get("comment")
# only keep an unused translation if there was translated
# text or a comment associated with it
if translation != None and (translation != "" or comment):
if not unusedExist:
unusedExist = True
lOut.append("\n\n" + comment_unused + "\n")
if params["break-long-lines"] and len(key) > doublespace_threshold and not lOut[-1] == "":
lOut.append("")
if comment != None:
lOut.append(comment)
lOut.append(f"{key}={translation}")
if params["break-long-lines"] and len(key) > doublespace_threshold:
lOut.append("")
return "\n".join(lOut) + '\n'
# Writes a template.txt file
# dkeyStrings is the dictionary returned by generate_template
def write_template(templ_file, dkeyStrings, mod_name):
# read existing template file to preserve comments
existing_template = import_tr_file(templ_file)
text = strings_to_text(dkeyStrings, existing_template[0], mod_name, existing_template[2], existing_template[3])
mkdir_p(os.path.dirname(templ_file))
with open(templ_file, "wt", encoding='utf-8') as template_file:
template_file.write(text)
# Gets all translatable strings from a lua file
def read_lua_file_strings(lua_file):
lOut = []
with open(lua_file, encoding='utf-8') as text_file:
text = text_file.read()
text = re.sub(pattern_concat, "", text)
strings = []
for s in pattern_lua_quoted.findall(text):
strings.append(s[1])
for s in pattern_lua_bracketed.findall(text):
strings.append(s)
for s in strings:
found_bad = pattern_bad_luastring.search(s)
if found_bad:
print("SYNTAX ERROR: Unescaped '@' in Lua string: " + s)
continue
s = s.replace('\\"', '"')
s = s.replace("\\'", "'")
s = s.replace("\n", "@n")
s = s.replace("\\n", "@n")
s = s.replace("=", "@=")
lOut.append(s)
return lOut
# Gets strings from an existing translation file
# returns both a dictionary of translations
# and the full original source text so that the new text
# can be compared to it for changes.
# Returns also header comments in the third return value.
def import_tr_file(tr_file):
dOut = {}
text = None
in_header = True
header_comments = None
textdomain = None
if os.path.exists(tr_file):
with open(tr_file, "r", encoding='utf-8') as existing_file :
# save the full text to allow for comparison
# of the old version with the new output
text = existing_file.read()
existing_file.seek(0)
# a running record of the current comment block
# we're inside, to allow preceeding multi-line comments
# to be retained for a translation line
latest_comment_block = None
for line in existing_file.readlines():
line = line.rstrip('\n')
# "##### not used anymore #####" comment
if line == comment_unused:
# Always delete the 'not used anymore' comment.
# It will be re-added to the file if neccessary.
latest_comment_block = None
if header_comments != None:
in_header = False
continue
# Comment lines
elif line.startswith("#"):
# Source file comments: ##[ file.lua ]##
if line.startswith(symbol_source_prefix) and line.endswith(symbol_source_suffix):
# This line marks the end of header comments.
if params["print-source"]:
in_header = False
# Remove those comments; they may be added back automatically.
continue
# Store first occurance of textdomain
# discard all subsequent textdomain lines
if line.startswith("# textdomain:"):
if textdomain == None:
textdomain = line
continue
elif in_header:
# Save header comments (normal comments at top of file)
if not header_comments:
header_comments = line
else:
header_comments = header_comments + "\n" + line
else:
# Save normal comments
if line.startswith("# textdomain:") and textdomain == None:
textdomain = line
elif not latest_comment_block:
latest_comment_block = line
else:
latest_comment_block = latest_comment_block + "\n" + line
continue
match = pattern_tr.match(line)
if match:
# this line is a translated line
outval = {}
outval["translation"] = match.group(2)
if latest_comment_block:
# if there was a comment, record that.
outval["comment"] = latest_comment_block
latest_comment_block = None
in_header = False
dOut[match.group(1)] = outval
return (dOut, text, header_comments, textdomain)
# like os.walk but returns sorted filenames
def sorted_os_walk(folder):
tuples = []
t = 0
for root, dirs, files in os.walk(folder):
tuples.append( (root, dirs, files) )
t = t + 1
tuples = sorted(tuples)
paths_and_files = []
f = 0
for tu in tuples:
root = tu[0]
dirs = tu[1]
files = tu[2]
files = sorted(files, key=str.lower)
for filename in files:
paths_and_files.append( (os.path.join(root, filename), filename) )
f = f + 1
return paths_and_files
# Walks all lua files in the mod folder, collects translatable strings,
# and writes it to a template.txt file
# Returns a dictionary of localized strings to source file lists
# that can be used with the strings_to_text function.
def generate_template(folder, mod_name):
dOut = {}
paths_and_files = sorted_os_walk(folder)
for paf in paths_and_files:
fullpath_filename = paf[0]
filename = paf[1]
if fnmatch.fnmatch(filename, "*.lua"):
found = read_lua_file_strings(fullpath_filename)
if params["verbose"]:
print(f"{fullpath_filename}: {str(len(found))} translatable strings")
for s in found:
sources = dOut.get(s, set())
sources.add(os.path.relpath(fullpath_filename, start=folder))
dOut[s] = sources
if len(dOut) == 0:
return None
# Convert source file set to list, sort it and add comment symbols.
# Needed because a set is unsorted and might result in unpredictable.
# output orders if any source string appears in multiple files.
for d in dOut:
sources = dOut.get(d, set())
sources = sorted(list(sources), key=str.lower)
newSources = []
for i in sources:
newSources.append(f"{symbol_source_prefix} {i} {symbol_source_suffix}")
dOut[d] = newSources
templ_file = os.path.join(folder, "locale/template.txt")
write_template(templ_file, dOut, mod_name)
return dOut
# Updates an existing .tr file, copying the old one to a ".old" file
# if any changes have happened
# dNew is the data used to generate the template, it has all the
# currently-existing localized strings
def update_tr_file(dNew, mod_name, tr_file):
if params["verbose"]:
print(f"updating {tr_file}")
tr_import = import_tr_file(tr_file)
dOld = tr_import[0]
textOld = tr_import[1]
textNew = strings_to_text(dNew, dOld, mod_name, tr_import[2], tr_import[3])
if textOld and textOld != textNew:
print(f"{tr_file} has changed.")
if params["old-file"]:
shutil.copyfile(tr_file, f"{tr_file}.old")
with open(tr_file, "w", encoding='utf-8') as new_tr_file:
new_tr_file.write(textNew)
# Updates translation files for the mod in the given folder
def update_mod(folder):
modname = get_modname(folder)
if modname is not None:
print(f"Updating translations for {modname}")
data = generate_template(folder, modname)
if data == None:
print(f"No translatable strings found in {modname}")
else:
for tr_file in get_existing_tr_files(folder):
update_tr_file(data, modname, os.path.join(folder, "locale/", tr_file))
else:
print(f"Unable to determine the mod name in folder {folder}. Missing 'name' field in mod.conf.", file=_stderr)
exit(1)
# Determines if the folder being pointed to is a mod or a mod pack
# and then runs update_mod accordingly
def update_folder(folder):
is_modpack = os.path.exists(os.path.join(folder, "modpack.txt")) or os.path.exists(os.path.join(folder, "modpack.conf"))
if is_modpack:
subfolders = [f.path for f in os.scandir(folder) if f.is_dir() and not f.name.startswith('.')]
for subfolder in subfolders:
update_mod(subfolder)
else:
update_mod(folder)
print("Done.")
def run_all_subfolders(folder):
for modfolder in [f.path for f in os.scandir(folder) if f.is_dir() and not f.name.startswith('.')]:
update_folder(modfolder)
main()
Binary file not shown.

After

Width:  |  Height:  |  Size: 122 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.0 KiB