# Copyright (C) 2022 Justin Schuh <code@justinschuh.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.

[gcode_macro before_layer_change]
description: Add this to the "before layer change" input box in the slicer.
  Usage: BEFORE_LAYER_CHANGE HEIGHT=<current_height> LAYER=<current_layer>
gcode:
  {% set height = params.HEIGHT|default(printer.toolhead.position.z)|float %}
  {% set layer = params.LAYER|default(-1)|int + 1 %}
  {% if height >= 0.0 and layer >= 0 %}
    SET_PRINT_STATS_INFO CURRENT_LAYER="{layer}"
    SET_GCODE_VARIABLE MACRO=_km_layer_run VARIABLE=cur_height VALUE="{height}"
    {% if printer["gcode_macro _km_layer_run"].clearance_z < height %}
      SET_GCODE_VARIABLE MACRO=_km_layer_run VARIABLE=clearance_z VALUE="{
        height}"
    {% endif %}
  {% endif %}
  _KM_LAYER_RUN BEFORE=1

[gcode_macro after_layer_change]
description: Add this to the "after layer change" input box in the slicer.
  Usage: AFTER_LAYER_CHANGE
gcode:
  _KM_LAYER_RUN BEFORE=0

[gcode_macro gcode_at_layer]
description: Schedules the specified g-code command to be run at the specified layer. LAYER=next will cause the command to run at the next layer change. 
  Usage: GCODE_AT_LAYER { HEIGHT=<pos> | LAYER=<layer> } COMMAND=<gcode> 
                         [BEFORE=<0|1>] [ALLOW_DUPLICATE=<0|1>]
gcode:
  {% set commands = printer["gcode_macro _km_layer_run"].commands %}
  {% set tot_layers = printer.print_stats.info.total_layer %}
  {% if params|length > 0 %}
    {% if not printer.pause_resume.is_paused and
          printer.idle_timeout.state|string != "Printing" %}
      {action_raise_error("No active print.")}
    {% endif %}

    {% set when = "before" if (params.BEFORE|default(0)|int) else "after" %}

    {% if "LAYER" in params %}
      {% set cur_layer = printer.print_stats.info.current_layer %}
      {% if "HEIGHT" in params %}
        {action_raise_error("Conflicting HEIGHT and LAYER arguments provided.")}
      {% elif params.LAYER|string|lower == "next" %}
        {% set LAYER = cur_layer + 1 %}
      {% else %}
        {% set LAYER = params.LAYER|int %}
      {% endif %}
      {% if LAYER <= cur_layer %}
        {action_raise_error("LAYER[%i] must be above current print layer[%i]."
                            | format(LAYER, cur_layer))}
      {% elif tot_layers and LAYER >= tot_layers %}
        {action_raise_error("LAYER[%i] must be below top layer[%i]."
                            | format(LAYER, tot_layers))}
      {% endif %}
      {% set key = "%12i_layer_%s"|format(LAYER, when)%}

    {% elif "HEIGHT" in params %}
      {% set HEIGHT = params.HEIGHT|float %}
      {% set cur_height = printer["gcode_macro _km_layer_run"].cur_height %}
      {% if HEIGHT <= cur_height %}
        {action_raise_error(
          "HEIGHT[%.3f] must be above current print height[%.3f].")
          | format(HEIGHT, cur_height)}
      {% elif HEIGHT >= printer.toolhead.axis_maximum.z %}
        {action_raise_error(
          "HEIGHT[%.3f] must be below maximum Z height[%.3f].")
          | format(HEIGHT, printer.toolhead.axis_maximum.z)}
      {% endif %}
      {% set key = "%12.3f_height_%s"|format(HEIGHT, when)%}

    {% else %}
      {action_raise_error("No HEIGHT or LAYER argument provided.")}
    {% endif %}
  
    {% set COMMAND = params.COMMAND %}
    {% if key not in commands %}
      {% set dummy = commands.__setitem__(key, []) %}
    {% endif %}
    {% if COMMAND in commands[key] or params.ALLOW_DUPLICATE|default(0)|int %}
      {action_raise_error("Duplicate command previously scheduled.")}
    {% else %}
      {% set dummy = commands[key].append(COMMAND) %}
      SET_GCODE_VARIABLE MACRO=_km_layer_run VARIABLE=commands VALUE="{
          commands|replace('\"','\\\"')}"
      {% set args = key.split('_') %}
      {% set pos = ("%i"|format(args[0]|int)) if args[1] == "layer" else
                   ("%.3fmm"|format(args[0]|float)) %}
      {action_respond_info("%s %s (%s):\n* %s" |
                           format(args[1], pos, args[2], COMMAND))}
    {% endif %}

  # No arguments means just list all the triggers.
  {% else %}
    {% set layers = [] %}
    {% set heights = [] %}
    {% for k in commands|list|sort %}
      {% set args = k.split('_') %}
      {% if args[1] == "layer" %}
        {% set dummy = layers.append("layer %i (%s):"
                                     | format(args[0]|int, args[2])) %}
        {% for c in commands[k] %}
          {% set dummy = layers.append("* %s" | format(c)) %}
        {% endfor %}
      {% else %}
        {% set dummy = heights.append("height %.3fmm (%s):"
                                      | format(args[0]|float, args[2])) %}
        {% for c in commands[k] %}
          {% set dummy = heights.append("* %s" | format(c)) %}
        {% endfor %}
      {% endif %}
    {% endfor %}
    {% set dummy = layers.extend(heights) %}
    {action_respond_info(layers|join('\n'))}
  {% endif %}

