├── .github └── workflows │ └── package-with-pyinstaller.yaml ├── .gitignore ├── .vscode ├── launch.json ├── settings.json └── tasks.json ├── LICENSE.md ├── README.md ├── assets ├── MFM-header-blank.png ├── MFM-header-blank.webp ├── MFM-header-short.webp ├── MFM-header.webp ├── bambustudio-preview-line-type.jpg ├── bambustudio-printer-settings.jpg ├── dice-animated-preview.gif ├── gui_screenshot.png ├── header.svg ├── icon-plain.ico ├── icon.ico ├── icon.png ├── icon.svg ├── icon.svg.2025_02_15_19_05_20.0.svg ├── mfm-icon.webp ├── prusa_wipe_end_still_printing_details.PNG ├── prusaslicer-post-processing-script-option.png ├── tc_wipe_end_prime.PNG └── thumbnail-360p.png ├── mfm-configuration-options-setup.md ├── minimal-toolchange-gcode.md ├── minimal_toolchanges ├── bambu-a1-mini.gcode ├── bambu-a1.gcode ├── bambu-manual.gcode ├── bambu-x1-p1-series-107mm3-flush.gcode ├── bambu-x1-p1-series-150mm3-flush.gcode ├── bambu-x1-p1-series-long-retraction-107mm3-flush.gcode ├── extra-purge-150mm3.gcode ├── generic-manual-swap-m600.gcode ├── generic.gcode ├── prusa-xl-series.gcode └── testing │ ├── bs-a1-toolchange-notes.nc │ └── bs-toolchange-notes.nc ├── minimized-toolchanges-on-layer-change.md ├── premade_options ├── 1to1.json ├── README.md ├── USAofPlastic-dual-lowpoly-meters.json ├── USAofPlastic-dual-meters-Z200-rise3mm-no-snow.json ├── USAofPlastic-dual-meters-Z200-rise3mm.json ├── USAofPlastic-dual-meters-Z200.json ├── USAofPlastic-dual-meters.json └── USAofPlastic-single-meters.json ├── printer-setup.md ├── pyinstaller ├── entitlements.plist └── pyinstaller-build.sh ├── references └── Bambu-gcodes.md ├── sample_models ├── 4-cubes.gcode.3mf ├── AMS_calibration_v1_updated.3mf ├── AMS_calibration_v1_updated_Cali 4 filaments = full AMS.gcode.3mf ├── CA │ ├── config-usaofplastic-200zperc.json │ └── slice settings.txt ├── dual_color_dice │ ├── Dice.3mf │ ├── Die.stl │ ├── Dots.stl │ ├── config-dice-test.json │ ├── source.txt │ └── tests │ │ ├── dice_multiple_bambu_no_prime.gcode │ │ ├── dice_multiple_bambu_prime.gcode │ │ ├── dice_multiple_bambu_prime_adaptive_layer_height.gcode │ │ ├── dice_multiple_prusa_no_prime.gcode │ │ ├── dice_multiple_prusa_prime.gcode │ │ ├── dice_single_bambu_no_prime.gcode │ │ └── dice_single_bambu_prime.gcode └── tall-cuboid.3mf ├── slicer-setup.md ├── src ├── MFM-linux32.spec ├── MFM-win64.spec ├── gui.py ├── mfm │ ├── app_constants.py │ ├── configuration.py │ ├── extra_purge.py │ ├── line_ending.py │ ├── map_post_process.py │ ├── plate_sliced.py │ ├── printing_classes.py │ └── printing_constants.py └── mfm_cmd.py ├── terminal-setup.md └── tests └── slicer-post-processing-scripts-option.sh /.github/workflows/package-with-pyinstaller.yaml: -------------------------------------------------------------------------------- 1 | 2 | name: Package Application with Pyinstaller 3 | 4 | on: 5 | #push: 6 | # branches: [ main ] 7 | #pull_request: 8 | # branches: [ main ] 9 | workflow_dispatch: 10 | 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ubuntu-latest 16 | 17 | steps: 18 | 19 | - uses: actions/checkout@v4 20 | 21 | - name: Package Application - Windows 22 | uses: JackMcKew/pyinstaller-action-windows@main 23 | with: 24 | path: src 25 | spec: MFM-win64.spec 26 | 27 | - uses: actions/upload-artifact@v4 28 | with: 29 | name: MFM-win64 30 | path: src/dist/windows 31 | 32 | - name: Package Application - Linux 33 | uses: JackMcKew/pyinstaller-action-linux@python3.10 34 | with: 35 | path: src 36 | spec: MFM-linux32.spec 37 | 38 | - uses: actions/upload-artifact@v4 39 | with: 40 | name: MFM-linux32 41 | path: src/dist/linux 42 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | dist 2 | build 3 | *.pyc 4 | *.spec 5 | *.gcode -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | 8 | { 9 | "name": "Python Debugger: GUI", 10 | "type": "debugpy", 11 | "request": "launch", 12 | "program": "src/gui.py", 13 | "console": "integratedTerminal" 14 | }, 15 | { 16 | "name": "Python Debugger: CMD", 17 | "type": "debugpy", 18 | "request": "launch", 19 | "program": "src/mfm_cmd.py", 20 | "args": ["./sample_models/dual_color_dice/tests/dice_multiple_bambu_prime.gcode", "-o", "dice-export.gcode", "-c", "./sample_models/dual_color_dice/config-dice-test.json", "-t", "./minimal_toolchanges/bambu-x1-p1-series-long-retraction-107mm3-flush.gcode", "--disable=0"], 21 | "console": "integratedTerminal" 22 | }, 23 | { 24 | "name": "Python Debugger: CMD custom file", 25 | "type": "debugpy", 26 | "request": "launch", 27 | "program": "src/mfm_cmd.py", 28 | "args": ["C:/Users/ansonl/Downloads/dice-test.gcode", "-o", "dice-export.gcode", "-c", "./sample_models/dual_color_dice/config-dice-test.json", "-t", "./minimal_toolchanges/bambu-x1-p1-series-long-retraction-107mm3-flush.gcode"], 29 | "console": "integratedTerminal" 30 | }, 31 | { 32 | "name": "Python Debugger: CMD custom file2", 33 | "type": "debugpy", 34 | "request": "launch", 35 | "program": "src/mfm_cmd.py", 36 | "args": ["C:/Users/ansonl/development/topo-map-post-processing/column.gcode", "-o", "dice-export.gcode", "-c", "./premade_options/1to1.json", "-t", "./minimal_toolchanges/bambu-x1-p1-series-long-retraction-107mm3-flush.gcode"], 37 | "console": "integratedTerminal" 38 | }, 39 | { 40 | "name": "Python Debugger: CMD overwrite input", 41 | "type": "debugpy", 42 | "request": "launch", 43 | "program": "src/mfm_cmd.py", 44 | "args": ["dice-export.gcode", "-c", "./sample_models/dual_color_dice/config-dice-test.json", "-t", "./minimal_toolchanges/bambu-x1-p1-series-long-retraction-107mm3-flush.gcode"], 45 | "preLaunchTask": "Run tests", 46 | "console": "integratedTerminal" 47 | }, 48 | { 49 | "name": "Python Debugger: Current File", 50 | "type": "debugpy", 51 | "request": "launch", 52 | "program": "${file}", 53 | "console": "integratedTerminal" 54 | } 55 | ] 56 | } -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "[python]": { 3 | "editor.formatOnType": true, 4 | "editor.defaultFormatter": "ms-python.autopep8", 5 | "editor.insertSpaces": true, 6 | "editor.tabSize": 2, 7 | "editor.detectIndentation": true, 8 | } 9 | } -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | // See https://go.microsoft.com/fwlink/?LinkId=733558 3 | // for the documentation about the tasks.json format 4 | "version": "2.0.0", 5 | "tasks": [ 6 | { 7 | "label": "Run tests", 8 | "type": "shell", 9 | "command": "cp ./sample_models/dual_color_dice/tests/dice_multiple_bambu_prime_adaptive_layer_height.gcode ./dice-export.gcode", 10 | "group": "test", 11 | "presentation": { 12 | "reveal": "always", 13 | "panel": "shared" 14 | } 15 | } 16 | ] 17 | } -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published by 637 | the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![MFM header](assets/MFM-header-short.webp) 2 | 3 | # 3D G-code Map Feature Modifier (MFM) 4 | 5 | Add colored [isolines (contour lines/elevation lines)](https://en.wikipedia.org/wiki/Contour_line) and recolor [elevation ranges](https://desktop.arcgis.com/en/arcmap/latest/map/styles-and-symbols/working-with-color-ramps.htm) to [3D printable map models](https://ansonliu.com/maps/). **3D G-code Map Feature Modifier (MFM)** is a G-code Post Processor made for 3D topo map models but any 3D model can be recolored with 2 additional colors. 6 | 7 | [![Tutorial video](assets/thumbnail-360p.png)](https://www.youtube.com/watch?v=3BnW-QVdqKM "Add Elevation Contour Lines to Topo Maps - 3D Printing Guide!") 8 | : ↑ MFM Tutorial video 9 | 10 | **Use the latest version of MFM in 1 of the following 3 ways → [Getting Started](#getting-started)** 11 | 12 | - [MFM App](https://github.com/ansonl/mfm/releases) - Easiest to use and get started with a graphical user interface. Supports G-code and Plate Sliced 3MF (G-code embedded 3MF). Precompiled for Windows/Linux/Mac 13 | - [Integrated Post Processing Script in PrusaSlicer/Bambu Studio/Orca Slicer](https://github.com/ansonl/mfm/archive/refs/heads/master.zip) - Runs automatically after slicing. Supports G-code. 14 | - [Python Script](https://github.com/ansonl/mfm/archive/refs/heads/master.zip) - Runnable from command line. Supports G-code. 15 | 16 | **MFM adds additional features to the model by post processing sliced [3D printer G-code](https://marlinfw.org/meta/gcode/). 3D models and printing g-code can be recolored at either layer or individual feature/line level granularity.** 17 | 18 | - **Feature/Line Type Scoping** - Recoloring can be set to only affect specific printing feature/line types. *Recolor only the top surfaces or walls at certain heights with MFM!* 19 | 20 | - **G-code Feature Print Order Optimization** - Printed features are rearranged for faster, more consistent prints. Nozzle pressure is maintained and the number of toolchanges is minimized. 21 | 22 | - **Wipe/Coasting Compensation** - Existing Wipe/Coasting flow compensation generated by the slicer is retained even when g-code features are relocated. MFM has a customizable flush volume based on the color used and can do a **Long retraction after cut** to reduce filament waste. 23 | 24 | - **Prime Tower Aware** - Existing Prime Towers are reused for optimal filament flow and color flushing. *No prime tower or large prime tower? Both configurations are supported.* 25 | 26 | - **Slicer Compatibility** - Tested to be compatible with PrusaSlicer, Bambu Studio, and OrcaSlicer. Supports G-code and Plate Sliced 3MF. 27 | 28 | - **G-code Gadgets** - MFM's G-code parser has an advantage over other post-processers because it organizes existing G-code features into reusable segments similar to [gadgets](https://www.youtube.com/watch?v=ajGX7odA87k&t=1868s) which are rearranged and chained for printing efficiency. 29 | 30 | ![map feature gcode post processing screenshot](/assets/gui_screenshot.png) 31 | 32 | If you find this tool helpful, please leave feedback and consider supporting my development and 3D modeling with a [Printables](https://www.printables.com/@ansonl) "club membership" or a one-time [Paypal](https://paypal.me/0x80) contribution. 33 | 34 | My 3D topo and other models are on [MakerWorld](https://makerworld.com/en/@ansonl) and [Printables](https://www.printables.com/@ansonl). 35 | 36 | ## Current G-code flavors supported 37 | 38 | - Marlin 2 ([PrusaSlicer](https://github.com/prusa3d/PrusaSlicer)/[Bambu Studio](https://github.com/bambulab/BambuStudio)/[Orca Slicer](https://github.com/SoftFever/OrcaSlicer)) 39 | 40 | > Your slicer **must generate g-code with [Relative Extrusion](https://www.ideamaker.io/dictionaryDetail.html?name=Relative%20Extrusion&category_name=Printer%20Settings)**. PrusaSlicer, Bambu Studio, and Orca Slicer default to relative extrusion. Cura defaults to absolute extrusion and relative extrusion must be explicitly enabled. 41 | 42 | | Slicer | Tested Version | 43 | | --- | --- | 44 | | PrusaSlicer | 2.7.1 | 45 | | Bambu Studio | 1.8.2.56 | 46 | | Orca Slicer | 2.2.0 | 47 | | Cura | N/A | 48 | 49 | If you would like support for your printer or slicer G-code flavor to be added, please open an issue and test the G-code on your printer. 50 | 51 | ## Getting Started 52 | 53 | Set up your slicer and printer for MFM by following the steps on each page below: 54 | 55 | 1. [Slicer Setup](slicer-setup.md) 56 | 57 | 2. [MFM Command Setup](terminal-setup.md) ***(Post Processing and Command Line only)*** 58 | 59 | 3. [Minimal Toolchange G-code](minimal-toolchange-gcode.md) 60 | 61 | 4. [MFM Config Options](mfm-configuration-options-setup.md) 62 | 63 | 5. [MFM Usage and Printer Setup](printer-setup.md) 64 | 65 | ## Running MFM Post-processor 66 | 67 | After doing ALL above setup steps, you can run MFM as a Slicer Post-processor Script/Python Script or Graphical App: 68 | 69 | ![MFM 3D map model app](./assets/mfm-icon.webp) 70 | 71 | ### Graphical App (GUI) 72 | 73 | Download the [latest GUI release of MFM](https://github.com/ansonl/mfm/releases) and run `MFM.exe` to start MFM. 74 | 75 | 1. Select the [import Plate Sliced 3MF or G-code](./slicer-setup.md) that was exported from your slicer 76 | 77 | 2. Select the [MFM Options JSON](./mfm-configuration-options-setup.md) for your model. 78 | 79 | 3. Select the [toolchange G-code](./minimal-toolchange-gcode.md) for your printer. 80 | 81 | 4. Check if the exported 3MF or G-code file location looks right 82 | 83 | 5. Press **Post Process** 84 | 85 | > If a release of MFM has not been built for your OS, you can launch the GUI by [downloading the code](https://github.com/ansonl/mfm/archive/refs/heads/master.zip), navigate to the code folder in the command line and run `python src/gui.py`. 86 | 87 | ### Slicer Post-processor Script or Python Script in Command Line 88 | 89 | 1. Add `mfm_cmd.py` command with the [listed parameters](terminal-setup.md) to slicer **Post-processing Scripts** setting. 90 | 91 | 2. **Slice** your model. 92 | 93 | 3. **Export Plate Sliced 3MF/G-code file** under the Print button in the upper right or File menu. 94 | 95 | > If you update the MFM Options file, you may need to add/delete a space at the end of the slicer **Post-processing Scripts** setting to get the slicer to allow reslicing. 96 | 97 | > ⚠️ **Known bug: The first color change may be set to the wrong color.** If the first color change is incorrect, open the G-code in a text editor and search for `TX` (e.g. `T3`) where `X` is the wrong color index and **replace the first match of `T3` with `T0`** or desired base starting color index. This issue randomly occurs ~50% of the time due to a known 10+ year old Windows Python [bug](https://stackoverflow.com/questions/15934950/python-file-tell-giving-strange-numbers). 98 | 99 | ### Printing Your Processed 3MF/G-code 100 | 101 | See [Printer Setup](./printer-setup.md) for more options and important set up steps. 102 | 103 | #### Plate Sliced 3MF 104 | 105 | 1. Add missing filament entries to the `Metadata/slicer_info.config` file within the 3MF archive if using `Print` from the slicer. This is needed to avoid missing AMS mapping error on the printer. 106 | 107 | 2. Open the processed 3MF in your slicer and **Send/Print** to your printer. 108 | 109 | #### G-code 110 | 111 | Place the processed G-code file an SD card and put the SD card in your 3D printer or transfer the G-code file to your printer over a network. 112 | 113 | 114 | 115 | ## Frequently Asked Questions 116 | 117 | | Question | Solution | 118 | | --- | --- | 119 | | How do I convert a 3D model into G-code for printing? | After importing and slicing your model in a slicer software, export the 3D printer commands as [ASCII] G-code. MFM can be process and recolor this saved G-code file. | 120 | | MFM did not add or change any colors. | Setup your slicer for MFM through [Slicer Setup](slicer-setup.md) | 121 | | How can MFM recoloring be customized? | Read [Options](mfm-configuration-options-setup.md) for details. | 122 | | How can MFM be used with a material other than PLA and customized toolchange? | See [Minimal Toolchange G-code](minimal-toolchange-gcode.md) on recommendations on how to setup your own toolchange. I may add an option to set toolchange temperatures based on material in the future. Open an issue with your use cases. | 123 | | Incorrect color was printed even though previewing the exported G-code in the slicer shows the correct color slots being used. | Assign a different filament to each slot in the Bambu AMS. Every slot with a different color **must have a different color assigned** in AMS. Otherwise Bambu AMS [Autoswitch](https://forum.bambulab.com/t/automatic-material-switch-over/4189) feature may try to use a single slot's filament for a shared material and color between multiple slots. | 124 | | Mixed OS line endings in the same file will lead to G-code errors. MFM tries to auto detect the line ending used with first line ending found. | Select the correct line ending of your G-code instead of auto detect. Either convert the entire G-code file with Unix line endings to Windows line endings before post processing or generate the G-code on Windows. [Python on Windows does not handle Unix line endings correctly.](https://stackoverflow.com/questions/15934950/python-file-tell-giving-strange-numbers) | 125 | | Only one isoline interval and/or colored elevation range can be set. | Only one of each is exposed at the moment. The implementation could support more in the future if there is a use case. | 126 | | Support and Bridge features are not explicitly prioritized to pprint first. | I could prioritize printing certain features first in the future. Open an issue with your use cases for this. | 127 | 128 | ## Bug Reports 129 | 130 | Open an issue on Github. Please note the OS, Slicer, printer, and provide the 3D model, MFM Options JSON, toolchange G-code, and logs. 131 | 132 | Logs are written to your home directory `~` in the files `mfm-script.log` and `mfm-script-stderr.log`. 133 | 134 | ## License and Disclaimer 135 | 136 | GNU AFFERO GENERAL PUBLIC LICENSE v3.0 137 | 138 | Copyright © 2023-2024 Anson Liu 139 | 140 | THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 141 | -------------------------------------------------------------------------------- /assets/MFM-header-blank.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ansonl/mfm/bf46c307ceccc87d6437c17dcfb071cba703c5fe/assets/MFM-header-blank.png -------------------------------------------------------------------------------- /assets/MFM-header-blank.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ansonl/mfm/bf46c307ceccc87d6437c17dcfb071cba703c5fe/assets/MFM-header-blank.webp -------------------------------------------------------------------------------- /assets/MFM-header-short.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ansonl/mfm/bf46c307ceccc87d6437c17dcfb071cba703c5fe/assets/MFM-header-short.webp -------------------------------------------------------------------------------- /assets/MFM-header.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ansonl/mfm/bf46c307ceccc87d6437c17dcfb071cba703c5fe/assets/MFM-header.webp -------------------------------------------------------------------------------- /assets/bambustudio-preview-line-type.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ansonl/mfm/bf46c307ceccc87d6437c17dcfb071cba703c5fe/assets/bambustudio-preview-line-type.jpg -------------------------------------------------------------------------------- /assets/bambustudio-printer-settings.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ansonl/mfm/bf46c307ceccc87d6437c17dcfb071cba703c5fe/assets/bambustudio-printer-settings.jpg -------------------------------------------------------------------------------- /assets/dice-animated-preview.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ansonl/mfm/bf46c307ceccc87d6437c17dcfb071cba703c5fe/assets/dice-animated-preview.gif -------------------------------------------------------------------------------- /assets/gui_screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ansonl/mfm/bf46c307ceccc87d6437c17dcfb071cba703c5fe/assets/gui_screenshot.png -------------------------------------------------------------------------------- /assets/icon-plain.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ansonl/mfm/bf46c307ceccc87d6437c17dcfb071cba703c5fe/assets/icon-plain.ico -------------------------------------------------------------------------------- /assets/icon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ansonl/mfm/bf46c307ceccc87d6437c17dcfb071cba703c5fe/assets/icon.ico -------------------------------------------------------------------------------- /assets/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ansonl/mfm/bf46c307ceccc87d6437c17dcfb071cba703c5fe/assets/icon.png -------------------------------------------------------------------------------- /assets/icon.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 19 | 39 | 41 | 49 | 54 | 60 | 65 | 70 | 76 | 77 | 78 | 82 | 90 | 95 | 100 | 106 | 112 | 118 | 122 | 127 | 132 | 133 | 138 | MFM 150 | 151 | 152 | 153 | -------------------------------------------------------------------------------- /assets/icon.svg.2025_02_15_19_05_20.0.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 19 | 39 | 41 | 49 | 54 | 60 | 65 | 70 | 76 | 77 | 78 | 82 | 90 | 95 | 100 | 106 | 112 | 118 | 122 | 127 | 132 | 133 | 138 | MFM 150 | 151 | 152 | 153 | -------------------------------------------------------------------------------- /assets/mfm-icon.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ansonl/mfm/bf46c307ceccc87d6437c17dcfb071cba703c5fe/assets/mfm-icon.webp -------------------------------------------------------------------------------- /assets/prusa_wipe_end_still_printing_details.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ansonl/mfm/bf46c307ceccc87d6437c17dcfb071cba703c5fe/assets/prusa_wipe_end_still_printing_details.PNG -------------------------------------------------------------------------------- /assets/prusaslicer-post-processing-script-option.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ansonl/mfm/bf46c307ceccc87d6437c17dcfb071cba703c5fe/assets/prusaslicer-post-processing-script-option.png -------------------------------------------------------------------------------- /assets/tc_wipe_end_prime.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ansonl/mfm/bf46c307ceccc87d6437c17dcfb071cba703c5fe/assets/tc_wipe_end_prime.PNG -------------------------------------------------------------------------------- /assets/thumbnail-360p.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ansonl/mfm/bf46c307ceccc87d6437c17dcfb071cba703c5fe/assets/thumbnail-360p.png -------------------------------------------------------------------------------- /mfm-configuration-options-setup.md: -------------------------------------------------------------------------------- 1 | # MFM Configuration 2 | 3 | **Use Premade Options in [premade_options](./premade_options/) for the [3D printable map models](https://ansonliu.com/maps/) collection.** 4 | 5 | Options values are provided for each [3D printable map model](https://ansonliu.com/maps/) on the [specifications page](https://ansonliu.com/maps/specifications/). 6 | 7 | > You can create 1:1 isolines without scaling applied by referencing `1to1.json`. This is useful for non-map models. 8 | 9 | You can test configurations with the sample dual color dice or tall cuboid model and G-code in the `sample_models` folder. 10 | 11 | The options file is formatted as a JSON dictionary with the following keys. 12 | 13 | ## Color Assignment 14 | 15 | Filament/color positions are 0-based. The first position is represented by `0`. The recommended filament order is: 16 | 17 | | Physical Position (left to right) → | 1 | 2 | 3 | 4 | 18 | | -------- | ------- | ------- | ------- | ------ | 19 | | 0-based tool index in software | `0` | `1` | `2` | `3` | 20 | | **Purpose** | Primary (base) | Secondary (hydro) | *Isoline (contour line)* | *Elevation Color Change* | 21 | 22 | ## Example Options file with Isoline and Elevation Change features 23 | 24 | ```json 25 | { 26 | "modelToRealWorldDefaultUnits": 1000, 27 | "modelOneToNVerticalScale": 500000, 28 | "modelSeaLevelBaseThickness": 1.8, 29 | "realWorldIsolineElevationInterval": 500, 30 | "realWorldIsolineElevationStart": 500, 31 | "realWorldIsolineElevationEnd": 30000, 32 | "modelIsolineHeight": 0.1, 33 | "isolineColorIndex": 2, 34 | "isolineColorFeatureTypes": [ 35 | "Outer wall", 36 | "External perimeter" 37 | ], 38 | "realWorldElevationReplacementColorStart": 2000, 39 | "realWorldElevationReplacementColorEnd": 30000, 40 | "replacementColorIndex": 3, 41 | "replacementOriginalColorIndex": 0, 42 | "extraPurgePreviousColors": [2] 43 | } 44 | ``` 45 | 46 | A map processed with this set of options will have the following appearance: 47 | 48 | - Map elevation (Z) scale is 1:500000. 49 | 50 | - Sea level start at 1.8mm in printed height. 51 | 52 | - The first isoline (contour line) will start at 500m of real world height and future isolines will appear at 500m intervals (1000, 1500, 2000, etc). The isolines will stop at 30000m which is high enough to mean that the isolines will not stop on a normal map. The isoline color will use the filament loaded at index 2. 53 | - The isoline color will affect all wall/perimeter features. 54 | 55 | - High elevation (snow line) replacement color will start at 2000m and end at 30000m. All uses of the filament at index 0 will be replaced with filament at index 3 when printing in the replacement color range. 56 | 57 | - Whenever a color swap (toolchange) has the previous color of index 2, extra purging (150mm³) will be done. 58 | 59 | ## All Options 60 | 61 | ### Required Options 62 | 63 | | Key | Value | Cardinality | Description | 64 | | -------- | ------- | ------- | ------- | 65 | | `modelToRealWorldDefaultUnits` | *(model-units:real-world-units)* | 1 | Model units to Real World units scale. **Model Gcode units usually default to millimeters.** Use one of the two below computed values. | 66 | | `modelToRealWorldDefaultUnits` (millimeters:meters) | `1000` | 1 | Use `1000` if you specify real world units in meters. | 67 | | `modelToRealWorldDefaultUnits` (millimeters:feet) | `304.8` | 1 | Use `304.8` if you specify real world units in feet. | 68 | | `modelOneToNVerticalScale` | *(real-world-scale:model-scale)* | 1 | Model to Real World scale *(E.g. 1:500000 = 0.1mm:50m)* | 69 | | `modelSeaLevelBaseThickness` | `float` | 1 | The model height at sea level (0 m) in model units. This is used as zero elevation for the isoline and elevation color change. *(E.g. 1.8 = 1.8mm)*| 70 | 71 | ### Isoline Options 72 | 73 | | Key | Value | Cardinality | Description | 74 | | -------- | ------- | ------- | ------- | 75 | | `realWorldIsolineElevationInterval` | `float` | 1 | Isoline elevation interval in real world units. | 76 | | `realWorldIsolineElevationStart` | `float` | 1 | Isoline starting elevation in real world units. | 77 | | `realWorldIsolineElevationEnd` | `float` | 1 | Isoline ending elevation in real world units. | 78 | | `modelIsolineHeight` | `float` | 1 | Isoline display height in model units. | 79 | | `isolineColorIndex` | `integer` | 1 | Isoline filament/color loaded position. Recommended index is 2 (third slot). | 80 | | `isolineColorFeatureTypes` | `[string]` | ≥0 | List of printing object feature/line types (extrusion roles) to recolor at isoline elevations. Empty array will recolor all feature types. Feature types are case sensitive. | 81 | 82 | ### Elevation Change Options 83 | 84 | | Key | Value | Cardinality | Description | 85 | | -------- | ------- | ------- | ------- | 86 | | `realWorldElevationReplacementColorStart` | `float` | 1 | Elevation based replacement color start elevation in real world units. | 87 | | `realWorldElevationReplacementColorEnd` | `float` | 1 | Elevation based replacement color end elevation in real world units. | 88 | | `replacementColorIndex` | `integer` | 1 | Elevation based replacement color filament/color loaded position. Recommended index is 3 (fourth slot). | 89 | | `replacementOriginalColorIndex` | `integer` | 1 | Elevation based replacement color **replaced** filament/color loaded position. Recommended index is 0 (first slot). | 90 | 91 | ### Purge/Flush Options 92 | 93 | | Key | Value | Cardinality | Description | 94 | | -------- | ------- | ------- | ------- | 95 | | `extraPurgePreviousColors` | `[int]` | ≥0 | Tool indices to add extra purging to when that tool is the previous tool in a toolchange. | 96 | 97 | ### Feature Types (Extrusion Roles) 98 | 99 | 3D printed Feature Types are different categories used to define printing order and settings of printing travel and extrusion movements. 100 | 101 | - `wall`s are vertical features. Wall/Perimeter on [Cura](https://support.makerbot.com/s/article/1837650983225) and [PrusaSlicer](https://help.prusa3d.com/article/layers-and-perimeters_1748#perimeters). 102 | - `surface`s are the horizontal features that make up the top and bottom layers of 3D objects. Surface/top and bottom on [Cura](https://support.makerbot.com/s/article/1667410780032) and [PrusaSlicer](https://help.prusa3d.com/article/layers-and-perimeters_1748#solid-layers-top-bottom) 103 | - `infill`s are the interior features. Infill on [Cura](https://support.makerbot.com/s/article/1667411002588) and [PrusaSlicer](*https://help.prusa3d.com/article/infill_42) 104 | - `support` is an extra structure generated by the slicer to hold up overhanging parts of the model against gravity when printing. You do not need supports enabled when printing the 3D maps. Support on [Cura](https://support.ultimaker.com/s/article/1667417606331) and [PrusaSlicer](https://help.prusa3d.com/article/organic-supports_480131) 105 | - `prime tower` is an extra structure generated by the slicer to get consistent flow after a toolchange. Depending on the colors you use and amount of small features in the model, you can disable or reduce the Prime Tower size. Prime/Wipe tower on [Cura](https://support.makerbot.com/s/article/1667418002331) and [PrusaSlicer](https://help.prusa3d.com/article/wipe-tower_125010) 106 | 107 | ![mfm slicer line type preview](assets/bambustudio-preview-line-type.jpg) 108 | 109 | Modifying the feature types colored at an isoline elevation will drastically the isoline's visual appearance. Different materials and colors will adhere to each other differently so strength can be affected. 110 | 111 | Feature Types vary depending on the slicer used to generate the G-code. You can view supported feature types for your slicer by previewing your G-code and setting the *Color scheme* to `Line Type`. [PrusaSlicer and BambuStudio extrusion roles source](https://github.com/prusa3d/PrusaSlicer/blob/97c3679a37e9ede812432e25a096e4906110d441/src/libslic3r/GCode/GCodeProcessor.cpp#L2486). 112 | 113 | MFM rearranges printing order of features to reduce the number of toolchanges a layer. Isoline recolored features are printed first. This may affect print quality of supported parts but you can work around that by specifying the `Support` and `Bridge` feature types for recoloring. 114 | 115 | ### Filament Color data in G-code (Bambu/Orca) 116 | 117 | If the final post processed G-code preview does not seem to show the right colors, you can set the filament color data in the `;CONFIG_BLOCK_START` of the G-code. 118 | 119 | ```gcode 120 | ; filament_colour = #00FF80;#0080FF;#FFFF00;#FF0000 121 | ``` 122 | 123 | This may happen when the tool indexes are not populated with colors in the slicer prior to exporting the G-code. 124 | 125 | Slicers may try to use the previous saved colors from your last opened project for the preview to overwrite the G-code color data. Assign the desired in a project and close then reopen and preview the G-code to see the updated colors. 126 | -------------------------------------------------------------------------------- /minimal-toolchange-gcode.md: -------------------------------------------------------------------------------- 1 | # MFM Minimal Toolchange G-code File 2 | 3 | You must supply MFM a file containing a minimal toolchange G-code sequence for your printer. 4 | 5 | This toolchange is used when a toolchange is needed but the existing Prime Tower and toolchange G-code cannot be located or used. 6 | 7 | ## Premade Minimal Toolchanges 8 | 9 | > **Note:** Premade minimal toolchanges' temperatures are set up for PLA material. Modify the `M104`, `M109`, and `M620.1` command temperature parameters with your material temperature settings. 10 | 11 | Premade minimal toolchange files can be downloaded from the [`minimal_toolchanges`](minimal_toolchanges/) directory. 12 | 13 | Current premade printer toolchanges: 14 | 15 | - Generic (firmware managed tool change with `T`) 16 | - Generic Manual (manual filament swap, requires `M600` filament change support in firmware) 17 | - Bambu X1/P1 series 18 | - ***Latest Recommended:*** 19 | - **Long retract on cut** enabled - `bambu-x1-p1-series-long-retraction-107mm3-flush.gcode` 20 | - No long retract - `bambu-x1-p1-series-107mm3-flush.gcode` 21 | - Bambu A1 22 | - Bambu A1 mini 23 | - Prusa XL 24 | 25 | Every 3D printer is different and you should manually verify that the provided G-code is compatible with your printer. I recommend you create your own minimal toolchange G-code using the information in the below section and the premade G-code as a reference. 26 | 27 | ## Requirements to Create a Minimal Toolchange 28 | 29 | 1. The location for next tool index (the tool/filament/color being switched to) **must** be replaced with `XX` in this text file. MFM will replace all instances of `XX` with the next tool index. *E.g. When switching to extruder 1, `TXX` will become `T1`* 30 | 31 | 1. The location for the previous tool index **must** be replaced with `YY` in this text file. This is only needed for G-code that needs the previous tool index e.g. `M620.11`. 32 | 33 | 1. MFM will insert extra purge G-code if needed after any occurance of `; EXTRA_PURGE_INSERTION`. 34 | 35 | 1. It is recommended to convert movement coordinates that change depending on the current print progress from absolute to relative. 36 | 37 | 1. All movements that are specific to a specific model must be removed or generalized to not interfere with printed models possibly being located anywhere in the print volume. 38 | 39 | 1. If possible, it is recommended to restore the printing state's original Z coordinate at the end of the minimal toolchange. MFM will add G-code to restore the original X/Y/Z position and acceleration values after the toolchange. 40 | 41 | > **TODO:** Fan speed is currently hardcoded to 78% at the end of the X1/P1 minimal toolchange. I may track fan speed to be restored in the future. 42 | 43 | ## Toolchange Movements in Firmware or Slicer? 44 | 45 | The movement commands to perform the toolchange can be set and managed within firmware or the slicer. 46 | 47 | I highly recommend setting your toolchange G-code within firmware as a macro in Marlin or Klipper. The firmware will handle both the hotend offset and toolchange which simplifies the process. Then all you need to do to perform a toolchange is write/send the [`T` command](https://marlinfw.org/docs/gcode/T.html) with the extruder index after it like `T0` or `T1`. 48 | 49 | With toolchange movements properly setup in firmware, a toolchange becomes as simple as the below. 50 | 51 | ```gcode 52 | ; Single-extruder Toolchange 53 | TXX 54 | 55 | ; Multi-extruder Toolchange 56 | M104 S170 ; Set the active hotend to the standby temperature 57 | M104 S210 TXX ; Set the next hotend index to the print/purge temperature 58 | TXX ; Execute the tool change 59 | M109 S210 ; Wait for next (now active) hotend to warm up 60 | ``` 61 | 62 | A properly set up tool change g-code in firmware example for a multi-extruder 3D printer can be seen for the Ultimaker DXUv2 [here](https://github.com/ansonl/DXU/blob/master/Firmware/README.md#toolchange-g-code). 63 | 64 | ## Contributing 65 | 66 | If you would like to contribute your tested toolchange G-Code or have feedback, please make an issue or pull request on this Github repo. 67 | -------------------------------------------------------------------------------- /minimal_toolchanges/bambu-a1-mini.gcode: -------------------------------------------------------------------------------- 1 | ; MFM MINIMAL A1MINI TOOLCHANGE START 2 | M106 P3 S0 3 | G392 S0 4 | M1007 S0 5 | M620 SXXA 6 | M204 S9000 7 | 8 | G17 9 | ;G2 ZINITIALLIFT I0.86 J0.86 P1 F10000 ; spiral lift a little from second lift 10 | G2 I0.86 J0.86 P1 F10000 ; spiral lift a little from second lift 11 | G91 12 | G1 Z0.4 13 | G90 14 | M83 15 | 16 | G91 17 | G1 Z2.6 F1200 18 | G90 19 | M83 20 | 21 | M400 22 | M106 P1 S0 23 | M106 P2 S0 24 | 25 | M104 S220 26 | 27 | 28 | G1 X180 F18000 29 | ; 30 | M620.1 E F523 T240 31 | TXX 32 | M620.1 E F523 T240 33 | 34 | G1 Y90 F9000 35 | 36 | 37 | M400 38 | 39 | G92 E0 40 | 41 | ; FLUSH_START 42 | ; always use highest temperature to flush 43 | M400 44 | M1002 set_filament_type:UNKNOWN 45 | M109 S240 46 | M106 P1 S60 47 | 48 | G1 E23.7 F523 ; do not need pulsatile flushing for start part 49 | G1 E0.690105 F50 50 | G1 E7.9362 F523 51 | G1 E0.690105 F50 52 | G1 E7.9362 F523 53 | G1 E0.690105 F50 54 | G1 E7.9362 F523 55 | G1 E0.690105 F50 56 | G1 E7.9362 F523 57 | 58 | ; FLUSH_END 59 | G1 E-2 F1800 60 | G1 E2 F300 61 | M400 62 | M1002 set_filament_type:PLA 63 | 64 | 65 | 66 | ; WIPE 67 | M400 68 | M106 P1 S178 69 | M400 S3 70 | G1 X-3.5 F18000 71 | G1 X-13.5 F3000 72 | G1 X-3.5 F18000 73 | G1 X-13.5 F3000 74 | G1 X-3.5 F18000 75 | G1 X-13.5 F3000 76 | M400 77 | M106 P1 S0 78 | 79 | 80 | 81 | M106 P1 S60 82 | ; FLUSH_START 83 | G1 E10.4769 F523 84 | G1 E1.1641 F50 85 | G1 E10.4769 F523 86 | G1 E1.1641 F50 87 | G1 E10.4769 F523 88 | G1 E1.1641 F50 89 | G1 E10.4769 F523 90 | G1 E1.1641 F50 91 | G1 E10.4769 F523 92 | G1 E1.1641 F50 93 | ; FLUSH_END 94 | G1 E-2 F1800 95 | G1 E2 F300 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | M400 107 | M106 P1 S60 108 | M109 S220 109 | G1 E5 F523 ;Compensate for filament spillage during waiting temperature 110 | M400 111 | G92 E0 112 | G1 E-2 F1800 113 | M400 114 | M106 P1 S178 115 | M400 S3 116 | G1 X-3.5 F18000 117 | G1 X-13.5 F3000 118 | G1 X-3.5 F18000 119 | G1 X-13.5 F3000 120 | G1 X-3.5 F18000 121 | G1 X-13.5 F3000 122 | G1 X-3.5 F18000 123 | M400 124 | 125 | M106 P1 S0 126 | 127 | M204 S6000 128 | 129 | 130 | M621 SXXA 131 | G392 S0 132 | M1007 S1 133 | 134 | M106 S186.15 135 | M106 P2 S178 136 | M104 S220 ; set nozzle temperature 137 | 138 | M106 P3 S200 139 | 140 | ;G1 E-.04 F1800 141 | 142 | G91 143 | G1 Z-2.6 F30000 144 | G90 145 | M83 146 | 147 | ;G91 148 | ;G1 Z-0.4 149 | ;G90 150 | ;M83 151 | 152 | ;G1 E2 F1800 153 | M204 S5000 154 | ; MFM MINIMAL TOOLCHANGE END -------------------------------------------------------------------------------- /minimal_toolchanges/bambu-a1.gcode: -------------------------------------------------------------------------------- 1 | ; MFM MINIMAL A1 TOOLCHANGE START 2 | M106 P3 S0 3 | G392 S0 4 | M620 SXXA 5 | M204 S9000 6 | 7 | G17 8 | ;G2 ZINITIALLIFT I0.86 J0.86 P1 F10000 ; spiral lift a little from second lift 9 | G2 I0.86 J0.86 P1 F10000 ; spiral lift a little from second lift 10 | G91 11 | G1 Z0.4 12 | G90 13 | M83 14 | 15 | G91 16 | G1 Z2.6 F1200 17 | G90 18 | M83 19 | 20 | M400 21 | M106 P1 S0 22 | M106 P2 S0 23 | 24 | M104 S220 25 | 26 | 27 | G1 X267 F18000 28 | ; 29 | M620.1 E F523 T240 30 | TXX 31 | M620.1 E F523 T240 32 | 33 | G1 Y128 F9000 34 | 35 | 36 | M400 37 | 38 | G92 E0 39 | 40 | ; FLUSH_START 41 | ; always use highest temperature to flush 42 | M400 43 | M1002 set_filament_type:UNKNOWN 44 | M109 S240 45 | M106 P1 S60 46 | 47 | G1 E23.7 F523 ; do not need pulsatile flushing for start part 48 | G1 E0.690105 F50 49 | G1 E7.9362 F523 50 | G1 E0.690105 F50 51 | G1 E7.9362 F523 52 | G1 E0.690105 F50 53 | G1 E7.9362 F523 54 | G1 E0.690105 F50 55 | G1 E7.9362 F523 56 | 57 | ; FLUSH_END 58 | G1 E-2 F1800 59 | G1 E2 F300 60 | M400 61 | M1002 set_filament_type:PLA 62 | 63 | 64 | 65 | ; WIPE 66 | M400 67 | M106 P1 S178 68 | M400 S3 69 | G1 X-38.5 F18000 70 | G1 X-48.5 F3000 71 | G1 X-38.5 F18000 72 | G1 X-48.5 F3000 73 | G1 X-38.5 F18000 74 | G1 X-48.5 F3000 75 | M400 76 | M106 P1 S0 77 | 78 | 79 | 80 | M106 P1 S60 81 | ; FLUSH_START 82 | G1 E10.4769 F523 83 | G1 E1.1641 F50 84 | G1 E10.4769 F523 85 | G1 E1.1641 F50 86 | G1 E10.4769 F523 87 | G1 E1.1641 F50 88 | G1 E10.4769 F523 89 | G1 E1.1641 F50 90 | G1 E10.4769 F523 91 | G1 E1.1641 F50 92 | ; FLUSH_END 93 | G1 E-2 F1800 94 | G1 E2 F300 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | M400 106 | M106 P1 S60 107 | M109 S220 108 | G1 E6 F523 ;Compensate for filament spillage during waiting temperature 109 | M400 110 | G92 E0 111 | G1 E-2 F1800 112 | M400 113 | M106 P1 S178 114 | M400 S3 115 | G1 X-38.5 F18000 116 | G1 X-48.5 F3000 117 | G1 X-38.5 F18000 118 | G1 X-48.5 F3000 119 | G1 X-38.5 F18000 120 | G1 X-48.5 F3000 121 | G1 X-38.5 F18000 122 | M400 123 | G1 Z10.28 F3000 124 | M106 P1 S0 125 | 126 | M204 S6000 127 | 128 | 129 | M621 SXXA 130 | G392 S1 131 | 132 | M106 S183.6 133 | M106 P2 S178 134 | M104 S220 ; set nozzle temperature 135 | 136 | M106 P3 S200 137 | 138 | ;G1 E-.04 F1800 139 | 140 | G91 141 | G1 Z-2.6 F30000 142 | G90 143 | M83 144 | 145 | ;G91 146 | ;G1 Z-0.4 147 | ;G90 148 | ;M83 149 | 150 | ;G1 E2 F1800 151 | M204 S5000 152 | ; MFM MINIMAL TOOLCHANGE END -------------------------------------------------------------------------------- /minimal_toolchanges/bambu-manual.gcode: -------------------------------------------------------------------------------- 1 | ; MFM MINIMAL BAMBU MANUAL TOOLCHANGE START 2 | M106 P3 S0 3 | M400 U1 4 | ; MFM MINIMAL TOOLCHANGE END -------------------------------------------------------------------------------- /minimal_toolchanges/bambu-x1-p1-series-107mm3-flush.gcode: -------------------------------------------------------------------------------- 1 | ; MFM MINIMAL X1/P1 TOOLCHANGE START 2 | ; 24DEC24 3 | M220 S100 4 | M106 P3 S0 5 | G1 E-.1 F1800 6 | 7 | M620 SXXA 8 | M204 S9000 9 | 10 | G17 11 | ;G2 ZINITIALLIFT I0.86 J0.86 P1 F10000 ; spiral lift a little from second lift 12 | G91 13 | G2 Z0.4 I0.86 J0.86 P1 F10000 ; spiral lift a little from second lift 14 | G90 15 | M83 16 | 17 | G91 18 | G1 Z2.6 F1200 19 | G90 20 | M83 21 | 22 | G1 X70 F21000 23 | G1 Y245 24 | G1 Y265 F3000 25 | M400 26 | M106 P1 S0 27 | M106 P2 S0 28 | 29 | M104 S220 30 | 31 | 32 | M620.11 S0 33 | 34 | M400 35 | G1 X90 36 | G1 Y255 F4000 37 | G1 X100 F5000 38 | G1 X120 F15000 39 | G1 X20 Y50 F21000 40 | G1 Y-3 41 | 42 | M620.1 E F299 T240 43 | TXX 44 | M620.1 E F299 T240 45 | 46 | 47 | 48 | M620.11 S0 49 | 50 | G92 E0 51 | 52 | M83 53 | ; FLUSH_START 54 | ; always use highest temperature to flush 55 | M400 56 | 57 | M109 S240 58 | 59 | 60 | G1 E23.7 F299 ; do not need pulsatile flushing for start part 61 | G1 E0.415709 F50 62 | G1 E4.78065 F299 63 | G1 E0.415709 F50 64 | G1 E4.78065 F299 65 | G1 E0.415709 F50 66 | G1 E4.78065 F299 67 | G1 E0.415709 F50 68 | G1 E4.78065 F299 69 | 70 | ; FLUSH_END 71 | G1 E-2 F1800 72 | G1 E2 F300 73 | 74 | ; EXTRA_PURGE_INSERTION 75 | 76 | ; FLUSH_START 77 | M400 78 | M109 S220 79 | G1 E2 F523 ;Compensate for filament spillage during waiting temperature 80 | ; FLUSH_END 81 | M400 82 | G92 E0 83 | G1 E-2 F1800 84 | M106 P1 S255 85 | M400 S3 86 | 87 | G1 X70 F5000 88 | G1 X90 F3000 89 | G1 Y255 F4000 90 | G1 X105 F5000 91 | G1 Y265 92 | G1 X70 F10000 93 | G1 X100 F5000 94 | G1 X70 F10000 95 | G1 X100 F5000 96 | 97 | G1 X70 F10000 98 | G1 X80 F15000 99 | G1 X60 100 | G1 X80 101 | G1 X60 102 | G1 X80 ; shake to put down garbage 103 | G1 X100 F5000 104 | G1 X165 F15000; wipe and shake 105 | G1 Y256 ; move Y to aside, prevent collision 106 | M400 107 | 108 | M204 S10000 109 | 110 | 111 | M621 SXXA 112 | 113 | M106 S200 ; resume fan speed 114 | M106 P2 S0 ; turn off aux fan, leave P3 chamber fan unchanged 115 | 116 | ;G91 117 | ;G1 Z-2.6 F30000 118 | ;G90 119 | ;M83 120 | 121 | ;G91 122 | ;G1 Z-0.4 123 | ;G90 124 | ;M83 125 | 126 | ; MFM will lower Z to original position and extrude E2 during pre-feature restore 127 | 128 | M204 S5000 129 | ; MFM MINIMAL TOOLCHANGE END -------------------------------------------------------------------------------- /minimal_toolchanges/bambu-x1-p1-series-150mm3-flush.gcode: -------------------------------------------------------------------------------- 1 | ; MFM MINIMAL X1/P1 TOOLCHANGE START 2 | ; 24DEC24 3 | M220 S100 4 | M106 P3 S0 5 | G1 E-.1 F1800 6 | 7 | M620 SXXA 8 | M204 S9000 9 | 10 | G17 11 | ;G2 ZINITIALLIFT I0.86 J0.86 P1 F10000 ; spiral lift a little from second lift 12 | G91 13 | G2 Z0.4 I0.86 J0.86 P1 F10000 ; spiral lift a little from second lift 14 | G90 15 | M83 16 | 17 | G91 18 | G1 Z2.6 F1200 19 | G90 20 | M83 21 | 22 | G1 X70 F21000 23 | G1 Y245 24 | G1 Y265 F3000 25 | M400 26 | M106 P1 S0 27 | M106 P2 S0 28 | 29 | M104 S220 30 | 31 | 32 | M620.11 S0 33 | 34 | M400 35 | G1 X90 36 | G1 Y255 F4000 37 | G1 X100 F5000 38 | G1 X120 F15000 39 | G1 X20 Y50 F21000 40 | G1 Y-3 41 | 42 | M620.1 E F299 T240 43 | TXX 44 | M620.1 E F299 T240 45 | 46 | 47 | 48 | M620.11 S0 49 | 50 | G92 E0 51 | 52 | M83 53 | ; FLUSH_START 54 | ; always use highest temperature to flush 55 | M400 56 | 57 | M109 S240 58 | 59 | 60 | G1 E23.7 F299 ; do not need pulsatile flushing for start part 61 | G1 E0.773255 F50 62 | G1 E8.89243 F299 63 | G1 E0.773255 F50 64 | G1 E8.89243 F299 65 | G1 E0.773255 F50 66 | G1 E8.89243 F299 67 | G1 E0.773255 F50 68 | G1 E8.89243 F299 69 | 70 | ; FLUSH_END 71 | G1 E-2 F1800 72 | G1 E2 F300 73 | 74 | ; FLUSH_START 75 | M400 76 | M109 S220 77 | G1 E2 F523 ;Compensate for filament spillage during waiting temperature 78 | ; FLUSH_END 79 | M400 80 | G92 E0 81 | G1 E-2 F1800 82 | M106 P1 S255 83 | M400 S3 84 | 85 | G1 X70 F5000 86 | G1 X90 F3000 87 | G1 Y255 F4000 88 | G1 X105 F5000 89 | G1 Y265 90 | G1 X70 F10000 91 | G1 X100 F5000 92 | G1 X70 F10000 93 | G1 X100 F5000 94 | 95 | G1 X70 F10000 96 | G1 X80 F15000 97 | G1 X60 98 | G1 X80 99 | G1 X60 100 | G1 X80 ; shake to put down garbage 101 | G1 X100 F5000 102 | G1 X165 F15000; wipe and shake 103 | G1 Y256 ; move Y to aside, prevent collision 104 | M400 105 | 106 | M204 S10000 107 | 108 | 109 | M621 SXXA 110 | 111 | M106 S200 ; resume fan speed 112 | M106 P2 S0 ; turn off aux fan, leave P3 chamber fan unchanged 113 | 114 | ;G91 115 | ;G1 Z-2.6 F30000 116 | ;G90 117 | ;M83 118 | 119 | ;G91 120 | ;G1 Z-0.4 121 | ;G90 122 | ;M83 123 | 124 | ; MFM will lower Z to original position and extrude E2 during pre-feature restore 125 | 126 | M204 S5000 127 | ; MFM MINIMAL TOOLCHANGE END -------------------------------------------------------------------------------- /minimal_toolchanges/bambu-x1-p1-series-long-retraction-107mm3-flush.gcode: -------------------------------------------------------------------------------- 1 | ; MFM MINIMAL X1/P1 TOOLCHANGE START 2 | ; 24DEC24 3 | M220 S100 4 | M106 P3 S0 5 | G1 E-.1 F1800 6 | 7 | M620 SXXA 8 | M204 S9000 9 | 10 | G17 11 | ;G2 ZINITIALLIFT I0.86 J0.86 P1 F10000 ; spiral lift a little from second lift 12 | G91 13 | G2 Z0.4 I0.86 J0.86 P1 F10000 ; spiral lift a little from second lift 14 | G90 15 | M83 16 | 17 | G91 18 | G1 Z2.6 F1200 19 | G90 20 | M83 21 | 22 | G1 X70 F21000 23 | G1 Y245 24 | G1 Y265 F3000 25 | M400 26 | M106 P1 S0 27 | M106 P2 S0 28 | 29 | M104 S220 30 | 31 | 32 | M620.11 S1 IYY E-12 F299 33 | 34 | M400 35 | G1 X90 36 | G1 Y255 F4000 37 | G1 X100 F5000 38 | G1 X120 F15000 39 | G1 X20 Y50 F21000 40 | G1 Y-3 41 | 42 | M620.1 E F299 T240 43 | TXX 44 | M620.1 E F299 T240 45 | 46 | 47 | 48 | M620.11 S1 IYY E12 F299 49 | M628 S1 50 | G92 E0 51 | G1 E12 F299 52 | M400 53 | M629 S1 54 | 55 | G92 E0 56 | 57 | M83 58 | ; FLUSH_START 59 | ; always use highest temperature to flush 60 | M400 61 | 62 | M109 S240 63 | 64 | 65 | G1 E23.7 F299 ; do not need pulsatile flushing for start part 66 | G1 E0.415709 F50 67 | G1 E4.78065 F299 68 | G1 E0.415709 F50 69 | G1 E4.78065 F299 70 | G1 E0.415709 F50 71 | G1 E4.78065 F299 72 | G1 E0.415709 F50 73 | G1 E4.78065 F299 74 | 75 | ; FLUSH_END 76 | G1 E-2 F1800 77 | G1 E2 F300 78 | 79 | ; EXTRA_PURGE_INSERTION 80 | 81 | ; FLUSH_START 82 | M400 83 | M109 S220 84 | G1 E2 F523 ;Compensate for filament spillage during waiting temperature 85 | ; FLUSH_END 86 | M400 87 | G92 E0 88 | G1 E-2 F1800 89 | M106 P1 S255 90 | M400 S3 91 | 92 | G1 X70 F5000 93 | G1 X90 F3000 94 | G1 Y255 F4000 95 | G1 X105 F5000 96 | G1 Y265 97 | G1 X70 F10000 98 | G1 X100 F5000 99 | G1 X70 F10000 100 | G1 X100 F5000 101 | 102 | G1 X70 F10000 103 | G1 X80 F15000 104 | G1 X60 105 | G1 X80 106 | G1 X60 107 | G1 X80 ; shake to put down garbage 108 | G1 X100 F5000 109 | G1 X165 F15000; wipe and shake 110 | G1 Y256 ; move Y to aside, prevent collision 111 | M400 112 | 113 | M204 S10000 114 | 115 | 116 | M621 SXXA 117 | 118 | M106 S200 ; resume fan speed 119 | M106 P2 S0 ; turn off aux fan, leave P3 chamber fan unchanged 120 | 121 | ;G91 122 | ;G1 Z-2.6 F30000 123 | ;G90 124 | ;M83 125 | 126 | ;G91 127 | ;G1 Z-0.4 128 | ;G90 129 | ;M83 130 | 131 | ; MFM will lower Z to original position and extrude E2 during pre-feature restore 132 | 133 | M204 S5000 134 | ; MFM MINIMAL TOOLCHANGE END -------------------------------------------------------------------------------- /minimal_toolchanges/extra-purge-150mm3.gcode: -------------------------------------------------------------------------------- 1 | ; This file is a reference file for the extra purge Gcode that is actually used in mfm/extra_purge.py 2 | 3 | G91 4 | G1 X3 F12000; move aside to extrude 5 | G90 6 | M83 7 | 8 | ; FLUSH_START 9 | G1 E11.2253 F299 10 | G1 E1.24726 F50 11 | G1 E11.2253 F299 12 | G1 E1.24726 F50 13 | G1 E11.2253 F299 14 | G1 E1.24726 F50 15 | G1 E11.2253 F299 16 | G1 E1.24726 F50 17 | G1 E11.2253 F299 18 | G1 E1.24726 F50 19 | ; FLUSH_END 20 | G1 E-2 F1800 21 | G1 E2 F300 -------------------------------------------------------------------------------- /minimal_toolchanges/generic-manual-swap-m600.gcode: -------------------------------------------------------------------------------- 1 | ; MFM MINIMAL GENERIC MANUAL M600 TOOLCHANGE START 2 | M117 Change to TXX filament now 3 | M600 4 | M117 Finished filament change to TXX 5 | ; MFM MINIMAL TOOLCHANGE END 6 | -------------------------------------------------------------------------------- /minimal_toolchanges/generic.gcode: -------------------------------------------------------------------------------- 1 | ; MFM MINIMAL GENERIC TOOLCHANGE START 2 | M104 S170 3 | M104 S210 TXX 4 | TXX 5 | M109 S210 6 | ; MFM MINIMAL TOOLCHANGE END 7 | -------------------------------------------------------------------------------- /minimal_toolchanges/prusa-xl-series.gcode: -------------------------------------------------------------------------------- 1 | ; MFM MINIMAL XL TOOLCHANGE START 2 | M220 B 3 | M220 S100 4 | ; CP TOOLCHANGE UNLOAD 5 | M900 K0 6 | G1 F12538 7 | G1 X169.000 F2400 8 | G4 S0 9 | G1 E-20 F2100 10 | ; Filament-specific end gcode 11 | ; Change Tool -> ToolXX 12 | G1 F21000 13 | P0 S1 L2 D0 14 | ; 0 15 | M109 S215 TXX 16 | TXX S1 L0 D0 17 | 18 | M900 K0.05 ; Filament gcode 19 | 20 | 21 | 22 | M142 S36 ; set heatbreak target temp 23 | M109 S215 T1 ; set temperature and wait for it to be reached 24 | 25 | G1 F24000 26 | G1 E20 F1500 27 | G4 S0 28 | ; CP TOOLCHANGE WIPE 29 | M220 R 30 | G1 F24000 31 | G4 S0 32 | G92 E0 33 | ; MFM MINIMAL TOOLCHANGE END 34 | -------------------------------------------------------------------------------- /minimal_toolchanges/testing/bs-a1-toolchange-notes.nc: -------------------------------------------------------------------------------- 1 | ;===== A1 20240913 ======================= 2 | M1007 S0 ; turn off mass estimation 3 | G392 S0 4 | M620 S[next_extruder]A 5 | M204 S9000 6 | {if toolchange_count > 1} 7 | G17 8 | G2 Z{max_layer_z + 0.4} I0.86 J0.86 P1 F10000 ; spiral lift a little from second lift 9 | {endif} 10 | G1 Z{max_layer_z + 3.0} F1200 11 | 12 | M400 13 | M106 P1 S0 14 | M106 P2 S0 15 | {if old_filament_temp > 142 && next_extruder < 255} 16 | M104 S[old_filament_temp] 17 | {endif} 18 | 19 | G1 X267 F18000 20 | 21 | {if long_retractions_when_cut[previous_extruder]} 22 | M620.11 S1 I[previous_extruder] E-{retraction_distances_when_cut[previous_extruder]} F1200 23 | {else} 24 | M620.11 S0 25 | {endif} 26 | M400 27 | 28 | M620.1 E F[old_filament_e_feedrate] T{nozzle_temperature_range_high[previous_extruder]} 29 | M620.10 A0 F[old_filament_e_feedrate] 30 | T[next_extruder] 31 | M620.1 E F[new_filament_e_feedrate] T{nozzle_temperature_range_high[next_extruder]} 32 | M620.10 A1 F[new_filament_e_feedrate] L[flush_length] H[nozzle_diameter] T[nozzle_temperature_range_high] 33 | 34 | G1 Y128 F9000 35 | 36 | {if next_extruder < 255} 37 | 38 | {if long_retractions_when_cut[previous_extruder]} 39 | M620.11 S1 I[previous_extruder] E{retraction_distances_when_cut[previous_extruder]} F{old_filament_e_feedrate} 40 | M628 S1 41 | G92 E0 42 | G1 E{retraction_distances_when_cut[previous_extruder]} F[old_filament_e_feedrate] 43 | M400 44 | M629 S1 45 | {else} 46 | M620.11 S0 47 | {endif} 48 | 49 | M400 50 | G92 E0 51 | M628 S0 ;turn off all AMS motor to allow extruder to be mover force 52 | 53 | {if flush_length_1 > 1} 54 | ; FLUSH_START 55 | ; always use highest temperature to flush 56 | M400 57 | M1002 set_filament_type:UNKNOWN 58 | M109 S[nozzle_temperature_range_high] 59 | M106 P1 S60 60 | {if flush_length_1 > 23.7} 61 | G1 E23.7 F{old_filament_e_feedrate} ; do not need pulsatile flushing for start part 62 | G1 E{(flush_length_1 - 23.7) * 0.02} F50 63 | G1 E{(flush_length_1 - 23.7) * 0.23} F{old_filament_e_feedrate} 64 | G1 E{(flush_length_1 - 23.7) * 0.02} F50 65 | G1 E{(flush_length_1 - 23.7) * 0.23} F{new_filament_e_feedrate} 66 | G1 E{(flush_length_1 - 23.7) * 0.02} F50 67 | G1 E{(flush_length_1 - 23.7) * 0.23} F{new_filament_e_feedrate} 68 | G1 E{(flush_length_1 - 23.7) * 0.02} F50 69 | G1 E{(flush_length_1 - 23.7) * 0.23} F{new_filament_e_feedrate} 70 | {else} 71 | G1 E{flush_length_1} F{old_filament_e_feedrate} 72 | {endif} 73 | ; FLUSH_END 74 | G1 E-[old_retract_length_toolchange] F1800 75 | G1 E[old_retract_length_toolchange] F300 76 | M400 77 | M1002 set_filament_type:{filament_type[next_extruder]} 78 | {endif} 79 | 80 | {if flush_length_1 > 45 && flush_length_2 > 1} 81 | ; WIPE 82 | M400 83 | M106 P1 S178 84 | M400 S3 85 | G1 X-38.2 F18000 86 | G1 X-48.2 F3000 87 | G1 X-38.2 F18000 88 | G1 X-48.2 F3000 89 | G1 X-38.2 F18000 90 | G1 X-48.2 F3000 91 | M400 92 | M106 P1 S0 93 | {endif} 94 | 95 | {if flush_length_2 > 1} 96 | M106 P1 S60 97 | ; FLUSH_START 98 | G1 E{flush_length_2 * 0.18} F{new_filament_e_feedrate} 99 | G1 E{flush_length_2 * 0.02} F50 100 | G1 E{flush_length_2 * 0.18} F{new_filament_e_feedrate} 101 | G1 E{flush_length_2 * 0.02} F50 102 | G1 E{flush_length_2 * 0.18} F{new_filament_e_feedrate} 103 | G1 E{flush_length_2 * 0.02} F50 104 | G1 E{flush_length_2 * 0.18} F{new_filament_e_feedrate} 105 | G1 E{flush_length_2 * 0.02} F50 106 | G1 E{flush_length_2 * 0.18} F{new_filament_e_feedrate} 107 | G1 E{flush_length_2 * 0.02} F50 108 | ; FLUSH_END 109 | G1 E-[new_retract_length_toolchange] F1800 110 | G1 E[new_retract_length_toolchange] F300 111 | {endif} 112 | 113 | {if flush_length_2 > 45 && flush_length_3 > 1} 114 | ; WIPE 115 | M400 116 | M106 P1 S178 117 | M400 S3 118 | G1 X-38.2 F18000 119 | G1 X-48.2 F3000 120 | G1 X-38.2 F18000 121 | G1 X-48.2 F3000 122 | G1 X-38.2 F18000 123 | G1 X-48.2 F3000 124 | M400 125 | M106 P1 S0 126 | {endif} 127 | 128 | {if flush_length_3 > 1} 129 | M106 P1 S60 130 | ; FLUSH_START 131 | G1 E{flush_length_3 * 0.18} F{new_filament_e_feedrate} 132 | G1 E{flush_length_3 * 0.02} F50 133 | G1 E{flush_length_3 * 0.18} F{new_filament_e_feedrate} 134 | G1 E{flush_length_3 * 0.02} F50 135 | G1 E{flush_length_3 * 0.18} F{new_filament_e_feedrate} 136 | G1 E{flush_length_3 * 0.02} F50 137 | G1 E{flush_length_3 * 0.18} F{new_filament_e_feedrate} 138 | G1 E{flush_length_3 * 0.02} F50 139 | G1 E{flush_length_3 * 0.18} F{new_filament_e_feedrate} 140 | G1 E{flush_length_3 * 0.02} F50 141 | ; FLUSH_END 142 | G1 E-[new_retract_length_toolchange] F1800 143 | G1 E[new_retract_length_toolchange] F300 144 | {endif} 145 | 146 | {if flush_length_3 > 45 && flush_length_4 > 1} 147 | ; WIPE 148 | M400 149 | M106 P1 S178 150 | M400 S3 151 | G1 X-38.2 F18000 152 | G1 X-48.2 F3000 153 | G1 X-38.2 F18000 154 | G1 X-48.2 F3000 155 | G1 X-38.2 F18000 156 | G1 X-48.2 F3000 157 | M400 158 | M106 P1 S0 159 | {endif} 160 | 161 | {if flush_length_4 > 1} 162 | M106 P1 S60 163 | ; FLUSH_START 164 | G1 E{flush_length_4 * 0.18} F{new_filament_e_feedrate} 165 | G1 E{flush_length_4 * 0.02} F50 166 | G1 E{flush_length_4 * 0.18} F{new_filament_e_feedrate} 167 | G1 E{flush_length_4 * 0.02} F50 168 | G1 E{flush_length_4 * 0.18} F{new_filament_e_feedrate} 169 | G1 E{flush_length_4 * 0.02} F50 170 | G1 E{flush_length_4 * 0.18} F{new_filament_e_feedrate} 171 | G1 E{flush_length_4 * 0.02} F50 172 | G1 E{flush_length_4 * 0.18} F{new_filament_e_feedrate} 173 | G1 E{flush_length_4 * 0.02} F50 174 | ; FLUSH_END 175 | {endif} 176 | 177 | M629 ; AMS turn off all feed monitoring? 178 | 179 | M400 180 | M106 P1 S60 181 | M109 S[new_filament_temp] 182 | G1 E6 F{new_filament_e_feedrate} ;Compensate for filament spillage during waiting temperature 183 | M400 184 | G92 E0 185 | G1 E-[new_retract_length_toolchange] F1800 186 | M400 187 | M106 P1 S178 188 | M400 S3 189 | G1 X-38.2 F18000 190 | G1 X-48.2 F3000 191 | G1 X-38.2 F18000 192 | G1 X-48.2 F3000 193 | G1 X-38.2 F18000 194 | G1 X-48.2 F3000 195 | G1 X-38.2 F18000 196 | G1 X-48.2 F3000 197 | M400 198 | G1 Z{max_layer_z + 3.0} F3000 199 | M106 P1 S0 200 | {if layer_z <= (initial_layer_print_height + 0.001)} 201 | M204 S[initial_layer_acceleration] 202 | {else} 203 | M204 S[default_acceleration] 204 | {endif} 205 | {else} 206 | G1 X[x_after_toolchange] Y[y_after_toolchange] Z[z_after_toolchange] F12000 207 | {endif} 208 | 209 | M622.1 S0 210 | M9833 F{outer_wall_volumetric_speed/2.4} A0.3 ; cali dynamic extrusion compensation 211 | M1002 judge_flag filament_need_cali_flag 212 | M622 J1 213 | G92 E0 214 | G1 E-[new_retract_length_toolchange] F1800 215 | M400 216 | 217 | M106 P1 S178 218 | M400 S4 219 | G1 X-38.2 F18000 220 | G1 X-48.2 F3000 221 | G1 X-38.2 F18000 ;wipe and shake 222 | G1 X-48.2 F3000 223 | G1 X-38.2 F12000 ;wipe and shake 224 | G1 X-48.2 F3000 225 | M400 226 | M106 P1 S0 227 | M623 228 | 229 | M621 S[next_extruder]A 230 | G392 S0 231 | 232 | M1007 S1 233 | -------------------------------------------------------------------------------- /minimal_toolchanges/testing/bs-toolchange-notes.nc: -------------------------------------------------------------------------------- 1 | M620 S[next_extruder]A ; AMS idle mode, turn off stepper motor? 2 | M204 S9000 3 | {if toolchange_count > 1 && (z_hop_types[current_extruder] == 0 || z_hop_types[current_extruder] == 3)} 4 | G17 5 | G2 Z{z_after_toolchange + 0.4} I0.86 J0.86 P1 F10000 ; spiral lift a little from second lift 6 | {endif} 7 | G1 Z{max_layer_z + 3.0} F1200 8 | 9 | G1 X70 F21000 10 | G1 Y245 11 | G1 Y265 F3000 12 | M400 13 | M106 P1 S0 14 | M106 P2 S0 15 | {if old_filament_temp > 142 && next_extruder < 255} 16 | M104 S[old_filament_temp] 17 | {endif} 18 | {if long_retractions_when_cut[previous_extruder]} 19 | M620.11 S1 I[previous_extruder] E-{retraction_distances_when_cut[previous_extruder]} F{old_filament_e_feedrate} ; retract HUB motor and prev extruder first stage spool by amount 20 | {else} 21 | M620.11 S0 22 | {endif} 23 | M400 24 | G1 X90 F3000 25 | G1 Y255 F4000 26 | G1 X100 F5000 27 | G1 X120 F15000 28 | G1 X20 Y50 F21000 29 | G1 Y-3 ; CUT filament 30 | {if toolchange_count == 2} 31 | ; get travel path for change filament 32 | M620.1 X[travel_point_1_x] Y[travel_point_1_y] F21000 P0 33 | M620.1 X[travel_point_2_x] Y[travel_point_2_y] F21000 P1 34 | M620.1 X[travel_point_3_x] Y[travel_point_3_y] F21000 P2 35 | {endif} 36 | M620.1 E F[old_filament_e_feedrate] T{nozzle_temperature_range_high[previous_extruder]} ;AMS set feedrate and temp of current prev extruder 37 | T[next_extruder] ;unload with AMS HUB MOTOR + FIRST STAGE SPOOL then load with next extruder. Assume AMS tracks feed distance and keeps old and new filament distance equal. New filament is pushed by AMS hub motor up to extruder cutter. AMS is in feed assist mode? 38 | M620.1 E F[new_filament_e_feedrate] T{nozzle_temperature_range_high[next_extruder]} ; AMS set feedrate and temp. Firmware lookahead gets this value? 39 | 40 | {if next_extruder < 255} 41 | {if long_retractions_when_cut[previous_extruder]} 42 | M620.11 S1 I[previous_extruder] E{retraction_distances_when_cut[previous_extruder]} F{old_filament_e_feedrate} ; AMS hub motor queue an extrude by the long retract amount. Previous extruder referenced because the previous filament is in the tip of the nozzle? 43 | M628 S1 ; ignore buffer feedback 44 | G92 E0 ;reset E position 45 | G1 E{retraction_distances_when_cut[previous_extruder]} F[old_filament_e_feedrate] ; extruder motor extrude by long retract amount. Previous extruder referenced because the previous filament is in the tip of the nozzle? 46 | M400 ; do both the extruder and hub motor movements 47 | M629 S1 ; monitor buffer feedback again 48 | {else} 49 | M620.11 S0 50 | {endif} 51 | G92 E0 52 | {if flush_length_1 > 1} 53 | M83 54 | ; FLUSH_START 55 | ; always use highest temperature to flush 56 | M400 57 | {if filament_type[next_extruder] == "PETG"} 58 | M109 S260 59 | {elsif filament_type[next_extruder] == "PVA"} 60 | M109 S210 61 | {else} 62 | M109 S[nozzle_temperature_range_high] 63 | {endif} 64 | {if flush_length_1 > 23.7} 65 | G1 E23.7 F{old_filament_e_feedrate} ; do not need pulsatile flushing for start part 66 | G1 E{(flush_length_1 - 23.7) * 0.02} F50 67 | G1 E{(flush_length_1 - 23.7) * 0.23} F{old_filament_e_feedrate} 68 | G1 E{(flush_length_1 - 23.7) * 0.02} F50 69 | G1 E{(flush_length_1 - 23.7) * 0.23} F{new_filament_e_feedrate} 70 | G1 E{(flush_length_1 - 23.7) * 0.02} F50 71 | G1 E{(flush_length_1 - 23.7) * 0.23} F{new_filament_e_feedrate} 72 | G1 E{(flush_length_1 - 23.7) * 0.02} F50 73 | G1 E{(flush_length_1 - 23.7) * 0.23} F{new_filament_e_feedrate} 74 | {else} 75 | G1 E{flush_length_1} F{old_filament_e_feedrate} 76 | {endif} 77 | ; FLUSH_END 78 | G1 E-[old_retract_length_toolchange] F1800 79 | G1 E[old_retract_length_toolchange] F300 80 | {endif} 81 | 82 | {if flush_length_2 > 1} 83 | 84 | G91 85 | G1 X3 F12000; move aside to extrude 86 | G90 87 | M83 88 | 89 | ; FLUSH_START 90 | G1 E{flush_length_2 * 0.18} F{new_filament_e_feedrate} 91 | G1 E{flush_length_2 * 0.02} F50 92 | G1 E{flush_length_2 * 0.18} F{new_filament_e_feedrate} 93 | G1 E{flush_length_2 * 0.02} F50 94 | G1 E{flush_length_2 * 0.18} F{new_filament_e_feedrate} 95 | G1 E{flush_length_2 * 0.02} F50 96 | G1 E{flush_length_2 * 0.18} F{new_filament_e_feedrate} 97 | G1 E{flush_length_2 * 0.02} F50 98 | G1 E{flush_length_2 * 0.18} F{new_filament_e_feedrate} 99 | G1 E{flush_length_2 * 0.02} F50 100 | ; FLUSH_END 101 | G1 E-[new_retract_length_toolchange] F1800 102 | G1 E[new_retract_length_toolchange] F300 103 | {endif} 104 | 105 | {if flush_length_3 > 1} 106 | 107 | G91 108 | G1 X3 F12000; move aside to extrude 109 | G90 110 | M83 111 | 112 | ; FLUSH_START 113 | G1 E{flush_length_3 * 0.18} F{new_filament_e_feedrate} 114 | G1 E{flush_length_3 * 0.02} F50 115 | G1 E{flush_length_3 * 0.18} F{new_filament_e_feedrate} 116 | G1 E{flush_length_3 * 0.02} F50 117 | G1 E{flush_length_3 * 0.18} F{new_filament_e_feedrate} 118 | G1 E{flush_length_3 * 0.02} F50 119 | G1 E{flush_length_3 * 0.18} F{new_filament_e_feedrate} 120 | G1 E{flush_length_3 * 0.02} F50 121 | G1 E{flush_length_3 * 0.18} F{new_filament_e_feedrate} 122 | G1 E{flush_length_3 * 0.02} F50 123 | ; FLUSH_END 124 | G1 E-[new_retract_length_toolchange] F1800 125 | G1 E[new_retract_length_toolchange] F300 126 | {endif} 127 | 128 | {if flush_length_4 > 1} 129 | 130 | G91 131 | G1 X3 F12000; move aside to extrude 132 | G90 133 | M83 134 | 135 | ; FLUSH_START 136 | G1 E{flush_length_4 * 0.18} F{new_filament_e_feedrate} 137 | G1 E{flush_length_4 * 0.02} F50 138 | G1 E{flush_length_4 * 0.18} F{new_filament_e_feedrate} 139 | G1 E{flush_length_4 * 0.02} F50 140 | G1 E{flush_length_4 * 0.18} F{new_filament_e_feedrate} 141 | G1 E{flush_length_4 * 0.02} F50 142 | G1 E{flush_length_4 * 0.18} F{new_filament_e_feedrate} 143 | G1 E{flush_length_4 * 0.02} F50 144 | G1 E{flush_length_4 * 0.18} F{new_filament_e_feedrate} 145 | G1 E{flush_length_4 * 0.02} F50 146 | ; FLUSH_END 147 | {endif} 148 | ; FLUSH_START 149 | M400 150 | M109 S[new_filament_temp] 151 | G1 E2 F{new_filament_e_feedrate} ;Compensate for filament spillage during waiting temperature 152 | ; FLUSH_END 153 | M400 154 | G92 E0 155 | G1 E-[new_retract_length_toolchange] F1800 156 | M106 P1 S255 157 | M400 S3 158 | 159 | G1 X70 F5000 160 | G1 X90 F3000 161 | G1 Y255 F4000 162 | G1 X105 F5000 163 | G1 Y265 F5000 164 | G1 X70 F10000 165 | G1 X100 F5000 166 | G1 X70 F10000 167 | G1 X100 F5000 168 | 169 | G1 X70 F10000 170 | G1 X80 F15000 171 | G1 X60 172 | G1 X80 173 | G1 X60 174 | G1 X80 ; shake to put down garbage 175 | G1 X100 F5000 176 | G1 X165 F15000; wipe and shake 177 | G1 Y256 ; move Y to aside, prevent collision 178 | M400 179 | G1 Z{max_layer_z + 3.0} F3000 180 | {if layer_z <= (initial_layer_print_height + 0.001)} 181 | M204 S[initial_layer_acceleration] 182 | {else} 183 | M204 S[default_acceleration] 184 | {endif} 185 | {else} 186 | G1 X[x_after_toolchange] Y[y_after_toolchange] Z[z_after_toolchange] F12000 187 | {endif} 188 | M621 S[next_extruder]A ; AMS finalize next extruder. AMS switch to feed assist mode 189 | -------------------------------------------------------------------------------- /minimized-toolchanges-on-layer-change.md: -------------------------------------------------------------------------------- 1 | # Toolchange Minimize Optimization Notes 2 | 3 | 1. Look at all layer boundaries that are sandwiched between 2 other layer boundaries. Look at the layer boundaries that match this condition and have the fewest colors in the layer boundary first. 4 | 5 | - Have the center layer boundary's layer change on the color that is least common (or not in) the 2 sandwiching layer boundaries. 6 | -------------------------------------------------------------------------------- /premade_options/1to1.json: -------------------------------------------------------------------------------- 1 | { 2 | "modelToRealWorldDefaultUnits": 1, 3 | "modelOneToNVerticalScale": 1, 4 | "modelSeaLevelBaseThickness": 0, 5 | "realWorldIsolineElevationInterval": 10, 6 | "realWorldIsolineElevationStart": 5, 7 | "realWorldIsolineElevationEnd": 50, 8 | "modelIsolineHeight": 1, 9 | "isolineColorIndex": 2, 10 | "isolineColorFeatureTypes": ["Outer wall", "External perimeter"], 11 | "realWorldElevationReplacementColorStart": 30, 12 | "realWorldElevationReplacementColorEnd": 60, 13 | "replacementColorIndex": 3, 14 | "replacementOriginalColorIndex": 0, 15 | "extraPurgePreviousColors": [] 16 | } -------------------------------------------------------------------------------- /premade_options/README.md: -------------------------------------------------------------------------------- 1 | # Premade Map Feature Modifier Options 2 | 3 | **Default scale** is `1:2500000` unless otherwise [specified](https://ansonliu.com/maps/specifications/). 200% scale is `1:1250000` and so forth. 4 | 5 | [Map Feature Modifier options documentation](../mfm-configuration-options-setup.md) 6 | 7 | > You can set a map model's X and Y scale to any percentage. X and Y scale do not matter because MFM only changes based on Z scale. 8 | 9 | | Map | Style | Options File | 10 | | --- | --- | --- | 11 | | [ansonl 3D Maps](ansonliu.com/maps) | Dual Color, default scale | `USAofPlastic-dual-meters.json` | 12 | | [ansonl 3D Maps](ansonliu.com/maps) | Single Color, default scale | `USAofPlastic-single-meters.json` | 13 | | [ansonl 3D Maps](ansonliu.com/maps) | Dual Color, 200% scale | `USAofPlastic-dual-meters-Z200.json` | 14 | | [California (CA) in hexagon pieces](https://makerworld.com/en/models/1170334-california-hex-puzzle-topographic-map-with-streams) | Dual Color, Sqrt, 200% scale | `USAofPlastic-dual-meters-Z200-rise1-5mm.json` | 15 | -------------------------------------------------------------------------------- /premade_options/USAofPlastic-dual-lowpoly-meters.json: -------------------------------------------------------------------------------- 1 | { 2 | "modelToRealWorldDefaultUnits": 1000, 3 | "modelOneToNVerticalScale": 166666.7, 4 | "modelSeaLevelBaseThickness": 3.6, 5 | "realWorldIsolineElevationInterval": 500, 6 | "realWorldIsolineElevationStart": 500, 7 | "realWorldIsolineElevationEnd": 30000, 8 | "modelIsolineHeight": 0.1, 9 | "isolineColorIndex": 2, 10 | "isolineColorFeatureTypes": ["Outer wall", "Inner wall", "External perimeter", "Perimeter"], 11 | "realWorldElevationReplacementColorStart": 2300, 12 | "realWorldElevationReplacementColorEnd": 30000, 13 | "replacementColorIndex": 3, 14 | "replacementOriginalColorIndex": 0, 15 | "extraPurgePreviousColors": [] 16 | } -------------------------------------------------------------------------------- /premade_options/USAofPlastic-dual-meters-Z200-rise3mm-no-snow.json: -------------------------------------------------------------------------------- 1 | { 2 | "modelToRealWorldDefaultUnits": 1000, 3 | "modelOneToNVerticalScale": 250000, 4 | "modelSeaLevelBaseThickness": 6.6, 5 | "realWorldIsolineElevationInterval": 300, 6 | "realWorldIsolineElevationStart": 301, 7 | "realWorldIsolineElevationEnd": 30000, 8 | "modelIsolineHeight": 0.01, 9 | "isolineColorIndex": 2, 10 | "isolineColorFeatureTypes": ["Outer wall", "External perimeter"], 11 | "realWorldElevationReplacementColorStart": 29999, 12 | "realWorldElevationReplacementColorEnd": 30000, 13 | "replacementColorIndex": 3, 14 | "replacementOriginalColorIndex": 0, 15 | "extraPurgePreviousColors": [] 16 | } -------------------------------------------------------------------------------- /premade_options/USAofPlastic-dual-meters-Z200-rise3mm.json: -------------------------------------------------------------------------------- 1 | { 2 | "modelToRealWorldDefaultUnits": 1000, 3 | "modelOneToNVerticalScale": 250000, 4 | "modelSeaLevelBaseThickness": 6.6, 5 | "realWorldIsolineElevationInterval": 300, 6 | "realWorldIsolineElevationStart": 301, 7 | "realWorldIsolineElevationEnd": 30000, 8 | "modelIsolineHeight": 0.01, 9 | "isolineColorIndex": 2, 10 | "isolineColorFeatureTypes": ["Outer wall", "External perimeter"], 11 | "realWorldElevationReplacementColorStart": 2300, 12 | "realWorldElevationReplacementColorEnd": 30000, 13 | "replacementColorIndex": 3, 14 | "replacementOriginalColorIndex": 0, 15 | "extraPurgePreviousColors": [1] 16 | } -------------------------------------------------------------------------------- /premade_options/USAofPlastic-dual-meters-Z200.json: -------------------------------------------------------------------------------- 1 | { 2 | "modelToRealWorldDefaultUnits": 1000, 3 | "modelOneToNVerticalScale": 250000, 4 | "modelSeaLevelBaseThickness": 3.6, 5 | "realWorldIsolineElevationInterval": 500, 6 | "realWorldIsolineElevationStart": 500, 7 | "realWorldIsolineElevationEnd": 30000, 8 | "modelIsolineHeight": 0.1, 9 | "isolineColorIndex": 2, 10 | "isolineColorFeatureTypes": ["Outer wall", "Inner wall", "External perimeter", "Perimeter"], 11 | "realWorldElevationReplacementColorStart": 2300, 12 | "realWorldElevationReplacementColorEnd": 30000, 13 | "replacementColorIndex": 3, 14 | "replacementOriginalColorIndex": 0, 15 | "extraPurgePreviousColors": [] 16 | } -------------------------------------------------------------------------------- /premade_options/USAofPlastic-dual-meters.json: -------------------------------------------------------------------------------- 1 | { 2 | "modelToRealWorldDefaultUnits": 1000, 3 | "modelOneToNVerticalScale": 500000, 4 | "modelSeaLevelBaseThickness": 1.8, 5 | "realWorldIsolineElevationInterval": 500, 6 | "realWorldIsolineElevationStart": 500, 7 | "realWorldIsolineElevationEnd": 30000, 8 | "modelIsolineHeight": 0.1, 9 | "isolineColorIndex": 2, 10 | "isolineColorFeatureTypes": ["Outer wall", "Inner wall", "External perimeter", "Perimeter"], 11 | "realWorldElevationReplacementColorStart": 2300, 12 | "realWorldElevationReplacementColorEnd": 30000, 13 | "replacementColorIndex": 3, 14 | "replacementOriginalColorIndex": 0, 15 | "extraPurgePreviousColors": [] 16 | } -------------------------------------------------------------------------------- /premade_options/USAofPlastic-single-meters.json: -------------------------------------------------------------------------------- 1 | { 2 | "modelToRealWorldDefaultUnits": 1000, 3 | "modelOneToNVerticalScale": 500000, 4 | "modelSeaLevelBaseThickness": 1.3, 5 | "realWorldIsolineElevationInterval": 500, 6 | "realWorldIsolineElevationStart": 500, 7 | "realWorldIsolineElevationEnd": 30000, 8 | "modelIsolineHeight": 0.1, 9 | "isolineColorIndex": 2, 10 | "isolineColorFeatureTypes": ["Outer wall", "Inner wall", "External perimeter", "Perimeter"], 11 | "realWorldElevationReplacementColorStart": 2300, 12 | "realWorldElevationReplacementColorEnd": 30000, 13 | "replacementColorIndex": 3, 14 | "replacementOriginalColorIndex": 0, 15 | "extraPurgePreviousColors": [] 16 | } -------------------------------------------------------------------------------- /printer-setup.md: -------------------------------------------------------------------------------- 1 | # Printer Setup for MFM 2 | 3 | You need to find a way to print the G-code on your 3D printer. 4 | 5 | ## Sending G-code and Plate Sliced 3MF to the 3D printer 6 | 7 | There are 2 options: Plate Sliced 3MF (G-code embedded 3MF) (preferred) and G-code 8 | 9 | ### Most 3D Printers 10 | 11 | For most 3D printers you can send or stream G-code directly to your printer with a USB or network serial connection. This feature is usually built into your slicer and you just import your G-code or 3MF file and click **Print**. 12 | 13 | You can also copy G-code to an SD card that you put into the printer. 14 | 15 | #### Plate Sliced 3MF 16 | 17 | 1. Make sure your slicer project has at least 4 distinct filament colors enabled that correspond to the color indices used by MFM. 18 | 19 | 2. Export your original project as a Plate Sliced 3MF with File > Export > **Export all plate sliced file**. 20 | 21 | 3. Run MFM with the plate sliced 3MF as the input file. 22 | - In the later version of Bambu Studio, you must set up an AMS mapping for ALL (4) used color indexes or the printer will fail with an AMS mapping error at layer with the unmapped color! If the slicer does not show AMS mapping for all used colors, you can force it to show the 4 mappings by editing the 3MF archive's `/Metadata/slice_info.config` (open it with 7zip) and adding the missing filament indexes for EACH plate. An example of what the config should look like is below: 23 | ``` 24 | 25 | 26 | 27 | 28 | ``` 29 | 30 | 4. Import the processed plate sliced 3MF in the Bambu Studio or OrcaSlicer. 31 | 32 | 5. Click **Print plate** 33 | 34 | 6. Select Bed Leveling and Timelapse as needed. Remap your AMS or multimaterial system if supported. Make sure you do not have duplicated materials across the slots as described in [Material Auto Refill](#material-auto-refill). 35 | 36 | #### G-code 37 | 38 | 1. Export your original G-code from the slicer. 39 | 40 | 2. Run MFM with the G-code as the input file. 41 | 42 | 3. Import the processed plate sliced 3MF in the Bambu Studio or OrcaSlicer and click **Print**. 43 | 44 | ### Bambu Lab Printers 45 | 46 | I recommend using the [Plate Sliced 3MF](#plate-sliced-3mf) method due to Bambu's overly restrictive limits on LAN mode. 47 | 48 | Bambu Studio allows you to **Send** previewed G-code to Bambu Lab printers over a network connection. You can print the sent G-code on the Bambu printer screen itself after ensuring the colors are physically located in the correct AMS slots. 49 | 50 | Bambu will not allow you to directly use the Bambu Studio **Print** action to run a G-code file. 51 | 52 | Bambu Lab has unreasonably required a printer have LAN Mode turned off to use SD storage features in Bambu Studio. 53 | 54 | #### You have LAN Mode turned off 55 | 56 | If you do not have LAN Mode enabled, you can remotely print and assign AMS mapping, Bed Leveling, and Timelapse settings to a Bambu Printer through the Device > MicroSD Card > Model screen. This method should work until you upgrade your printer's firmware after January 2025 or Bambu remotely triggers a firmware update on your printer. Newer firmware will require Bambu Cloud authorization to print all files from a computer (even if you turn on LAN mode). 57 | 58 | #### You have LAN Mode turned on 59 | 60 | Use **Send** in Bambu Studio or [FTPS](https://forum.bambulab.com/t/we-can-now-connect-to-ftp-on-the-p1-and-a1-series/6464) to transfer the G-code file to the printer. Your filament must be placed in the correct indices in the AMS. 61 | 62 | Start G-code file using the printer display or an MQTT integration. 63 | 64 | ## Material Auto Refill 65 | 66 | ### Bambu AMS 67 | 68 | **AMS loaded filaments must be set such that each slot shows a different material type or color**. Bambu printers will try to substitute slots with similar material and a toolchange between slots with the same material and color set may be ignored. 69 | 70 | **Auto Refill should be turned off.** 71 | 72 | > The actual physical material and colors loaded do not need to be different or accurately reflected in the printer screen or slicer Device tab. Only the material/color shown on the printer or Device tab need to be distinct from each other. 73 | 74 | ### Bambu AMS out of filament behavior 75 | 76 | If you want to swap/save filament by changing out filament in the same AMS slot, you should swap the filament from the AMS slot when it is **not** the active filament. 77 | 78 | When the active filament is detected as "run out" by the AMS, the printer will purge the ENTIRE filament tube of filament all the way from the AMS to the extruder. This is a huge waste of material and should be avoided. This behavior is probably because backing out filament that ends inside the first stage feeder is considered unreliable by Bambu. 79 | 80 | ## Timelapse 81 | 82 | ### Bambu Studio 83 | 84 | Bambu Studio does not allow you to directly Print imported G-code to LAN Mode printers so you cannot enable the timelapse checkbox. You can enable default timelapse in a G-code file by replacing all occurences of 85 | 86 | ```gcode 87 | M622 J1 88 | ; timelapse without wipe tower 89 | M971 S11 C10 O0 90 | 91 | M623 92 | ``` 93 | 94 | with 95 | 96 | ```gcode 97 | M971 S11 C10 O0 98 | ``` 99 | 100 | or replacing `M622 J1` with `M622 J0` for only the conditional timelapse statements that check the timelapse checkbox option normally sent from Bambu Studio. 101 | -------------------------------------------------------------------------------- /pyinstaller/entitlements.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | com.apple.security.cs.allow-jit 7 | 8 | com.apple.security.cs.allow-unsigned-executable-memory 9 | 10 | com.apple.security.cs.disable-library-validation 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /pyinstaller/pyinstaller-build.sh: -------------------------------------------------------------------------------- 1 | # Windows 2 | pyinstaller --onefile src/gui.py --name MFM 3 | 4 | # MacOS 5 | # Create code signing identity first 6 | # https://github.com/pyinstaller/pyinstaller/issues/6167#issuecomment-906307356 7 | pyinstaller --onefile src/gui.py --codesign-identity ansonliu-imac-code-sign --name MFM -------------------------------------------------------------------------------- /references/Bambu-gcodes.md: -------------------------------------------------------------------------------- 1 | # Bambu G-code list 2 | 3 | Non-standard Bambu G-code that has undocumented parameters or deviates from [Marlin G-code](https://marlinfw.org/docs/gcode). 4 | 5 | Please contribute edits and corrections with a [pull request](https://github.com/ansonl/mfm/pulls) or [issue](https://github.com/ansonl/mfm/issues). 6 | 7 | More guesses can be found on this [thread](https://forum.bambulab.com/t/bambu-lab-x1-specific-g-code/666). 8 | 9 | ## M106 - Set Fan Speed 10 | 11 | | Parameter | Notes | Related flags | 12 | | -------- | ------- | ------- | 13 | | none | Part cooling fan | | 14 | | P1 | Hotend cooling fan | | 15 | | P2 | Remote part cooling/big fan | | 16 | | P3 | Chamber fan | `support_air_filtration` | 17 | | S | speed | 18 | 19 | ## M620 - AMS Toolchange 20 | 21 | Bambu AMS Toolchange 22 | 23 | | Parameter | Notes | 24 | | -------- | ------- | 25 | | SXXA | Switch to XX filament. `M620 M` previous line and four spaces on next lines for conditional execution if AMS exists and material switched. | 26 | | S255 | pull back filament to AMS | 27 | | .1 E F523 T240 | Switch to XX filament | 28 | 29 | ## M620.1 - AMS Do Toolchange 30 | 31 | | Parameter | Notes | 32 | | -------- | ------- | 33 | | E | | 34 | | F523 | Filament extrude feedrate | 35 | | TXX | Extruder temperature XX | 36 | 37 | ## M620.11 - AMS Do Toolchange Long Retract Version 38 | 39 | | Parameter | Notes | 40 | | -------- | ------- | 41 | | E | Move the extruder and AMS hub motor if negative. Move only AMS hub motor if positive. | 42 | | F523 | Filament extrude feedrate | 43 | | TXX | Extruder temperature XX | 44 | 45 | ## M621 - AMS Toolchange 46 | 47 | Bambu AMS Toolchange 48 | 49 | | Parameter | Notes | 50 | | -------- | ------- | 51 | | SXXA | Switch to XX filament | 52 | 53 | ## M622 conditional after M1002 54 | 55 | Gcode between `M622`` and `M623`` runs if timelapse is on. 56 | 57 | | Parameter | Values | Notes | 58 | | -------- | ------- | ------- | 59 | | J | 0 1 | conditional | 60 | 61 | ## M623 jump location for conditional 62 | 63 | ## M624 - Stop main part 64 | 65 | | Parameter | Values | Notes | 66 | | -------- | ------- | ------- | 67 | | AQAAAAAAAAA= | | | 68 | 69 | ## M625 - Start main part 70 | 71 | ## M900 - Set flow 72 | 73 | | Parameter | Values | Notes | 74 | | -------- | ------- | ------- | 75 | | K | | 76 | | M | `outer_wall_volumetric_speed/(1.75*1.75/4*3.14)*0.02` | 77 | 78 | ## M901 end smooth timelapse at safe pos 79 | 80 | | Parameter | Values | Notes | 81 | | -------- | ------- | ------- | 82 | | S | 0 | 83 | | P | -1 | | 84 | 85 | ## M960 - laser 86 | 87 | See [thread](https://forum.bambulab.com/t/bambu-lab-x1-specific-g-code/666) for `M960`` 88 | 89 | | Parameter | Values | Notes | 90 | | -------- | ------- | ------- | 91 | | S | | | 92 | | P | | 93 | 94 | ## M969 - scanning 95 | 96 | | Parameter | Values | Notes | 97 | | -------- | ------- | ------- | 98 | | S | 0 1 2 | 99 | | P | 0 1 | 100 | 101 | ## M971 - scanning 102 | 103 | | Parameter | Values | Notes | 104 | | -------- | ------- | ------- | 105 | | S | 5 | 106 | | P | 2 | 107 | 108 | ## M973 109 | 110 | | Parameter | Values | Notes | 111 | | -------- | ------- | ------- | 112 | | S | 4 | turn off scanner | 113 | 114 | ## M975 115 | 116 | | Parameter | Values | Notes | 117 | | -------- | ------- | ------- | 118 | | S | 1 | `turn on mech mode supression` | 119 | 120 | ## M991 - notify layer change 121 | 122 | `M991` notifies printer display of layer change. 123 | 124 | | Parameter | Values | Notes | 125 | | -------- | ------- | ------- | 126 | | S | 0 | | 127 | | P | 0 | | 128 | 129 | ## M1002 - judge_last_extrude_cali_success / gcode_claim_action : 0 130 | 131 | See [thread](https://forum.bambulab.com/t/bambu-lab-x1-specific-g-code/666) 132 | 133 | | Parameter | Values | Notes | 134 | | -------- | ------- | ------- | 135 | | set_gcode_claim_speed_level | 0 | showhide message on screen | 136 | 137 | ## T - ~~Select~~ or Report Tool 138 | 139 | `T` command tells the printer which filament (tool) is now selected. 140 | 141 | Bambu firmware does not do the toolchange with `T` command. The actual toolchange with AMS uses the M620 command. 142 | 143 | | Parameter | Notes | 144 | | -------- | ------- | 145 | | 255 | Switch to empty tool | 146 | | 1000 | change to nozzle space | 147 | | 1100 | change to scanning space on X1 | 148 | 149 | -------------------------------------------------------------------------------- /sample_models/4-cubes.gcode.3mf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ansonl/mfm/bf46c307ceccc87d6437c17dcfb071cba703c5fe/sample_models/4-cubes.gcode.3mf -------------------------------------------------------------------------------- /sample_models/AMS_calibration_v1_updated.3mf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ansonl/mfm/bf46c307ceccc87d6437c17dcfb071cba703c5fe/sample_models/AMS_calibration_v1_updated.3mf -------------------------------------------------------------------------------- /sample_models/AMS_calibration_v1_updated_Cali 4 filaments = full AMS.gcode.3mf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ansonl/mfm/bf46c307ceccc87d6437c17dcfb071cba703c5fe/sample_models/AMS_calibration_v1_updated_Cali 4 filaments = full AMS.gcode.3mf -------------------------------------------------------------------------------- /sample_models/CA/config-usaofplastic-200zperc.json: -------------------------------------------------------------------------------- 1 | { 2 | "modelToRealWorldDefaultUnits": 1000, 3 | "modelOneToNVerticalScale": 250000, 4 | "modelSeaLevelBaseThickness": 3.6, 5 | "realWorldIsolineElevationInterval": 500, 6 | "realWorldIsolineElevationStart": 500, 7 | "realWorldIsolineElevationEnd": 30000, 8 | "modelIsolineHeight": 0.1, 9 | "isolineColorIndex": 2, 10 | "isolineColorFeatureTypes": ["Outer wall", "Inner wall", "External perimeter", "Perimeter"], 11 | "realWorldElevationReplacementColorStart": 2000, 12 | "realWorldElevationReplacementColorEnd": 30000, 13 | "replacementColorIndex": 3, 14 | "replacementOriginalColorIndex": 0 15 | } -------------------------------------------------------------------------------- /sample_models/CA/slice settings.txt: -------------------------------------------------------------------------------- 1 | p1 2 | ironing on 3 | top surface pattern monotonic line 4 | solid infill pattern monotonic line 5 | prime 6 | 7 | p2 8 | ironing on 9 | top surface pattern monotonic 10 | solid infill pattern monotonic line 11 | no prime 12 | 13 | p3 14 | ironing on 15 | top surface pattern monotonic line 16 | solid infill pattern monotonic 17 | no prime 18 | 19 | p4 20 | ironing on 21 | top surface pattern monotonic line 22 | solid infill pattern rectilinear 23 | no prime -------------------------------------------------------------------------------- /sample_models/dual_color_dice/Dice.3mf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ansonl/mfm/bf46c307ceccc87d6437c17dcfb071cba703c5fe/sample_models/dual_color_dice/Dice.3mf -------------------------------------------------------------------------------- /sample_models/dual_color_dice/Die.stl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ansonl/mfm/bf46c307ceccc87d6437c17dcfb071cba703c5fe/sample_models/dual_color_dice/Die.stl -------------------------------------------------------------------------------- /sample_models/dual_color_dice/Dots.stl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ansonl/mfm/bf46c307ceccc87d6437c17dcfb071cba703c5fe/sample_models/dual_color_dice/Dots.stl -------------------------------------------------------------------------------- /sample_models/dual_color_dice/config-dice-test.json: -------------------------------------------------------------------------------- 1 | { 2 | "modelToRealWorldDefaultUnits": 1000, 3 | "modelOneToNVerticalScale": 500000, 4 | "modelSeaLevelBaseThickness": 0.1, 5 | "realWorldIsolineElevationInterval": 500, 6 | "realWorldIsolineElevationStart": 200, 7 | "realWorldIsolineElevationEnd": 5000, 8 | "modelIsolineHeight": 0.5, 9 | "isolineColorIndex": 2, 10 | "isolineColorFeatureTypes": ["Outer wall", "Inner wall", "External perimeter", "Perimeter"], 11 | "realWorldElevationReplacementColorStart": 3650, 12 | "realWorldElevationReplacementColorEnd": 9000, 13 | "replacementColorIndex": 3, 14 | "replacementOriginalColorIndex": 0, 15 | "extraPurgePreviousColors": [2] 16 | } -------------------------------------------------------------------------------- /sample_models/dual_color_dice/source.txt: -------------------------------------------------------------------------------- 1 | https://makerworld.com/en/models/25703#profileId-113988 -------------------------------------------------------------------------------- /sample_models/tall-cuboid.3mf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ansonl/mfm/bf46c307ceccc87d6437c17dcfb071cba703c5fe/sample_models/tall-cuboid.3mf -------------------------------------------------------------------------------- /slicer-setup.md: -------------------------------------------------------------------------------- 1 | # Slicer Setup for MFM 2 | 3 | ## G-code coordinate positioning mode 4 | 5 | All printing G-code must use [Relative Positioning for Extrusion](https://www.ideamaker.io/dictionaryDetail.html?name=Relative%20Extrusion&category_name=Printer%20Settings). 6 | 7 | Printhead XYZE absolute positioning mode can be set with `G91` and only the Extruder (E) can be set to relative positioning with `M83`. If too little/too much filament is extruded, check to see if your extrusion positioning is incorrectly set to absolute in the slicer. 8 | 9 | ## Set Printer G-code 10 | 11 | Add markers in your slicer software G-code for the end of new layer change and start and end of toolchange. 12 | 13 | Save the printer profile with a new name and select the new printer profile for your prints. 14 | 15 | ![mfm slicer setup](assets/bambustudio-printer-settings.jpg) 16 | 17 | ### PrusaSlicer / BambuStudio / Orca Slicer steps 18 | 19 | 1. Printer > Settings > **Custom G-code / Machine G-code** 20 | 21 | 2. Add `; MFM LAYER CHANGE END` on a new line at the end of **After layer change G-code / Layer change G-code**. 22 | 23 | 3. Add `; MFM TOOLCHANGE START` on a new line at the beginning of **Tool change G-code / Change filament G-code**. 24 | 25 | 4. Add `; MFM TOOLCHANGE END` on a new line at the end of **Tool change G-code / Change filament G-code**. 26 | 27 | 5. If you do not have the Bambu specific **Long retraction when cut** `long_retractions_when_cut` option enabled for any of the used filament profiles, skip to last step. 28 | 29 | 6. **Long retraction only:** Add `; EXTRA_PURGE_INSERTION` on a new line after the last `{if flush_length_4 > 1}...{endif}` block. The added new line must be before the last occurance of `; FLUSH_START`. 30 | 31 | 7. The resulting settings text fields should have an order like below 32 | 33 | #### [After] Layer change G-code 34 | 35 | ```gcode 36 | ; Existing layer change G-code stays HERE 37 | 38 | ; MFM LAYER CHANGE END 39 | ``` 40 | 41 | #### Tool change G-code / Change filament G-code 42 | 43 | ```gcode 44 | ; MFM TOOLCHANGE START 45 | 46 | ; Existing toolchange G-code stays HERE 47 | 48 | ; MFM TOOLCHANGE END 49 | ``` 50 | 51 | #### Tool change G-code / Change filament G-code - Long retraction version 52 | 53 | ```gcode 54 | ; MFM TOOLCHANGE START ; <-- Add this line 55 | 56 | ; Existing toolchange G-code stays HERE 57 | {if flush_length_4 > 1} ; <-- This should be the last high extruding flush 58 | ... <-- Last extruding flush G-code 59 | {endif} 60 | 61 | ; EXTRA_PURGE_INSERTION ; <-- Add this line 62 | 63 | ; FLUSH_START <-- This is a short flush that does not extrude much 64 | M400 65 | ... 66 | ; Existing toolchange G-code stays HERE 67 | 68 | ; MFM TOOLCHANGE END ; <-- Add this line 69 | ``` 70 | 71 | ## Set Filament Settings 72 | 73 | ### `Long retraction when cut` (Bambu Studio/Orca Slicer) 74 | 75 | Bambu Slicer and Orca Slicer have a conditional section in the toolchange that uses a proprietary G-code `M620.11` to perform a longer retraction before cutting filament. This can reduce purged filament by 20-30% on average. 76 | 77 | For every filament used: 78 | 79 | 1. Filament > **Setting Overrides** 80 | 81 | 2. Check or Uncheck `Long retraction when cut` respectively if you want **Long retraction when cut** enabled or disabled. 82 | 83 | > `M620.11` command parameter asks for the previous extruder index for some movements that strictly speaking, should not need it. MFM is compatible with `M620.11` and can do long retractions by tracking the previous tool. 84 | 85 | ## Set Post-processing Scripts *(optional)* 86 | 87 | Add MFM as a post-processing script if you want to automatically run MFM in your Slicer. 88 | 89 | If you plan to do the processing through the standalone MFM GUI app, you can skip this step. 90 | 91 | ### PrusaSlicer 92 | 93 | 1. Set the settings view to **Expert Mode** in the upper right. 94 | 95 | 1. Print Settings > Output options > **Post-processing scripts** 96 | 97 | ![PrusaSlicer postprocessing script printer setting option](assets/prusaslicer-post-processing-script-option.png) 98 | 99 | ### Bambu Studio / Orca Slicer 100 | 101 | 1. Enable **Advanced** view for Process 102 | 103 | 1. Process > Others > **Post-processing scripts** 104 | 105 | ### Next Steps for All Slicers 106 | 107 | 3. Create the MFM command text as described in [MFM Command Setup](terminal-setup.md) 108 | 109 | 4. Add the final command text to **Post-processing scripts** 110 | 111 | ## Slicer Print Settings 112 | 113 | ### Ironing 114 | 115 | If you intend to add isolines and using Ironing on the top surface, the standard ironing inset will cover up the isoline color on the outer wall. 116 | 117 | Set Ironing inset to your line width (nozzle diameter) multiplied between 1 and 1.25 to not obscure the isolines. 118 | 119 | ### Flushing Volumes 120 | 121 | Slicer generated toolchange flushing volumes are readily mixed between all tools when processed with MFM so it is recommended to **set all flushing volumes to the minimum amount** needed between all colors (e.g. 107mm³) for consistency. 122 | 123 | 1. Determine the flushing volume between your 4 colors by running this [calibration](https://makerworld.com/en/models/69131). 124 | 125 | 2. Find the minimum flushing volume needed for any color change. This should be ~107mm³. 126 | 127 | 3. If any color requires extra flushing volume beyond the minimum flushing volume, add that color index to the comma separated array for the key `extraPurgePreviousColors` the [MFM Config Option JSON file](mfm-configuration-options-setup.md). This will add an additional 150mm³ of flushing volume which can be increased by modifying the hard-coded flushing G-code in `mfm/extra_purge.py`. 128 | 129 | > The default G-code for extra purging in `mfm/extra_purge.py` is made for the Bambu X1/P1 and you can modify that for your printer. 130 | -------------------------------------------------------------------------------- /src/MFM-linux32.spec: -------------------------------------------------------------------------------- 1 | # -*- mode: python ; coding: utf-8 -*- 2 | 3 | 4 | a = Analysis( 5 | ['gui.py'], 6 | pathex=[], 7 | binaries=[], 8 | datas=[], 9 | hiddenimports=[], 10 | hookspath=[], 11 | hooksconfig={}, 12 | runtime_hooks=[], 13 | excludes=[], 14 | noarchive=False, 15 | ) 16 | pyz = PYZ(a.pure) 17 | 18 | exe = EXE( 19 | pyz, 20 | a.scripts, 21 | a.binaries, 22 | a.datas, 23 | [], 24 | name='MFM', 25 | debug=False, 26 | bootloader_ignore_signals=False, 27 | strip=False, 28 | upx=True, 29 | upx_exclude=[], 30 | runtime_tmpdir=None, 31 | console=True, 32 | disable_windowed_traceback=False, 33 | argv_emulation=False, 34 | target_arch=None, 35 | codesign_identity=None, 36 | entitlements_file=None, 37 | icon='..\\assets\\icon.ico', 38 | ) 39 | -------------------------------------------------------------------------------- /src/MFM-win64.spec: -------------------------------------------------------------------------------- 1 | # -*- mode: python ; coding: utf-8 -*- 2 | 3 | 4 | a = Analysis( 5 | ['gui.py'], 6 | pathex=[], 7 | binaries=[], 8 | datas=[], 9 | hiddenimports=[], 10 | hookspath=[], 11 | hooksconfig={}, 12 | runtime_hooks=[], 13 | excludes=[], 14 | noarchive=False, 15 | ) 16 | pyz = PYZ(a.pure) 17 | 18 | exe = EXE( 19 | pyz, 20 | a.scripts, 21 | a.binaries, 22 | a.datas, 23 | [], 24 | name='MFM', 25 | debug=False, 26 | bootloader_ignore_signals=False, 27 | strip=False, 28 | upx=True, 29 | upx_exclude=[], 30 | runtime_tmpdir=None, 31 | console=True, 32 | disable_windowed_traceback=False, 33 | argv_emulation=False, 34 | target_arch=None, 35 | codesign_identity=None, 36 | entitlements_file=None, 37 | icon=['..\\assets\\icon.ico'], 38 | ) 39 | -------------------------------------------------------------------------------- /src/gui.py: -------------------------------------------------------------------------------- 1 | import tkinter as tk 2 | from tkinter import ttk 3 | from tkinter import filedialog as fd 4 | from tkinter import messagebox 5 | 6 | import json 7 | import os 8 | 9 | import threading 10 | import queue 11 | 12 | import enum 13 | 14 | import webbrowser 15 | 16 | from mfm.configuration import * 17 | from mfm.map_post_process import * 18 | from mfm.plate_sliced import * 19 | 20 | # RUNTIME Flag 21 | TEST_MODE = False 22 | 23 | # UI Constants 24 | POST_PROCESS_BUTTON = 'Post Process' 25 | POST_PROCESS_BUTTON_PROCESSING = 'Processing' 26 | 27 | # Options keys 28 | #CONFIG_INPUT_FILE = 'importGcodeFilename' 29 | IMPORT_OPTIONS_FILENAME = 'importOptionsFilename' 30 | #CONFIG_OUTPUT_FILE = 'exportGcodeFilename' 31 | 32 | 33 | 34 | LINE_ENDING_FLAVOR = 'lineEndingFlavor' 35 | 36 | # user options dict 37 | userOptions = {} 38 | 39 | def select_open_file(filetypes:tuple[str]): 40 | filetypes.append(('All files', '*.*')) 41 | 42 | filename = fd.askopenfilename( 43 | title='Open a file', 44 | initialdir='./', 45 | filetypes=filetypes) 46 | 47 | return filename 48 | 49 | def select_save_file(filetypes:tuple[str]): 50 | filetypes.append(('All files', '*.*')) 51 | 52 | filename = fd.asksaveasfilename( 53 | title='Save as file', 54 | initialdir='./', 55 | filetypes=filetypes) 56 | 57 | return filename 58 | 59 | def truncateMiddleLength(s, length): 60 | if len(s) > length: 61 | s = f"{s[:int(length/2)-3]}...{s[-int(length/2):]}" 62 | return s 63 | 64 | def addExportToFilename(fn): 65 | fnSplit = fn.rsplit('.', 2) 66 | exportFn = f"{fnSplit[0]}" 67 | if len(fnSplit) == 3: 68 | if fnSplit[1].lower() == 'gcode' and fnSplit[2].lower() == '3mf': 69 | exportFn += f"-{MFM_EXPORT_FILE_SUFFIX}.{fnSplit[1]}.{fnSplit[2]}" 70 | else: 71 | exportFn += f"{fnSplit[1]}-{MFM_EXPORT_FILE_SUFFIX}.{fnSplit[2]}" 72 | elif len(fnSplit) == 2: 73 | exportFn += f"-{MFM_EXPORT_FILE_SUFFIX}.{fnSplit[1]}" 74 | elif len(fnSplit) == 1: 75 | exportFn += f"-{MFM_EXPORT_FILE_SUFFIX}" 76 | return exportFn 77 | 78 | class App(tk.Tk): 79 | def __init__(self, queue: queue.Queue): 80 | super().__init__() 81 | 82 | self.title(f'{APP_NAME} {APP_VERSION}') 83 | self.minsize(500, 300) 84 | self.resizable(False, False) 85 | 86 | # configure the grid 87 | self.columnconfigure(0, weight=1) 88 | self.columnconfigure(1, weight=3) 89 | 90 | self.queue = queue 91 | self.postProcessThread: threading.Thread = None 92 | 93 | # UI strings 94 | self.statusLeft = tk.StringVar() 95 | self.statusRight = tk.StringVar() 96 | self.progress = tk.DoubleVar() 97 | self.progressButtonString = tk.StringVar(value=POST_PROCESS_BUTTON) 98 | 99 | self.create_widgets() 100 | 101 | def create_widgets(self): 102 | 103 | gcodeFlavorLabel = tk.Label( 104 | master=self, 105 | text='G-code Flavor' 106 | ) 107 | gcodeFlavorLabel.grid(row=0, column=0, sticky=tk.W, padx=10) 108 | gcodeFlavorComboBox = ttk.Combobox( 109 | state="readonly", 110 | values=['Marlin 2 (PrusaSlicer/Bambu Studio/Orca Slicer)'] 111 | ) 112 | gcodeFlavorComboBox.current(0) 113 | gcodeFlavorComboBox.grid(row=0, column=1, sticky=tk.EW, padx=10, pady=10) 114 | 115 | def selectImportGcodeFile(): 116 | fn = select_open_file([('All supported files', '.gcode .gcode.3mf .3mf'), ('G-code', '*.gcode'), ('Plate Sliced 3MF', '*.gcode.3mf'), ('3MF', '*.3mf')]) 117 | if fn: 118 | importGcodeButton.config(text=truncateMiddleLength(fn, 50)) 119 | exportFn = addExportToFilename(fn) 120 | exportGcodeButton.config(text=truncateMiddleLength(exportFn, 50)) 121 | userOptions[CONFIG_INPUT_FILE] = fn 122 | userOptions[CONFIG_OUTPUT_FILE] = exportFn 123 | 124 | def selectOptionsFile(): 125 | fn = select_open_file([('JSON file', '*.json')]) 126 | if fn: 127 | importOptionsButton.config(text=truncateMiddleLength(fn, 50)) 128 | userOptions[IMPORT_OPTIONS_FILENAME] = fn 129 | 130 | def selectToolchangeBareFile(): 131 | fn = select_open_file([('G-code file', '*.gcode')]) 132 | if fn: 133 | importToolchangeBareButton.config(text=truncateMiddleLength(fn, 50)) 134 | userOptions[CONFIG_TOOLCHANGE_MINIMAL_FILE] = fn 135 | 136 | def selectExportGcodeFile(): 137 | fn = select_save_file([('G-code file', '*.gcode')]) 138 | if fn: 139 | if fn == userOptions[CONFIG_INPUT_FILE]: 140 | fn = addExportToFilename(fn) 141 | messagebox.showinfo( 142 | title='Invalid selection', 143 | message='Export file must be different from import file. The export filename has been changed to be different.' 144 | ) 145 | exportGcodeButton.config(text=truncateMiddleLength(fn, 50)) 146 | userOptions[CONFIG_OUTPUT_FILE] = fn 147 | 148 | def selectLineEndingFlavor(event): 149 | print(event) 150 | selectedLineEnding = None 151 | if lineEndingFlavorComboBox.get() == LINE_ENDING_AUTODETECT_TITLE: 152 | selectedLineEnding = LineEnding.AUTODETECT 153 | elif lineEndingFlavorComboBox.get() == LINE_ENDING_WINDOWS_TITLE: 154 | selectedLineEnding = LineEnding.WINDOWS 155 | elif lineEndingFlavorComboBox.get() == LINE_ENDING_UNIX_TITLE: 156 | selectedLineEnding = LineEnding.UNIX 157 | userOptions[LINE_ENDING_FLAVOR] = selectedLineEnding 158 | print("selected "+ lineEndingFlavorComboBox.get()) 159 | 160 | importLabel = tk.Label( 161 | master=self, 162 | text='Input Print G-code' 163 | ) 164 | importLabel.grid(row=1, column=0, sticky=tk.W, padx=10) 165 | importGcodeButton = tk.Button( 166 | master=self, 167 | text='Select G-code / Plate Sliced 3MF', 168 | command=selectImportGcodeFile 169 | ) 170 | importGcodeButton.grid(row=1, column=1, sticky=tk.EW, padx=10, pady=5) 171 | 172 | optionsLabel = tk.Label( 173 | master=self, 174 | text='MFM Config Options' 175 | ) 176 | optionsLabel.grid(row=2, column=0, sticky=tk.W, padx=10) 177 | importOptionsButton = tk.Button( 178 | master=self, 179 | text='Select JSON', 180 | command=selectOptionsFile 181 | ) 182 | importOptionsButton.grid(row=2, column=1, sticky=tk.EW, padx=10, pady=5) 183 | 184 | toolchangeBareLabel = tk.Label( 185 | master=self, 186 | text='Toolchange G-code' 187 | ) 188 | toolchangeBareLabel.grid(row=3, column=0, sticky=tk.W, padx=10) 189 | importToolchangeBareButton = tk.Button( 190 | master=self, 191 | text='Select G-code', 192 | command=selectToolchangeBareFile 193 | ) 194 | importToolchangeBareButton.grid(row=3, column=1, sticky=tk.EW, padx=10, pady=5) 195 | 196 | exportLabel = tk.Label( 197 | master=self, 198 | text='Output G-code' 199 | ) 200 | exportLabel.grid(row=4, column=0, sticky=tk.W, padx=10) 201 | exportGcodeButton = tk.Button( 202 | master=self, 203 | text='Select output G-code location', 204 | command=selectExportGcodeFile 205 | ) 206 | exportGcodeButton.grid(row=4, column=1, sticky=tk.EW, padx=10, pady=5) 207 | 208 | # Line ending 209 | lineEndingFlavorLabel = tk.Label( 210 | master=self, 211 | text='G-code Line Ending' 212 | ) 213 | lineEndingFlavorLabel.grid(row=5, column=0, sticky=tk.W, padx=10) 214 | lineEndingFlavorComboBox = ttk.Combobox( 215 | state="readonly", 216 | values=[LINE_ENDING_AUTODETECT_TITLE, LINE_ENDING_WINDOWS_TITLE, LINE_ENDING_UNIX_TITLE] 217 | ) 218 | lineEndingFlavorComboBox.grid(row=5, column=1, sticky=tk.EW, padx=10, pady=5) 219 | lineEndingFlavorComboBox.bind('<>', selectLineEndingFlavor) 220 | lineEndingFlavorComboBox.current(0) 221 | 222 | separator = ttk.Separator(self, orient=tk.HORIZONTAL) 223 | separator.grid(row=6, column=0, sticky=tk.EW, columnspan=2, padx=15, pady=5) 224 | 225 | self.processStatusLabelLeft = tk.Label( 226 | master=self, 227 | textvariable=self.statusLeft, 228 | wraplength=150, 229 | anchor=tk.W 230 | ) 231 | self.processStatusLabelLeft.grid(row=7, column=0, columnspan=1, padx=10, sticky=tk.EW) 232 | self.statusLeft.set("Current Layer N/A") 233 | 234 | self.processStatusLabelRight = tk.Label( 235 | master=self, 236 | textvariable=self.statusRight, 237 | wraplength=400, 238 | anchor=tk.E 239 | ) 240 | self.processStatusLabelRight.grid(row=7, column=1, columnspan=1, padx=10, sticky=tk.EW) 241 | 242 | self.processStatusProgressBar = ttk.Progressbar( 243 | self, 244 | orient=tk.HORIZONTAL, 245 | variable=self.progress 246 | ) 247 | self.processStatusProgressBar.grid(row=8, column=0, columnspan=2, padx=10, sticky=tk.EW) 248 | 249 | def startPostProcess(): 250 | self.progress.set(0) 251 | self.progressButtonString.set(POST_PROCESS_BUTTON_PROCESSING) 252 | 253 | def postProcessTask(): 254 | global userOptions 255 | userOptions = { 256 | CONFIG_INPUT_FILE : userOptions.get(CONFIG_INPUT_FILE), 257 | IMPORT_OPTIONS_FILENAME : userOptions.get(IMPORT_OPTIONS_FILENAME), 258 | CONFIG_TOOLCHANGE_MINIMAL_FILE : userOptions.get(CONFIG_TOOLCHANGE_MINIMAL_FILE), 259 | CONFIG_OUTPUT_FILE : userOptions.get(CONFIG_OUTPUT_FILE), 260 | LINE_ENDING_FLAVOR : userOptions.get(LINE_ENDING_FLAVOR) 261 | } 262 | 263 | if TEST_MODE: 264 | #userOptions[CONFIG_INPUT_FILE] = 'sample_models/dual_color_dice/tests/dice_multiple_bambu_prime.gcode' 265 | #userOptions[CONFIG_INPUT_FILE] = 'sample_models/dual_color_dice/tests/dice_multiple_bambu_no_prime.gcode' 266 | userOptions[CONFIG_INPUT_FILE] = 'sample_models/dual_color_dice/tests/dice_multiple_orca_prime.gcode' 267 | #userOptions[CONFIG_INPUT_FILE] = 'sample_models/dual_color_dice/tests/dice_multiple_orca_no_prime.gcode' 268 | #userOptions[CONFIG_INPUT_FILE] = 'sample_models/dual_color_dice/tests/dice_multiple_prusa_prime.gcode' 269 | #userOptions[CONFIG_INPUT_FILE] = 'sample_models/dual_color_dice/tests/dice_multiple_prusa_no_prime.gcode' 270 | userOptions[IMPORT_OPTIONS_FILENAME] = 'sample_models/dual_color_dice/config-dice-test.json' 271 | userOptions[CONFIG_TOOLCHANGE_MINIMAL_FILE] = 'minimal_toolchanges/bambu-x1-series.gcode' 272 | #userOptions[CONFIG_TOOLCHANGE_MINIMAL_FILE] = 'minimal_toolchanges/prusa-xl-series.gcode' 273 | userOptions[CONFIG_OUTPUT_FILE] = 'dice-export.gcode' 274 | 275 | #userOptions[CONFIG_INPUT_FILE] = 'sample_models/CA/ca_p3.gcode' 276 | #userOptions[IMPORT_OPTIONS_FILENAME] = 'sample_models/CA/config-usaofplastic-200zperc.json' 277 | #userOptions[CONFIG_TOOLCHANGE_MINIMAL_FILE] = 'minimal_toolchanges/bambu-x1-series.gcode' 278 | #userOptions[CONFIG_OUTPUT_FILE] = 'CA-export.gcode' 279 | 280 | #userOptions[CONFIG_INPUT_FILE] = 'longs.gcode' 281 | #userOptions[IMPORT_OPTIONS_FILENAME] = 'configuration-CO-z1000perc.json' 282 | #userOptions[CONFIG_TOOLCHANGE_MINIMAL_FILE] = 'minimal_toolchanges/bambu-p1-series.gcode' 283 | #userOptions[CONFIG_OUTPUT_FILE] = 'longs-export.gcode' 284 | 285 | else: 286 | if userOptions.get(CONFIG_INPUT_FILE) == None or userOptions.get(IMPORT_OPTIONS_FILENAME) == None or userOptions.get(CONFIG_TOOLCHANGE_MINIMAL_FILE) == None or userOptions.get(CONFIG_OUTPUT_FILE) == None: 287 | messagebox.showerror( 288 | title='Post Process Requirements', 289 | message='Need Print G-code, Options, Toolchange G-code, and Exported G-code to be selected.' 290 | ) 291 | return 292 | 293 | if readUserOptions(userOptions=userOptions, optionsFilename=userOptions.get(IMPORT_OPTIONS_FILENAME)) != None: 294 | messagebox.showerror( 295 | title='Unable to load options', 296 | message='Check if options file format is JSON' 297 | ) 298 | 299 | print(userOptions) 300 | 301 | periodicColors = parsePeriodicColors(userOptions=userOptions) 302 | replacementColors = parseReplacementColors(userOptions=userOptions) 303 | extraPurgePrevColors = parseExtraPurgePrevColors(userOptions=userOptions) 304 | 305 | lineEndingFlavor = userOptions[LINE_ENDING_FLAVOR] if userOptions[LINE_ENDING_FLAVOR] else LineEnding.AUTODETECT 306 | print(f"User selected {repr(lineEndingFlavor)} line ending.") 307 | 308 | mfmConfig = MFMConfiguration() 309 | mfmConfig[CONFIG_GCODE_FLAVOR] = MARLIN_2_BAMBU_PRUSA_MARKED_GCODE 310 | mfmConfig[CONFIG_INPUT_FILE] = userOptions[CONFIG_INPUT_FILE] 311 | mfmConfig[CONFIG_OUTPUT_FILE] = userOptions[CONFIG_OUTPUT_FILE] 312 | mfmConfig[CONFIG_TOOLCHANGE_MINIMAL_FILE] = userOptions[CONFIG_TOOLCHANGE_MINIMAL_FILE] 313 | mfmConfig[CONFIG_PERIODIC_COLORS] = periodicColors 314 | mfmConfig[CONFIG_REPLACEMENT_COLORS] = replacementColors 315 | mfmConfig[CONFIG_EXTRA_PURGE_COLORS] = extraPurgePrevColors 316 | mfmConfig[CONFIG_LINE_ENDING] = lineEndingFlavor.value 317 | mfmConfig[CONFIG_APP_NAME] = APP_NAME 318 | mfmConfig[CONFIG_APP_VERSION] = APP_VERSION 319 | 320 | # Process based on GCODE or 3MF 321 | _, inputFileExtension = os.path.splitext(userOptions.get(CONFIG_INPUT_FILE)) 322 | 323 | if inputFileExtension.lower() == FileExtensions.GCODE.value: 324 | if lineEndingFlavor == LineEnding.AUTODETECT: 325 | with open(userOptions[CONFIG_INPUT_FILE], mode='rb') as f: 326 | lineEndingFlavor = determineLineEndingTypeInFile(fb=f) 327 | print(f"Detected {repr(lineEndingFlavor)} line ending in input file {userOptions[CONFIG_INPUT_FILE]}.") 328 | if lineEndingFlavor == LineEnding.UNKNOWN: 329 | lineEndingFlavor = LineEnding.UNIX 330 | print(f"Defaulting to {LINE_ENDING_UNIX_TITLE}") 331 | 332 | mfmConfig[CONFIG_LINE_ENDING] = lineEndingFlavor.value 333 | 334 | process(configuration=mfmConfig, inputFP=open(userOptions[CONFIG_INPUT_FILE], mode='r'), outputFP=open(userOptions[CONFIG_OUTPUT_FILE], mode='w'), statusQueue=statusQueue) 335 | elif inputFileExtension.lower() == FileExtensions.THREEMF.value: 336 | with zipFilePointerForZip(zipPath=userOptions.get(CONFIG_INPUT_FILE), write=False) as inputZipFile, open(userOptions[CONFIG_OUTPUT_FILE], mode='wb') as outputZipFileFP: 337 | processAllPlateGcodeForZipFile(inputZip=inputZipFile, out=outputZipFileFP, configuration=mfmConfig, statusQueue=statusQueue) 338 | 339 | startPostProcessButton["state"] = "disabled" 340 | 341 | postProcessThread = threading.Thread(target=postProcessTask) 342 | postProcessThread.start() 343 | 344 | # Wait on post process thread in another thread to reset UI 345 | def resetButton(): 346 | postProcessThread.join() 347 | startPostProcessButton["state"] = "normal" 348 | self.progressButtonString.set(POST_PROCESS_BUTTON) 349 | threading.Thread(target=resetButton).start() 350 | 351 | startPostProcessButton = tk.Button( 352 | master=self, 353 | textvariable=self.progressButtonString, 354 | command=startPostProcess 355 | ) 356 | startPostProcessButton.grid(row=9, column=0, sticky=tk.EW, columnspan=2, padx=10) 357 | 358 | infoButton = tk.Button( 359 | master=self, 360 | text=f'About', 361 | command=lambda: 362 | messagebox.showinfo( 363 | title=f"{APP_NAME} v{APP_VERSION}", 364 | message=f'Add isolines and elevation color change features to your 3D model g-code. Meant for use with 3D Topo Maps.\n\n{APP_NAME} is licensed under GNU Affero General Public License, version 3\n\n www.AnsonLiu.com/maps\n© 2023 Anson Liu' 365 | ) 366 | ) 367 | infoButton.grid(row=10, column=0, sticky=tk.W, columnspan=1, padx=10, pady=10) 368 | 369 | websiteButton = tk.Button( 370 | master=self, 371 | text='Help', 372 | command=lambda: 373 | webbrowser.open('https://github.com/ansonl/mfm') 374 | ) 375 | websiteButton.grid(row=10, column=0, sticky=tk.E, columnspan=1, padx=10, pady=10) 376 | 377 | infoLabel = tk.Label( 378 | master=self, 379 | text=f"v{APP_VERSION}" 380 | ) 381 | infoLabel.grid(row=10, column=1, sticky=tk.E, padx=10) 382 | 383 | if __name__ == "__main__": 384 | statusQueue: queue.Queue[StatusQueueItem] = queue.Queue() 385 | app = App(queue=statusQueue) 386 | 387 | def worker(): 388 | while True: 389 | item = statusQueue.get() 390 | statusQueue.task_done() 391 | if item.statusLeft != None: 392 | app.statusLeft.set(item.statusLeft) 393 | if item.statusRight != None: 394 | app.statusRight.set(item.statusRight) 395 | if item.progress != None: 396 | app.progress.set(item.progress) 397 | 398 | threading.Thread(target=worker, daemon=True).start() 399 | 400 | app.mainloop() -------------------------------------------------------------------------------- /src/mfm/app_constants.py: -------------------------------------------------------------------------------- 1 | APP_NAME_ABBREVIATION = 'MFM' 2 | APP_NAME = f'3D G-code Map Feature Modifier ({APP_NAME_ABBREVIATION})' 3 | APP_VERSION = '1.6.8' -------------------------------------------------------------------------------- /src/mfm/configuration.py: -------------------------------------------------------------------------------- 1 | import typing, queue 2 | 3 | import json 4 | 5 | from .printing_classes import PeriodicColor, ReplacementColorAtHeight 6 | 7 | # Only export MFMConfiguration and not any imported values 8 | #__all__ = ['MFMConfiguration'] 9 | MFM_EXPORT_FILE_SUFFIX = 'MFM-export' 10 | 11 | MODEL_TO_REAL_WORLD_DEFAULT_UNITS = 'modelToRealWorldDefaultUnits' 12 | MODEL_ONE_TO_N_VERTICAL_SCALE = 'modelOneToNVerticalScale' 13 | MODEL_SEA_LEVEL_BASE_THICKNESS = 'modelSeaLevelBaseThickness' 14 | 15 | REAL_WORLD_ISOLINE_ELEVATION_INTERVAL = 'realWorldIsolineElevationInterval' 16 | REAL_WORLD_ISOLINE_ELEVATION_START = 'realWorldIsolineElevationStart' 17 | REAL_WORLD_ISOLINE_ELEVATION_END = 'realWorldIsolineElevationEnd' 18 | MODEL_ISOLINE_HEIGHT = 'modelIsolineHeight' #in model units (mm) 19 | ISOLINE_COLOR_INDEX = 'isolineColorIndex' 20 | ISOLINE_ENABLED_FEATURES = 'isolineColorFeatureTypes' 21 | 22 | REAL_WORLD_ELEVATION_REPLACEMENT_COLOR_START = 'realWorldElevationReplacementColorStart' 23 | REAL_WORLD_ELEVATION_REPLACEMENT_COLOR_END = 'realWorldElevationReplacementColorEnd' 24 | REPLACEMENT_COLOR_INDEX = 'replacementColorIndex' 25 | REPLACEMENT_ORIGINAL_COLOR_INDEX = 'replacementOriginalColorIndex' 26 | 27 | EXTRA_PURGE_PREV_COLORS = 'extraPurgePreviousColors' 28 | 29 | periodicColorRequiredOptions = [ 30 | MODEL_TO_REAL_WORLD_DEFAULT_UNITS, 31 | MODEL_ONE_TO_N_VERTICAL_SCALE, 32 | MODEL_SEA_LEVEL_BASE_THICKNESS, 33 | REAL_WORLD_ISOLINE_ELEVATION_INTERVAL, 34 | REAL_WORLD_ISOLINE_ELEVATION_START, 35 | REAL_WORLD_ISOLINE_ELEVATION_END, 36 | MODEL_ISOLINE_HEIGHT, 37 | ISOLINE_COLOR_INDEX, 38 | ISOLINE_ENABLED_FEATURES 39 | ] 40 | 41 | replacementColorRequiredOptions = [ 42 | MODEL_TO_REAL_WORLD_DEFAULT_UNITS, 43 | MODEL_ONE_TO_N_VERTICAL_SCALE, 44 | MODEL_SEA_LEVEL_BASE_THICKNESS, 45 | REAL_WORLD_ELEVATION_REPLACEMENT_COLOR_START, 46 | REAL_WORLD_ELEVATION_REPLACEMENT_COLOR_END, 47 | REPLACEMENT_COLOR_INDEX, 48 | REPLACEMENT_ORIGINAL_COLOR_INDEX 49 | ] 50 | 51 | class MFMConfiguration(typing.TypedDict): 52 | CONFIG_GCODE_FLAVOR: str 53 | CONFIG_INPUT_FILE: str 54 | CONFIG_OUTPUT_FILE: str 55 | CONFIG_TOOLCHANGE_MINIMAL_FILE: str 56 | CONFIG_PERIODIC_COLORS: list[PeriodicColor] 57 | CONFIG_REPLACEMENT_COLORS: list[ReplacementColorAtHeight] 58 | CONFIG_EXTRA_PURGE_COLORS: list[int] 59 | CONFIG_LINE_ENDING: str 60 | CONFIG_APP_NAME: str 61 | CONFIG_APP_VERSION: str 62 | 63 | def readUserOptions(userOptions:dict, optionsFilename:str) -> ValueError: 64 | # Read in user options 65 | with open(optionsFilename) as f: 66 | try: 67 | data = json.load(f) 68 | if isinstance(data,dict): 69 | for item in data.items(): 70 | userOptions[item[0]] = item[1] 71 | else: 72 | raise ValueError() 73 | except ValueError: 74 | return ValueError 75 | return None 76 | 77 | ''' 78 | periodicColors = [ 79 | PeriodicColor(colorIndex=2, startHeight=0.3, endHeight=10, height=0.5, period=1) 80 | ] 81 | replacementColors = [ 82 | ReplacementColorAtHeight(colorIndex=3, originalColorIndex=0, startHeight=8, endHeight=float('inf')) 83 | ] 84 | ''' 85 | 86 | def createIsoline(modelToRealWorldDefaultUnits: float, modelOneToNVerticalScale: float, modelSeaLevelBaseThickness: float, realWorldIsolineElevationInterval: float, realWorldIsolineElevationStart: float, realWorldIsolineElevationEnd: float, modelIsolineHeight: float, colorIndex: int, enabledFeatures: list[str]): 87 | return PeriodicColor(colorIndex=colorIndex, startHeight=modelSeaLevelBaseThickness + modelToRealWorldDefaultUnits*realWorldIsolineElevationStart/modelOneToNVerticalScale, endHeight=modelToRealWorldDefaultUnits*realWorldIsolineElevationEnd/modelOneToNVerticalScale, height=modelIsolineHeight, period=modelToRealWorldDefaultUnits*realWorldIsolineElevationInterval/modelOneToNVerticalScale, enabledFeatures=enabledFeatures) 88 | 89 | def createReplacementColor(modelToRealWorldDefaultUnits: float, modelOneToNVerticalScale: float, modelSeaLevelBaseThickness: float, realWorldElevationStart: float, realWorldElevationEnd: float, colorIndex: int, originalColorIndex: int): 90 | return ReplacementColorAtHeight(colorIndex=colorIndex, originalColorIndex=originalColorIndex, startHeight=modelSeaLevelBaseThickness + modelToRealWorldDefaultUnits*realWorldElevationStart/modelOneToNVerticalScale, endHeight=modelSeaLevelBaseThickness + modelToRealWorldDefaultUnits*realWorldElevationEnd/modelOneToNVerticalScale) 91 | 92 | def parsePeriodicColors(userOptions: dict) -> list[PeriodicColor]: 93 | periodicColors: list[PeriodicColor] = [] 94 | if all (opt in userOptions for opt in periodicColorRequiredOptions): 95 | periodicColors.append( 96 | createIsoline( 97 | modelToRealWorldDefaultUnits=userOptions[MODEL_TO_REAL_WORLD_DEFAULT_UNITS], 98 | modelOneToNVerticalScale=userOptions[MODEL_ONE_TO_N_VERTICAL_SCALE], 99 | modelSeaLevelBaseThickness=userOptions[MODEL_SEA_LEVEL_BASE_THICKNESS], 100 | realWorldIsolineElevationInterval=userOptions[REAL_WORLD_ISOLINE_ELEVATION_INTERVAL], 101 | realWorldIsolineElevationStart=userOptions[REAL_WORLD_ISOLINE_ELEVATION_START], 102 | realWorldIsolineElevationEnd=userOptions[REAL_WORLD_ISOLINE_ELEVATION_END], 103 | modelIsolineHeight=userOptions[MODEL_ISOLINE_HEIGHT], 104 | colorIndex=userOptions[ISOLINE_COLOR_INDEX], 105 | enabledFeatures=userOptions[ISOLINE_ENABLED_FEATURES] 106 | ) 107 | ) 108 | print("Added isoline based on options") 109 | return periodicColors 110 | 111 | def parseReplacementColors(userOptions: dict) -> list[ReplacementColorAtHeight]: 112 | replacementColors: list[ReplacementColorAtHeight] = [] 113 | if all (opt in userOptions for opt in replacementColorRequiredOptions): 114 | replacementColors.append( 115 | createReplacementColor( 116 | modelToRealWorldDefaultUnits=userOptions[MODEL_TO_REAL_WORLD_DEFAULT_UNITS], 117 | modelOneToNVerticalScale=userOptions[MODEL_ONE_TO_N_VERTICAL_SCALE], 118 | modelSeaLevelBaseThickness=userOptions[MODEL_SEA_LEVEL_BASE_THICKNESS], 119 | realWorldElevationStart=userOptions[REAL_WORLD_ELEVATION_REPLACEMENT_COLOR_START], 120 | realWorldElevationEnd=userOptions[REAL_WORLD_ELEVATION_REPLACEMENT_COLOR_END], 121 | colorIndex=userOptions[REPLACEMENT_COLOR_INDEX], 122 | originalColorIndex=userOptions[REPLACEMENT_ORIGINAL_COLOR_INDEX] 123 | ) 124 | ) 125 | print("Added replacement color based on options") 126 | return replacementColors 127 | 128 | def parseExtraPurgePrevColors(userOptions: dict) -> list[int]: 129 | extraPurgePrevColors: list[int] = [] 130 | if EXTRA_PURGE_PREV_COLORS in userOptions and type(userOptions[EXTRA_PURGE_PREV_COLORS]) is list: 131 | extraPurgePrevColors = userOptions[EXTRA_PURGE_PREV_COLORS] 132 | return extraPurgePrevColors -------------------------------------------------------------------------------- /src/mfm/extra_purge.py: -------------------------------------------------------------------------------- 1 | # Purge 150mm^3 of 1.75mm filament 2 | EXTRA_PURGE_GCODE = """ 3 | G91 4 | G1 X3 F12000; move aside to extrude 5 | G90 6 | M83 7 | 8 | ; FLUSH_START 9 | G1 E11.2253 F299 10 | G1 E1.24726 F50 11 | G1 E11.2253 F299 12 | G1 E1.24726 F50 13 | G1 E11.2253 F299 14 | G1 E1.24726 F50 15 | G1 E11.2253 F299 16 | G1 E1.24726 F50 17 | G1 E11.2253 F299 18 | G1 E1.24726 F50 19 | ; FLUSH_END 20 | G1 E-2 F1800 21 | G1 E2 F300 22 | """ -------------------------------------------------------------------------------- /src/mfm/line_ending.py: -------------------------------------------------------------------------------- 1 | import enum, typing 2 | 3 | class LineEnding(enum.Enum): 4 | AUTODETECT = "autodetect" 5 | WINDOWS = "\r\n" 6 | UNIX = "\n" 7 | UNKNOWN = "unknown" 8 | 9 | LINE_ENDING_AUTODETECT_TITLE = f"Autodetect" 10 | LINE_ENDING_WINDOWS_TITLE = f"Windows {repr(LineEnding.WINDOWS.value)}" 11 | LINE_ENDING_UNIX_TITLE = f"Unix {repr(LineEnding.UNIX.value)}" 12 | 13 | def determineLineEndingTypeInFile(fb: typing.TextIO) -> LineEnding: 14 | # with open(fn, mode='rb') as f: 15 | sample1 = b'' 16 | sample2 = b'' 17 | c = 0 18 | while True: 19 | block = fb.read(32) 20 | if not block: 21 | break 22 | if c%2: 23 | sample2=block 24 | else: 25 | sample1=block 26 | 27 | if bytes(LineEnding.WINDOWS.value,'utf-8') in (sample1+sample2 if c%2 else sample2+sample1): 28 | return LineEnding.WINDOWS 29 | if bytes(LineEnding.UNIX.value,'utf-8') in (sample2+sample1 if not c%2 else sample1+sample2): 30 | return LineEnding.UNIX 31 | c^=1 32 | 33 | return LineEnding.UNKNOWN -------------------------------------------------------------------------------- /src/mfm/plate_sliced.py: -------------------------------------------------------------------------------- 1 | import zipfile, re, typing, queue, io, enum, os 2 | 3 | from .configuration import * 4 | from .map_post_process import * 5 | from .line_ending import * 6 | 7 | # AMS remapping in Print dialog requires 8 | # N settings for N colors in Metadata/project_settings.config 9 | # N for N colors in Metadata/slice_info.config 10 | 11 | class FileExtensions(enum.Enum): 12 | UNKNOWN = "unknown" 13 | GCODE = ".gcode" 14 | THREEMF = ".3mf" 15 | 16 | PLATE_N = 'plate_\d+.gcode$' 17 | 18 | def zipFilePointerForZip(zipPath: str, write: bool): 19 | return zipfile.ZipFile(zipPath, 'w' if write else 'r') 20 | 21 | # Adapted from https://medium.com/dev-bits/ultimate-guide-for-working-with-i-o-streams-and-zip-archives-in-python-3-6f3cf96dca50 22 | def processAllPlateGcodeForZipFile(inputZip: zipfile.ZipFile, out: typing.TextIO, configuration: MFMConfiguration, statusQueue: queue.Queue): 23 | startTime = time.monotonic() 24 | new_zip = io.BytesIO() 25 | 26 | with zipfile.ZipFile(new_zip, 'w') as new_archive: 27 | platesProcessed = 0 28 | for item in inputZip.filelist: 29 | # If you spot an existing file, create a new object 30 | if re.match(PLATE_N, os.path.basename(item.filename)): 31 | if statusQueue: 32 | sqItem = StatusQueueItem() 33 | sqItem.statusLeft = f"{os.path.basename(item.filename)}" 34 | sqItem.statusRight = f"Starting" 35 | sqItem.progress = 0 36 | statusQueue.put(item=sqItem) 37 | 38 | zi = zipfile.ZipInfo(item.filename) 39 | 40 | tmpGcodeFilename = os.path.basename(item.filename) 41 | tmpGcodeFile = open(tmpGcodeFilename, mode='w') 42 | 43 | # Detect line ending of Gcode file 44 | if configuration[CONFIG_LINE_ENDING] == LineEnding.AUTODETECT.value: 45 | lineEndingFlavor = LineEnding.AUTODETECT 46 | with io.BytesIO(initial_bytes=inputZip.read(item.filename)) as gcodeBytes: 47 | lineEndingFlavor = determineLineEndingTypeInFile(fb=gcodeBytes) 48 | print(f"Detected {repr(lineEndingFlavor)} line ending in input file {zi.filename}.") 49 | if lineEndingFlavor == LineEnding.UNKNOWN: 50 | lineEndingFlavor = LineEnding.UNIX 51 | print(f"Defaulting to {LINE_ENDING_UNIX_TITLE}") 52 | configuration[CONFIG_LINE_ENDING] = lineEndingFlavor.value 53 | 54 | with io.TextIOWrapper(io.BytesIO(initial_bytes=inputZip.read(item.filename))) as gcodeText: 55 | process(configuration=configuration, inputFP=gcodeText, outputFP=tmpGcodeFile, statusQueue=statusQueue) 56 | 57 | # Zipfile implementation of seek is too slow because it restarts from start of file each time 58 | # https://stackoverflow.com/questions/51801213/complexity-of-f-seek-in-python/51801243 59 | #process(configuration=configuration, inputFP=io.TextIOWrapper(inputZip.open(zi.filename, mode='r')), outputFP=tmpGcodeFile, statusQueue=statusQueue) 60 | 61 | if statusQueue: 62 | sqItem = StatusQueueItem() 63 | sqItem.statusLeft = f"{os.path.basename(item.filename)}" 64 | sqItem.statusRight = f"Compressing" 65 | sqItem.progress = 50 66 | statusQueue.put(item=sqItem) 67 | 68 | new_archive.write(tmpGcodeFilename, arcname=item.filename, compress_type=zipfile.ZIP_DEFLATED, compresslevel=9) 69 | platesProcessed += 1 70 | else: 71 | if statusQueue: 72 | sqItem = StatusQueueItem() 73 | sqItem.statusLeft = f"{os.path.basename(item.filename)}" 74 | sqItem.statusRight = f"Compressing" 75 | sqItem.progress = 50 76 | statusQueue.put(item=sqItem) 77 | 78 | # Copy other contents as it is 79 | # Bambu Studio only supports DEFLATE compression 80 | new_archive.writestr(item, inputZip.read(item.filename), compress_type=zipfile.ZIP_DEFLATED, compresslevel=9) 81 | 82 | if statusQueue: 83 | sqItem = StatusQueueItem() 84 | sqItem.statusLeft = f"{os.path.basename(configuration[CONFIG_INPUT_FILE])}" 85 | sqItem.statusRight = f"Saving" 86 | sqItem.progress = 75 87 | statusQueue.put(item=sqItem) 88 | 89 | out.write(new_zip.getbuffer()) 90 | 91 | if statusQueue: 92 | sqItem = StatusQueueItem() 93 | sqItem.statusRight = f"Completed all {platesProcessed} plate sliced G-code{'s' if platesProcessed > 0 else ''} in {str(datetime.timedelta(seconds=time.monotonic()-startTime))}s" if platesProcessed > 0 else "Did not find any plate sliced G-code to process." 94 | sqItem.progress = 100 95 | statusQueue.put(item=sqItem) 96 | 97 | def allPlateGcodeFilePointersForZipFile(z: zipfile.ZipFile) -> list[typing.TextIO]: 98 | plateGcodeFilePointers = [] 99 | 100 | for zi in z.infolist(): 101 | if re.match(PLATE_N, zi.filename): 102 | plateGcodeFilePointers.append(io.TextIOWrapper(z.open(zi))) 103 | -------------------------------------------------------------------------------- /src/mfm/printing_classes.py: -------------------------------------------------------------------------------- 1 | import enum 2 | 3 | class StatusQueueItem: 4 | "Status Queue Item properties to send to the user." 5 | def __init__(self): 6 | self.statusLeft = None 7 | self.statusRight = None 8 | self.progress = None 9 | 10 | # Position 11 | class Position: 12 | """Position, Feedrate, and Acceleration values for printing""" 13 | def __init__(self): 14 | # Position 15 | self.X: float 16 | self.Y: float 17 | self.Z: float 18 | self.E: float 19 | 20 | # Feedrate 21 | self.F: float 22 | self.FTravel: float 23 | 24 | # Acceleration 25 | self.P: float 26 | """Printing acceleration""" 27 | self.R: float 28 | """Retract acceleration""" 29 | self.T: float 30 | """Travel acceleration for moves with no extrusion.""" 31 | 32 | class ToolchangeType(enum.Enum): 33 | NONE = enum.auto() 34 | """No toolchange""" 35 | MINIMAL = enum.auto() 36 | """Minimal toolchange is a generic toolchange procedure.""" 37 | FULL = enum.auto() 38 | """Full toolchange is derived from an existing toolchange in the original G-code.""" 39 | 40 | # Reason for skip when looping that is set when first starting a feature 41 | class SkipType(enum.Enum): 42 | PRIME_TOWER_FEATURE = enum.auto() 43 | """Prime Tower or Wipe Tower""" 44 | FEATURE_ORIG_TOOLCHANGE_AND_WIPE_END = enum.auto() 45 | """The original toolchange and Wipe End within a feature.""" 46 | 47 | # State of current Print FILE 48 | class PrintState: 49 | """The current state of the processed G-code file.""" 50 | 51 | def __init__(self): 52 | """Constructor method 53 | """ 54 | super().__init__() 55 | 56 | self.height: float = -1 57 | """The current printing height relative to the buildplate.""" 58 | self.layerHeight: float = 0 59 | """The layer height of an individual layer relative to the top of the last layer. E.g. 0.12, 0.2""" 60 | self.previousLayerHeight: float = 0 61 | """The previous layer's layer height.""" 62 | self.layerStart: int = 0 63 | """The character position of the layer start.""" 64 | self.layerEnd: int = 0 65 | """The character position of the layer end.""" 66 | self.lastFeature: Feature = None 67 | """Reference to last original feature of the previous layer. Used in case it originally continues to next layer.""" 68 | self.prevLayerLastFeature: Feature = None 69 | """Reference to last original feature of the layer before the previous layer.""" 70 | 71 | # Color info 72 | self.originalColor: int = -1 73 | """last color changed to in original print at the start of the layer""" 74 | self.layerEndOriginalColor: int = -1 75 | """last color changed to in the original print at the end of the current layer""" 76 | self.printingColor: int = -1 77 | """current modified color""" 78 | self.printingPeriodicColor: bool = False 79 | """last layer was PeriodicColor?""" 80 | self.isPeriodicLine: bool = False 81 | """is this layer supposed to have periodic lines?""" 82 | 83 | # Movement info 84 | self.originalPosition: Position = Position() # Restore original XYZ position after inserting a TC. Then do E2 for minimal TC. Full Prime tower TC already does E.8 85 | """The position of the extruder in the original print file.""" 86 | 87 | # Prime tower / Toolchange values for current layer 88 | self.features: list[Feature] = [] 89 | """Printing features found on the current layer""" 90 | self.primeTowerFeatures: list[Feature] = [] # The available prime tower features. 91 | """Prime Tower features found on the current layer""" 92 | self.stopPositions: list[int] = [] 93 | """Stop Positions for process() loop to stop and process next printing feature""" 94 | self.toolchangeInsertionPoint: int = 0 95 | """The next toolchange insertion point""" 96 | self.featureWipeEndPrime: Position = None 97 | """prime values at end of wipe_end""" 98 | 99 | #Loop settings 100 | self.skipWrite: bool = False 101 | """Skip writing at the end of process loop.""" 102 | self.skipWriteForCurrentLine: bool = False 103 | """Skip writing the current line at the end of process loop. Reset at the end of the loop.""" 104 | 105 | #self.toolchangeBareInsertionPoint: Feature = None 106 | #self.toolchangeFullInsertionPoint: Feature = None 107 | #self.toolchangeNewColorIndex: int = -1 108 | #self.skipOriginalPrimeTowerAndToolchangeOnLayer: bool = False 109 | #self.skipOriginalToolchangeOnLayer: bool = False 110 | 111 | class Feature: 112 | """Printing Feature properties""" 113 | 114 | def __init__(self): 115 | """Constructor""" 116 | super().__init__() 117 | self.featureType: str = None 118 | self.start: int = 0 119 | self.end: int = 0 120 | self.toolchange: Feature = None 121 | self.isPeriodicColor: bool = False 122 | self.originalColor: int = -1 123 | self.printingColor: int = -1 124 | self.startPosition: Position = Position() 125 | self.wipeStart: Feature = None 126 | self.wipeEnd: Feature = None 127 | self.skipType: SkipType = None 128 | 129 | class PeriodicColor: 130 | """A repeating Periodic Color (isoline) properties""" 131 | def __init__(self, colorIndex = -1, startHeight = -1, endHeight = -1, height = -1, period = -1, enabledFeatures=[]): 132 | self.colorIndex: int = colorIndex 133 | self.startHeight: float = startHeight 134 | self.endHeight: float = endHeight 135 | self.height: float = height 136 | self.period: float = period 137 | self.enabledFeatures: list[str] = enabledFeatures 138 | 139 | class PrintColor: 140 | """Tracks an individual tool and the replacement tool (color) index.""" 141 | def __init__(self, index=-1, replacementColorIndex=-1, humanColor=None): 142 | self.index: int = index 143 | self.replacementColorIndex: int = replacementColorIndex #the current replacement color 144 | self.humanColor: str = humanColor 145 | self.extraPurgeIfPrevious: bool = False 146 | 147 | loadedColors: list[PrintColor] = [ 148 | PrintColor(0, -1, 'Base Color'), 149 | PrintColor(1, -1, 'River Color'), 150 | PrintColor(2, -1, 'Isoline Color'), 151 | PrintColor(3, -1, 'High Elevation Color') 152 | ] 153 | """All loaded tools (colors)""" 154 | 155 | class ReplacementColorAtHeight: 156 | """A replacement color at height properties""" 157 | def __init__(self, colorIndex, originalColorIndex, startHeight, endHeight): 158 | self.colorIndex: int = colorIndex 159 | self.originalColorIndex: int = originalColorIndex 160 | self.startHeight: float = startHeight 161 | self.endHeight: float = endHeight -------------------------------------------------------------------------------- /src/mfm/printing_constants.py: -------------------------------------------------------------------------------- 1 | # Settings keys 2 | CONFIG_GCODE_FLAVOR = 'SETTING_GCODE_FLAVOR' 3 | CONFIG_INPUT_FILE = 'CONFIG_INPUT_FILE' 4 | CONFIG_OUTPUT_FILE = 'CONFIG_OUTPUT_FILE' 5 | CONFIG_TOOLCHANGE_MINIMAL_FILE = 'CONFIG_TOOLCHANGE_MINIMAL_FILE' 6 | CONFIG_PERIODIC_COLORS = 'CONFIG_PERIODIC_COLORS' 7 | CONFIG_REPLACEMENT_COLORS = 'CONFIG_REPLACEMENT_COLORS' 8 | CONFIG_EXTRA_PURGE_COLORS = 'CONFIG_EXTRA_PURGE_COLORS' 9 | CONFIG_LINE_ENDING = 'CONFIG_LINE_ENDING' 10 | CONFIG_APP_NAME = 'CONFIG_APP_NAME' 11 | CONFIG_APP_VERSION = 'CONFIG_APP_VERSION' 12 | 13 | # Gcode flavors 14 | MARLIN_2_BAMBU_PRUSA_MARKED_GCODE = 'marlin2_bambu_prusa_markedtoolchangegcode' 15 | 16 | # Universal MFM Gcode Tags 17 | UNIVERSAL_TOOLCHANGE_START = '^; MFM TOOLCHANGE START' 18 | UNIVERSAL_TOOLCHANGE_END = '^; MFM TOOLCHANGE END' 19 | UNIVERSAL_LAYER_CHANGE_END = '^; MFM LAYER CHANGE END' 20 | 21 | # Gcode Regex and Constants 22 | 23 | # Movement 24 | MOVEMENT_G0 = 'G0' 25 | MOVEMENT_G = '^(?:G(?:0|1|2|3) )\s?(?:([XYZIJPREF])(-?\d*\.?\d*))?(?:\s+([XYZIJPREF])(-?\d*\.?\d*))?(?:\s+([XYZIJPREF])(-?\d*\.?\d*))?(?:\s+([XYZIJPREF])(-?\d*\.?\d*))?(?:\s+([XYZIJPREF])(-?\d*\.?\d*))?(?:\s+([XYZIJPREF])(-?\d*\.?\d*))?(?:\s+([XYZIJPREF])(-?\d*\.?\d*))?' 26 | 27 | # Acceration M204 28 | ACCELERATION_M204 = 'M204' 29 | ACCELERATION_M = '^(?:M(?:204) )\s?(?:([PRTS])(-?\d*\.?\d*))?(?:\s+([PRTS])(-?\d*\.?\d*))?(?:\s+([PRTS])(-?\d*\.?\d*))?(?:\s+([PRTS])(-?\d*\.?\d*))?(?:\s+([PRTS])(-?\d*\.?\d*))?(?:\s+([PRTS])(-?\d*\.?\d*))?(?:\s+([PRTS])(-?\d*\.?\d*))?' 30 | 31 | # Layer Change 32 | LAYER_CHANGE = '^;\s?(?:CHANGE_LAYER|LAYER_CHANGE)' 33 | LAYER_Z_HEIGHT = '^;\s?(?:Z_HEIGHT|Z):\s?(\d*\.?\d*)' # Current object layer height including current layer height 34 | LAYER_HEIGHT = '^;\s?(?:LAYER_HEIGHT|HEIGHT):\s?(\d*\.?\d*)' # Current layer height 35 | 36 | # Prime inserts 37 | FULL_TOOLCHANGE_PRIME = 'G1 E.8 F1800' 38 | MINIMAL_TOOLCHANGE_PRIME = 'G1 E2 F1800' 39 | #FEATURE_START_DEFAULT_PRIME = 'G1 E.2 F1500' 40 | 41 | # Filament End gcode tag - if layer starts with UNIVERSAL_TOOLCHANGE_START instead of m204 or feature. Filament end gcode appears right before UNIVERSAL_TOOLCHANGE_START LINE_WIDTH tag usually appears after FEATURE but appears appear layer_change if continuing feature. 42 | FILAMENT_END_GCODE = '^;\s?filament end gcode' 43 | # M204 S 44 | M204 = '^M204\sS(?:\d*)' 45 | # LINE_WIDTH tag 46 | LINE_WIDTH = '^;\s?(?:LINE_WIDTH|WIDTH):' 47 | 48 | # Feature/Line Type 49 | FEATURE_TYPE = '^;\s?(?:FEATURE|TYPE):\s?(.*)' 50 | PRIME_TOWER = 'Prime tower' 51 | WIPE_TOWER = 'Wipe tower' 52 | # MFM placeholders 53 | TOOLCHANGE = 'Toolchange' 54 | UNKNOWN_CONTINUED = 'Unknown continued' 55 | 56 | # Slicer toolchange start 57 | TOOLCHANGE_START = '^; CP TOOLCHANGE START' 58 | 59 | # Toolchange 60 | M620 = '^M620 S(\d*)A' 61 | TOOLCHANGE_T = '^\s*T(?!255$|1000|1100$)(\d+)' # Do not match T255,T1000,T1100 which are nonstandard by Bambu. We do not change tabbed T commands. There is a bug where the file pointer will jump to the beginning. This regex needs to handle whitespace in beginning to get the initial AMS toolchange 62 | M621 = '^M621 S(\d*)A' 63 | EXTRA_PURGE_INSERTION = '; EXTRA_PURGE_INSERTION' 64 | EXTRA_PURGE_INSERTION_RE = f'^{EXTRA_PURGE_INSERTION}' 65 | 66 | # Feature Wipe sections 67 | WIPE_START = '^;\s?WIPE_START' 68 | WIPE_END = '^;\s?WIPE_END' 69 | RETAIN_WIPE_END_FEATURE_TYPES = ['Internal infill'] 70 | RETAIN_WIPE_END_IF_FEATURE_END_NOT_WITHIN_N_LINES = 6 71 | 72 | # Start and stop individual object 73 | #STOP_OBJECT = '^;\s(?:stop printing object)\s?(?:, unique label|.*)\sid:?\s?(\d*)' 74 | #START_OBJECT = '^;\s(?:start printing object|printing)\s?(?:, unique label|.*)\sid:?\s?(\d*)' 75 | 76 | CHANGE_LAYER_CURA = '^;LAYER:\d*' 77 | FEATURE_CURA = '^;TYPE:(.*)' -------------------------------------------------------------------------------- /src/mfm_cmd.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import enum 3 | import shutil 4 | import os 5 | import logging 6 | import sys 7 | import threading 8 | 9 | from mfm.line_ending import * 10 | from mfm.map_post_process import * 11 | 12 | 13 | class LineEndingCommandLineParameter(enum.Enum): 14 | AUTODETECT = "AUTO" 15 | WINDOWS = "WINDOWS" 16 | UNIX = "UNIX" 17 | 18 | 19 | TEMP_OUTPUT_GCODE_FILE = 'mfm-output.gcode' 20 | 21 | # python ./src/mfm_cmd.py ./sample_models/dual_color_dice/tests/dice_multiple_bambu_prime.gcode -o dice-export.gcode -c ./sample_models/dual_color_dice/config-dice-test.json -t ./minimal_toolchanges/bambu-p1-series.gcode 22 | 23 | # python ./src/mfm_cmd.py "C:\Users\ansonl\Downloads\Die and Dots_PLA_3h21m.gcode" -o dice-export.gcode -c ./sample_models/dual_color_dice/config-dice-test.json -t ./minimal_toolchanges/bambu-p1-series.gcode 24 | 25 | # Mac Slicer Post processing 26 | # /usr/local/bin/python3 ~/development/topo-map-post-processing/src/mfm_cmd.py ~/development/topo-map-post-processing/sample_models/dual_color_dice/tests/dice_multiple_bambu_prime.gcode -c ~/development/topo-map-post-processing/sample_models/dual_color_dice/config-dice-test.json -t ~/development/topo-map-post-processing/minimal_toolchanges/bambu-p1-series.gcode 27 | 28 | # Mac Slicer Post processing (general) 29 | # python3 ~/src/mfm_cmd.py ~/sample_models/dual_color_dice/tests/dice_multiple_bambu_prime.gcode -c ./sample_models/dual_color_dice/config-dice-test.json -t ./minimal_toolchanges/bambu-p1-series.gcode 30 | 31 | # Slicer Post-processing Scripts (general) 32 | # "PYTHONPATH/python3.11.exe" "SCRIPTPATH/mfm_cmd.py" -c "OPTIONSPATH/options.json" -t "TOOLCHANGEPATH/toolchange.gcode"; 33 | 34 | # Slicer Post-processing Scripts (windows) (put project folder in user home folder) 35 | # "C:\Users\USERNAME\AppData\Local\Microsoft\WindowsApps\python3.11.exe" "C:\Users\USERNAME\topo-map-post-processing\src\mfm_cmd.py" -c "C:\Users\USERNAME\topo-map-post-processing\sample_models\dual_color_dice\config-dice-test.json" -t "C:\Users\USERNAME\topo-map-post-processing\minimal_toolchanges\bambu-p1-series.gcode"; 36 | 37 | 38 | def setupLogging(): 39 | redirectSTDERR = open(os.path.join( 40 | os.path.expanduser('~'), 'mfm-script-stderr.log'), "w") 41 | sys.stderr.write = redirectSTDERR.write 42 | 43 | ''' 44 | redirectSTDOUT = open(os.path.join(os.path.expanduser('~'), 'mfm-script-stdout.log'), "w") 45 | sys.stdout.write = redirectSTDOUT.write 46 | ''' 47 | 48 | log_file_path = os.path.join(os.path.expanduser('~'), 'mfm-script.log') 49 | try: 50 | logging.basicConfig(level=logging.DEBUG, 51 | format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s', 52 | filename=log_file_path, 53 | filemode='w') 54 | console = logging.StreamHandler(stream=sys.stdout) 55 | console.setLevel(logging.DEBUG) 56 | formatter = logging.Formatter( 57 | '%(name)-12s: %(levelname)-8s %(message)s') 58 | console.setFormatter(formatter) 59 | logging.getLogger('').addHandler(console) 60 | logging.getLogger('').setLevel(logging.DEBUG) 61 | except Exception as e: 62 | print(f"Failed to create log file: {e}") 63 | 64 | logging.info(f"Logging started") 65 | 66 | 67 | def runScript(): 68 | 69 | # Set up status queue 70 | statusQueue: queue.Queue[StatusQueueItem] = queue.Queue() 71 | 72 | def worker(): 73 | while True: 74 | item = statusQueue.get() 75 | statusQueue.task_done() 76 | status = None 77 | if item.statusLeft != None: 78 | status = item.statusLeft 79 | if item.statusRight != None: 80 | status = item.statusRight 81 | if item.progress != None: 82 | status = f'Progress {item.progress}' 83 | logging.info(status) 84 | threading.Thread(target=worker, daemon=True).start() 85 | 86 | # Setup arguments to parse 87 | parser = argparse.ArgumentParser( 88 | description='3D G-code Map Feature Modifier (MFM)', 89 | epilog='Report issues and contribute at https://github.com/ansonl/mfm' 90 | ) 91 | parser.add_argument('input_gcode', type=str, help='Input G-code file') 92 | parser.add_argument('-o', '--output_gcode', 93 | help='Output G-code file. Overwrite Input G-code file if no output provided.') 94 | parser.add_argument('-c', '--config', required=True, 95 | help='Options configuration JSON file') 96 | parser.add_argument('-t', '--toolchange', required=True, 97 | help='Toolchange G-code file') 98 | parser.add_argument('-le', choices=[LineEndingCommandLineParameter.AUTODETECT.value, LineEndingCommandLineParameter.WINDOWS.value, 99 | LineEndingCommandLineParameter.UNIX.value], default=LineEndingCommandLineParameter.AUTODETECT, help='Line ending style') 100 | parser.add_argument('--disable', type=int, 101 | choices=[0, 1], default=0, help='Disable post processing') 102 | 103 | args = parser.parse_args() 104 | logging.info(f'Parsed args {args}') 105 | 106 | inputGcodeFile = args.input_gcode 107 | outputGcodeFile = args.output_gcode 108 | configFile = args.config 109 | toolchangeFile = args.toolchange 110 | lineEndingFlavor = args.le 111 | disable = args.disable 112 | 113 | if outputGcodeFile == None: 114 | outputGcodeFile = TEMP_OUTPUT_GCODE_FILE 115 | status = f"No Output G-code file provided. Temp output at {outputGcodeFile}. input file will be replaced by temp file." 116 | logging.info(status) 117 | 118 | status = f"Input G-code file is {inputGcodeFile}" 119 | logging.info(status) 120 | 121 | # Load Options from JSON file 122 | userOptions = {} 123 | loadOptionsError = readUserOptions( 124 | userOptions=userOptions, optionsFilename=configFile) 125 | if loadOptionsError != None: 126 | status = f'Config JSON file could not be parsed. {loadOptionsError}' 127 | logging.error(status) 128 | status = f'UserOptions are {userOptions}' 129 | logging.info(status) 130 | 131 | # Parse colors 132 | periodicColors = parsePeriodicColors(userOptions=userOptions) 133 | replacementColors = parseReplacementColors(userOptions=userOptions) 134 | extraPurgePrevColors = parseExtraPurgePrevColors(userOptions=userOptions) 135 | 136 | # Determine line ending 137 | if lineEndingFlavor == LineEndingCommandLineParameter.AUTODETECT: 138 | lineEndingFlavor = LineEnding.AUTODETECT 139 | if lineEndingFlavor == LineEndingCommandLineParameter.WINDOWS: 140 | lineEndingFlavor = LineEnding.WINDOWS 141 | elif lineEndingFlavor == LineEndingCommandLineParameter.UNIX: 142 | lineEndingFlavor = LineEnding.UNIX 143 | else: 144 | lineEndingFlavor = LineEnding.AUTODETECT 145 | 146 | status = f"User selected {repr(lineEndingFlavor)} line ending." 147 | logging.info(status) 148 | if lineEndingFlavor == LineEnding.AUTODETECT: 149 | with open(inputGcodeFile, mode='rb') as f: 150 | lineEndingFlavor = determineLineEndingTypeInFile(fb=f) 151 | status = f"Detected {repr(lineEndingFlavor)} line ending in input G-code file." 152 | logging.info(status) 153 | if lineEndingFlavor == LineEnding.UNKNOWN: 154 | lineEndingFlavor = LineEnding.UNIX 155 | status = f"Defaulting to {LINE_ENDING_UNIX_TITLE}" 156 | logging.warning(status) 157 | 158 | if disable == 1: 159 | status = "Script skipping because --disable flag was 1. " 160 | print(status) 161 | logging.info(status) 162 | return 163 | 164 | # Create config dict that is sent to process loop 165 | mfmConfig = MFMConfiguration() 166 | mfmConfig[CONFIG_GCODE_FLAVOR] = MARLIN_2_BAMBU_PRUSA_MARKED_GCODE 167 | mfmConfig[CONFIG_INPUT_FILE] = inputGcodeFile 168 | mfmConfig[CONFIG_OUTPUT_FILE] = outputGcodeFile 169 | mfmConfig[CONFIG_TOOLCHANGE_MINIMAL_FILE] = toolchangeFile 170 | mfmConfig[CONFIG_PERIODIC_COLORS] = periodicColors 171 | mfmConfig[CONFIG_REPLACEMENT_COLORS] = replacementColors 172 | mfmConfig[CONFIG_EXTRA_PURGE_COLORS] = extraPurgePrevColors 173 | mfmConfig[CONFIG_LINE_ENDING] = lineEndingFlavor.value 174 | mfmConfig[CONFIG_APP_NAME] = APP_NAME 175 | mfmConfig[CONFIG_APP_VERSION] = APP_VERSION 176 | 177 | process(configuration=mfmConfig, inputFP=open(mfmConfig[CONFIG_INPUT_FILE], mode='r'), outputFP=open( 178 | mfmConfig[CONFIG_OUTPUT_FILE], mode='w'), statusQueue=statusQueue) 179 | 180 | status = f'Wrote output G-code to {outputGcodeFile}\n' 181 | logging.info(status) 182 | 183 | # Overwrite the input G-code file if no output file was passed 184 | if outputGcodeFile == TEMP_OUTPUT_GCODE_FILE: 185 | shutil.move(TEMP_OUTPUT_GCODE_FILE, inputGcodeFile) 186 | status = f'Moved temp output G-code to {inputGcodeFile}\n' 187 | logging.info(status) 188 | 189 | 190 | if __name__ == "__main__": 191 | 192 | setupLogging() 193 | runScript() 194 | -------------------------------------------------------------------------------- /terminal-setup.md: -------------------------------------------------------------------------------- 1 | # MFM Command Setup 2 | 3 | 1. Download the [current code of MFM](https://github.com/ansonl/mfm/archive/refs/heads/master.zip) and extract the entire folder to a location such as your user home directory `~`. 4 | 5 | 2. Replace the UPPERCASE of the below sample MFM command text as described further below. 6 | 7 | ```sh 8 | "PYTHONPATH/python3.exe" "SCRIPTPATH/mfm_cmd.py" -c "OPTIONSPATH/options.json" -t "TOOLCHANGEPATH/toolchange.gcode" --disable 0; 9 | ``` 10 | 11 | Command structure: 12 | 13 | - `PYTHONPATH` is the location of your [Python](https://python.org) installation. This is the folder that the Python executable is in. You may need to change `python3.exe` to match your Python name. 14 | 15 | - `SCRIPTPATH` is the location of all the files in the `src` directory. 16 | 17 | - `-c` – Options JSON 18 | - `OPTIONSPATH` is the location of your Options JSON file. Change `options.json` to the options file name. 19 | 20 | - `-t` – Toolchange G-code 21 | - `TOOLCHANGEPATH` is the location of your Minimal Toolchange G-code file. Change `toolchange.json` to the toolchange filename. 22 | 23 | - `-le` *optional* – Line ending style 24 | - `AUTO` – Auto detect 25 | - `WINDOWS` – `\r\n` 26 | - `UNIX` – `\n` 27 | 28 | - `-o` *optional* – Output Print G-code location. 29 | - **Omit this parameter if using MFM as an intergrated Post-processing Script within the slicer.** This is the location of the output printing G-code. MFM will overwrite the input file if no output file is specified. 30 | 31 | - `--disable` *optional* – Quick toggle for enable/disable MFM post processing without needing to clear the entire slicer Post-processing scripts option. 32 | - `0` – MFM is enabled 33 | - `1` – MFM is disabled 34 | 35 | - `-h` – Show parameter help. 36 | 37 | ## Windows command example 38 | 39 | Put the downloaded project folder in your user home folder. Replace `USERNAME` with your username. 40 | 41 | ```sh 42 | "C:\Users\USERNAME\AppData\Local\Microsoft\WindowsApps\python3.exe" "C:\Users\USERNAME\mfm\src\mfm_cmd.py" -c "C:\Users\USERNAME\mfm\premade_options\USAofPlastic-meters.json" -t "C:\Users\USERNAME\mfm\minimal_toolchanges\bambu-p1-series.gcode" --disable 0; 43 | ``` 44 | 45 | ## Linux / Mac command example 46 | 47 | Put the downloaded project folder in your user home folder. 48 | 49 | ```sh 50 | /usr/local/bin/python3 "~/mfm/src/mfm_cmd.py" -c "~/mfm/premade_options/USAofPlastic-meters.json" -t "~/mfm/minimal_toolchanges/bambu-p1-series.gcode" --disable 0; 51 | ``` 52 | 53 | ## Python path (PYTHONPATH) 54 | 55 | The exact PYTHONPATH will depend on how you [installed Python](https://docs.python.org/3/using/windows.html). 56 | 57 | Find where your Python location by running 58 | 59 | - Windows cmd.exe `where python3` or `where python` or [`Get-Command`](https://superuser.com/a/676107) 60 | - Linux/Mac terminal `which python3` or `which python` 61 | 62 | Common Python install locations for Windows are 63 | 64 | - `C:\Program Files\Python X.Y` Python installer "for everyone" option 65 | - `C:\Users\USERNAME\AppData\Local\Programs\Python\PythonXY` Python installer "for me" option 66 | - `C:\Users\USERNAME\AppData\Local\Microsoft\WindowsApps\python3.exe` VSCode Python install 67 | 68 | Common Python install locations for Linux/Mac are 69 | 70 | - `/usr/local/bin/python3` 71 | - `python3` or `python` -------------------------------------------------------------------------------- /tests/slicer-post-processing-scripts-option.sh: -------------------------------------------------------------------------------- 1 | "C:\Users\ansonl\AppData\Local\Microsoft\WindowsApps\python3.11.exe" "C:\Users\ansonl\development\topo-map-post-processing\src\mfm_cmd.py" -c "C:\Users\ansonl\development\topo-map-post-processing\sample_models\dual_color_dice\config-dice-test.json" -t "C:\Users\ansonl\development\topo-map-post-processing\minimal_toolchanges\bambu-p1-series.gcode"; --------------------------------------------------------------------------------