z_mirror/CursorEnhancements

git clone https://git.raiguard.me/z_mirror/CursorEnhancements

Caleb HeuerImprove quick-crafting behavior48ea56d

trunk
2.5 KiB90 linesraw
1local util = require("scripts.util")
2
3local crafting_controllers = {
4  [defines.controllers.character] = true,
5  [defines.controllers.god] = true,
6}
7
8--- @param e EventData.CustomInputEvent
9local function on_quick_craft(e)
10  local player = game.get_player(e.player_index)
11  if not player then
12    return
13  end
14
15  if not crafting_controllers[player.controller_type] then
16    return
17  end
18
19  local selected = e.selected_prototype
20  if not selected then
21    return
22  end
23
24  if selected.base_type == "entity" and selected.name == "entity-ghost" then
25    -- Get ghost entity name
26    local real_selected = player.selected
27    if not real_selected or real_selected.name ~= "entity-ghost" then
28      return
29    end
30    selected.name = real_selected.ghost_name
31  end
32
33  -- Prioritize items over resources
34  if selected.derived_type == "resource" then
35    local cursor_stack = player.cursor_stack
36    local cursor_ghost = player.cursor_ghost
37    if cursor_stack and cursor_stack.valid_for_read then
38      selected = {
39        base_type = "item",
40        derived_type = cursor_stack.type,
41        name = cursor_stack.name,
42        quality = cursor_stack.quality.name,
43      }
44    elseif cursor_ghost then
45      selected = {
46        base_type = "item",
47        derived_type = cursor_ghost.type,
48        name = cursor_ghost.name.name,
49        quality = cursor_ghost.quality.name,
50      }
51    end
52  end
53
54  local recipes = util.get_selected_recipes(selected)
55  if not recipes then
56    return
57  end
58
59  -- TODO: Crafting functions cannot have quality specified; Add this to the API.
60  for _, recipe in pairs(recipes) do
61    local craftable_count = player.cheat_mode and math.huge or player.get_craftable_count(recipe.name) --[[@as uint]]
62    if craftable_count == 0 then
63      goto continue
64    end
65    local main_product = recipe.main_product or recipe.products[1]
66    if not main_product then
67      goto continue
68    end
69    local craft_count_setting = player.mod_settings["cen-quick-craft-count"].value --[[@as uint]]
70    local main_product_amount = main_product.amount
71    if not main_product_amount then
72      goto continue
73    end
74    local craft_count = math.min(craftable_count, math.ceil(craft_count_setting / main_product_amount) --[[@as uint]])
75    player.begin_crafting({ recipe = recipe.name, count = craft_count })
76    -- Language server and formatter don't like a label after break...
77    do
78      break
79    end
80    ::continue::
81  end
82end
83
84local quick_craft = {}
85
86quick_craft.events = {
87  ["cen-quick-craft"] = on_quick_craft,
88}
89
90return quick_craft