[gcode_macro init_layer_gcode]
description: Clears scheduled gcode commands and state for all layers.
  Usage: INIT_LAYER_GCODE LAYERS=<num>
gcode:
  SET_PRINT_STATS_INFO TOTAL_LAYER="{params.LAYERS|int}"
  SET_GCODE_VARIABLE MACRO=_km_layer_run VARIABLE=cur_height VALUE="{0.0}"
  SET_GCODE_VARIABLE MACRO=_km_layer_run VARIABLE=clearance_z VALUE="{0.0}"
  SET_GCODE_VARIABLE MACRO=_km_layer_run VARIABLE=commands VALUE="{{}}"

[gcode_macro _reset_layer_gcode]
description: Clears scheduled gcode commands and state for all layers.
  Usage: _RESET_LAYER_GCODE
gcode:
  SET_PRINT_STATS_INFO TOTAL_LAYER="0"
  SET_GCODE_VARIABLE MACRO=_km_layer_run VARIABLE=cur_height VALUE="{0.0}"
  SET_GCODE_VARIABLE MACRO=_km_layer_run VARIABLE=clearance_z VALUE="{0.0}"
  SET_GCODE_VARIABLE MACRO=_km_layer_run VARIABLE=commands VALUE="{{}}"

[gcode_macro cancel_all_layer_gcode]
description: Clears all scheduled gcode commands.
  Usage: CANCEL_ALL_LAYER_GCODE
gcode:
  SET_GCODE_VARIABLE MACRO=_km_layer_run VARIABLE=commands VALUE="{{}}"

[gcode_macro pause_next_layer]
description: Convenience macro to schedule the current print to pause at the next layer change. See PAUSE for additional arguments.
  Usage: PAUSE_NEXT_LAYER ...
gcode:
  _CHECK_KINEMATIC_LIMITS{% for k in params%}{' ' ~k~ '=' ~ params[k]
    }{% endfor %}
  GCODE_AT_LAYER LAYER=NEXT COMMAND="PAUSE{% for k in params %}{
    ' ' ~ k ~ '=' ~ params[k]}{% endfor %}"

[gcode_macro _km_layer_run]
description: Runs pending commands for the current layer change.
  Usage: _KM_LAYER_RUN BEFORE=<0|1>
variable_cur_height: 0.0
variable_clearance_z: 0.0
variable_commands: {}
gcode:
  {% set BEFORE = params.BEFORE|int %}
  {% set cur_layer = printer.print_stats.info.current_layer %}
  {% for k in commands | list | sort %}
    {% set args = k.split('_') %}
    {% set cmd_pos = args[0]|float %}
    {% set cmd_type = args[1] %}
    {% set cmd_before = 1 if args[2] == "before" else 0 %}
    {% if cmd_before == BEFORE and (
         (cmd_type == "layer" and cmd_pos|int <= cur_layer) or
         (cmd_type == "height" and cmd_pos <= cur_height)) %}
      {action_respond_info("Executing scheduled commands at %s %s:\n%s" |
         format(args[1], args[0].strip(), commands[k]|join('\n')))}
      {% for c in commands[k] %}
        {c}
      {% endfor %}
      {% set dummy = commands.__delitem__(k) %}
    {% endif %}
  {% endfor %}
  SET_GCODE_VARIABLE MACRO=_km_layer_run VARIABLE=commands VALUE="{
      commands|replace('\"','\\\"')}"

[gcode_macro pause_at_layer]
description: Convenience macro to schedule the current print to pause at the specified layer change. LAYER=next will cause the command to run at the next layer change. See PAUSE for additional arguments.
  Usage: PAUSE_AT_LAYER { HEIGHT=<pos> | LAYER=<layer> } ...
gcode:
  # Dummy argument block for Mainsail
  {% set dummy = None if True else "
  {% set dummy = params.LAYER|default(layer number)|float %}
  {% set dummy = params.HEIGHT|default(Z height)|int %}
  " %} # End argument block for Mainsail
  {% set filtered_params = params|reject('in',['HEIGHT','LAYER'])|list|sort %}
  _CHECK_KINEMATIC_LIMITS{% for k in filtered_params%}{' ' ~k~ '=' ~ params[k]
   }{% endfor %}
  GCODE_AT_LAYER {% for k in params|select('in',['HEIGHT','LAYER'])|list %}{
      ' ' ~ k ~ '=' ~ params[k] }{% endfor
    %} COMMAND="PAUSE{% for k in filtered_params %}{
      ' ' ~ k ~ '=' ~ params[k]}{% endfor %}"

[gcode_macro speed_at_layer]
description: Convenience macro to schedule a feedrate adjustment at the specified layer change. LAYER=next will cause the command to run at the next layer change. (SPEED parameter behaves the same as the M220 S parameter.)
  Usage: SPEED_AT_LAYER { HEIGHT=<pos> | LAYER=<layer> } SPEED=<percentage>
gcode:
  {% set SPEED = params.SPEED|default(0)|int %}
  {% if SPEED < 1 or SPEED > 500 %}
    {action_raise_error("SPEED[%i] parameter between 1 and 500 is required."
                        % SPEED)}
  {% endif %}
  GCODE_AT_LAYER {% for k in params|select('in',['HEIGHT','LAYER'])|list %}{
      ' ' ~ k ~ '=' ~ params[k] }{% endfor %} COMMAND="M220 S{SPEED|int}"
  # Dummy argument block for Mainsail
  {% set dummy = None if True else "
  {% set dummy = params.LAYER|default(layer number)|float %}
  {% set dummy = params.HEIGHT|default(Z height)|int %}
  {% set dummy = params.SPEED|default(percentage)|int %}
  " %} # End argument block for Mainsail

[gcode_macro flow_at_layer]
description: Convenience macro to schedule a flow percentage adjustment at the specified layer change. LAYER=next will cause the command to run at the next layer change. (FLOW parameter behaves the same as the M221 S parameter.)
  Usage: FLOW_AT_LAYER { HEIGHT=<pos> | LAYER=<layer> } FLOW=<percentage>
gcode:
  {% set FLOW = params.FLOW|default(0)|int %}
  {% if FLOW < 1 or FLOW > 500 %}
    {action_raise_error("FLOW[%i] parameter between 1 and 500 is required."
                        % FLOW)}
  {% endif %}
  GCODE_AT_LAYER {% for k in params|select('in',['HEIGHT','LAYER'])|list %}{
      ' ' ~ k ~ '=' ~ params[k] }{% endfor %} COMMAND="M221 S{FLOW|int}"
  # Dummy argument block for Mainsail
  {% set dummy = None if True else "
  {% set dummy = params.LAYER|default(layer number)|float %}
  {% set dummy = params.HEIGHT|default(Z height)|int %}
  {% set dummy = params.FLOW|default(percentage)|int %}
  " %} # End argument block for Mainsail

[gcode_macro fan_at_layer]
description: Convenience macro to schedule a fan adjustment at the specified layer change. LAYER=next will cause the command to run at the next layer change. See SET_FAN_SCALING for additional arguments.
  Usage: FAN_AT_LAYER { HEIGHT=<pos> | LAYER=<layer> } ...
gcode:
  # Dummy argument block for Mainsail
  {% set dummy = None if True else "
  {% set dummy = params.LAYER|default(layer number)|float %}
  {% set dummy = params.HEIGHT|default(Z height)|int %}
  {% set dummy = params.SCALE|default(1.0)|float %}
  {% set dummy = params.BUMP|default(0)|int %}
  {% set dummy = params.MAXIMUM|default(0)|int %}
  {% set dummy = params.MINIMUM|default(255)|int %}
  {% set dummy = params.SPEED|default(current speed)|int %}
  " %} # End argument block for Mainsail
  {% set filtered_params = params|reject('in',['HEIGHT','LAYER'])|list|sort %}
  {% if filtered_params|length == 0 %}
    {action_raise_error("No fan parameters provided.")}
  {% endif %}
  _CHECK_FAN_PARAMS{% for k in filtered_params %}{' '~k~'='~params[k]
    }{% endfor %}
  GCODE_AT_LAYER {% for k in params|select('in',['HEIGHT','LAYER'])|list %}{
      ' ' ~ k ~ '=' ~ params[k] }{% endfor
    %} COMMAND="SET_FAN_SCALING{% for k in filtered_params %}{
      ' ' ~ k ~ '=' ~ params[k]}{% endfor %}"

[gcode_macro heater_at_layer]
description: Convenience macro to schedule a heater adjustment at the specified layer change. LAYER=next will cause the command to run at the next layer change. See SET_HEATER_SCALING for additional arguments.
  Usage: HEATER_AT_LAYER { HEIGHT=<pos> | LAYER=<layer> } ...
gcode:
  # Dummy argument block for Mainsail
  {% set dummy = None if True else "
  {% set dummy = params.LAYER|default(layer number)|float %}
  {% set dummy = params.HEIGHT|default(Z height)|int %}
  {% set dummy = params.HEATER|default(e.g. extruder) %}
  {% set dummy = params.SCALE|default(1.0)|float %}
  {% set dummy = params.BUMP|default(0.0)|float %}
  {% set dummy = params.MAXIMUM|default(max_temp)|float %}
  {% set dummy = params.MINIMUM|default(min_temp)|float %}
  {% set dummy = params.TARGET|default(current target)|float %}
  " %} # End argument block for Mainsail
  {% set filtered_params = params|reject('in',['HEIGHT','LAYER'])|list|sort %}
  _CHECK_HEATER_PARAMS{% for k in filtered_params%}{' ' ~ k ~ '=' ~ params[k]
    }{% endfor %}
  GCODE_AT_LAYER{% for k in params|select('in',['HEIGHT','LAYER'])|list %}{
      ' ' ~ k ~ '=' ~ params[k] }{% endfor
    %} COMMAND="SET_HEATER_SCALING{% for k in filtered_params %}{
      ' ' ~ k ~ '=\\\"' ~ params[k]|replace('\\','\\\\')|replace('\'','\\\'')
                                   |replace('\"','\\\"') ~ '\\\"'
    }{% endfor %}"
