meerk40t 0.9.3001__py2.py3-none-any.whl → 0.9.7010__py2.py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (445) hide show
  1. meerk40t/__init__.py +1 -1
  2. meerk40t/balormk/balor_params.py +167 -167
  3. meerk40t/balormk/clone_loader.py +457 -457
  4. meerk40t/balormk/controller.py +1566 -1512
  5. meerk40t/balormk/cylindermod.py +64 -0
  6. meerk40t/balormk/device.py +966 -1959
  7. meerk40t/balormk/driver.py +778 -591
  8. meerk40t/balormk/galvo_commands.py +1195 -0
  9. meerk40t/balormk/gui/balorconfig.py +237 -111
  10. meerk40t/balormk/gui/balorcontroller.py +191 -184
  11. meerk40t/balormk/gui/baloroperationproperties.py +116 -115
  12. meerk40t/balormk/gui/corscene.py +845 -0
  13. meerk40t/balormk/gui/gui.py +179 -147
  14. meerk40t/balormk/livelightjob.py +466 -382
  15. meerk40t/balormk/mock_connection.py +131 -109
  16. meerk40t/balormk/plugin.py +133 -135
  17. meerk40t/balormk/usb_connection.py +306 -301
  18. meerk40t/camera/__init__.py +1 -1
  19. meerk40t/camera/camera.py +514 -397
  20. meerk40t/camera/gui/camerapanel.py +1241 -1095
  21. meerk40t/camera/gui/gui.py +58 -58
  22. meerk40t/camera/plugin.py +441 -399
  23. meerk40t/ch341/__init__.py +27 -27
  24. meerk40t/ch341/ch341device.py +628 -628
  25. meerk40t/ch341/libusb.py +595 -589
  26. meerk40t/ch341/mock.py +171 -171
  27. meerk40t/ch341/windriver.py +157 -157
  28. meerk40t/constants.py +13 -0
  29. meerk40t/core/__init__.py +1 -1
  30. meerk40t/core/bindalias.py +550 -539
  31. meerk40t/core/core.py +47 -47
  32. meerk40t/core/cutcode/cubiccut.py +73 -73
  33. meerk40t/core/cutcode/cutcode.py +315 -312
  34. meerk40t/core/cutcode/cutgroup.py +141 -137
  35. meerk40t/core/cutcode/cutobject.py +192 -185
  36. meerk40t/core/cutcode/dwellcut.py +37 -37
  37. meerk40t/core/cutcode/gotocut.py +29 -29
  38. meerk40t/core/cutcode/homecut.py +29 -29
  39. meerk40t/core/cutcode/inputcut.py +34 -34
  40. meerk40t/core/cutcode/linecut.py +33 -33
  41. meerk40t/core/cutcode/outputcut.py +34 -34
  42. meerk40t/core/cutcode/plotcut.py +335 -335
  43. meerk40t/core/cutcode/quadcut.py +61 -61
  44. meerk40t/core/cutcode/rastercut.py +168 -148
  45. meerk40t/core/cutcode/waitcut.py +34 -34
  46. meerk40t/core/cutplan.py +1843 -1316
  47. meerk40t/core/drivers.py +330 -329
  48. meerk40t/core/elements/align.py +801 -669
  49. meerk40t/core/elements/branches.py +1844 -1507
  50. meerk40t/core/elements/clipboard.py +229 -219
  51. meerk40t/core/elements/element_treeops.py +4561 -2837
  52. meerk40t/core/elements/element_types.py +125 -105
  53. meerk40t/core/elements/elements.py +4329 -3617
  54. meerk40t/core/elements/files.py +117 -64
  55. meerk40t/core/elements/geometry.py +473 -224
  56. meerk40t/core/elements/grid.py +467 -316
  57. meerk40t/core/elements/materials.py +158 -94
  58. meerk40t/core/elements/notes.py +50 -38
  59. meerk40t/core/elements/offset_clpr.py +933 -912
  60. meerk40t/core/elements/offset_mk.py +963 -955
  61. meerk40t/core/elements/penbox.py +339 -267
  62. meerk40t/core/elements/placements.py +300 -83
  63. meerk40t/core/elements/render.py +785 -687
  64. meerk40t/core/elements/shapes.py +2618 -2092
  65. meerk40t/core/elements/trace.py +651 -563
  66. meerk40t/core/elements/tree_commands.py +415 -409
  67. meerk40t/core/elements/undo_redo.py +116 -58
  68. meerk40t/core/elements/wordlist.py +319 -200
  69. meerk40t/core/exceptions.py +9 -9
  70. meerk40t/core/laserjob.py +220 -220
  71. meerk40t/core/logging.py +63 -63
  72. meerk40t/core/node/blobnode.py +83 -86
  73. meerk40t/core/node/bootstrap.py +105 -103
  74. meerk40t/core/node/branch_elems.py +40 -31
  75. meerk40t/core/node/branch_ops.py +45 -38
  76. meerk40t/core/node/branch_regmark.py +48 -41
  77. meerk40t/core/node/cutnode.py +29 -32
  78. meerk40t/core/node/effect_hatch.py +375 -257
  79. meerk40t/core/node/effect_warp.py +398 -0
  80. meerk40t/core/node/effect_wobble.py +441 -309
  81. meerk40t/core/node/elem_ellipse.py +404 -309
  82. meerk40t/core/node/elem_image.py +1082 -801
  83. meerk40t/core/node/elem_line.py +358 -292
  84. meerk40t/core/node/elem_path.py +259 -201
  85. meerk40t/core/node/elem_point.py +129 -102
  86. meerk40t/core/node/elem_polyline.py +310 -246
  87. meerk40t/core/node/elem_rect.py +376 -286
  88. meerk40t/core/node/elem_text.py +445 -418
  89. meerk40t/core/node/filenode.py +59 -40
  90. meerk40t/core/node/groupnode.py +138 -74
  91. meerk40t/core/node/image_processed.py +777 -766
  92. meerk40t/core/node/image_raster.py +156 -113
  93. meerk40t/core/node/layernode.py +31 -31
  94. meerk40t/core/node/mixins.py +135 -107
  95. meerk40t/core/node/node.py +1427 -1304
  96. meerk40t/core/node/nutils.py +117 -114
  97. meerk40t/core/node/op_cut.py +462 -335
  98. meerk40t/core/node/op_dots.py +296 -251
  99. meerk40t/core/node/op_engrave.py +414 -311
  100. meerk40t/core/node/op_image.py +755 -369
  101. meerk40t/core/node/op_raster.py +787 -522
  102. meerk40t/core/node/place_current.py +37 -40
  103. meerk40t/core/node/place_point.py +329 -126
  104. meerk40t/core/node/refnode.py +58 -47
  105. meerk40t/core/node/rootnode.py +225 -219
  106. meerk40t/core/node/util_console.py +48 -48
  107. meerk40t/core/node/util_goto.py +84 -65
  108. meerk40t/core/node/util_home.py +61 -61
  109. meerk40t/core/node/util_input.py +102 -102
  110. meerk40t/core/node/util_output.py +102 -102
  111. meerk40t/core/node/util_wait.py +65 -65
  112. meerk40t/core/parameters.py +709 -707
  113. meerk40t/core/planner.py +875 -785
  114. meerk40t/core/plotplanner.py +656 -652
  115. meerk40t/core/space.py +120 -113
  116. meerk40t/core/spoolers.py +706 -705
  117. meerk40t/core/svg_io.py +1836 -1549
  118. meerk40t/core/treeop.py +534 -445
  119. meerk40t/core/undos.py +278 -124
  120. meerk40t/core/units.py +784 -680
  121. meerk40t/core/view.py +393 -322
  122. meerk40t/core/webhelp.py +62 -62
  123. meerk40t/core/wordlist.py +513 -504
  124. meerk40t/cylinder/cylinder.py +247 -0
  125. meerk40t/cylinder/gui/cylindersettings.py +41 -0
  126. meerk40t/cylinder/gui/gui.py +24 -0
  127. meerk40t/device/__init__.py +1 -1
  128. meerk40t/device/basedevice.py +322 -123
  129. meerk40t/device/devicechoices.py +50 -0
  130. meerk40t/device/dummydevice.py +163 -128
  131. meerk40t/device/gui/defaultactions.py +618 -602
  132. meerk40t/device/gui/effectspanel.py +114 -0
  133. meerk40t/device/gui/formatterpanel.py +253 -290
  134. meerk40t/device/gui/warningpanel.py +337 -260
  135. meerk40t/device/mixins.py +13 -13
  136. meerk40t/dxf/__init__.py +1 -1
  137. meerk40t/dxf/dxf_io.py +766 -554
  138. meerk40t/dxf/plugin.py +47 -35
  139. meerk40t/external_plugins.py +79 -79
  140. meerk40t/external_plugins_build.py +28 -28
  141. meerk40t/extra/cag.py +112 -116
  142. meerk40t/extra/coolant.py +403 -0
  143. meerk40t/extra/encode_detect.py +198 -0
  144. meerk40t/extra/ezd.py +1165 -1165
  145. meerk40t/extra/hershey.py +835 -340
  146. meerk40t/extra/imageactions.py +322 -316
  147. meerk40t/extra/inkscape.py +630 -622
  148. meerk40t/extra/lbrn.py +424 -424
  149. meerk40t/extra/outerworld.py +284 -0
  150. meerk40t/extra/param_functions.py +1542 -1556
  151. meerk40t/extra/potrace.py +257 -253
  152. meerk40t/extra/serial_exchange.py +118 -0
  153. meerk40t/extra/updater.py +602 -453
  154. meerk40t/extra/vectrace.py +147 -146
  155. meerk40t/extra/winsleep.py +83 -83
  156. meerk40t/extra/xcs_reader.py +597 -0
  157. meerk40t/fill/fills.py +781 -335
  158. meerk40t/fill/patternfill.py +1061 -1061
  159. meerk40t/fill/patterns.py +614 -567
  160. meerk40t/grbl/control.py +87 -87
  161. meerk40t/grbl/controller.py +990 -903
  162. meerk40t/grbl/device.py +1081 -768
  163. meerk40t/grbl/driver.py +989 -771
  164. meerk40t/grbl/emulator.py +532 -497
  165. meerk40t/grbl/gcodejob.py +783 -767
  166. meerk40t/grbl/gui/grblconfiguration.py +373 -298
  167. meerk40t/grbl/gui/grblcontroller.py +485 -271
  168. meerk40t/grbl/gui/grblhardwareconfig.py +269 -153
  169. meerk40t/grbl/gui/grbloperationconfig.py +105 -0
  170. meerk40t/grbl/gui/gui.py +147 -116
  171. meerk40t/grbl/interpreter.py +44 -44
  172. meerk40t/grbl/loader.py +22 -22
  173. meerk40t/grbl/mock_connection.py +56 -56
  174. meerk40t/grbl/plugin.py +294 -264
  175. meerk40t/grbl/serial_connection.py +93 -88
  176. meerk40t/grbl/tcp_connection.py +81 -79
  177. meerk40t/grbl/ws_connection.py +112 -0
  178. meerk40t/gui/__init__.py +1 -1
  179. meerk40t/gui/about.py +2042 -296
  180. meerk40t/gui/alignment.py +1644 -1608
  181. meerk40t/gui/autoexec.py +199 -0
  182. meerk40t/gui/basicops.py +791 -670
  183. meerk40t/gui/bufferview.py +77 -71
  184. meerk40t/gui/busy.py +170 -133
  185. meerk40t/gui/choicepropertypanel.py +1673 -1469
  186. meerk40t/gui/consolepanel.py +706 -542
  187. meerk40t/gui/devicepanel.py +687 -581
  188. meerk40t/gui/dialogoptions.py +110 -107
  189. meerk40t/gui/executejob.py +316 -306
  190. meerk40t/gui/fonts.py +90 -90
  191. meerk40t/gui/functionwrapper.py +252 -0
  192. meerk40t/gui/gui_mixins.py +729 -0
  193. meerk40t/gui/guicolors.py +205 -182
  194. meerk40t/gui/help_assets/help_assets.py +218 -201
  195. meerk40t/gui/helper.py +154 -0
  196. meerk40t/gui/hersheymanager.py +1430 -846
  197. meerk40t/gui/icons.py +3422 -2747
  198. meerk40t/gui/imagesplitter.py +555 -508
  199. meerk40t/gui/keymap.py +354 -344
  200. meerk40t/gui/laserpanel.py +892 -806
  201. meerk40t/gui/laserrender.py +1470 -1232
  202. meerk40t/gui/lasertoolpanel.py +805 -793
  203. meerk40t/gui/magnetoptions.py +436 -0
  204. meerk40t/gui/materialmanager.py +2917 -0
  205. meerk40t/gui/materialtest.py +1722 -1694
  206. meerk40t/gui/mkdebug.py +646 -359
  207. meerk40t/gui/mwindow.py +163 -140
  208. meerk40t/gui/navigationpanels.py +2605 -2467
  209. meerk40t/gui/notes.py +143 -142
  210. meerk40t/gui/opassignment.py +414 -410
  211. meerk40t/gui/operation_info.py +310 -299
  212. meerk40t/gui/plugin.py +494 -328
  213. meerk40t/gui/position.py +714 -669
  214. meerk40t/gui/preferences.py +901 -650
  215. meerk40t/gui/propertypanels/attributes.py +1461 -1131
  216. meerk40t/gui/propertypanels/blobproperty.py +117 -114
  217. meerk40t/gui/propertypanels/consoleproperty.py +83 -80
  218. meerk40t/gui/propertypanels/gotoproperty.py +77 -0
  219. meerk40t/gui/propertypanels/groupproperties.py +223 -217
  220. meerk40t/gui/propertypanels/hatchproperty.py +489 -469
  221. meerk40t/gui/propertypanels/imageproperty.py +2244 -1384
  222. meerk40t/gui/propertypanels/inputproperty.py +59 -58
  223. meerk40t/gui/propertypanels/opbranchproperties.py +82 -80
  224. meerk40t/gui/propertypanels/operationpropertymain.py +1890 -1638
  225. meerk40t/gui/propertypanels/outputproperty.py +59 -58
  226. meerk40t/gui/propertypanels/pathproperty.py +389 -380
  227. meerk40t/gui/propertypanels/placementproperty.py +1214 -383
  228. meerk40t/gui/propertypanels/pointproperty.py +140 -136
  229. meerk40t/gui/propertypanels/propertywindow.py +313 -181
  230. meerk40t/gui/propertypanels/rasterwizardpanels.py +996 -912
  231. meerk40t/gui/propertypanels/regbranchproperties.py +76 -0
  232. meerk40t/gui/propertypanels/textproperty.py +770 -755
  233. meerk40t/gui/propertypanels/waitproperty.py +56 -55
  234. meerk40t/gui/propertypanels/warpproperty.py +121 -0
  235. meerk40t/gui/propertypanels/wobbleproperty.py +255 -204
  236. meerk40t/gui/ribbon.py +2468 -2210
  237. meerk40t/gui/scene/scene.py +1100 -1051
  238. meerk40t/gui/scene/sceneconst.py +22 -22
  239. meerk40t/gui/scene/scenepanel.py +439 -349
  240. meerk40t/gui/scene/scenespacewidget.py +365 -365
  241. meerk40t/gui/scene/widget.py +518 -505
  242. meerk40t/gui/scenewidgets/affinemover.py +215 -215
  243. meerk40t/gui/scenewidgets/attractionwidget.py +315 -309
  244. meerk40t/gui/scenewidgets/bedwidget.py +120 -97
  245. meerk40t/gui/scenewidgets/elementswidget.py +137 -107
  246. meerk40t/gui/scenewidgets/gridwidget.py +785 -745
  247. meerk40t/gui/scenewidgets/guidewidget.py +765 -765
  248. meerk40t/gui/scenewidgets/laserpathwidget.py +66 -66
  249. meerk40t/gui/scenewidgets/machineoriginwidget.py +86 -86
  250. meerk40t/gui/scenewidgets/nodeselector.py +28 -28
  251. meerk40t/gui/scenewidgets/rectselectwidget.py +589 -346
  252. meerk40t/gui/scenewidgets/relocatewidget.py +33 -33
  253. meerk40t/gui/scenewidgets/reticlewidget.py +83 -83
  254. meerk40t/gui/scenewidgets/selectionwidget.py +2952 -2756
  255. meerk40t/gui/simpleui.py +357 -333
  256. meerk40t/gui/simulation.py +2431 -2094
  257. meerk40t/gui/snapoptions.py +208 -203
  258. meerk40t/gui/spoolerpanel.py +1227 -1180
  259. meerk40t/gui/statusbarwidgets/defaultoperations.py +480 -353
  260. meerk40t/gui/statusbarwidgets/infowidget.py +520 -483
  261. meerk40t/gui/statusbarwidgets/opassignwidget.py +356 -355
  262. meerk40t/gui/statusbarwidgets/selectionwidget.py +172 -171
  263. meerk40t/gui/statusbarwidgets/shapepropwidget.py +754 -236
  264. meerk40t/gui/statusbarwidgets/statusbar.py +272 -260
  265. meerk40t/gui/statusbarwidgets/statusbarwidget.py +268 -270
  266. meerk40t/gui/statusbarwidgets/strokewidget.py +267 -251
  267. meerk40t/gui/themes.py +200 -78
  268. meerk40t/gui/tips.py +591 -0
  269. meerk40t/gui/toolwidgets/circlebrush.py +35 -35
  270. meerk40t/gui/toolwidgets/toolcircle.py +248 -242
  271. meerk40t/gui/toolwidgets/toolcontainer.py +82 -77
  272. meerk40t/gui/toolwidgets/tooldraw.py +97 -90
  273. meerk40t/gui/toolwidgets/toolellipse.py +219 -212
  274. meerk40t/gui/toolwidgets/toolimagecut.py +25 -132
  275. meerk40t/gui/toolwidgets/toolline.py +39 -144
  276. meerk40t/gui/toolwidgets/toollinetext.py +79 -236
  277. meerk40t/gui/toolwidgets/toollinetext_inline.py +296 -0
  278. meerk40t/gui/toolwidgets/toolmeasure.py +160 -216
  279. meerk40t/gui/toolwidgets/toolnodeedit.py +2088 -2074
  280. meerk40t/gui/toolwidgets/toolnodemove.py +92 -94
  281. meerk40t/gui/toolwidgets/toolparameter.py +754 -668
  282. meerk40t/gui/toolwidgets/toolplacement.py +108 -108
  283. meerk40t/gui/toolwidgets/toolpoint.py +68 -59
  284. meerk40t/gui/toolwidgets/toolpointlistbuilder.py +294 -0
  285. meerk40t/gui/toolwidgets/toolpointmove.py +183 -0
  286. meerk40t/gui/toolwidgets/toolpolygon.py +288 -403
  287. meerk40t/gui/toolwidgets/toolpolyline.py +38 -196
  288. meerk40t/gui/toolwidgets/toolrect.py +211 -207
  289. meerk40t/gui/toolwidgets/toolrelocate.py +72 -72
  290. meerk40t/gui/toolwidgets/toolribbon.py +598 -113
  291. meerk40t/gui/toolwidgets/tooltabedit.py +546 -0
  292. meerk40t/gui/toolwidgets/tooltext.py +98 -89
  293. meerk40t/gui/toolwidgets/toolvector.py +213 -204
  294. meerk40t/gui/toolwidgets/toolwidget.py +39 -39
  295. meerk40t/gui/usbconnect.py +98 -91
  296. meerk40t/gui/utilitywidgets/buttonwidget.py +18 -18
  297. meerk40t/gui/utilitywidgets/checkboxwidget.py +90 -90
  298. meerk40t/gui/utilitywidgets/controlwidget.py +14 -14
  299. meerk40t/gui/utilitywidgets/cyclocycloidwidget.py +343 -340
  300. meerk40t/gui/utilitywidgets/debugwidgets.py +148 -0
  301. meerk40t/gui/utilitywidgets/handlewidget.py +27 -27
  302. meerk40t/gui/utilitywidgets/harmonograph.py +450 -447
  303. meerk40t/gui/utilitywidgets/openclosewidget.py +40 -40
  304. meerk40t/gui/utilitywidgets/rotationwidget.py +54 -54
  305. meerk40t/gui/utilitywidgets/scalewidget.py +75 -75
  306. meerk40t/gui/utilitywidgets/seekbarwidget.py +183 -183
  307. meerk40t/gui/utilitywidgets/togglewidget.py +142 -142
  308. meerk40t/gui/utilitywidgets/toolbarwidget.py +8 -8
  309. meerk40t/gui/wordlisteditor.py +985 -931
  310. meerk40t/gui/wxmeerk40t.py +1444 -1169
  311. meerk40t/gui/wxmmain.py +5578 -4112
  312. meerk40t/gui/wxmribbon.py +1591 -1076
  313. meerk40t/gui/wxmscene.py +1635 -1453
  314. meerk40t/gui/wxmtree.py +2410 -2089
  315. meerk40t/gui/wxutils.py +1769 -1099
  316. meerk40t/gui/zmatrix.py +102 -102
  317. meerk40t/image/__init__.py +1 -1
  318. meerk40t/image/dither.py +429 -0
  319. meerk40t/image/imagetools.py +2778 -2269
  320. meerk40t/internal_plugins.py +150 -130
  321. meerk40t/kernel/__init__.py +63 -12
  322. meerk40t/kernel/channel.py +259 -212
  323. meerk40t/kernel/context.py +538 -538
  324. meerk40t/kernel/exceptions.py +41 -41
  325. meerk40t/kernel/functions.py +463 -414
  326. meerk40t/kernel/jobs.py +100 -100
  327. meerk40t/kernel/kernel.py +3809 -3571
  328. meerk40t/kernel/lifecycles.py +71 -71
  329. meerk40t/kernel/module.py +49 -49
  330. meerk40t/kernel/service.py +147 -147
  331. meerk40t/kernel/settings.py +383 -343
  332. meerk40t/lihuiyu/controller.py +883 -876
  333. meerk40t/lihuiyu/device.py +1181 -1069
  334. meerk40t/lihuiyu/driver.py +1466 -1372
  335. meerk40t/lihuiyu/gui/gui.py +127 -106
  336. meerk40t/lihuiyu/gui/lhyaccelgui.py +377 -363
  337. meerk40t/lihuiyu/gui/lhycontrollergui.py +741 -651
  338. meerk40t/lihuiyu/gui/lhydrivergui.py +470 -446
  339. meerk40t/lihuiyu/gui/lhyoperationproperties.py +238 -237
  340. meerk40t/lihuiyu/gui/tcpcontroller.py +226 -190
  341. meerk40t/lihuiyu/interpreter.py +53 -53
  342. meerk40t/lihuiyu/laserspeed.py +450 -450
  343. meerk40t/lihuiyu/loader.py +90 -90
  344. meerk40t/lihuiyu/parser.py +404 -404
  345. meerk40t/lihuiyu/plugin.py +101 -102
  346. meerk40t/lihuiyu/tcp_connection.py +111 -109
  347. meerk40t/main.py +231 -165
  348. meerk40t/moshi/builder.py +788 -781
  349. meerk40t/moshi/controller.py +505 -499
  350. meerk40t/moshi/device.py +495 -442
  351. meerk40t/moshi/driver.py +862 -696
  352. meerk40t/moshi/gui/gui.py +78 -76
  353. meerk40t/moshi/gui/moshicontrollergui.py +538 -522
  354. meerk40t/moshi/gui/moshidrivergui.py +87 -75
  355. meerk40t/moshi/plugin.py +43 -43
  356. meerk40t/network/console_server.py +102 -57
  357. meerk40t/network/kernelserver.py +10 -9
  358. meerk40t/network/tcp_server.py +142 -140
  359. meerk40t/network/udp_server.py +103 -77
  360. meerk40t/network/web_server.py +390 -0
  361. meerk40t/newly/controller.py +1158 -1144
  362. meerk40t/newly/device.py +874 -732
  363. meerk40t/newly/driver.py +540 -412
  364. meerk40t/newly/gui/gui.py +219 -188
  365. meerk40t/newly/gui/newlyconfig.py +116 -101
  366. meerk40t/newly/gui/newlycontroller.py +193 -186
  367. meerk40t/newly/gui/operationproperties.py +51 -51
  368. meerk40t/newly/mock_connection.py +82 -82
  369. meerk40t/newly/newly_params.py +56 -56
  370. meerk40t/newly/plugin.py +1214 -1246
  371. meerk40t/newly/usb_connection.py +322 -322
  372. meerk40t/rotary/gui/gui.py +52 -46
  373. meerk40t/rotary/gui/rotarysettings.py +240 -232
  374. meerk40t/rotary/rotary.py +202 -98
  375. meerk40t/ruida/control.py +291 -91
  376. meerk40t/ruida/controller.py +138 -1088
  377. meerk40t/ruida/device.py +672 -231
  378. meerk40t/ruida/driver.py +534 -472
  379. meerk40t/ruida/emulator.py +1494 -1491
  380. meerk40t/ruida/exceptions.py +4 -4
  381. meerk40t/ruida/gui/gui.py +71 -76
  382. meerk40t/ruida/gui/ruidaconfig.py +239 -72
  383. meerk40t/ruida/gui/ruidacontroller.py +187 -184
  384. meerk40t/ruida/gui/ruidaoperationproperties.py +48 -47
  385. meerk40t/ruida/loader.py +54 -52
  386. meerk40t/ruida/mock_connection.py +57 -109
  387. meerk40t/ruida/plugin.py +124 -87
  388. meerk40t/ruida/rdjob.py +2084 -945
  389. meerk40t/ruida/serial_connection.py +116 -0
  390. meerk40t/ruida/tcp_connection.py +146 -0
  391. meerk40t/ruida/udp_connection.py +73 -0
  392. meerk40t/svgelements.py +9671 -9669
  393. meerk40t/tools/driver_to_path.py +584 -579
  394. meerk40t/tools/geomstr.py +5583 -4680
  395. meerk40t/tools/jhfparser.py +357 -292
  396. meerk40t/tools/kerftest.py +904 -890
  397. meerk40t/tools/livinghinges.py +1168 -1033
  398. meerk40t/tools/pathtools.py +987 -949
  399. meerk40t/tools/pmatrix.py +234 -0
  400. meerk40t/tools/pointfinder.py +942 -942
  401. meerk40t/tools/polybool.py +940 -940
  402. meerk40t/tools/rasterplotter.py +1660 -547
  403. meerk40t/tools/shxparser.py +989 -901
  404. meerk40t/tools/ttfparser.py +726 -446
  405. meerk40t/tools/zinglplotter.py +595 -593
  406. {meerk40t-0.9.3001.dist-info → meerk40t-0.9.7010.dist-info}/LICENSE +21 -21
  407. {meerk40t-0.9.3001.dist-info → meerk40t-0.9.7010.dist-info}/METADATA +150 -139
  408. meerk40t-0.9.7010.dist-info/RECORD +445 -0
  409. {meerk40t-0.9.3001.dist-info → meerk40t-0.9.7010.dist-info}/WHEEL +1 -1
  410. {meerk40t-0.9.3001.dist-info → meerk40t-0.9.7010.dist-info}/top_level.txt +0 -1
  411. {meerk40t-0.9.3001.dist-info → meerk40t-0.9.7010.dist-info}/zip-safe +1 -1
  412. meerk40t/balormk/elementlightjob.py +0 -159
  413. meerk40t-0.9.3001.dist-info/RECORD +0 -437
  414. test/bootstrap.py +0 -63
  415. test/test_cli.py +0 -12
  416. test/test_core_cutcode.py +0 -418
  417. test/test_core_elements.py +0 -144
  418. test/test_core_plotplanner.py +0 -397
  419. test/test_core_viewports.py +0 -312
  420. test/test_drivers_grbl.py +0 -108
  421. test/test_drivers_lihuiyu.py +0 -443
  422. test/test_drivers_newly.py +0 -113
  423. test/test_element_degenerate_points.py +0 -43
  424. test/test_elements_classify.py +0 -97
  425. test/test_elements_penbox.py +0 -22
  426. test/test_file_svg.py +0 -176
  427. test/test_fill.py +0 -155
  428. test/test_geomstr.py +0 -1523
  429. test/test_geomstr_nodes.py +0 -18
  430. test/test_imagetools_actualize.py +0 -306
  431. test/test_imagetools_wizard.py +0 -258
  432. test/test_kernel.py +0 -200
  433. test/test_laser_speeds.py +0 -3303
  434. test/test_length.py +0 -57
  435. test/test_lifecycle.py +0 -66
  436. test/test_operations.py +0 -251
  437. test/test_operations_hatch.py +0 -57
  438. test/test_ruida.py +0 -19
  439. test/test_spooler.py +0 -22
  440. test/test_tools_rasterplotter.py +0 -29
  441. test/test_wobble.py +0 -133
  442. test/test_zingl.py +0 -124
  443. {test → meerk40t/cylinder}/__init__.py +0 -0
  444. /meerk40t/{core/element_commands.py → cylinder/gui/__init__.py} +0 -0
  445. {meerk40t-0.9.3001.dist-info → meerk40t-0.9.7010.dist-info}/entry_points.txt +0 -0
@@ -1,2094 +1,2431 @@
1
- import math
2
- import platform
3
-
4
- import wx
5
-
6
- from meerk40t.kernel import Job, signal_listener
7
-
8
- from ..core.cutcode.cubiccut import CubicCut
9
- from ..core.cutcode.cutcode import CutCode
10
- from ..core.cutcode.dwellcut import DwellCut
11
- from ..core.cutcode.gotocut import GotoCut
12
- from ..core.cutcode.homecut import HomeCut
13
- from ..core.cutcode.inputcut import InputCut
14
- from ..core.cutcode.linecut import LineCut
15
- from ..core.cutcode.outputcut import OutputCut
16
- from ..core.cutcode.plotcut import PlotCut
17
- from ..core.cutcode.quadcut import QuadCut
18
- from ..core.cutcode.rastercut import RasterCut
19
- from ..core.cutcode.waitcut import WaitCut
20
- from ..core.node.util_console import ConsoleOperation
21
- from ..core.node.util_goto import GotoOperation
22
- from ..core.node.util_home import HomeOperation
23
- from ..core.node.util_wait import WaitOperation
24
- from ..core.units import Length
25
- from ..svgelements import Matrix
26
- from .choicepropertypanel import ChoicePropertyPanel
27
- from .icons import (
28
- STD_ICON_SIZE,
29
- get_default_icon_size,
30
- icon_bell,
31
- icon_close_window,
32
- icon_console,
33
- icon_external,
34
- icon_internal,
35
- icon_return,
36
- icon_round_stop,
37
- icon_timer,
38
- icons8_circled_play,
39
- icons8_home_filled,
40
- icons8_image,
41
- icons8_laser_beam_hazard,
42
- icons8_pause,
43
- icons8_route,
44
- )
45
- from .laserrender import DRAW_MODE_BACKGROUND, LaserRender
46
- from .mwindow import MWindow
47
- from .scene.scenepanel import ScenePanel
48
- from .scene.widget import Widget
49
- from .scenewidgets.bedwidget import BedWidget
50
- from .scenewidgets.gridwidget import GridWidget
51
- from .wxutils import StaticBoxSizer, dip_size
52
- from .zmatrix import ZMatrix
53
-
54
- _ = wx.GetTranslation
55
-
56
-
57
- class OperationsPanel(wx.Panel):
58
- """
59
- OperationsPanel is a panel that display cutplan operations and allows to edit them
60
- """
61
-
62
- def __init__(self, *args, context=None, cutplan=None, **kwds):
63
- # begin wxGlade: PassesPanel.__init__
64
- kwds["style"] = kwds.get("style", 0)
65
- wx.Panel.__init__(self, *args, **kwds)
66
- self.parent = args[0]
67
- self.context = context
68
- self.cutplan = cutplan
69
- if self.cutplan is None:
70
- self.plan_name = ""
71
- else:
72
- self.plan_name = self.cutplan.name
73
- self.list_operations = wx.ListCtrl(self, wx.ID_ANY, style=wx.LC_LIST)
74
- self.text_operation_param = wx.TextCtrl(
75
- self, wx.ID_ANY, "", style=wx.TE_PROCESS_ENTER
76
- )
77
- self.check_decompile = wx.CheckBox(self, wx.ID_ANY, "D")
78
- self.check_decompile.SetToolTip(
79
- _("Decompile cutplan = make operations visible and editable again")
80
- )
81
- self.text_operation_param.SetToolTip(
82
- _("Modify operation parameter, press Enter to apply")
83
- )
84
-
85
- self.list_operations.Bind(
86
- wx.EVT_RIGHT_DOWN, self.on_listbox_operation_rightclick
87
- )
88
- self.list_operations.Bind(
89
- wx.EVT_LIST_ITEM_SELECTED, self.on_listbox_operation_select
90
- )
91
- self.text_operation_param.Bind(wx.EVT_TEXT_ENTER, self.on_text_operation_param)
92
- self.check_decompile.Bind(wx.EVT_CHECKBOX, self.on_check_decompile)
93
-
94
- ops_sizer = wx.BoxSizer(wx.VERTICAL)
95
- ops_sizer.Add(self.list_operations, 1, wx.EXPAND, 0)
96
- hsizer = wx.BoxSizer(wx.HORIZONTAL)
97
- hsizer.Add(self.text_operation_param, 1, wx.EXPAND, 0)
98
- hsizer.Add(self.check_decompile, 0, wx.ALIGN_CENTER_VERTICAL, 0)
99
- ops_sizer.Add(hsizer, 0, wx.EXPAND, 0)
100
- self.setup_state_images()
101
- self.SetSizer(ops_sizer)
102
- self.Layout()
103
- self.context.setting(bool, "cutplan_decompile", False)
104
- decompile = self.context.cutplan_decompile
105
- self.check_decompile.SetValue(decompile)
106
- self.set_cut_plan(self.cutplan)
107
-
108
- def setup_state_images(self):
109
- iconsize = 20
110
- self.default_images = [
111
- ["beep", icon_bell],
112
- ["interrupt", icon_round_stop],
113
- ["quit", icon_close_window],
114
- ["wait", icon_timer],
115
- ["home", icons8_home_filled],
116
- ["goto", icon_return],
117
- ["origin", icon_return],
118
- ["output", icon_external],
119
- ["input", icon_internal],
120
- ["cutcode", icons8_laser_beam_hazard],
121
- # Intentionally the last...
122
- ["console", icon_console],
123
- ]
124
- self.options_images = wx.ImageList()
125
- self.options_images.Create(width=iconsize, height=iconsize)
126
- for entry in self.default_images:
127
- image = entry[1].GetBitmap(resize=(iconsize, iconsize), noadjustment=True)
128
- image_id1 = self.options_images.Add(bitmap=image)
129
- self.list_operations.AssignImageList(self.options_images, wx.IMAGE_LIST_SMALL)
130
-
131
- def establish_state(self, typename, opname):
132
- # Establish icon
133
- stateidx = -1
134
- tofind = opname.lower()
135
- for idx, entry in enumerate(self.default_images):
136
- if tofind.startswith(entry[0]):
137
- stateidx = idx
138
- break
139
- if stateidx < 0 and typename == "ConsoleOperation":
140
- stateidx = len(self.default_images) - 1
141
- # print(f"opname={opname}, parameter={parameter}, state={stateidx}")
142
- return stateidx
143
-
144
- def on_check_decompile(self, event):
145
- flag = self.check_decompile.GetValue()
146
- if self.context.cutplan_decompile != flag:
147
- self.context.cutplan_decompile = flag
148
- if flag:
149
- self.set_cut_plan(self.cutplan)
150
-
151
- def set_cut_plan(self, cutplan):
152
- def name_str(e):
153
- res1 = type(e).__name__
154
- try:
155
- res2 = e.__name__
156
- except AttributeError:
157
- res2 = str(e)
158
- # print(f"{res1} -> {res2}")
159
- return res1, res2
160
-
161
- decompile = self.context.cutplan_decompile
162
- oldidx = self.list_operations.GetFirstSelected()
163
- self.cutplan = cutplan
164
- self.plan_name = self.cutplan.name
165
- if decompile:
166
- changes = True
167
- while changes:
168
- changes = False # Prove me wrong...
169
- for idx, cut in enumerate(self.cutplan.plan):
170
- if isinstance(cut, CutCode):
171
- # Let's have a look at the beginning
172
- myidx = idx
173
- while len(cut) > 0:
174
- entry = cut[0]
175
- if isinstance(entry, GotoCut):
176
- # reverse engineer
177
- changes = True
178
- x = entry._start_x
179
- y = entry._start_y
180
- newop = GotoOperation(x=x, y=y)
181
- self.cutplan.plan.insert(myidx, newop)
182
- myidx += 1
183
- cut.pop(0)
184
- elif isinstance(entry, HomeCut):
185
- # reverse engineer
186
- changes = True
187
- newop = HomeOperation()
188
- self.cutplan.plan.insert(myidx, newop)
189
- myidx += 1
190
- cut.pop(0)
191
- elif isinstance(entry, WaitCut):
192
- # reverse engineer
193
- changes = True
194
- wt = entry.dwell_time
195
- newop = WaitOperation(wait=wt)
196
- self.cutplan.plan.insert(myidx, newop)
197
- myidx += 1
198
- cut.pop(0)
199
- else:
200
- # 'Real ' stuff starts that's enough...
201
- break
202
-
203
- # And now look to the end
204
- while len(cut) > 0:
205
- last = len(cut) - 1
206
- entry = cut[last]
207
- if isinstance(entry, GotoCut):
208
- # reverse engineer
209
- changes = True
210
- x = entry._start_x
211
- y = entry._start_y
212
- newop = GotoOperation(x=x, y=y)
213
- self.cutplan.plan.insert(myidx + 1, newop)
214
- cut.pop(last)
215
- elif isinstance(entry, HomeCut):
216
- # reverse engineer
217
- changes = True
218
- newop = HomeOperation()
219
- self.cutplan.plan.insert(myidx + 1, newop)
220
- cut.pop(last)
221
- elif isinstance(entry, WaitCut):
222
- # reverse engineer
223
- changes = True
224
- wt = entry.dwell_time
225
- newop = WaitOperation(wait=wt)
226
- self.cutplan.plan.insert(myidx + 1, newop)
227
- cut.pop(last)
228
- else:
229
- # 'Real ' stuff starts that's enough...
230
- break
231
- if len(cut) == 0:
232
- idx = self.cutplan.plan.index(cut)
233
- self.cutplan.plan.pop(idx)
234
- changes = True
235
-
236
- if changes:
237
- # Break from inner loop and try again...
238
- break
239
-
240
- self.list_operations.DeleteAllItems()
241
- if self.cutplan.plan is not None and len(self.cutplan.plan) != 0:
242
- for idx, entry in enumerate(self.cutplan.plan):
243
- tname, info = name_str(entry)
244
- item = self.list_operations.InsertItem(
245
- self.list_operations.GetItemCount(), f"{idx:02d}# - {info}"
246
- )
247
-
248
- state = self.establish_state(tname, info)
249
- if state >= 0:
250
- self.list_operations.SetItemImage(item, state)
251
-
252
- if 0 <= oldidx < len(self.cutplan.plan):
253
- self.list_operations.SetItemState(
254
- oldidx, wx.LIST_STATE_SELECTED, wx.LIST_STATE_SELECTED
255
- )
256
- self.on_listbox_operation_select(None)
257
-
258
- # def on_listbox_operation_drag_drop(self, event):
259
- # idx1 = 0
260
- # idx2 = 0
261
- # temp = self.cutplan.plan[idx1]
262
- # self.cutplan.plan[idx1] = self.cutplan.plan[idx2]
263
- # self.cutplan.plan[idx2] = temp
264
-
265
- def on_text_operation_param(self, event):
266
- content = self.text_operation_param.GetValue()
267
- idx = self.list_operations.GetFirstSelected()
268
- flag = False
269
- if idx >= 0:
270
- op = self.cutplan.plan[idx]
271
- if isinstance(op, ConsoleOperation):
272
- op.command = content
273
- flag = True
274
- elif isinstance(op, GotoOperation):
275
- params = content.split(",")
276
- x = 0
277
- y = 0
278
- if len(params) > 0:
279
- try:
280
- x = float(Length(params[0]))
281
- except ValueError:
282
- return
283
- if len(params) > 1:
284
- try:
285
- y = float(Length(params[1]))
286
- except ValueError:
287
- return
288
- op.x = x
289
- op.y = y
290
- flag = True
291
- elif isinstance(op, WaitOperation):
292
- try:
293
- duration = float(content)
294
- op.wait = duration
295
- flag = True
296
- except ValueError:
297
- return
298
- else:
299
- op.x = None
300
- op.y = None
301
- flag = True
302
- if flag:
303
- self.context.signal("plan", self.plan_name, 1)
304
-
305
- def on_listbox_operation_select(self, event):
306
- flag = False
307
- content = ""
308
- idx = self.list_operations.GetFirstSelected()
309
- cutcode = None
310
- if idx >= 0:
311
- op = self.cutplan.plan[idx]
312
- if isinstance(op, ConsoleOperation):
313
- content = op.command
314
- flag = True
315
- elif isinstance(op, GotoOperation):
316
- content = str(op.x) + "," + str(op.y)
317
- flag = True
318
- elif isinstance(op, WaitOperation):
319
- content = str(op.wait)
320
- flag = True
321
- elif isinstance(op, CutCode):
322
- cutcode = op
323
- self.parent.set_cutcode_entry(cutcode)
324
- self.text_operation_param.SetValue(content)
325
- self.text_operation_param.Enable(flag)
326
-
327
- def on_listbox_operation_rightclick(self, event):
328
- def remove_operation(event):
329
- idx = self.list_operations.GetFirstSelected()
330
- self.cutplan.plan.pop(idx)
331
- self.context.signal("plan", self.plan_name, 1)
332
- # self._refresh_simulated_plan()
333
-
334
- def append_operation(operation):
335
- def check(event):
336
- self.cutplan.plan.append(my_operation)
337
- self.context.signal("plan", self.plan_name, 1)
338
-
339
- my_operation = operation
340
- return check
341
-
342
- def insert_operation(operation):
343
- def check(event):
344
- self.cutplan.plan.insert(
345
- self.list_operations.GetFirstSelected(), my_operation
346
- )
347
- self.context.signal("plan", self.plan_name, 1)
348
-
349
- my_operation = operation
350
- return check
351
-
352
- if self.list_operations.GetFirstSelected() < 0:
353
- return
354
-
355
- gui = self
356
-
357
- menu = wx.Menu()
358
- self.Bind(
359
- wx.EVT_MENU,
360
- remove_operation,
361
- menu.Append(
362
- wx.ID_ANY,
363
- _("Remove operation"),
364
- _("Removes the current operation from the active cutplan"),
365
- ),
366
- )
367
- standards = (
368
- ("Home", "util home", ""),
369
- ("Goto Origin", "util goto", "0,0"),
370
- ("Beep", "util console", "beep"),
371
- ("Interrupt", "util console", 'interrupt "Spooling was interrupted"'),
372
- ("Console", "util console", "echo 'Still burning'"),
373
- ("Wait", "util wait", "5"),
374
- )
375
- pre_items = []
376
- for elem in standards:
377
- desc = elem[0]
378
- optype = elem[1]
379
- opparam = elem[2]
380
-
381
- if optype is not None:
382
- addop = None
383
- if optype == "util console":
384
- addop = ConsoleOperation(command=opparam)
385
- elif optype == "util home":
386
- addop = HomeOperation()
387
- # elif optype == "util output":
388
- # if opparam is not None:
389
- # params = opparam.split(",")
390
- # mask = 0
391
- # setvalue = 0
392
- # if len(params) > 0:
393
- # try:
394
- # mask = int(params[0])
395
- # except ValueError:
396
- # mask = 0
397
- # if len(params) > 1:
398
- # try:
399
- # setvalue = int(params[1])
400
- # except ValueError:
401
- # setvalue = 0
402
- # if mask != 0 or setvalue != 0:
403
- # addop = OutputOperation(mask, setvalue)
404
- elif optype == "util goto":
405
- if opparam is not None:
406
- params = opparam.split(",")
407
- x = 0
408
- y = 0
409
- if len(params) > 0:
410
- try:
411
- x = float(Length(params[0]))
412
- except ValueError:
413
- x = 0
414
- if len(params) > 1:
415
- try:
416
- y = float(Length(params[1]))
417
- except ValueError:
418
- y = 0
419
- addop = GotoOperation(x=x, y=y)
420
- elif optype == "util wait":
421
- if opparam is not None:
422
- try:
423
- opparam = float(opparam)
424
- except ValueError:
425
- opparam = None
426
- if opparam is not None:
427
- addop = WaitOperation(wait=opparam)
428
- if addop is not None:
429
- pre_items.append([desc, addop])
430
-
431
- menu.AppendSeparator()
432
- for entry in pre_items:
433
- self.Bind(
434
- wx.EVT_MENU,
435
- insert_operation(entry[1]),
436
- menu.Append(
437
- wx.ID_ANY,
438
- _("Insert '{operation}' before").format(operation=entry[0]),
439
- _(
440
- "Inserts this special operation before the current cutplan entry"
441
- ),
442
- ),
443
- )
444
- menu.AppendSeparator()
445
- for entry in pre_items:
446
- self.Bind(
447
- wx.EVT_MENU,
448
- append_operation(entry[1]),
449
- menu.Append(
450
- wx.ID_ANY,
451
- _("Appends '{operation}' at end").format(operation=entry[0]),
452
- _("Appends this special operation at the end of the cutplan"),
453
- ),
454
- )
455
-
456
- if menu.MenuItemCount != 0:
457
- gui.PopupMenu(menu)
458
- menu.Destroy()
459
-
460
-
461
- class CutcodePanel(wx.Panel):
462
- """
463
- CutcodePanel is a panel that display cutplan Cutcode and allows to edit them
464
- """
465
-
466
- def __init__(self, *args, context=None, cutcode=None, plan_name=None, **kwds):
467
- # begin wxGlade: PassesPanel.__init__
468
- kwds["style"] = kwds.get("style", 0)
469
- self.parent = args[0]
470
- wx.Panel.__init__(self, *args, **kwds)
471
- self.context = context
472
- self.cutcode = cutcode
473
- self.plan_name = plan_name
474
- self.list_cutcode = wx.ListBox(
475
- self, wx.ID_ANY, choices=[], style=wx.LB_MULTIPLE
476
- )
477
- self.last_selected = []
478
- # self.text_operation_param = wx.TextCtrl(
479
- # self, wx.ID_ANY, "", style=wx.TE_PROCESS_ENTER
480
- # )
481
- # self.text_operation_param.SetToolTip(
482
- # _("Modify operation parameter, press Enter to apply")
483
- # )
484
-
485
- self.list_cutcode.Bind(wx.EVT_RIGHT_DOWN, self.on_listbox_operation_rightclick)
486
- self.list_cutcode.Bind(wx.EVT_LISTBOX_DCLICK, self.on_listbox_operation_dclick)
487
- self.list_cutcode.Bind(wx.EVT_LISTBOX, self.on_listbox_operation_select)
488
- # self.text_operation_param.Bind(wx.EVT_TEXT_ENTER, self.on_text_operation_param)
489
-
490
- ops_sizer = wx.BoxSizer(wx.VERTICAL)
491
- ops_sizer.Add(self.list_cutcode, 1, wx.EXPAND, 0)
492
- # ops_sizer.Add(self.text_operation_param, 0, wx.EXPAND, 0)
493
- self.SetSizer(ops_sizer)
494
- self.Layout()
495
- self.set_cutcode_entry(self.cutcode, self.plan_name)
496
-
497
- def set_cutcode_entry(self, cutcode, plan_name):
498
- def name_str(e):
499
- res = ""
500
- if isinstance(e, RasterCut):
501
- res = f"Raster: {e.width} x {e.height}"
502
- elif isinstance(e, CubicCut):
503
- res = f"Cubic: ({e.start[0]:.0f}, {e.start[1]:.0f}) - ({e.end[0]:.0f}, {e.end[1]:.0f})"
504
- res += f" (c1=({e.c1()[0]:.0f}, {e.c1()[1]:.0f}), c2=({e.c2()[0]:.0f}, {e.c2()[1]:.0f}) )"
505
- elif isinstance(e, LineCut):
506
- res = f"Line: ({e.start[0]:.0f}, {e.start[1]:.0f}) - ({e.end[0]:.0f}, {e.end[1]:.0f})"
507
- elif isinstance(e, DwellCut):
508
- res = f"Dwell: {e.dwell_time}"
509
- elif isinstance(e, WaitCut):
510
- res = f"Wait: {e.dwell_time}"
511
- elif isinstance(e, HomeCut):
512
- res = f"Home"
513
- elif isinstance(e, GotoCut):
514
- coord = f"({e._start_x:.0f}, {e._start_y:.0f})"
515
- res = f"Goto: ({e.start[0]:.0f}, {e.start[1]:.0f}) {coord}"
516
- elif isinstance(e, InputCut):
517
- res = f"Input: {e.input_value:b} (mask: {e.input_mask:b})"
518
- elif isinstance(e, OutputCut):
519
- res = f"Output: {e.output_value:b} (mask: {e.output_mask:b})"
520
- elif isinstance(e, PlotCut):
521
- res = f"Plot: {len(e)} points"
522
- elif isinstance(e, QuadCut):
523
- res = f"Quad: {e.start[0]:.0f}, {e.start[1]:.0f} - {e.end[0]:.0f}, {e.end[1]:.0f}"
524
- res += f" (c={e.c()[0]:.0f}, {e.c()[1]:.0f})"
525
- else:
526
- try:
527
- res = e.__name__
528
- except AttributeError:
529
- res = str(e)
530
- return res
531
-
532
- self.cutcode = cutcode
533
- # Reset highlighted flags
534
- if cutcode is not None:
535
- for cut in self.cutcode:
536
- cut.highlighted = False
537
- self.plan_name = plan_name
538
- self.list_cutcode.Clear()
539
- self.list_cutcode.Enable(True)
540
- if self.cutcode is None:
541
- self.list_cutcode.InsertItems(
542
- [_("Please select a cutcode entry"), _("from the operations panel")], 0
543
- )
544
- self.list_cutcode.Enable(False)
545
- elif len(self.cutcode) != 0:
546
- self.list_cutcode.InsertItems([name_str(e) for e in self.cutcode], 0)
547
-
548
- def on_listbox_operation_select(self, event):
549
- for cut in self.last_selected:
550
- if cut < len(self.cutcode):
551
- self.cutcode[cut].highlighted = False
552
- self.last_selected = self.list_cutcode.GetSelections()
553
- if self.last_selected is None:
554
- self.last_selected = []
555
- for cut in self.last_selected:
556
- self.cutcode[cut].highlighted = True
557
- self.context.signal("refresh_simulation")
558
-
559
- def on_listbox_operation_dclick(self, event):
560
- # No useful logic yet, the old logic fails as it is opening a wrong node
561
- # There are no property panels for CutObjects yet
562
- return
563
-
564
- def on_listbox_operation_rightclick(self, event):
565
- def remove_operation(event):
566
- selected = self.list_cutcode.GetSelections()
567
- if selected is None or len(selected) == 0:
568
- return
569
- #
570
- idx = len(selected) - 1
571
- while idx >= 0:
572
- entry = selected[idx]
573
- self.cutcode.pop(entry)
574
- idx -= 1
575
- self.context.signal("plan", self.plan_name, 1)
576
-
577
- def remove_before(event):
578
- selected = self.list_cutcode.GetSelections()
579
- if selected is None or len(selected) == 0:
580
- return
581
- #
582
- entry = selected[0]
583
- if entry > 0:
584
- del self.cutcode[:entry]
585
- self.context.signal("plan", self.plan_name, 1)
586
-
587
- def remove_after(event):
588
- selected = self.list_cutcode.GetSelections()
589
- if selected is None or len(selected) == 0:
590
- return
591
- #
592
- entry = selected[-1]
593
- if entry < len(self.cutcode) - 1:
594
- del self.cutcode[entry + 1 :]
595
- self.context.signal("plan", self.plan_name, 1)
596
-
597
- def append_operation(cutcode):
598
- def check(event):
599
- self.cutcode.append(my_cutcode)
600
- self.context.signal("plan", self.plan_name, 1)
601
-
602
- my_cutcode = cutcode
603
- return check
604
-
605
- def insert_operation(cutcode):
606
- def check(event):
607
- selected = self.list_cutcode.GetSelections()
608
- if selected is None or len(selected) == 0:
609
- return
610
- idx = selected[0]
611
- self.cutcode.insert(idx, my_cutcode)
612
- self.context.signal("plan", self.plan_name, 1)
613
-
614
- my_cutcode = cutcode
615
- return check
616
-
617
- selected = self.list_cutcode.GetSelections()
618
- if selected is None or len(selected) == 0:
619
- return
620
- sel_min = selected[0]
621
- sel_max = selected[-1]
622
- gui = self
623
-
624
- menu = wx.Menu()
625
- self.Bind(
626
- wx.EVT_MENU,
627
- remove_operation,
628
- menu.Append(
629
- wx.ID_ANY,
630
- _("Remove cutcode"),
631
- _("Removes the selected cutcode-entries from the active cutplan"),
632
- ),
633
- )
634
- if sel_min > 0:
635
- self.Bind(
636
- wx.EVT_MENU,
637
- remove_before,
638
- menu.Append(
639
- wx.ID_ANY,
640
- _("Delete cuts before"),
641
- _("Delete all cuts before the first selected"),
642
- ),
643
- )
644
- if sel_max < len(self.cutcode) - 1:
645
- self.Bind(
646
- wx.EVT_MENU,
647
- remove_after,
648
- menu.Append(
649
- wx.ID_ANY,
650
- _("Delete cuts after"),
651
- _("Delete all cuts after the last selected"),
652
- ),
653
- )
654
- standards = (
655
- ("Home", "home", ""),
656
- ("Goto Origin", "goto", "0,0"),
657
- # ("Info", "info", "Still burning"),
658
- ("Wait", "wait", "5"),
659
- )
660
- pre_items = []
661
- for elem in standards:
662
- desc = elem[0]
663
- optype = elem[1]
664
- opparam = elem[2]
665
-
666
- if optype is not None:
667
- addop = None
668
- if optype == "console":
669
- # addop = ConsoleOperation(command=opparam)
670
- pass
671
- # elif optype == "info":
672
- # addop = InfoCut(message=opparam)
673
- elif optype == "home":
674
- addop = HomeCut()
675
- # elif optype == "util output":
676
- # if opparam is not None:
677
- # params = opparam.split(",")
678
- # mask = 0
679
- # setvalue = 0
680
- # if len(params) > 0:
681
- # try:
682
- # mask = int(params[0])
683
- # except ValueError:
684
- # mask = 0
685
- # if len(params) > 1:
686
- # try:
687
- # setvalue = int(params[1])
688
- # except ValueError:
689
- # setvalue = 0
690
- # if mask != 0 or setvalue != 0:
691
- # addop = OutputOperation(mask, setvalue)
692
- elif optype == "goto":
693
- if opparam is not None:
694
- params = opparam.split(",")
695
- x = 0
696
- y = 0
697
- if len(params) > 0:
698
- try:
699
- x = float(Length(params[0]))
700
- except ValueError:
701
- x = 0
702
- if len(params) > 1:
703
- try:
704
- y = float(Length(params[1]))
705
- except ValueError:
706
- y = 0
707
- addop = GotoCut((x, y))
708
- elif optype == "wait":
709
- if opparam is not None:
710
- try:
711
- opparam = float(opparam)
712
- except ValueError:
713
- opparam = None
714
- if opparam is not None:
715
- addop = WaitCut(wait=1000 * opparam)
716
- if addop is not None:
717
- pre_items.append([desc, addop])
718
-
719
- menu.AppendSeparator()
720
- for entry in pre_items:
721
- self.Bind(
722
- wx.EVT_MENU,
723
- insert_operation(entry[1]),
724
- menu.Append(
725
- wx.ID_ANY,
726
- _("Insert '{operation}' before").format(operation=entry[0]),
727
- _(
728
- "Inserts this special operation before the current cutplan entry"
729
- ),
730
- ),
731
- )
732
- menu.AppendSeparator()
733
- for entry in pre_items:
734
- self.Bind(
735
- wx.EVT_MENU,
736
- append_operation(entry[1]),
737
- menu.Append(
738
- wx.ID_ANY,
739
- _("Appends '{operation}' at end").format(operation=entry[0]),
740
- _("Appends this special operation at the end of the cutplan"),
741
- ),
742
- )
743
-
744
- if menu.MenuItemCount != 0:
745
- gui.PopupMenu(menu)
746
- menu.Destroy()
747
-
748
-
749
- class SimulationPanel(wx.Panel, Job):
750
- def __init__(
751
- self,
752
- *args,
753
- context=None,
754
- plan_name=None,
755
- auto_clear=True,
756
- optimise_at_start=True,
757
- **kwds,
758
- ):
759
- kwds["style"] = kwds.get("style", 0) | wx.TAB_TRAVERSAL
760
- wx.Panel.__init__(self, *args, **kwds)
761
- self.parent = args[0]
762
- self.context = context
763
- self.plan_name = plan_name
764
- self.auto_clear = auto_clear
765
-
766
- Job.__init__(self)
767
- self._playback_cuts = True
768
- self._cut_end_time = []
769
-
770
- self.job_name = "simulate"
771
- self.run_main = True
772
- self.process = self.animate_sim
773
- self.interval = 0.1
774
- if plan_name:
775
- self.cutplan = self.context.planner.get_or_make_plan(plan_name)
776
- else:
777
- self.cutplan = self.context.planner.default_plan
778
- self.plan_name = self.cutplan.name
779
- self.operations = self.cutplan.plan
780
- # for e in self.operations:
781
- # print(f"Init: {type(e).__name__} {e}")
782
- self.cutcode = CutCode()
783
-
784
- for c in self.operations:
785
- if isinstance(c, CutCode):
786
- self.cutcode.extend(c)
787
- self.cutcode = CutCode(self.cutcode.flat())
788
- self.statistics = self.cutcode.provide_statistics()
789
-
790
- self.max = max(len(self.cutcode), 0) + 1
791
- self.progress = self.max
792
- self.view_pane = ScenePanel(
793
- self.context,
794
- self,
795
- scene_name="SimScene",
796
- style=wx.EXPAND,
797
- )
798
- self.view_pane.start_scene()
799
- self.view_pane.SetCanFocus(False)
800
- self.widget_scene = self.view_pane.scene
801
-
802
- # poor mans slide out
803
- self.btn_slide_options = wx.Button(self, wx.ID_ANY, "<")
804
- self.btn_slide_options.Bind(wx.EVT_BUTTON, self.slide_out)
805
- self.btn_slide_options.SetToolTip(
806
- _("Show/Hide optimization options for this job.")
807
- )
808
- from copy import copy
809
-
810
- prechoices = copy(context.lookup("choices/optimize"))
811
- choices = list(map(copy, prechoices))
812
- # Clear the page-entry
813
- for entry in choices:
814
- entry["page"] = ""
815
- self.subpanel_optimize = wx.Panel(self, wx.ID_ANY)
816
- self.options_optimize = ChoicePropertyPanel(
817
- self, wx.ID_ANY, context=self.context, choices=choices, scrolling=False
818
- )
819
- self.options_optimize.SetupScrolling()
820
- self.subpanel_operations = OperationsPanel(
821
- self, wx.ID_ANY, context=self.context, cutplan=self.cutplan
822
- )
823
- self.subpanel_cutcode = CutcodePanel(
824
- self, wx.ID_ANY, context=self.context, cutcode=None, plan_name=None
825
- )
826
-
827
- self.panel_optimize = wx.Notebook(self, wx.ID_ANY)
828
- self.subpanel_optimize.Reparent(self.panel_optimize)
829
- self.subpanel_operations.Reparent(self.panel_optimize)
830
- self.subpanel_cutcode.Reparent(self.panel_optimize)
831
- self.panel_optimize.AddPage(self.subpanel_optimize, _("Optimizations"))
832
- self.panel_optimize.AddPage(self.subpanel_operations, _("Operations"))
833
- self.panel_optimize.AddPage(self.subpanel_cutcode, _("Cutcode"))
834
- self.checkbox_optimize = wx.CheckBox(self, wx.ID_ANY, _("Optimize"))
835
- self.checkbox_optimize.SetToolTip(_("Enable/Disable Optimize"))
836
- self.checkbox_optimize.SetValue(self.context.planner.do_optimization)
837
- self.btn_redo_it = wx.Button(self, wx.ID_ANY, _("Recalculate"))
838
- self.btn_redo_it.Bind(wx.EVT_BUTTON, self.on_redo_it)
839
-
840
- self.slider_progress = wx.Slider(self, wx.ID_ANY, self.max, 0, self.max)
841
- self.slider_progress.SetFocus()
842
- self.text_distance_laser = wx.TextCtrl(
843
- self, wx.ID_ANY, "", style=wx.TE_READONLY
844
- )
845
- self.text_distance_travel = wx.TextCtrl(
846
- self, wx.ID_ANY, "", style=wx.TE_READONLY
847
- )
848
- self.text_distance_total = wx.TextCtrl(
849
- self, wx.ID_ANY, "", style=wx.TE_READONLY
850
- )
851
- self.text_time_laser = wx.TextCtrl(self, wx.ID_ANY, "", style=wx.TE_READONLY)
852
- self.text_time_travel = wx.TextCtrl(self, wx.ID_ANY, "", style=wx.TE_READONLY)
853
- self.text_time_extra = wx.TextCtrl(self, wx.ID_ANY, "", style=wx.TE_READONLY)
854
- self.text_time_total = wx.TextCtrl(self, wx.ID_ANY, "", style=wx.TE_READONLY)
855
- self.text_distance_laser_step = wx.TextCtrl(
856
- self, wx.ID_ANY, "", style=wx.TE_READONLY
857
- )
858
- self.text_distance_travel_step = wx.TextCtrl(
859
- self, wx.ID_ANY, "", style=wx.TE_READONLY
860
- )
861
- self.text_distance_total_step = wx.TextCtrl(
862
- self, wx.ID_ANY, "", style=wx.TE_READONLY
863
- )
864
- self.text_time_laser_step = wx.TextCtrl(
865
- self, wx.ID_ANY, "", style=wx.TE_READONLY
866
- )
867
- self.text_time_travel_step = wx.TextCtrl(
868
- self, wx.ID_ANY, "", style=wx.TE_READONLY
869
- )
870
- self.text_time_extra_step = wx.TextCtrl(
871
- self, wx.ID_ANY, "", style=wx.TE_READONLY
872
- )
873
- self.text_time_total_step = wx.TextCtrl(
874
- self, wx.ID_ANY, "", style=wx.TE_READONLY
875
- )
876
- self.button_play = wx.Button(self, wx.ID_ANY, "")
877
- self.slider_playbackspeed = wx.Slider(self, wx.ID_ANY, 180, 0, 310)
878
- self.text_playback_speed = wx.TextCtrl(
879
- self, wx.ID_ANY, "100%", style=wx.TE_READONLY
880
- )
881
- self.radio_cut = wx.RadioButton(self, wx.ID_ANY, _("Steps"))
882
- self.radio_time_seconds = wx.RadioButton(self, wx.ID_ANY, _("Time (sec.)"))
883
- self.radio_time_minutes = wx.RadioButton(self, wx.ID_ANY, _("Time (min)"))
884
- self.radio_cut.SetToolTip(
885
- _(
886
- "Cut operations Playback-Mode: play will jump from one completed operations to next"
887
- )
888
- )
889
- self.radio_time_seconds.SetToolTip(
890
- _("Timed Playback-Mode: play will jump from one second to next")
891
- )
892
- self.radio_time_minutes.SetToolTip(
893
- _("Timed Playback-Mode: play will jump from one minute to next")
894
- )
895
-
896
- self.button_spool = wx.Button(self, wx.ID_ANY, _("Send to Laser"))
897
- self._slided_in = None
898
-
899
- self.__set_properties()
900
- self.__do_layout()
901
-
902
- self.matrix = Matrix()
903
-
904
- self.previous_window_position = None
905
- self.previous_scene_position = None
906
- self._Buffer = None
907
-
908
- self.Bind(wx.EVT_SLIDER, self.on_slider_progress, self.slider_progress)
909
- self.Bind(wx.EVT_BUTTON, self.on_button_play, self.button_play)
910
- self.Bind(wx.EVT_SLIDER, self.on_slider_playback, self.slider_playbackspeed)
911
- # self.Bind(wx.EVT_COMBOBOX, self.on_combo_device, self.combo_device)
912
- self.Bind(wx.EVT_BUTTON, self.on_button_spool, self.button_spool)
913
- self.Bind(wx.EVT_RIGHT_DOWN, self.on_mouse_right_down)
914
- self.Bind(wx.EVT_RADIOBUTTON, self.on_radio_playback_mode, self.radio_cut)
915
- self.Bind(
916
- wx.EVT_RADIOBUTTON, self.on_radio_playback_mode, self.radio_time_seconds
917
- )
918
- self.Bind(
919
- wx.EVT_RADIOBUTTON, self.on_radio_playback_mode, self.radio_time_minutes
920
- )
921
- self.view_pane.scene_panel.Bind(wx.EVT_RIGHT_DOWN, self.on_mouse_right_down)
922
- self.Bind(wx.EVT_CHECKBOX, self.on_checkbox_optimize, self.checkbox_optimize)
923
- # end wxGlade
924
- self.on_checkbox_optimize(None)
925
-
926
- ##############
927
- # BUILD SCENE
928
- ##############
929
-
930
- self.widget_scene.add_scenewidget(SimulationWidget(self.widget_scene, self))
931
- self.sim_travel = SimulationTravelWidget(self.widget_scene, self)
932
- self.widget_scene.add_scenewidget(self.sim_travel)
933
-
934
- self.grid = GridWidget(
935
- self.widget_scene, name="Simulation", suppress_labels=True
936
- )
937
- # Don't let grid resize itself
938
- self.grid.auto_tick = False
939
- if self.context.units_name == "mm":
940
- self.grid.tick_distance = 10 # mm
941
- elif self.context.units_name == "cm":
942
- self.grid.tick_distance = 1
943
- elif self.context.units_name == "inch":
944
- self.grid.tick_distance = 0.5
945
- elif self.context.units_name == "mil":
946
- self.grid.tick_distance = 500
947
- self.widget_scene.add_scenewidget(self.grid)
948
- self.widget_scene.add_scenewidget(
949
- BedWidget(self.widget_scene, name="Simulation")
950
- )
951
- self.widget_scene.add_interfacewidget(SimReticleWidget(self.widget_scene, self))
952
-
953
- self.parent.add_module_delegate(self.options_optimize)
954
- self.context.setting(int, "simulation_mode", 0)
955
- default = self.context.simulation_mode
956
- if default == 0:
957
- self.radio_cut.SetValue(True)
958
- elif default == 1:
959
- self.radio_time_seconds.SetValue(True)
960
- elif default == 2:
961
- self.radio_time_minutes.SetValue(True)
962
- self.on_radio_playback_mode(None)
963
- # Allow Scene update from now on (are suppressed by default during startup phase)
964
- self.widget_scene.suppress_changes = False
965
-
966
- self.running = False
967
-
968
- def __set_properties(self):
969
- self.text_distance_laser.SetToolTip(_("Distance Estimate: while Lasering"))
970
- self.text_distance_travel.SetToolTip(_("Distance Estimate: Traveling"))
971
- self.text_distance_total.SetToolTip(_("Distance Estimate: Total"))
972
- self.text_time_laser.SetToolTip(_("Time Estimate: Lasering Time"))
973
- self.text_time_travel.SetToolTip(_("Time Estimate: Traveling Time"))
974
- self.text_time_extra.SetToolTip(
975
- _("Time Estimate: Extra Time (ie to swing around)")
976
- )
977
- self.text_time_total.SetToolTip(_("Time Estimate: Total Time"))
978
- self.button_play.SetBitmap(
979
- icons8_circled_play.GetBitmap(resize=get_default_icon_size())
980
- )
981
- self.text_playback_speed.SetMinSize(dip_size(self, 55, 23))
982
- # self.combo_device.SetToolTip(_("Select the device"))
983
- self.button_spool.SetFont(
984
- wx.Font(
985
- 18,
986
- wx.FONTFAMILY_DEFAULT,
987
- wx.FONTSTYLE_NORMAL,
988
- wx.FONTWEIGHT_NORMAL,
989
- 0,
990
- "Segoe UI",
991
- )
992
- )
993
- self.button_spool.SetBitmap(
994
- icons8_route.GetBitmap(resize=1.5 * get_default_icon_size())
995
- )
996
- # end wxGlade
997
-
998
- def __do_layout(self):
999
- # begin wxGlade: Simulation.__do_layout
1000
- self.text_distance_laser.SetMinSize(dip_size(self, 35, -1))
1001
- self.text_distance_laser_step.SetMinSize(dip_size(self, 35, -1))
1002
- self.text_distance_total.SetMinSize(dip_size(self, 35, -1))
1003
- self.text_distance_total_step.SetMinSize(dip_size(self, 35, -1))
1004
- self.text_distance_travel.SetMinSize(dip_size(self, 35, -1))
1005
- self.text_distance_travel_step.SetMinSize(dip_size(self, 35, -1))
1006
- self.text_time_laser.SetMinSize(dip_size(self, 35, -1))
1007
- self.text_time_laser_step.SetMinSize(dip_size(self, 35, -1))
1008
- self.text_time_total.SetMinSize(dip_size(self, 35, -1))
1009
- self.text_time_total_step.SetMinSize(dip_size(self, 35, -1))
1010
- self.text_time_travel.SetMinSize(dip_size(self, 35, -1))
1011
- self.text_time_travel_step.SetMinSize(dip_size(self, 35, -1))
1012
- self.text_time_extra.SetMinSize(dip_size(self, 35, -1))
1013
- self.text_time_extra_step.SetMinSize(dip_size(self, 35, -1))
1014
- v_sizer_main = wx.BoxSizer(wx.VERTICAL)
1015
- h_sizer_scroll = wx.BoxSizer(wx.HORIZONTAL)
1016
- h_sizer_text_1 = wx.BoxSizer(wx.HORIZONTAL)
1017
- h_sizer_text_2 = wx.BoxSizer(wx.HORIZONTAL)
1018
- h_sizer_buttons = wx.BoxSizer(wx.HORIZONTAL)
1019
-
1020
- sizer_execute = wx.BoxSizer(wx.VERTICAL)
1021
- sizer_speed_options = wx.BoxSizer(wx.VERTICAL)
1022
- sizer_pb_speed = wx.BoxSizer(wx.HORIZONTAL)
1023
- sizer_total_time = StaticBoxSizer(
1024
- self, wx.ID_ANY, _("Total Time"), wx.HORIZONTAL
1025
- )
1026
- sizer_travel_time = StaticBoxSizer(
1027
- self, wx.ID_ANY, _("Travel Time"), wx.HORIZONTAL
1028
- )
1029
- sizer_laser_time = StaticBoxSizer(
1030
- self, wx.ID_ANY, _("Laser Time"), wx.HORIZONTAL
1031
- )
1032
- sizer_extra_time = StaticBoxSizer(
1033
- self, wx.ID_ANY, _("Extra Time"), wx.HORIZONTAL
1034
- )
1035
- sizer_total_distance = StaticBoxSizer(
1036
- self, wx.ID_ANY, _("Total Distance"), wx.HORIZONTAL
1037
- )
1038
- sizer_travel_distance = StaticBoxSizer(
1039
- self, wx.ID_ANY, _("Travel Distance"), wx.HORIZONTAL
1040
- )
1041
- sizer_laser_distance = StaticBoxSizer(
1042
- self, wx.ID_ANY, _("Laser Distance"), wx.HORIZONTAL
1043
- )
1044
- # +--------+---+-------+
1045
- # | P | | Optim |
1046
- # | R | | |
1047
- # | E | |Options|
1048
- # | V | > | |
1049
- # | I | | |
1050
- # | E | +-------+
1051
- # | W | |Refresh|
1052
- # +--------+---+-------+
1053
-
1054
- opt_sizer = wx.BoxSizer(wx.VERTICAL)
1055
- self.options_optimize.Reparent(self.subpanel_optimize)
1056
- self.checkbox_optimize.Reparent(self.subpanel_optimize)
1057
- self.btn_redo_it.Reparent(self.subpanel_optimize)
1058
-
1059
- self.checkbox_optimize.SetMinSize(dip_size(self, -1, 23))
1060
- opt_sizer.Add(self.options_optimize, 1, wx.EXPAND, 0)
1061
- opt_sizer.Add(self.checkbox_optimize, 0, wx.EXPAND, 0)
1062
- opt_sizer.Add(self.btn_redo_it, 0, wx.EXPAND, 0)
1063
- self.subpanel_optimize.SetSizer(opt_sizer)
1064
- self.subpanel_optimize.Layout()
1065
-
1066
- # Linux requires a minimum height / width to display a text inside a button
1067
- system = platform.system()
1068
- if system == "Darwin":
1069
- mysize = 40
1070
- elif system == "Windows":
1071
- mysize = 23
1072
- elif system == "Linux":
1073
- mysize = 40
1074
- else:
1075
- mysize = 20
1076
- self.btn_slide_options.SetMinSize(dip_size(self, mysize, -1))
1077
- self.voption_sizer = wx.BoxSizer(wx.VERTICAL)
1078
- self.voption_sizer.Add(self.panel_optimize, 1, wx.EXPAND, 0)
1079
-
1080
- self.hscene_sizer = wx.BoxSizer(wx.HORIZONTAL)
1081
- self.hscene_sizer.Add(self.view_pane, 2, wx.EXPAND, 0)
1082
- self.hscene_sizer.Add(self.btn_slide_options, 0, wx.EXPAND, 0)
1083
- self.hscene_sizer.Add(self.voption_sizer, 1, wx.EXPAND, 0)
1084
-
1085
- h_sizer_scroll.Add(self.slider_progress, 1, wx.EXPAND, 0)
1086
-
1087
- sizer_laser_distance.Add(self.text_distance_laser_step, 1, wx.EXPAND, 0)
1088
- sizer_laser_distance.Add(self.text_distance_laser, 1, wx.EXPAND, 0)
1089
- h_sizer_text_1.Add(sizer_laser_distance, 1, wx.EXPAND, 0)
1090
-
1091
- sizer_travel_distance.Add(self.text_distance_travel_step, 1, wx.EXPAND, 0)
1092
- sizer_travel_distance.Add(self.text_distance_travel, 1, wx.EXPAND, 0)
1093
- h_sizer_text_1.Add(sizer_travel_distance, 1, wx.EXPAND, 0)
1094
-
1095
- sizer_total_distance.Add(self.text_distance_total_step, 1, wx.EXPAND, 0)
1096
- sizer_total_distance.Add(self.text_distance_total, 1, wx.EXPAND, 0)
1097
- h_sizer_text_1.Add(sizer_total_distance, 1, wx.EXPAND, 0)
1098
-
1099
- sizer_laser_time.Add(self.text_time_laser_step, 1, wx.EXPAND, 0)
1100
- sizer_laser_time.Add(self.text_time_laser, 1, wx.EXPAND, 0)
1101
- h_sizer_text_2.Add(sizer_laser_time, 1, wx.EXPAND, 0)
1102
-
1103
- sizer_travel_time.Add(self.text_time_travel_step, 1, wx.EXPAND, 0)
1104
- sizer_travel_time.Add(self.text_time_travel, 1, wx.EXPAND, 0)
1105
- h_sizer_text_2.Add(sizer_travel_time, 1, wx.EXPAND, 0)
1106
-
1107
- sizer_total_time.Add(self.text_time_total_step, 1, wx.EXPAND, 0)
1108
- sizer_total_time.Add(self.text_time_total, 1, wx.EXPAND, 0)
1109
- h_sizer_text_2.Add(sizer_total_time, 1, wx.EXPAND, 0)
1110
-
1111
- sizer_extra_time.Add(self.text_time_extra_step, 1, wx.EXPAND, 0)
1112
- sizer_extra_time.Add(self.text_time_extra, 1, wx.EXPAND, 0)
1113
- h_sizer_text_2.Add(sizer_extra_time, 1, wx.EXPAND, 0)
1114
-
1115
- h_sizer_buttons.Add(self.button_play, 0, 0, 0)
1116
- sizer_speed_options.Add(self.slider_playbackspeed, 0, wx.EXPAND, 0)
1117
-
1118
- label_playback_speed = wx.StaticText(self, wx.ID_ANY, _("Playback Speed") + " ")
1119
- sizer_pb_speed.Add(label_playback_speed, 2, wx.ALIGN_CENTER_VERTICAL, 0)
1120
- sizer_pb_speed.Add(self.text_playback_speed, 1, wx.EXPAND, 0)
1121
-
1122
- sizer_display = wx.BoxSizer(wx.HORIZONTAL)
1123
- label_playback_mode = wx.StaticText(self, wx.ID_ANY, _("Mode") + " ")
1124
- sizer_display.Add(label_playback_mode, 1, wx.ALIGN_CENTER_VERTICAL, 0)
1125
- # Make sure it has about textbox size, otherwise too narrow
1126
- self.radio_cut.SetMinSize(dip_size(self, -1, 23))
1127
- sizer_display.Add(self.radio_cut, 1, wx.ALIGN_CENTER_VERTICAL, 0)
1128
- sizer_display.Add(self.radio_time_seconds, 1, wx.ALIGN_CENTER_VERTICAL, 0)
1129
- sizer_display.Add(self.radio_time_minutes, 1, wx.ALIGN_CENTER_VERTICAL, 0)
1130
- sizer_speed_options.Add(sizer_pb_speed, 0, wx.EXPAND, 0)
1131
- sizer_speed_options.Add(sizer_display, 0, wx.EXPAND, 0)
1132
- h_sizer_buttons.Add(sizer_speed_options, 1, wx.EXPAND, 0)
1133
- # sizer_execute.Add(self.combo_device, 0, wx.EXPAND, 0)
1134
- sizer_execute.Add(self.button_spool, 1, wx.EXPAND, 0)
1135
- h_sizer_buttons.Add(sizer_execute, 1, wx.EXPAND, 0)
1136
-
1137
- v_sizer_main.Add(self.hscene_sizer, 1, wx.EXPAND, 0)
1138
- v_sizer_main.Add(h_sizer_scroll, 0, wx.EXPAND, 0)
1139
- v_sizer_main.Add(h_sizer_text_1, 0, wx.EXPAND, 0)
1140
- v_sizer_main.Add(h_sizer_text_2, 0, wx.EXPAND, 0)
1141
- v_sizer_main.Add(h_sizer_buttons, 0, wx.EXPAND, 0)
1142
- self.SetSizer(v_sizer_main)
1143
- self.slided_in = True # Hide initially
1144
- self.Layout()
1145
- # end wxGlade
1146
-
1147
- # Manages the display, non-display of the optimisation-options
1148
- @property
1149
- def slided_in(self):
1150
- return self._slided_in
1151
-
1152
- @slided_in.setter
1153
- def slided_in(self, newvalue):
1154
- self._slided_in = newvalue
1155
- if newvalue:
1156
- # Slided in ->
1157
- self.hscene_sizer.Show(sizer=self.voption_sizer, show=False, recursive=True)
1158
- self.voption_sizer.Layout()
1159
- self.btn_slide_options.SetLabel("<")
1160
- self.hscene_sizer.Layout()
1161
- self.Layout()
1162
- else:
1163
- # Slided out ->
1164
- self.hscene_sizer.Show(sizer=self.voption_sizer, show=True, recursive=True)
1165
- self.voption_sizer.Layout()
1166
- self.btn_slide_options.SetLabel(">")
1167
- self.hscene_sizer.Layout()
1168
- self.Layout()
1169
-
1170
- def toggle_background(self, event):
1171
- """
1172
- Toggle the draw mode for the background
1173
- """
1174
- self.widget_scene.context.draw_mode ^= DRAW_MODE_BACKGROUND
1175
- self.widget_scene.request_refresh()
1176
-
1177
- def toggle_grid(self, gridtype):
1178
- if gridtype == "primary":
1179
- self.grid.draw_grid_primary = not self.grid.draw_grid_primary
1180
- elif gridtype == "secondary":
1181
- self.grid.draw_grid_secondary = not self.grid.draw_grid_secondary
1182
- elif gridtype == "circular":
1183
- self.grid.draw_grid_circular = not self.grid.draw_grid_circular
1184
- self.widget_scene.request_refresh()
1185
-
1186
- def toggle_grid_p(self, event):
1187
- self.toggle_grid("primary")
1188
-
1189
- def toggle_grid_s(self, event):
1190
- self.toggle_grid("secondary")
1191
-
1192
- def toggle_grid_c(self, event):
1193
- self.toggle_grid("circular")
1194
-
1195
- def remove_background(self, event):
1196
- self.widget_scene._signal_widget(
1197
- self.widget_scene.widget_root, "background", None
1198
- )
1199
- self.widget_scene.request_refresh()
1200
-
1201
- def fit_scene_to_panel(self):
1202
- bbox = self.context.device.view.source_bbox()
1203
- self.widget_scene.widget_root.focus_viewport_scene(
1204
- bbox, self.view_pane.Size, 0.1
1205
- )
1206
- self.widget_scene.request_refresh()
1207
-
1208
- def set_cutcode_entry(self, cutcode):
1209
- self.subpanel_cutcode.set_cutcode_entry(cutcode, self.plan_name)
1210
-
1211
- def progress_to_idx(self, progress):
1212
- residual = 0
1213
- idx = progress
1214
- if not self._playback_cuts:
1215
- # progress is the time indicator
1216
- idx = len(self.statistics) - 1
1217
- prev_time = None
1218
- while idx >= 0:
1219
- item = self.statistics[idx]
1220
- this_time = item["time_at_end_of_burn"]
1221
- # print (f"{idx} {this_time} vs {progress} - {item}")
1222
- if this_time <= progress:
1223
- if prev_time is not None:
1224
- # We compute a 0 to 1 ratio of the progress
1225
- residual = (progress - this_time) / (prev_time - this_time)
1226
- break
1227
- prev_time = this_time
1228
- idx -= 1
1229
- idx += 1
1230
- if idx == 0:
1231
- item = self.statistics[idx]
1232
- start_time = item["time_at_start"]
1233
- this_time = item["time_at_end_of_burn"]
1234
- residual = (progress - start_time) / (this_time - start_time)
1235
-
1236
- if idx >= len(self.statistics):
1237
- idx = len(self.statistics) - 1
1238
- if idx < 0:
1239
- idx = 0
1240
- # print(
1241
- # f"Cut-Mode={self._playback_cuts}, prog={progress}, idx={idx}, stats={len(self.statistics)}"
1242
- # )
1243
- return idx, residual
1244
-
1245
- def on_mouse_right_down(self, event=None):
1246
- def cut_before(event):
1247
- step, residual = self.progress_to_idx(self.progress)
1248
- self.context(f"plan{self.plan_name} sublist {step} -1\n")
1249
-
1250
- def cut_after(event):
1251
- step, residual = self.progress_to_idx(self.progress)
1252
- self.context(f"plan{self.plan_name} sublist 0 {step}\n")
1253
-
1254
- gui = self
1255
- menu = wx.Menu()
1256
- if self.radio_cut.GetValue():
1257
- self.Bind(
1258
- wx.EVT_MENU,
1259
- cut_before,
1260
- menu.Append(
1261
- wx.ID_ANY,
1262
- _("Delete cuts before"),
1263
- _("Delete all cuts before the current position in Simulation"),
1264
- ),
1265
- )
1266
- self.Bind(
1267
- wx.EVT_MENU,
1268
- cut_after,
1269
- menu.Append(
1270
- wx.ID_ANY,
1271
- _("Delete cuts after"),
1272
- _("Delete all cuts after the current position in Simulation"),
1273
- ),
1274
- )
1275
- menu.AppendSeparator()
1276
- id1 = menu.Append(
1277
- wx.ID_ANY,
1278
- _("Show Background"),
1279
- _("Display the background picture in the Simulation pane"),
1280
- wx.ITEM_CHECK,
1281
- )
1282
- self.Bind(wx.EVT_MENU, self.toggle_background, id=id1.GetId())
1283
- menu.Check(
1284
- id1.GetId(),
1285
- (self.widget_scene.context.draw_mode & DRAW_MODE_BACKGROUND == 0),
1286
- )
1287
- id2 = menu.Append(
1288
- wx.ID_ANY,
1289
- _("Show Primary Grid"),
1290
- _("Display the primary grid in the Simulation pane"),
1291
- wx.ITEM_CHECK,
1292
- )
1293
- self.Bind(wx.EVT_MENU, self.toggle_grid_p, id=id2.GetId())
1294
- menu.Check(id2.GetId(), self.grid.draw_grid_primary)
1295
- id3 = menu.Append(
1296
- wx.ID_ANY,
1297
- _("Show Secondary Grid"),
1298
- _("Display the secondary grid in the Simulation pane"),
1299
- wx.ITEM_CHECK,
1300
- )
1301
- self.Bind(wx.EVT_MENU, self.toggle_grid_s, id=id3.GetId())
1302
- menu.Check(id3.GetId(), self.grid.draw_grid_secondary)
1303
- id4 = menu.Append(
1304
- wx.ID_ANY,
1305
- _("Show Circular Grid"),
1306
- _("Display the circular grid in the Simulation pane"),
1307
- wx.ITEM_CHECK,
1308
- )
1309
- self.Bind(wx.EVT_MENU, self.toggle_grid_c, id=id4.GetId())
1310
- menu.Check(id4.GetId(), self.grid.draw_grid_circular)
1311
- if self.widget_scene.has_background:
1312
- menu.AppendSeparator()
1313
- id5 = menu.Append(wx.ID_ANY, _("Remove Background"), "")
1314
- self.Bind(wx.EVT_MENU, self.remove_background, id=id5.GetId())
1315
- menu.AppendSeparator()
1316
- self.Bind(
1317
- wx.EVT_MENU,
1318
- lambda e: self.fit_scene_to_panel(),
1319
- menu.Append(
1320
- wx.ID_ANY,
1321
- _("Zoom to Bed"),
1322
- _("View the whole laser bed"),
1323
- ),
1324
- )
1325
-
1326
- if menu.MenuItemCount != 0:
1327
- gui.PopupMenu(menu)
1328
- menu.Destroy()
1329
-
1330
- def _set_slider_dimensions(self):
1331
- if self._playback_cuts:
1332
- self.max = max(len(self.cutcode), 1)
1333
- else:
1334
- totalduration = 0
1335
- maxidx = len(self.statistics)
1336
- if maxidx > 0:
1337
- totalduration = int(
1338
- self.statistics[-1]["total_time_extra"]
1339
- + self.statistics[-1]["total_time_travel"]
1340
- + self.statistics[-1]["total_time_cut"]
1341
- )
1342
- self.max = max(totalduration, 1)
1343
- self.progress = self.max
1344
- self.slider_progress.SetMin(0)
1345
- self.slider_progress.SetMax(self.max)
1346
- self.slider_progress.SetValue(self.max)
1347
- value = self.slider_playbackspeed.GetValue()
1348
- value = int((10.0 ** (value // 90)) * (1.0 + float(value % 90) / 10.0))
1349
- if self.radio_cut.GetValue():
1350
- factor = 0.1 # steps
1351
- else:
1352
- factor = 1 # seconds
1353
- self.interval = factor * 100.0 / float(value)
1354
-
1355
- def _refresh_simulated_plan(self):
1356
- # Stop animation
1357
- if self.running:
1358
- self._stop()
1359
- return
1360
- # Refresh cutcode
1361
- if self.plan_name:
1362
- self.cutplan = self.context.planner.get_or_make_plan(self.plan_name)
1363
- else:
1364
- self.cutplan = self.context.planner.default_plan
1365
- self.plan_name = self.cutplan.name
1366
- self.operations = self.cutplan.plan
1367
- self.subpanel_cutcode.set_cutcode_entry(None, self.plan_name)
1368
- self.subpanel_operations.set_cut_plan(self.cutplan)
1369
- # for e in self.operations:
1370
- # print(f"Refresh: {type(e).__name__} {e}")
1371
- # try:
1372
- # idx = 0
1373
- # for n in e:
1374
- # print(f"Entry {idx}#: {name_str(n)}")
1375
- # idx += 1
1376
- # except:
1377
- # pass
1378
-
1379
- self.cutcode = CutCode()
1380
-
1381
- for c in self.operations:
1382
- if isinstance(c, CutCode):
1383
- self.cutcode.extend(c)
1384
- self.cutcode = CutCode(self.cutcode.flat())
1385
- self.statistics = self.cutcode.provide_statistics()
1386
- # for idx, stat in enumerate(self.statistics):
1387
- # print(f"#{idx}: {stat}")
1388
- self._set_slider_dimensions()
1389
- self.sim_travel.initvars()
1390
- self.update_fields()
1391
- self.request_refresh()
1392
-
1393
- @signal_listener("plan")
1394
- def on_plan_change(self, origin, plan_name, status):
1395
- if plan_name == self.plan_name:
1396
- self._refresh_simulated_plan()
1397
-
1398
- @signal_listener("refresh_simulation")
1399
- def on_request_refresh(self, origin, *args):
1400
- self.widget_scene.request_refresh()
1401
-
1402
- def on_radio_playback_mode(self, event):
1403
- self._playback_cuts = self.radio_cut.GetValue()
1404
- default = 0
1405
- if self.radio_cut.GetValue():
1406
- default = 0
1407
- elif self.radio_time_seconds.GetValue():
1408
- default = 1
1409
- elif self.radio_time_minutes.GetValue():
1410
- default = 2
1411
- self.context.simulation_mode = default
1412
- self._set_slider_dimensions()
1413
-
1414
- def on_checkbox_optimize(self, event):
1415
- if self.checkbox_optimize.GetValue():
1416
- self.options_optimize.Enable(True)
1417
- else:
1418
- self.options_optimize.Enable(False)
1419
-
1420
- def update_fields(self):
1421
- def len_str(value):
1422
- if abs(value) >= 1000000:
1423
- result = f"{value / 1000000:.2f}km"
1424
- elif abs(value) >= 1000:
1425
- result = f"{value / 1000:.2f}m"
1426
- else:
1427
- result = f"{value:.0f}mm"
1428
- return result
1429
-
1430
- step, residual = self.progress_to_idx(self.progress)
1431
- item = self.statistics[step - 1]
1432
- partials = {
1433
- "total_distance_travel": 0,
1434
- "total_distance_cut": 0,
1435
- "total_time_travel": 0,
1436
- "total_time_cut": 0,
1437
- "total_time_extra": 0,
1438
- }
1439
- if residual != 0 and step < len(self.statistics):
1440
- itemnext = self.statistics[step]
1441
- for entry in partials:
1442
- partials[entry] = residual * (itemnext[entry] - item[entry])
1443
-
1444
- ###################
1445
- # UPDATE POSITIONAL
1446
- ###################
1447
-
1448
- mm = self.cutcode.settings.get("native_mm", 39.3701)
1449
- # item = (i, distance_travel, distance_cut, extra, duration_travel, duration_cut)
1450
- travel_mm = (
1451
- item["total_distance_travel"] + partials["total_distance_travel"]
1452
- ) / mm
1453
- cuts_mm = (item["total_distance_cut"] + partials["total_distance_cut"]) / mm
1454
- # travel_mm = self.cutcode.length_travel(stop_at=step) / mm
1455
- # cuts_mm = self.cutcode.length_cut(stop_at=step) / mm
1456
- self.text_distance_travel_step.SetValue(len_str(travel_mm))
1457
- self.text_distance_laser_step.SetValue(len_str(cuts_mm))
1458
- self.text_distance_total_step.SetValue(len_str(travel_mm + cuts_mm))
1459
- try:
1460
- time_travel = item["total_time_travel"] + partials["total_time_travel"]
1461
- t_hours = int(time_travel // 3600)
1462
- t_mins = int((time_travel % 3600) // 60)
1463
- t_seconds = int(time_travel % 60)
1464
- self.text_time_travel_step.SetValue(
1465
- f"{int(t_hours)}:{int(t_mins):02d}:{int(t_seconds):02d}"
1466
- )
1467
- except ZeroDivisionError:
1468
- time_travel = 0
1469
- try:
1470
- time_cuts = item["total_time_cut"] + partials["total_time_cut"]
1471
- t_hours = int(time_cuts // 3600)
1472
- t_mins = int((time_cuts % 3600) // 60)
1473
- t_seconds = int(time_cuts % 60)
1474
- self.text_time_laser_step.SetValue(
1475
- f"{int(t_hours)}:{int(t_mins):02d}:{int(t_seconds):02d}"
1476
- )
1477
- except ZeroDivisionError:
1478
- time_cuts = 0
1479
- try:
1480
- extra = item["total_time_extra"] + partials["total_time_extra"]
1481
- t_hours = int(extra // 3600)
1482
- t_mins = int((extra % 3600) // 60)
1483
- t_seconds = int(extra % 60)
1484
- self.text_time_extra_step.SetValue(
1485
- f"{int(t_hours)}:{int(t_mins):02d}:{int(t_seconds):02d}"
1486
- )
1487
- time_total = time_travel + time_cuts + extra
1488
- if self._playback_cuts:
1489
- time_total = time_travel + time_cuts + extra
1490
- else:
1491
- time_total = self.progress
1492
- t_hours = int(time_total // 3600)
1493
- t_mins = int((time_total % 3600) // 60)
1494
- t_seconds = int(time_total % 60)
1495
- self.text_time_total_step.SetValue(
1496
- f"{int(t_hours)}:{int(t_mins):02d}:{int(t_seconds):02d}"
1497
- )
1498
- except ZeroDivisionError:
1499
- pass
1500
-
1501
- ###################
1502
- # UPDATE TOTAL
1503
- ###################
1504
-
1505
- travel_mm = self.statistics[-1]["total_distance_travel"] / mm
1506
- cuts_mm = self.statistics[-1]["total_distance_cut"] / mm
1507
- self.text_distance_travel.SetValue(len_str(travel_mm))
1508
- self.text_distance_laser.SetValue(len_str(cuts_mm))
1509
- self.text_distance_total.SetValue(len_str(travel_mm + cuts_mm))
1510
-
1511
- try:
1512
- time_travel = self.statistics[-1]["total_time_travel"]
1513
- t_hours = int(time_travel // 3600)
1514
- t_mins = int((time_travel % 3600) // 60)
1515
- t_seconds = int(time_travel % 60)
1516
- self.text_time_travel.SetValue(f"{t_hours}:{t_mins:02d}:{t_seconds:02d}")
1517
- except ZeroDivisionError:
1518
- time_travel = 0
1519
- try:
1520
- time_cuts = self.statistics[-1]["total_time_cut"]
1521
- t_hours = int(time_cuts // 3600)
1522
- t_mins = int((time_cuts % 3600) // 60)
1523
- t_seconds = int(time_cuts % 60)
1524
- self.text_time_laser.SetValue(f"{t_hours}:{t_mins:02d}:{t_seconds:02d}")
1525
- except ZeroDivisionError:
1526
- time_cuts = 0
1527
- try:
1528
- extra = self.statistics[-1]["total_time_extra"]
1529
- t_hours = int(extra // 3600)
1530
- t_mins = int((extra % 3600) // 60)
1531
- t_seconds = int(extra % 60)
1532
- self.text_time_extra.SetValue(f"{t_hours}:{t_mins:02d}:{t_seconds:02d}")
1533
- time_total = time_travel + time_cuts + extra
1534
- t_hours = int(time_total // 3600)
1535
- t_mins = int((time_total % 3600) // 60)
1536
- t_seconds = int(time_total % 60)
1537
- self.text_time_total.SetValue(f"{t_hours}:{t_mins:02d}:{t_seconds:02d}")
1538
- except ZeroDivisionError:
1539
- pass
1540
-
1541
- def slide_out(self, event):
1542
- self.slided_in = not self.slided_in
1543
- event.Skip()
1544
-
1545
- def on_redo_it(self, event):
1546
- busy = self.context.kernel.busyinfo
1547
- busy.start(msg=_("Preparing simulation..."))
1548
-
1549
- plan = self.plan_name
1550
- if self.checkbox_optimize.GetValue():
1551
- opt = " optimize"
1552
- self.context.planner.do_optimization = True
1553
- else:
1554
- opt = ""
1555
- self.context.planner.do_optimization = False
1556
- self.context(
1557
- f"plan{plan} clear\nplan{plan} copy preprocess validate blob preopt{opt}\n"
1558
- )
1559
- busy.end()
1560
- self._refresh_simulated_plan()
1561
-
1562
- def pane_show(self):
1563
- self.context.setting(str, "units_name", "mm")
1564
-
1565
- bbox = self.context.device.view.source_bbox()
1566
- self.widget_scene.widget_root.focus_viewport_scene(
1567
- bbox, self.view_pane.Size, 0.1
1568
- )
1569
- self.update_fields()
1570
- # self.panel_optimize.pane_show()
1571
- self.panel_optimize.Show()
1572
-
1573
- def pane_hide(self):
1574
- if self.auto_clear:
1575
- self.context(f"plan{self.plan_name} clear\n")
1576
- self.context.close("SimScene")
1577
- self.context.unschedule(self)
1578
- self.running = False
1579
- # self.panel_optimize.pane_hide()
1580
- try:
1581
- self.panel_optimize.Hide()
1582
- except RuntimeError:
1583
- pass
1584
-
1585
- @signal_listener("refresh_scene")
1586
- def on_refresh_scene(self, origin, scene_name=None, *args):
1587
- """
1588
- Called by 'refresh_scene' change. To refresh tree.
1589
- @param origin: the path of the originating signal
1590
- @param scene_name: Scene to refresh on if matching
1591
- @param args:
1592
- @return:
1593
- """
1594
- if scene_name == "SimScene":
1595
- self.request_refresh()
1596
-
1597
- def request_refresh(self, *args):
1598
- self.widget_scene.request_refresh(*args)
1599
-
1600
- def on_slider_progress(self, event=None): # wxGlade: Simulation.<event_handler>
1601
- self.progress = min(self.slider_progress.GetValue(), self.max)
1602
- self.update_fields()
1603
- self.context.signal("refresh_scene", self.widget_scene.name)
1604
-
1605
- def _start(self):
1606
- self.button_play.SetBitmap(
1607
- icons8_pause.GetBitmap(resize=get_default_icon_size())
1608
- )
1609
- self.context.schedule(self)
1610
- self.running = True
1611
-
1612
- def _stop(self):
1613
- self.button_play.SetBitmap(
1614
- icons8_circled_play.GetBitmap(resize=get_default_icon_size())
1615
- )
1616
- self.context.unschedule(self)
1617
- self.running = False
1618
-
1619
- def on_button_play(self, event=None): # wxGlade: Simulation.<event_handler>
1620
- if self.running:
1621
- self._stop()
1622
- return
1623
- if self.progress >= self.max:
1624
- self.progress = 0
1625
- self.slider_progress.SetValue(self.progress)
1626
- self.update_fields()
1627
- self._start()
1628
-
1629
- def animate_sim(self, event=None):
1630
- if self.radio_time_minutes.GetValue():
1631
- self.progress += 60
1632
- else:
1633
- self.progress += 1
1634
- if self.progress >= self.max:
1635
- self.progress = self.max
1636
- self.slider_progress.SetValue(self.progress)
1637
- self._stop()
1638
- else:
1639
- self.slider_progress.SetValue(self.progress)
1640
- self.update_fields()
1641
- self.context.signal("refresh_scene", self.widget_scene.name)
1642
-
1643
- def on_slider_playback(self, event=None): # wxGlade: Simulation.<event_handler>
1644
- # Slider is now pseudo logarithmic in scale varying from 1% to 5,000%.
1645
-
1646
- value = self.slider_playbackspeed.GetValue()
1647
- value = int((10.0 ** (value // 90)) * (1.0 + float(value % 90) / 10.0))
1648
- if self.radio_cut.GetValue():
1649
- factor = 0.1 # steps
1650
- else:
1651
- factor = 1 # seconds
1652
- self.interval = factor * 100.0 / float(value)
1653
-
1654
- self.text_playback_speed.SetValue(f"{value}%")
1655
-
1656
- def on_button_spool(self, event=None): # wxGlade: Simulation.<event_handler>
1657
- self.context(f"plan{self.plan_name} spool\n")
1658
- self.context("window close Simulation\n")
1659
- if self.context.auto_spooler:
1660
- self.context("window open JobSpooler\n")
1661
-
1662
-
1663
- class SimulationWidget(Widget):
1664
- """
1665
- The simulation widget is responsible for rendering the cutcode to the scene. This should be
1666
- done such that both progress of 0 and 1 render nothing and items begin to draw at 2.
1667
- """
1668
-
1669
- def __init__(self, scene, sim):
1670
- Widget.__init__(self, scene, all=False)
1671
- self.renderer = LaserRender(self.scene.context)
1672
- self.sim = sim
1673
- self.matrix.post_cat(~scene.context.device.view.matrix)
1674
- self.last_msg = None
1675
-
1676
- def process_draw(self, gc: wx.GraphicsContext):
1677
- if self.sim.progress >= 0:
1678
- residual = 0
1679
- idx = 0
1680
- if self.sim.progress < self.sim.max:
1681
- idx, residual = self.sim.progress_to_idx(self.sim.progress)
1682
- # print(f"SimWidget, idx={idx}, residual={residual:.3f}")
1683
- sim_cut = self.sim.cutcode[:idx]
1684
- else:
1685
- sim_cut = self.sim.cutcode
1686
- self.renderer.draw_cutcode(sim_cut, gc, 0, 0)
1687
- if residual > 0:
1688
- # We draw interpolated lines to acknowledge we are in the middle of a cut operation
1689
- starts = []
1690
- ends = []
1691
- cutstart = wx.Point2D(*self.sim.cutcode[idx].start)
1692
- cutend = wx.Point2D(*self.sim.cutcode[idx].end)
1693
- if self.sim.statistics[idx]["type"] == "RasterCut":
1694
- # Rastercut object.
1695
- x = 0
1696
- y = 0
1697
- cut = self.sim.cutcode[idx]
1698
- image = cut.image
1699
- gc.PushState()
1700
- matrix = Matrix.scale(cut.step_x, cut.step_y)
1701
- matrix.post_translate(
1702
- cut.offset_x + x, cut.offset_y + y
1703
- ) # Adjust image xy
1704
- gc.ConcatTransform(
1705
- wx.GraphicsContext.CreateMatrix(gc, ZMatrix(matrix))
1706
- )
1707
- try:
1708
- cache = cut._cache
1709
- cache_id = cut._cache_id
1710
- except AttributeError:
1711
- cache = None
1712
- cache_id = -1
1713
- if cache_id != id(image):
1714
- # Cached image is invalid.
1715
- cache = None
1716
- if cache is None:
1717
- # No valid cache. Generate.
1718
- cut._cache_width, cut._cache_height = image.size
1719
- try:
1720
- cut._cache = self.renderer.make_thumbnail(
1721
- image, maximum=5000
1722
- )
1723
- except (MemoryError, RuntimeError):
1724
- cut._cache = None
1725
- cut._cache_id = id(image)
1726
- # Set draw - constraint
1727
- if cut.horizontal:
1728
- if cut.start_minimum_y:
1729
- # mode = "T2B"
1730
- clip_w = cut._cache_width
1731
- clip_h = int(residual * cut._cache_height)
1732
- clip_x = 0
1733
- clip_y = 0
1734
- else:
1735
- # mode = "B2T"
1736
- clip_w = cut._cache_width
1737
- clip_h = int(residual * cut._cache_height)
1738
- clip_x = 0
1739
- clip_y = cut._cache_height - clip_h
1740
- else:
1741
- if cut.start_minimum_x:
1742
- # mode = "L2R"
1743
- clip_w = int(residual * cut._cache_width)
1744
- clip_h = cut._cache_height
1745
- clip_x = 0
1746
- clip_y = 0
1747
- else:
1748
- # mode = "R2L"
1749
- clip_w = int(residual * cut._cache_width)
1750
- clip_h = cut._cache_height
1751
- clip_x = cut._cache_width - clip_w
1752
- clip_y = 0
1753
-
1754
- # msg = f"Mode: {mode}, Horiz: {cut.horizontal}, from left: {cut.start_on_left}, from top: {cut.start_on_top}"
1755
- # if msg != self.last_msg:
1756
- # print (msg)
1757
- # self.last_msg = msg
1758
- gc.Clip(clip_x, clip_y, clip_w, clip_h)
1759
- if cut._cache is not None:
1760
- # Cache exists and is valid.
1761
- gc.DrawBitmap(
1762
- cut._cache, 0, 0, cut._cache_width, cut._cache_height
1763
- )
1764
- # gc.SetBrush(wx.RED_BRUSH)
1765
- # gc.DrawRectangle(0, 0, cut._cache_width, cut._cache_height)
1766
- else:
1767
- # Image was too large to cache, draw a red rectangle instead.
1768
- gc.SetBrush(wx.RED_BRUSH)
1769
- gc.DrawRectangle(0, 0, cut._cache_width, cut._cache_height)
1770
- gc.DrawBitmap(
1771
- icons8_image.GetBitmap(),
1772
- 0,
1773
- 0,
1774
- cut._cache_width,
1775
- cut._cache_height,
1776
- )
1777
- gc.ResetClip()
1778
- gc.PopState()
1779
-
1780
- # # We draw a rectangle covering the raster area
1781
- # spath = str(self.sim.cutcode[idx].path)
1782
- # sparse = re.compile(" ([0-9,\.]*) ")
1783
- # min_x = None
1784
- # max_x = None
1785
- # path_width = 0
1786
- # for numpair in sparse.findall(spath):
1787
- # comma_idx = numpair.find(",")
1788
- # if comma_idx >= 0:
1789
- # left_num = numpair[:comma_idx]
1790
- # right_num = numpair[comma_idx + 1 :]
1791
- # # print (f"'{numpair}' -> '{left_num}', '{right_num}'")
1792
- # try:
1793
- # c_x = float(left_num)
1794
- # c_y = float(right_num)
1795
- # if min_x is None:
1796
- # min_x = c_x
1797
- # max_x = c_x
1798
- # else:
1799
- # if c_x < min_x:
1800
- # min_x = c_x
1801
- # if c_x > max_x:
1802
- # max_x = c_x
1803
- # path_width = max_x - min_x
1804
- # except ValueError:
1805
- # pass
1806
- # print(f"path={self.sim.cutcode[idx].path}")
1807
- # print(f"Raster: ({cutstart[0]}, {cutstart[1]}) - ({cutend[0]}, {cutend[1]})")
1808
- # print(f"w={abs(cutend[0] - cutstart[0])}, w-cutop = {2*self.sim.cutcode[idx].width}, w_path={path_width}")
1809
- # c_vars = vars(self.sim.cutcode[idx])
1810
- # for cv in c_vars:
1811
- # print(f"{cv}={c_vars[cv]}")
1812
- # rect_y = cutstart[1]
1813
- # rect_x = self.sim.cutcode[idx].offset_x
1814
- # rect_w = max(2 * self.sim.cutcode[idx].width, path_width)
1815
- rect_h = residual * (cutend[1] - cutstart[1])
1816
- # interim_pen = wx.Pen(wx.GREEN, 1, wx.PENSTYLE_SOLID)
1817
- # gc.SetPen(interim_pen)
1818
- # gc.DrawRectangle(rect_x, rect_y, rect_w, rect_h)
1819
- else:
1820
- end = wx.Point2D(
1821
- cutstart[0] + residual * (cutend[0] - cutstart[0]),
1822
- cutstart[1] + residual * (cutend[1] - cutstart[1]),
1823
- )
1824
- starts.append(cutstart)
1825
- ends.append(end)
1826
- interim_pen = wx.Pen(wx.GREEN, 1, wx.PENSTYLE_SOLID)
1827
- gc.SetPen(interim_pen)
1828
- gc.StrokeLineSegments(starts, ends)
1829
-
1830
-
1831
- class SimulationTravelWidget(Widget):
1832
- """
1833
- The simulation Travel Widget is responsible for the background of dotted lines and arrows
1834
- within the simulation scene.
1835
- """
1836
-
1837
- def __init__(self, scene, sim):
1838
- Widget.__init__(self, scene, all=False)
1839
- self.sim_matrix = ~scene.context.device.view.matrix
1840
- self.sim = sim
1841
- self.matrix.post_cat(~scene.context.device.view.matrix)
1842
- self.initvars()
1843
-
1844
- def initvars(self):
1845
- self.starts = list()
1846
- self.ends = list()
1847
- self.pos = list()
1848
- self.starts.append(wx.Point2D(0, 0))
1849
- self.ends.append(wx.Point2D(0, 0))
1850
- prev = None
1851
- for i, curr in enumerate(list(self.sim.cutcode)):
1852
- if prev is not None:
1853
- if prev.end != curr.start:
1854
- # This is a travel
1855
- start = wx.Point2D(*prev.end)
1856
- end = wx.Point2D(*curr.start)
1857
- self.starts.append(start)
1858
- self.ends.append(end)
1859
- # print (f"Travel found at idx {i}, {start}->{end}")
1860
- s = complex(start[0], start[1])
1861
- e = complex(end[0], end[1])
1862
- d = abs(s - e)
1863
- if d >= 127:
1864
- for p in [0.75]:
1865
- m = p * (e - s) + s
1866
- ang = math.atan2((s - e).imag, (s - e).real)
1867
- # arrow_size = d / 10.0
1868
- arrow_size = 50
1869
- m0 = m + complex(
1870
- math.cos(ang + math.tau / 10) * arrow_size,
1871
- math.sin(ang + math.tau / 10) * arrow_size,
1872
- )
1873
- m1 = m + complex(
1874
- math.cos(ang - math.tau / 10) * arrow_size,
1875
- math.sin(ang - math.tau / 10) * arrow_size,
1876
- )
1877
- m = wx.Point2D(m.real, m.imag)
1878
- self.starts.append(m)
1879
- self.ends.append(wx.Point2D(m0.real, m0.imag))
1880
- self.starts.append(m)
1881
- self.ends.append(wx.Point2D(m1.real, m1.imag))
1882
- else:
1883
- end = wx.Point2D(*curr.start)
1884
- self.starts = list()
1885
- self.ends = list()
1886
- self.starts.append(wx.Point2D(0, 0))
1887
- self.ends.append(end)
1888
- self.pos.append(len(self.starts))
1889
- prev = curr
1890
-
1891
- def process_draw(self, gc: wx.GraphicsContext):
1892
- if len(self.pos):
1893
- residual = 0
1894
- if self.sim.progress < self.sim.max:
1895
- idx, residual = self.sim.progress_to_idx(self.sim.progress)
1896
- pos = self.pos[idx]
1897
- # print(f"TravelWidget, idx={idx}, residual={residual:.3f}, pos={pos}")
1898
- else:
1899
- pos = self.pos[-1]
1900
- if pos >= 0:
1901
- starts = self.starts[:pos]
1902
- ends = self.ends[:pos]
1903
- if residual > 0 and idx > 0:
1904
- p1 = self.sim.cutcode[idx - 1].end
1905
- p2 = self.sim.cutcode[idx - 1].start
1906
- # progress = time
1907
- t1 = self.sim.statistics[idx - 1]
1908
- t2 = self.sim.statistics[idx]
1909
- end_time = t1["time_at_end_of_travel"]
1910
- # Time after travel.
1911
- new_time = t2["time_at_end_of_travel"]
1912
- if (
1913
- t1["total_time_travel"] != t2["total_time_travel"]
1914
- ): # Travel time
1915
- fact = (min(self.sim.progress, new_time) - end_time) / (
1916
- new_time - end_time
1917
- )
1918
- newstart = wx.Point2D(p1[0], p1[1])
1919
- newend = wx.Point2D(
1920
- p1[0] + fact * (p2[0] - p1[0]),
1921
- p1[1] + fact * (p2[1] - p1[1]),
1922
- )
1923
- mystarts = list()
1924
- myends = list()
1925
- mystarts.append(newstart)
1926
- myends.append(newend)
1927
- interim_pen = wx.Pen(wx.GREEN, 1, wx.PENSTYLE_DOT)
1928
- gc.SetPen(interim_pen)
1929
- gc.StrokeLineSegments(mystarts, myends)
1930
- gc.SetPen(wx.BLACK_DASHED_PEN)
1931
- gc.StrokeLineSegments(starts, ends)
1932
- # for idx, pt_start in enumerate(starts):
1933
- # pt_end = ends[idx]
1934
- # print (f"#{idx}: ({pt_start[0]:.0f}, {pt_start[1]:.0f}) - ({pt_end[0]:.0f}, {pt_end[1]:.0f})")
1935
- # starts = list()
1936
- # ends = list()
1937
- # starts.append(wx.Point2D(0, 0))
1938
- # ends.append(wx.Point2D(10000, 10000))
1939
- # starts.append(wx.Point2D(0, 10000))
1940
- # ends.append(wx.Point2D(10000, 0))
1941
- # gc.SetPen(wx.CYAN_PEN)
1942
- # gc.StrokeLineSegments(starts, ends)
1943
-
1944
-
1945
- class SimReticleWidget(Widget):
1946
- """
1947
- The simulation Reticle widget is responsible for rendering the three green circles.
1948
- The position at 0 should be 0,0. At 1 the start position. And at all other positions
1949
- the end of the current cut object.
1950
- """
1951
-
1952
- def __init__(self, scene, sim):
1953
- Widget.__init__(self, scene, all=False)
1954
- self.sim_matrix = ~scene.context.device.view.matrix
1955
- self.sim = sim
1956
-
1957
- def process_draw(self, gc):
1958
- x = 0
1959
- y = 0
1960
- if (
1961
- # self.sim.progress > 0 and
1962
- self.sim.cutcode is not None
1963
- and len(self.sim.cutcode)
1964
- ):
1965
- idx, residual = self.sim.progress_to_idx(self.sim.progress)
1966
- dx = 0
1967
- dy = 0
1968
- if self.sim.progress != self.sim.max:
1969
- if idx > 0:
1970
- pos = self.sim.cutcode[idx - 1].end
1971
- else:
1972
- pos = self.sim.cutcode[idx].start
1973
- if residual > 0:
1974
- # We could still be traversing or already burning...
1975
- # We have two time stamps one after travel,
1976
- # one after burn
1977
- item = self.sim.statistics[idx]
1978
- # print(
1979
- # f"Time stamp: {self.sim.progress}, "
1980
- # + f"at start: {item['time_at_start']}, "
1981
- # + f"after travel: {item['time_at_end_of_travel']}, "
1982
- # + f"after burn: {item['time_at_end_of_burn']}"
1983
- # )
1984
- if self.sim.progress < item["time_at_end_of_travel"]:
1985
- # All travel done...
1986
- fraction = (self.sim.progress - item["time_at_start"]) / (
1987
- item["time_at_end_of_travel"] - item["time_at_start"]
1988
- )
1989
- pos = self.sim.cutcode[idx - 1].end
1990
- npos = self.sim.cutcode[idx].start
1991
- else:
1992
- # Still travelling, duration
1993
- fraction = (
1994
- self.sim.progress - item["time_at_end_of_travel"]
1995
- ) / (
1996
- item["time_at_end_of_burn"] - item["time_at_end_of_travel"]
1997
- )
1998
- pos = self.sim.cutcode[idx].start
1999
- npos = self.sim.cutcode[idx].end
2000
-
2001
- dx = fraction * (npos[0] - pos[0])
2002
- dy = fraction * (npos[1] - pos[1])
2003
- else:
2004
- pos = self.sim.cutcode[idx].end
2005
- x = pos[0] + dx
2006
- y = pos[1] + dy
2007
- x, y = self.sim_matrix.point_in_matrix_space((x, y))
2008
-
2009
- try:
2010
- # Draw Reticle
2011
- gc.SetPen(wx.Pen(wx.Colour(0, 255, 0, alpha=127)))
2012
- gc.SetBrush(wx.TRANSPARENT_BRUSH)
2013
- x, y = self.scene.convert_scene_to_window([x, y])
2014
- gc.DrawEllipse(x - 5, y - 5, 10, 10)
2015
- gc.DrawEllipse(x - 10, y - 10, 20, 20)
2016
- gc.DrawEllipse(x - 20, y - 20, 40, 40)
2017
- except AttributeError:
2018
- pass
2019
-
2020
-
2021
- class Simulation(MWindow):
2022
- def __init__(self, *args, **kwds):
2023
- super().__init__(706, 755, *args, **kwds)
2024
- if len(args) > 3:
2025
- plan_name = args[3]
2026
- else:
2027
- plan_name = None
2028
- if len(args) > 4:
2029
- auto_clear = bool(int(args[4]))
2030
- else:
2031
- auto_clear = True
2032
- if len(args) > 5:
2033
- optimise = bool(int(args[5]))
2034
- else:
2035
- optimise = True
2036
-
2037
- self.panel = SimulationPanel(
2038
- self,
2039
- wx.ID_ANY,
2040
- context=self.context,
2041
- plan_name=plan_name,
2042
- auto_clear=auto_clear,
2043
- optimise_at_start=optimise,
2044
- )
2045
- _icon = wx.NullIcon
2046
- _icon.CopyFromBitmap(icons8_laser_beam_hazard.GetBitmap())
2047
- self.SetIcon(_icon)
2048
- self.SetTitle(_("Simulation"))
2049
-
2050
- @staticmethod
2051
- def sub_register(kernel):
2052
- def open_simulator(v=None):
2053
- busy = kernel.busyinfo
2054
- busy.change(msg=_("Preparing simulation..."))
2055
- busy.start()
2056
-
2057
- kernel.console(
2058
- "planz copy preprocess validate blob preopt optimize\nwindow toggle Simulation z\n"
2059
- )
2060
- busy.end()
2061
-
2062
- kernel.register(
2063
- "button/jobstart/Simulation",
2064
- {
2065
- "label": _("Simulate"),
2066
- "icon": icons8_laser_beam_hazard,
2067
- "tip": _("Simulate the current laser job"),
2068
- "action": open_simulator,
2069
- "size": STD_ICON_SIZE,
2070
- "priority": 1,
2071
- },
2072
- )
2073
-
2074
- def window_open(self):
2075
- self.panel.pane_show()
2076
-
2077
- def window_close(self):
2078
- self.panel.pane_hide()
2079
-
2080
- def delegates(self):
2081
- yield self.panel
2082
-
2083
- @signal_listener("background")
2084
- def on_background_signal(self, origin, background):
2085
- if background is not None:
2086
- background = wx.Bitmap.FromBuffer(*background)
2087
- self.panel.widget_scene._signal_widget(
2088
- self.panel.widget_scene.widget_root, "background", background
2089
- )
2090
- self.panel.widget_scene.request_refresh()
2091
-
2092
- @staticmethod
2093
- def submenu():
2094
- return "Burning", "Simulation"
1
+ import math
2
+ import platform
3
+ from time import perf_counter, sleep
4
+
5
+ import wx
6
+
7
+ from meerk40t.kernel import Job, signal_listener
8
+
9
+ from ..core.cutcode.cubiccut import CubicCut
10
+ from ..core.cutcode.cutcode import CutCode
11
+ from ..core.cutcode.dwellcut import DwellCut
12
+ from ..core.cutcode.gotocut import GotoCut
13
+ from ..core.cutcode.homecut import HomeCut
14
+ from ..core.cutcode.inputcut import InputCut
15
+ from ..core.cutcode.linecut import LineCut
16
+ from ..core.cutcode.outputcut import OutputCut
17
+ from ..core.cutcode.plotcut import PlotCut
18
+ from ..core.cutcode.quadcut import QuadCut
19
+ from ..core.cutcode.rastercut import RasterCut
20
+ from ..core.cutcode.waitcut import WaitCut
21
+ from ..core.node.util_console import ConsoleOperation
22
+ from ..core.node.util_goto import GotoOperation
23
+ from ..core.node.util_home import HomeOperation
24
+ from ..core.node.util_wait import WaitOperation
25
+ from ..core.units import Length
26
+ from ..svgelements import Matrix
27
+ from .choicepropertypanel import ChoicePropertyPanel
28
+ from .icons import (
29
+ STD_ICON_SIZE,
30
+ get_default_icon_size,
31
+ icon_bell,
32
+ icon_close_window,
33
+ icon_console,
34
+ icon_external,
35
+ icon_internal,
36
+ icon_return,
37
+ icon_round_stop,
38
+ icon_timer,
39
+ icons8_circled_play,
40
+ icons8_home_filled,
41
+ icons8_image,
42
+ icons8_laser_beam_hazard,
43
+ icons8_pause,
44
+ icons8_route,
45
+ )
46
+ from .laserrender import DRAW_MODE_BACKGROUND, LaserRender
47
+ from .mwindow import MWindow
48
+ from .scene.scenepanel import ScenePanel
49
+ from .scene.widget import Widget
50
+ from .scenewidgets.bedwidget import BedWidget
51
+ from .scenewidgets.gridwidget import GridWidget
52
+ from .wxutils import (
53
+ StaticBoxSizer,
54
+ TextCtrl,
55
+ dip_size,
56
+ get_gc_scale,
57
+ wxButton,
58
+ wxCheckBox,
59
+ wxListBox,
60
+ wxListCtrl,
61
+ wxStaticText,
62
+ )
63
+ from .zmatrix import ZMatrix
64
+
65
+ _ = wx.GetTranslation
66
+
67
+
68
+ class OperationsPanel(wx.Panel):
69
+ """
70
+ OperationsPanel is a panel that display cutplan operations and allows to edit them
71
+ """
72
+
73
+ def __init__(self, *args, context=None, cutplan=None, **kwds):
74
+ # begin wxGlade: PassesPanel.__init__
75
+ kwds["style"] = kwds.get("style", 0)
76
+ wx.Panel.__init__(self, *args, **kwds)
77
+ self.parent = args[0]
78
+ self.context = context
79
+ self.context.themes.set_window_colors(self)
80
+
81
+ self.cutplan = cutplan
82
+ if self.cutplan is None:
83
+ self.plan_name = ""
84
+ else:
85
+ self.plan_name = self.cutplan.name
86
+ self.list_operations = wxListCtrl(self, wx.ID_ANY, style=wx.LC_LIST)
87
+ self.context.themes.set_window_colors(self.list_operations)
88
+
89
+ self.text_operation_param = TextCtrl(
90
+ self, wx.ID_ANY, "", style=wx.TE_PROCESS_ENTER
91
+ )
92
+ self.check_decompile = wxCheckBox(self, wx.ID_ANY, "D")
93
+ self.check_decompile.SetToolTip(
94
+ _("Decompile cutplan = make operations visible and editable again")
95
+ )
96
+ self.text_operation_param.SetToolTip(
97
+ _("Modify operation parameter, press Enter to apply")
98
+ )
99
+
100
+ self.list_operations.Bind(
101
+ wx.EVT_RIGHT_DOWN, self.on_listbox_operation_rightclick
102
+ )
103
+ self.list_operations.Bind(
104
+ wx.EVT_LIST_ITEM_SELECTED, self.on_listbox_operation_select
105
+ )
106
+ self.text_operation_param.Bind(wx.EVT_TEXT_ENTER, self.on_text_operation_param)
107
+ self.check_decompile.Bind(wx.EVT_CHECKBOX, self.on_check_decompile)
108
+
109
+ ops_sizer = wx.BoxSizer(wx.VERTICAL)
110
+ ops_sizer.Add(self.list_operations, 1, wx.EXPAND, 0)
111
+ hsizer = wx.BoxSizer(wx.HORIZONTAL)
112
+ hsizer.Add(self.text_operation_param, 1, wx.EXPAND, 0)
113
+ hsizer.Add(self.check_decompile, 0, wx.ALIGN_CENTER_VERTICAL, 0)
114
+ ops_sizer.Add(hsizer, 0, wx.EXPAND, 0)
115
+ self.setup_state_images()
116
+ self.SetSizer(ops_sizer)
117
+ self.Layout()
118
+ self.context.setting(bool, "cutplan_decompile", False)
119
+ decompile = self.context.cutplan_decompile
120
+ self.check_decompile.SetValue(decompile)
121
+ self.set_cut_plan(self.cutplan)
122
+
123
+ def setup_state_images(self):
124
+ iconsize = 20
125
+ self.default_images = [
126
+ ["beep", icon_bell],
127
+ ["interrupt", icon_round_stop],
128
+ ["quit", icon_close_window],
129
+ ["wait", icon_timer],
130
+ ["home", icons8_home_filled],
131
+ ["goto", icon_return],
132
+ ["origin", icon_return],
133
+ ["output", icon_external],
134
+ ["input", icon_internal],
135
+ ["cutcode", icons8_laser_beam_hazard],
136
+ # Intentionally the last...
137
+ ["console", icon_console],
138
+ ]
139
+ self.options_images = wx.ImageList()
140
+ self.options_images.Create(width=iconsize, height=iconsize)
141
+ for entry in self.default_images:
142
+ image = entry[1].GetBitmap(resize=(iconsize, iconsize), noadjustment=True)
143
+ image_id1 = self.options_images.Add(bitmap=image)
144
+ self.list_operations.AssignImageList(self.options_images, wx.IMAGE_LIST_SMALL)
145
+
146
+ def establish_state(self, typename, opname):
147
+ # Establish icon
148
+ stateidx = -1
149
+ tofind = opname.lower()
150
+ for idx, entry in enumerate(self.default_images):
151
+ if tofind.startswith(entry[0]):
152
+ stateidx = idx
153
+ break
154
+ if stateidx < 0 and typename == "ConsoleOperation":
155
+ stateidx = len(self.default_images) - 1
156
+ # print(f"opname={opname}, parameter={parameter}, state={stateidx}")
157
+ return stateidx
158
+
159
+ def on_check_decompile(self, event):
160
+ flag = self.check_decompile.GetValue()
161
+ if self.context.cutplan_decompile != flag:
162
+ self.context.cutplan_decompile = flag
163
+ if flag:
164
+ self.set_cut_plan(self.cutplan)
165
+
166
+ def set_cut_plan(self, cutplan):
167
+ def name_str(e):
168
+ res1 = type(e).__name__
169
+ try:
170
+ res2 = e.__name__
171
+ except AttributeError:
172
+ res2 = str(e)
173
+ # print(f"{res1} -> {res2}")
174
+ return res1, res2
175
+
176
+ decompile = self.context.cutplan_decompile
177
+ oldidx = self.list_operations.GetFirstSelected()
178
+ self.cutplan = cutplan
179
+ self.plan_name = self.cutplan.name
180
+ if decompile:
181
+ changes = True
182
+ while changes:
183
+ changes = False # Prove me wrong...
184
+ for idx, cut in enumerate(self.cutplan.plan):
185
+ if isinstance(cut, CutCode):
186
+ # Let's have a look at the beginning
187
+ myidx = idx
188
+ while len(cut) > 0:
189
+ entry = cut[0]
190
+ if isinstance(entry, GotoCut):
191
+ # reverse engineer
192
+ changes = True
193
+ x = entry._start_x
194
+ y = entry._start_y
195
+ newop = GotoOperation(x=x, y=y)
196
+ self.cutplan.plan.insert(myidx, newop)
197
+ myidx += 1
198
+ cut.pop(0)
199
+ elif isinstance(entry, HomeCut):
200
+ # reverse engineer
201
+ changes = True
202
+ newop = HomeOperation()
203
+ self.cutplan.plan.insert(myidx, newop)
204
+ myidx += 1
205
+ cut.pop(0)
206
+ elif isinstance(entry, WaitCut):
207
+ # reverse engineer
208
+ changes = True
209
+ wt = entry.dwell_time
210
+ newop = WaitOperation(wait=wt)
211
+ self.cutplan.plan.insert(myidx, newop)
212
+ myidx += 1
213
+ cut.pop(0)
214
+ else:
215
+ # 'Real ' stuff starts that's enough...
216
+ break
217
+
218
+ # And now look to the end
219
+ while len(cut) > 0:
220
+ last = len(cut) - 1
221
+ entry = cut[last]
222
+ if isinstance(entry, GotoCut):
223
+ # reverse engineer
224
+ changes = True
225
+ x = entry._start_x
226
+ y = entry._start_y
227
+ newop = GotoOperation(x=x, y=y)
228
+ self.cutplan.plan.insert(myidx + 1, newop)
229
+ cut.pop(last)
230
+ elif isinstance(entry, HomeCut):
231
+ # reverse engineer
232
+ changes = True
233
+ newop = HomeOperation()
234
+ self.cutplan.plan.insert(myidx + 1, newop)
235
+ cut.pop(last)
236
+ elif isinstance(entry, WaitCut):
237
+ # reverse engineer
238
+ changes = True
239
+ wt = entry.dwell_time
240
+ newop = WaitOperation(wait=wt)
241
+ self.cutplan.plan.insert(myidx + 1, newop)
242
+ cut.pop(last)
243
+ else:
244
+ # 'Real ' stuff starts that's enough...
245
+ break
246
+ if len(cut) == 0:
247
+ idx = self.cutplan.plan.index(cut)
248
+ self.cutplan.plan.pop(idx)
249
+ changes = True
250
+
251
+ if changes:
252
+ # Break from inner loop and try again...
253
+ break
254
+
255
+ self.list_operations.DeleteAllItems()
256
+ if self.cutplan.plan is not None and len(self.cutplan.plan) != 0:
257
+ for idx, entry in enumerate(self.cutplan.plan):
258
+ tname, info = name_str(entry)
259
+ item = self.list_operations.InsertItem(
260
+ self.list_operations.GetItemCount(), f"{idx:02d}# - {info}"
261
+ )
262
+
263
+ state = self.establish_state(tname, info)
264
+ if state >= 0:
265
+ self.list_operations.SetItemImage(item, state)
266
+
267
+ if 0 <= oldidx < len(self.cutplan.plan):
268
+ self.list_operations.SetItemState(
269
+ oldidx, wx.LIST_STATE_SELECTED, wx.LIST_STATE_SELECTED
270
+ )
271
+ self.on_listbox_operation_select(None)
272
+
273
+ # def on_listbox_operation_drag_drop(self, event):
274
+ # idx1 = 0
275
+ # idx2 = 0
276
+ # temp = self.cutplan.plan[idx1]
277
+ # self.cutplan.plan[idx1] = self.cutplan.plan[idx2]
278
+ # self.cutplan.plan[idx2] = temp
279
+
280
+ def on_text_operation_param(self, event):
281
+ content = self.text_operation_param.GetValue()
282
+ idx = self.list_operations.GetFirstSelected()
283
+ flag = False
284
+ if idx < 0:
285
+ return
286
+ op = self.cutplan.plan[idx]
287
+ if isinstance(op, ConsoleOperation):
288
+ op.command = content
289
+ elif isinstance(op, GotoOperation):
290
+ params = content.split(",")
291
+ x = 0
292
+ y = 0
293
+ if len(params) > 0:
294
+ try:
295
+ x = float(Length(params[0]))
296
+ except ValueError:
297
+ return
298
+ if len(params) > 1:
299
+ try:
300
+ y = float(Length(params[1]))
301
+ except ValueError:
302
+ return
303
+ op.x = x
304
+ op.y = y
305
+ elif isinstance(op, WaitOperation):
306
+ try:
307
+ duration = float(content)
308
+ op.wait = duration
309
+ except ValueError:
310
+ return
311
+ op.x = None
312
+ op.y = None
313
+ else:
314
+ return
315
+ self.context.signal("plan", self.plan_name, 1)
316
+
317
+ def on_listbox_operation_select(self, event):
318
+ flag = False
319
+ content = ""
320
+ idx = self.list_operations.GetFirstSelected()
321
+ cutcode = None
322
+ if idx >= 0:
323
+ op = self.cutplan.plan[idx]
324
+ if isinstance(op, ConsoleOperation):
325
+ content = op.command
326
+ flag = True
327
+ elif isinstance(op, GotoOperation):
328
+ content = str(op.x) + "," + str(op.y)
329
+ flag = True
330
+ elif isinstance(op, WaitOperation):
331
+ content = str(op.wait)
332
+ flag = True
333
+ elif isinstance(op, CutCode):
334
+ cutcode = op
335
+ self.parent.set_cutcode_entry(cutcode)
336
+ self.text_operation_param.SetValue(content)
337
+ self.text_operation_param.Enable(flag)
338
+
339
+ def on_listbox_operation_rightclick(self, event):
340
+ def remove_operation(event):
341
+ idx = self.list_operations.GetFirstSelected()
342
+ self.cutplan.plan.pop(idx)
343
+ self.context.signal("plan", self.plan_name, 1)
344
+ # self._refresh_simulated_plan()
345
+
346
+ def append_operation(operation):
347
+ def check(event):
348
+ self.cutplan.plan.append(my_operation)
349
+ self.context.signal("plan", self.plan_name, 1)
350
+
351
+ my_operation = operation
352
+ return check
353
+
354
+ def insert_operation(operation):
355
+ def check(event):
356
+ self.cutplan.plan.insert(
357
+ self.list_operations.GetFirstSelected(), my_operation
358
+ )
359
+ self.context.signal("plan", self.plan_name, 1)
360
+
361
+ my_operation = operation
362
+ return check
363
+
364
+ if self.list_operations.GetFirstSelected() < 0:
365
+ return
366
+
367
+ gui = self
368
+
369
+ menu = wx.Menu()
370
+ self.Bind(
371
+ wx.EVT_MENU,
372
+ remove_operation,
373
+ menu.Append(
374
+ wx.ID_ANY,
375
+ _("Remove operation"),
376
+ _("Removes the current operation from the active cutplan"),
377
+ ),
378
+ )
379
+ standards = (
380
+ ("Home", "util home", ""),
381
+ ("Goto Origin", "util goto", "0,0"),
382
+ ("Beep", "util console", "beep"),
383
+ ("Interrupt", "util console", 'interrupt "Spooling was interrupted"'),
384
+ ("Console", "util console", "echo 'Still burning'"),
385
+ ("Wait", "util wait", "5"),
386
+ )
387
+ pre_items = []
388
+ for elem in standards:
389
+ desc = elem[0]
390
+ optype = elem[1]
391
+ opparam = elem[2]
392
+
393
+ if optype is not None:
394
+ addop = None
395
+ if optype == "util console":
396
+ addop = ConsoleOperation(command=opparam)
397
+ elif optype == "util home":
398
+ addop = HomeOperation()
399
+ # elif optype == "util output":
400
+ # if opparam is not None:
401
+ # params = opparam.split(",")
402
+ # mask = 0
403
+ # setvalue = 0
404
+ # if len(params) > 0:
405
+ # try:
406
+ # mask = int(params[0])
407
+ # except ValueError:
408
+ # mask = 0
409
+ # if len(params) > 1:
410
+ # try:
411
+ # setvalue = int(params[1])
412
+ # except ValueError:
413
+ # setvalue = 0
414
+ # if mask != 0 or setvalue != 0:
415
+ # addop = OutputOperation(mask, setvalue)
416
+ elif optype == "util goto":
417
+ if opparam is not None:
418
+ params = opparam.split(",")
419
+ x = 0
420
+ y = 0
421
+ if len(params) > 0:
422
+ try:
423
+ x = float(Length(params[0]))
424
+ except ValueError:
425
+ x = 0
426
+ if len(params) > 1:
427
+ try:
428
+ y = float(Length(params[1]))
429
+ except ValueError:
430
+ y = 0
431
+ addop = GotoOperation(x=x, y=y)
432
+ elif optype == "util wait":
433
+ if opparam is not None:
434
+ try:
435
+ opparam = float(opparam)
436
+ except ValueError:
437
+ opparam = None
438
+ if opparam is not None:
439
+ addop = WaitOperation(wait=opparam)
440
+ if addop is not None:
441
+ pre_items.append([desc, addop])
442
+
443
+ menu.AppendSeparator()
444
+ for entry in pre_items:
445
+ self.Bind(
446
+ wx.EVT_MENU,
447
+ insert_operation(entry[1]),
448
+ menu.Append(
449
+ wx.ID_ANY,
450
+ _("Insert '{operation}' before").format(operation=entry[0]),
451
+ _(
452
+ "Inserts this special operation before the current cutplan entry"
453
+ ),
454
+ ),
455
+ )
456
+ menu.AppendSeparator()
457
+ for entry in pre_items:
458
+ self.Bind(
459
+ wx.EVT_MENU,
460
+ append_operation(entry[1]),
461
+ menu.Append(
462
+ wx.ID_ANY,
463
+ _("Appends '{operation}' at end").format(operation=entry[0]),
464
+ _("Appends this special operation at the end of the cutplan"),
465
+ ),
466
+ )
467
+
468
+ if menu.MenuItemCount != 0:
469
+ gui.PopupMenu(menu)
470
+ menu.Destroy()
471
+
472
+
473
+ class CutcodePanel(wx.Panel):
474
+ """
475
+ CutcodePanel is a panel that display cutplan Cutcode and allows to edit them
476
+ """
477
+
478
+ def __init__(self, *args, context=None, cutcode=None, plan_name=None, **kwds):
479
+ # begin wxGlade: PassesPanel.__init__
480
+ kwds["style"] = kwds.get("style", 0)
481
+ self.parent = args[0]
482
+ wx.Panel.__init__(self, *args, **kwds)
483
+ self.context = context
484
+ self.context.themes.set_window_colors(self)
485
+
486
+ self.cutcode = cutcode
487
+ self.plan_name = plan_name
488
+ self.list_cutcode = wxListBox(
489
+ self, wx.ID_ANY, choices=[], style=wx.LB_MULTIPLE
490
+ )
491
+ self.last_selected = []
492
+ self.display_highlighted_only = False
493
+ # self.text_operation_param = TextCtrl(
494
+ # self, wx.ID_ANY, "", style=wx.TE_PROCESS_ENTER
495
+ # )
496
+ # self.text_operation_param.SetToolTip(
497
+ # _("Modify operation parameter, press Enter to apply")
498
+ # )
499
+
500
+ self.list_cutcode.Bind(wx.EVT_RIGHT_DOWN, self.on_listbox_operation_rightclick)
501
+ # self.list_cutcode.Bind(wx.EVT_LISTBOX_DCLICK, self.on_listbox_operation_dclick)
502
+ self.list_cutcode.Bind(wx.EVT_LISTBOX, self.on_listbox_operation_select)
503
+ # self.text_operation_param.Bind(wx.EVT_TEXT_ENTER, self.on_text_operation_param)
504
+
505
+ ops_sizer = wx.BoxSizer(wx.VERTICAL)
506
+ ops_sizer.Add(self.list_cutcode, 1, wx.EXPAND, 0)
507
+ # ops_sizer.Add(self.text_operation_param, 0, wx.EXPAND, 0)
508
+ self.SetSizer(ops_sizer)
509
+ self.Layout()
510
+ self.set_cutcode_entry(self.cutcode, self.plan_name)
511
+
512
+ def set_cutcode_entry(self, cutcode, plan_name):
513
+ def name_str(e):
514
+ if isinstance(e, RasterCut):
515
+ res = f"Raster: {e.width} x {e.height}"
516
+ elif isinstance(e, CubicCut):
517
+ res = f"Cubic: ({e.start[0]:.0f}, {e.start[1]:.0f}) - ({e.end[0]:.0f}, {e.end[1]:.0f})"
518
+ res += f" (c1=({e.c1()[0]:.0f}, {e.c1()[1]:.0f}), c2=({e.c2()[0]:.0f}, {e.c2()[1]:.0f}) )"
519
+ elif isinstance(e, LineCut):
520
+ res = f"Line: ({e.start[0]:.0f}, {e.start[1]:.0f}) - ({e.end[0]:.0f}, {e.end[1]:.0f})"
521
+ elif isinstance(e, DwellCut):
522
+ res = f"Dwell: {e.dwell_time}"
523
+ elif isinstance(e, WaitCut):
524
+ res = f"Wait: {e.dwell_time}"
525
+ elif isinstance(e, HomeCut):
526
+ res = "Home"
527
+ elif isinstance(e, GotoCut):
528
+ coord = f"({e._start_x:.0f}, {e._start_y:.0f})"
529
+ res = f"Goto: ({e.start[0]:.0f}, {e.start[1]:.0f}) {coord}"
530
+ elif isinstance(e, InputCut):
531
+ res = f"Input: {e.input_value:b} (mask: {e.input_mask:b})"
532
+ elif isinstance(e, OutputCut):
533
+ res = f"Output: {e.output_value:b} (mask: {e.output_mask:b})"
534
+ elif isinstance(e, PlotCut):
535
+ res = f"Plot: {len(e)} points"
536
+ elif isinstance(e, QuadCut):
537
+ res = f"Quad: {e.start[0]:.0f}, {e.start[1]:.0f} - {e.end[0]:.0f}, {e.end[1]:.0f}"
538
+ res += f" (c={e.c()[0]:.0f}, {e.c()[1]:.0f})"
539
+ else:
540
+ try:
541
+ res = e.__name__
542
+ except AttributeError:
543
+ res = str(e)
544
+ if hasattr(e, "label") and getattr(e, "label") is not None:
545
+ res += f" ({getattr(e, 'label')})"
546
+ return res
547
+
548
+ self.cutcode = cutcode
549
+ # Reset highlighted flags
550
+ if cutcode is not None:
551
+ for cut in self.cutcode:
552
+ cut.highlighted = False
553
+ cut.visible = True
554
+ self.plan_name = plan_name
555
+ self.list_cutcode.Clear()
556
+ self.list_cutcode.Enable(True)
557
+ if self.cutcode is None:
558
+ self.list_cutcode.InsertItems(
559
+ [_("Please select a cutcode entry"), _("from the operations panel")], 0
560
+ )
561
+ self.list_cutcode.Enable(False)
562
+ elif len(self.cutcode) != 0:
563
+ self.list_cutcode.InsertItems([name_str(e) for e in self.cutcode], 0)
564
+
565
+ def on_listbox_operation_select(self, event):
566
+ if self.display_highlighted_only:
567
+ for cut in self.cutcode:
568
+ cut.visible = False
569
+ for cut in self.last_selected:
570
+ if cut < len(self.cutcode):
571
+ self.cutcode[cut].highlighted = False
572
+ self.last_selected = self.list_cutcode.GetSelections()
573
+ if self.last_selected is None:
574
+ self.last_selected = []
575
+ for cut in self.last_selected:
576
+ self.cutcode[cut].highlighted = True
577
+ self.cutcode[cut].visible = True
578
+ self.context.signal("refresh_simulation")
579
+
580
+ def on_listbox_operation_dclick(self, event):
581
+ # No useful logic yet, the old logic fails as it is opening a wrong node
582
+ # There are no property panels for CutObjects yet
583
+ return
584
+
585
+ def on_listbox_operation_rightclick(self, event):
586
+ def remove_operation(event):
587
+ selected = self.list_cutcode.GetSelections()
588
+ if selected is None or len(selected) == 0:
589
+ return
590
+ #
591
+ idx = len(selected) - 1
592
+ while idx >= 0:
593
+ entry = selected[idx]
594
+ self.cutcode.pop(entry)
595
+ idx -= 1
596
+ self.context.signal("plan", self.plan_name, 1)
597
+
598
+ def display_selected(event):
599
+ self.display_highlighted_only = not self.display_highlighted_only
600
+ if self.display_highlighted_only:
601
+ for cut in self.cutcode:
602
+ cut.visible = False
603
+ for cut in self.last_selected:
604
+ self.cutcode[cut].visible = True
605
+ else:
606
+ for cut in self.cutcode:
607
+ cut.visible = True
608
+ self.context.signal("refresh_simulation")
609
+
610
+ def remove_before(event):
611
+ selected = self.list_cutcode.GetSelections()
612
+ if selected is None or len(selected) == 0:
613
+ return
614
+ #
615
+ entry = selected[0]
616
+ if entry > 0:
617
+ del self.cutcode[:entry]
618
+ self.context.signal("plan", self.plan_name, 1)
619
+
620
+ def remove_after(event):
621
+ selected = self.list_cutcode.GetSelections()
622
+ if selected is None or len(selected) == 0:
623
+ return
624
+ #
625
+ entry = selected[-1]
626
+ if entry < len(self.cutcode) - 1:
627
+ del self.cutcode[entry + 1 :]
628
+ self.context.signal("plan", self.plan_name, 1)
629
+
630
+ def append_operation(cutcode):
631
+ def check(event):
632
+ self.cutcode.append(my_cutcode)
633
+ self.context.signal("plan", self.plan_name, 1)
634
+
635
+ my_cutcode = cutcode
636
+ return check
637
+
638
+ def insert_operation(cutcode):
639
+ def check(event):
640
+ selected = self.list_cutcode.GetSelections()
641
+ if selected is None or len(selected) == 0:
642
+ return
643
+ idx = selected[0]
644
+ self.cutcode.insert(idx, my_cutcode)
645
+ self.context.signal("plan", self.plan_name, 1)
646
+
647
+ my_cutcode = cutcode
648
+ return check
649
+
650
+ selected = self.list_cutcode.GetSelections()
651
+ if selected is None or len(selected) == 0:
652
+ return
653
+ sel_min = selected[0]
654
+ sel_max = selected[-1]
655
+ gui = self
656
+
657
+ menu = wx.Menu()
658
+ self.Bind(
659
+ wx.EVT_MENU,
660
+ remove_operation,
661
+ menu.Append(
662
+ wx.ID_ANY,
663
+ _("Remove cutcode"),
664
+ _("Removes the selected cutcode-entries from the active cutplan"),
665
+ ),
666
+ )
667
+ if sel_min > 0:
668
+ self.Bind(
669
+ wx.EVT_MENU,
670
+ remove_before,
671
+ menu.Append(
672
+ wx.ID_ANY,
673
+ _("Delete cuts before"),
674
+ _("Delete all cuts before the first selected"),
675
+ ),
676
+ )
677
+ if sel_max < len(self.cutcode) - 1:
678
+ self.Bind(
679
+ wx.EVT_MENU,
680
+ remove_after,
681
+ menu.Append(
682
+ wx.ID_ANY,
683
+ _("Delete cuts after"),
684
+ _("Delete all cuts after the last selected"),
685
+ ),
686
+ )
687
+ standards = (
688
+ ("Home", "home", ""),
689
+ ("Goto Origin", "goto", "0,0"),
690
+ # ("Info", "info", "Still burning"),
691
+ ("Wait", "wait", "5"),
692
+ )
693
+ pre_items = []
694
+ for elem in standards:
695
+ desc = elem[0]
696
+ optype = elem[1]
697
+ opparam = elem[2]
698
+
699
+ if optype is not None:
700
+ addop = None
701
+ if optype == "console":
702
+ # addop = ConsoleOperation(command=opparam)
703
+ pass
704
+ # elif optype == "info":
705
+ # addop = InfoCut(message=opparam)
706
+ elif optype == "home":
707
+ addop = HomeCut()
708
+ # elif optype == "util output":
709
+ # if opparam is not None:
710
+ # params = opparam.split(",")
711
+ # mask = 0
712
+ # setvalue = 0
713
+ # if len(params) > 0:
714
+ # try:
715
+ # mask = int(params[0])
716
+ # except ValueError:
717
+ # mask = 0
718
+ # if len(params) > 1:
719
+ # try:
720
+ # setvalue = int(params[1])
721
+ # except ValueError:
722
+ # setvalue = 0
723
+ # if mask != 0 or setvalue != 0:
724
+ # addop = OutputOperation(mask, setvalue)
725
+ elif optype == "goto":
726
+ if opparam is not None:
727
+ params = opparam.split(",")
728
+ x = 0
729
+ y = 0
730
+ if len(params) > 0:
731
+ try:
732
+ x = float(Length(params[0]))
733
+ except ValueError:
734
+ x = 0
735
+ if len(params) > 1:
736
+ try:
737
+ y = float(Length(params[1]))
738
+ except ValueError:
739
+ y = 0
740
+ addop = GotoCut((x, y))
741
+ elif optype == "wait":
742
+ if opparam is not None:
743
+ try:
744
+ opparam = float(opparam)
745
+ except ValueError:
746
+ opparam = None
747
+ if opparam is not None:
748
+ addop = WaitCut(wait=1000 * opparam)
749
+ if addop is not None:
750
+ pre_items.append([desc, addop])
751
+
752
+ menu.AppendSeparator()
753
+ for entry in pre_items:
754
+ self.Bind(
755
+ wx.EVT_MENU,
756
+ insert_operation(entry[1]),
757
+ menu.Append(
758
+ wx.ID_ANY,
759
+ _("Insert '{operation}' before").format(operation=entry[0]),
760
+ _(
761
+ "Inserts this special operation before the current cutplan entry"
762
+ ),
763
+ ),
764
+ )
765
+ menu.AppendSeparator()
766
+ for entry in pre_items:
767
+ self.Bind(
768
+ wx.EVT_MENU,
769
+ append_operation(entry[1]),
770
+ menu.Append(
771
+ wx.ID_ANY,
772
+ _("Appends '{operation}' at end").format(operation=entry[0]),
773
+ _("Appends this special operation at the end of the cutplan"),
774
+ ),
775
+ )
776
+
777
+ menu.AppendSeparator()
778
+ item = menu.AppendCheckItem(
779
+ wx.ID_ANY,
780
+ _("Only show highlighted cutcode items"),
781
+ )
782
+ self.Bind(wx.EVT_MENU, display_selected, item)
783
+ item.Check(self.display_highlighted_only)
784
+
785
+ if menu.MenuItemCount != 0:
786
+ gui.PopupMenu(menu)
787
+ menu.Destroy()
788
+
789
+
790
+ class SimulationPanel(wx.Panel, Job):
791
+ def __init__(
792
+ self,
793
+ *args,
794
+ context=None,
795
+ plan_name=None,
796
+ auto_clear=True,
797
+ optimise_at_start=True,
798
+ **kwds,
799
+ ):
800
+ kwds["style"] = kwds.get("style", 0) | wx.TAB_TRAVERSAL
801
+ wx.Panel.__init__(self, *args, **kwds)
802
+ self.parent = args[0]
803
+ self.context = context
804
+ self.context.themes.set_window_colors(self)
805
+ self.SetHelpText("simulate")
806
+
807
+ self.retries = 0
808
+ self.plan_name = plan_name
809
+ self.auto_clear = auto_clear
810
+ # Display travel paths?
811
+ self.display_travel = self.context.setting(bool, "display_travel", True)
812
+ self.raster_as_image = self.context.setting(bool, "raster_as_image", True)
813
+ self.laserspot_display = self.context.setting(bool, "laserspot_display", True)
814
+ self.laserspot_width = None
815
+ self.calc_laser_spot_width()
816
+
817
+ Job.__init__(self)
818
+ self._playback_cuts = True
819
+ self._cut_end_time = []
820
+
821
+ self.update_job = Job(
822
+ process=self.cache_updater,
823
+ job_name="cache_updater",
824
+ interval=0.25,
825
+ times=1,
826
+ run_main=False,
827
+ )
828
+
829
+ self.job_name = "simulate"
830
+ self.run_main = True
831
+ self.process = self.animate_sim
832
+ self.interval = 0.1
833
+ if plan_name:
834
+ self.cutplan = self.context.planner.get_or_make_plan(plan_name)
835
+ else:
836
+ self.cutplan = self.context.planner.default_plan
837
+ self.plan_name = self.cutplan.name
838
+ self.operations = self.cutplan.plan
839
+ # for e in self.operations:
840
+ # print(f"Init: {type(e).__name__} {e}")
841
+ self.cutcode = CutCode()
842
+
843
+ for c in self.operations:
844
+ if isinstance(c, CutCode):
845
+ self.cutcode.extend(c)
846
+ self.cutcode = CutCode(self.cutcode.flat())
847
+
848
+ self.statistics = self.cutcode.provide_statistics()
849
+
850
+ self.max = max(len(self.cutcode), 0) + 1
851
+ self.progress = self.max
852
+ self.view_pane = ScenePanel(
853
+ self.context,
854
+ self,
855
+ scene_name="SimScene",
856
+ style=wx.EXPAND,
857
+ )
858
+ self.view_pane.start_scene()
859
+ self.view_pane.SetCanFocus(False)
860
+ self.widget_scene = self.view_pane.scene
861
+ # poor mans slide out
862
+ self.btn_slide_options = wxButton(self, wx.ID_ANY, "<")
863
+ self.btn_slide_options.Bind(wx.EVT_BUTTON, self.slide_out)
864
+ self.btn_slide_options.SetToolTip(
865
+ _("Show/Hide optimization options for this job.")
866
+ )
867
+ from copy import copy
868
+
869
+ prechoices = copy(context.lookup("choices/optimize"))
870
+ choices = list(map(copy, prechoices))
871
+ # Clear the page-entry
872
+ for entry in choices:
873
+ entry["page"] = ""
874
+ self.subpanel_optimize = wx.Panel(self, wx.ID_ANY)
875
+ self.options_optimize = ChoicePropertyPanel(
876
+ self, wx.ID_ANY, context=self.context, choices=choices, scrolling=False
877
+ )
878
+ self.options_optimize.SetupScrolling()
879
+ self.subpanel_operations = OperationsPanel(
880
+ self, wx.ID_ANY, context=self.context, cutplan=self.cutplan
881
+ )
882
+ self.subpanel_cutcode = CutcodePanel(
883
+ self, wx.ID_ANY, context=self.context, cutcode=None, plan_name=None
884
+ )
885
+
886
+ self.panel_optimize = wx.Notebook(self, wx.ID_ANY)
887
+ self.context.themes.set_window_colors(self.panel_optimize)
888
+
889
+ self.subpanel_optimize.Reparent(self.panel_optimize)
890
+ self.subpanel_operations.Reparent(self.panel_optimize)
891
+ self.subpanel_cutcode.Reparent(self.panel_optimize)
892
+ self.panel_optimize.AddPage(self.subpanel_optimize, _("Optimizations"))
893
+ self.panel_optimize.AddPage(self.subpanel_operations, _("Operations"))
894
+ self.panel_optimize.AddPage(self.subpanel_cutcode, _("Cutcode"))
895
+ self.checkbox_optimize = wxCheckBox(self, wx.ID_ANY, _("Optimize"))
896
+ self.checkbox_optimize.SetToolTip(_("Enable/Disable Optimize"))
897
+ self.checkbox_optimize.SetValue(self.context.planner.do_optimization)
898
+ self.btn_redo_it = wxButton(self, wx.ID_ANY, _("Recalculate"))
899
+ self.btn_redo_it.Bind(wx.EVT_BUTTON, self.on_redo_it)
900
+ self.btn_redo_it.SetToolTip(_("Apply the settings and recalculate the cutplan"))
901
+
902
+ self.slider_progress = wx.Slider(self, wx.ID_ANY, self.max, 0, self.max)
903
+ self.slider_progress.SetFocus()
904
+ self.text_distance_laser = TextCtrl(
905
+ self, wx.ID_ANY, "", style=wx.TE_READONLY
906
+ )
907
+ self.text_distance_travel = TextCtrl(
908
+ self, wx.ID_ANY, "", style=wx.TE_READONLY
909
+ )
910
+ self.text_distance_total = TextCtrl(
911
+ self, wx.ID_ANY, "", style=wx.TE_READONLY
912
+ )
913
+ self.text_time_laser = TextCtrl(self, wx.ID_ANY, "", style=wx.TE_READONLY)
914
+ self.text_time_travel = TextCtrl(self, wx.ID_ANY, "", style=wx.TE_READONLY)
915
+ self.text_time_extra = TextCtrl(self, wx.ID_ANY, "", style=wx.TE_READONLY)
916
+ self.text_time_total = TextCtrl(self, wx.ID_ANY, "", style=wx.TE_READONLY)
917
+ self.text_distance_laser_step = TextCtrl(
918
+ self, wx.ID_ANY, "", style=wx.TE_READONLY
919
+ )
920
+ self.text_distance_travel_step = TextCtrl(
921
+ self, wx.ID_ANY, "", style=wx.TE_READONLY
922
+ )
923
+ self.text_distance_total_step = TextCtrl(
924
+ self, wx.ID_ANY, "", style=wx.TE_READONLY
925
+ )
926
+ self.text_time_laser_step = TextCtrl(
927
+ self, wx.ID_ANY, "", style=wx.TE_READONLY
928
+ )
929
+ self.text_time_travel_step = TextCtrl(
930
+ self, wx.ID_ANY, "", style=wx.TE_READONLY
931
+ )
932
+ self.text_time_extra_step = TextCtrl(
933
+ self, wx.ID_ANY, "", style=wx.TE_READONLY
934
+ )
935
+ self.text_time_total_step = TextCtrl(
936
+ self, wx.ID_ANY, "", style=wx.TE_READONLY
937
+ )
938
+ self.button_play = wxButton(self, wx.ID_ANY, "")
939
+ self.button_play.SetToolTip(_("Start the simulation replay"))
940
+ self.slider_playbackspeed = wx.Slider(self, wx.ID_ANY, 180, 0, 310)
941
+ self.slider_playbackspeed.SetToolTip(_("Set the speed for the simulation"))
942
+ self.text_playback_speed = TextCtrl(
943
+ self, wx.ID_ANY, "100%", style=wx.TE_READONLY
944
+ )
945
+ self.radio_cut = wx.RadioButton(self, wx.ID_ANY, _("Steps"))
946
+ self.radio_time_seconds = wx.RadioButton(self, wx.ID_ANY, _("Time (sec.)"))
947
+ self.radio_time_minutes = wx.RadioButton(self, wx.ID_ANY, _("Time (min)"))
948
+ self.radio_cut.SetToolTip(
949
+ _(
950
+ "Cut operations Playback-Mode: play will jump from one completed operations to next"
951
+ )
952
+ )
953
+ self.radio_time_seconds.SetToolTip(
954
+ _("Timed Playback-Mode: play will jump from one second to next")
955
+ )
956
+ self.radio_time_minutes.SetToolTip(
957
+ _("Timed Playback-Mode: play will jump from one minute to next")
958
+ )
959
+
960
+ self.button_spool = wxButton(self, wx.ID_ANY, _("Send to Laser"))
961
+ self.button_spool.SetToolTip(_("Send the current cutplan to the laser."))
962
+ self._slided_in = None
963
+
964
+ self.__set_properties()
965
+ self.__do_layout()
966
+
967
+ self.matrix = Matrix()
968
+
969
+ self.previous_window_position = None
970
+ self.previous_scene_position = None
971
+ self._Buffer = None
972
+
973
+ self.Bind(wx.EVT_SLIDER, self.on_slider_progress, self.slider_progress)
974
+ self.Bind(wx.EVT_BUTTON, self.on_button_play, self.button_play)
975
+ self.Bind(wx.EVT_SLIDER, self.on_slider_playback, self.slider_playbackspeed)
976
+ # self.Bind(wx.EVT_COMBOBOX, self.on_combo_device, self.combo_device)
977
+ self.Bind(wx.EVT_BUTTON, self.on_button_spool, self.button_spool)
978
+ self.Bind(wx.EVT_RIGHT_DOWN, self.on_mouse_right_down)
979
+ self.Bind(wx.EVT_RADIOBUTTON, self.on_radio_playback_mode, self.radio_cut)
980
+ self.Bind(
981
+ wx.EVT_RADIOBUTTON, self.on_radio_playback_mode, self.radio_time_seconds
982
+ )
983
+ self.Bind(
984
+ wx.EVT_RADIOBUTTON, self.on_radio_playback_mode, self.radio_time_minutes
985
+ )
986
+ self.view_pane.scene_panel.Bind(wx.EVT_RIGHT_DOWN, self.on_mouse_right_down)
987
+
988
+ # end wxGlade
989
+ self.Bind(wx.EVT_CHECKBOX, self.on_checkbox_optimize, self.checkbox_optimize)
990
+ self.on_checkbox_optimize(None)
991
+
992
+ self.Bind(wx.EVT_SIZE, self.on_size)
993
+
994
+ ##############
995
+ # BUILD SCENE
996
+ ##############
997
+
998
+ self.sim_cutcode = SimulationWidget(self.widget_scene, self)
999
+ self.sim_cutcode.raster_as_image = self.raster_as_image
1000
+ self.sim_cutcode.laserspot_width = self.laserspot_width
1001
+ self.widget_scene.add_scenewidget(self.sim_cutcode)
1002
+ self.sim_travel = SimulationTravelWidget(self.widget_scene, self)
1003
+ self.sim_travel.display = self.display_travel
1004
+ self.widget_scene.add_scenewidget(self.sim_travel)
1005
+
1006
+ self.grid = GridWidget(
1007
+ self.widget_scene, name="Simulation", suppress_labels=True
1008
+ )
1009
+ # Don't let grid resize itself
1010
+ self.grid.auto_tick = False
1011
+ if self.context.units_name == "mm":
1012
+ self.grid.tick_distance = 10 # mm
1013
+ elif self.context.units_name == "cm":
1014
+ self.grid.tick_distance = 1
1015
+ elif self.context.units_name == "inch":
1016
+ self.grid.tick_distance = 0.5
1017
+ elif self.context.units_name == "mil":
1018
+ self.grid.tick_distance = 500
1019
+ self.widget_scene.add_scenewidget(self.grid)
1020
+ self.widget_scene.add_scenewidget(
1021
+ BedWidget(self.widget_scene, name="Simulation")
1022
+ )
1023
+ self.widget_scene.add_interfacewidget(SimReticleWidget(self.widget_scene, self))
1024
+ self.parent.add_module_delegate(self.options_optimize)
1025
+ self.context.setting(int, "simulation_mode", 0)
1026
+ default = self.context.simulation_mode
1027
+ if default == 0:
1028
+ self.radio_cut.SetValue(True)
1029
+ elif default == 1:
1030
+ self.radio_time_seconds.SetValue(True)
1031
+ elif default == 2:
1032
+ self.radio_time_minutes.SetValue(True)
1033
+ self.on_radio_playback_mode(None)
1034
+ # Allow Scene update from now on (are suppressed by default during startup phase)
1035
+ self.widget_scene.suppress_changes = False
1036
+ # self.Show()
1037
+ self.running = False
1038
+ self.slided_in = True
1039
+ self.start_time = perf_counter()
1040
+ self.debug(f"Init done: {perf_counter()-self.start_time}")
1041
+
1042
+ def reload_statistics(self):
1043
+ try:
1044
+ self.statistics = self.cutcode.provide_statistics()
1045
+ self._set_slider_dimensions()
1046
+ self.sim_travel.initvars()
1047
+ self.update_fields()
1048
+ except RuntimeError:
1049
+ # Was already deleted
1050
+ pass
1051
+
1052
+ def debug(self, message):
1053
+ # print (message)
1054
+ return
1055
+
1056
+ def _startup(self):
1057
+ self.debug(f"Startup: {perf_counter()-self.start_time}")
1058
+ self.slided_in = True
1059
+ self.fit_scene_to_panel()
1060
+
1061
+ def __set_properties(self):
1062
+ self.text_distance_laser.SetToolTip(_("Distance Estimate: while Lasering"))
1063
+ self.text_distance_travel.SetToolTip(_("Distance Estimate: Traveling"))
1064
+ self.text_distance_total.SetToolTip(_("Distance Estimate: Total"))
1065
+ self.text_time_laser.SetToolTip(_("Time Estimate: Lasering Time"))
1066
+ self.text_time_travel.SetToolTip(_("Time Estimate: Traveling Time"))
1067
+ self.text_time_extra.SetToolTip(
1068
+ _("Time Estimate: Extra Time (i.e. to swing around)")
1069
+ )
1070
+ self.text_time_total.SetToolTip(_("Time Estimate: Total Time"))
1071
+ self.button_play.SetBitmap(
1072
+ icons8_circled_play.GetBitmap(resize=get_default_icon_size(self.context))
1073
+ )
1074
+ self.text_playback_speed.SetMinSize(dip_size(self, 55, 23))
1075
+ # self.combo_device.SetToolTip(_("Select the device"))
1076
+ self.button_spool.SetFont(
1077
+ wx.Font(
1078
+ 18,
1079
+ wx.FONTFAMILY_DEFAULT,
1080
+ wx.FONTSTYLE_NORMAL,
1081
+ wx.FONTWEIGHT_NORMAL,
1082
+ 0,
1083
+ "Segoe UI",
1084
+ )
1085
+ )
1086
+ self.button_spool.SetBitmap(
1087
+ icons8_route.GetBitmap(resize=1.5 * get_default_icon_size(self.context))
1088
+ )
1089
+ # end wxGlade
1090
+
1091
+ def __do_layout(self):
1092
+ # begin wxGlade: Simulation.__do_layout
1093
+ self.text_distance_laser.SetMinSize(dip_size(self, 35, -1))
1094
+ self.text_distance_laser_step.SetMinSize(dip_size(self, 35, -1))
1095
+ self.text_distance_total.SetMinSize(dip_size(self, 35, -1))
1096
+ self.text_distance_total_step.SetMinSize(dip_size(self, 35, -1))
1097
+ self.text_distance_travel.SetMinSize(dip_size(self, 35, -1))
1098
+ self.text_distance_travel_step.SetMinSize(dip_size(self, 35, -1))
1099
+ self.text_time_laser.SetMinSize(dip_size(self, 35, -1))
1100
+ self.text_time_laser_step.SetMinSize(dip_size(self, 35, -1))
1101
+ self.text_time_total.SetMinSize(dip_size(self, 35, -1))
1102
+ self.text_time_total_step.SetMinSize(dip_size(self, 35, -1))
1103
+ self.text_time_travel.SetMinSize(dip_size(self, 35, -1))
1104
+ self.text_time_travel_step.SetMinSize(dip_size(self, 35, -1))
1105
+ self.text_time_extra.SetMinSize(dip_size(self, 35, -1))
1106
+ self.text_time_extra_step.SetMinSize(dip_size(self, 35, -1))
1107
+ v_sizer_main = wx.BoxSizer(wx.VERTICAL)
1108
+ h_sizer_scroll = wx.BoxSizer(wx.HORIZONTAL)
1109
+ h_sizer_text_1 = wx.BoxSizer(wx.HORIZONTAL)
1110
+ h_sizer_text_2 = wx.BoxSizer(wx.HORIZONTAL)
1111
+ h_sizer_buttons = wx.BoxSizer(wx.HORIZONTAL)
1112
+
1113
+ sizer_execute = wx.BoxSizer(wx.VERTICAL)
1114
+ sizer_speed_options = wx.BoxSizer(wx.VERTICAL)
1115
+ sizer_pb_speed = wx.BoxSizer(wx.HORIZONTAL)
1116
+ sizer_total_time = StaticBoxSizer(
1117
+ self, wx.ID_ANY, _("Total Time"), wx.HORIZONTAL
1118
+ )
1119
+ sizer_travel_time = StaticBoxSizer(
1120
+ self, wx.ID_ANY, _("Travel Time"), wx.HORIZONTAL
1121
+ )
1122
+ sizer_laser_time = StaticBoxSizer(
1123
+ self, wx.ID_ANY, _("Laser Time"), wx.HORIZONTAL
1124
+ )
1125
+ sizer_extra_time = StaticBoxSizer(
1126
+ self, wx.ID_ANY, _("Extra Time"), wx.HORIZONTAL
1127
+ )
1128
+ sizer_total_distance = StaticBoxSizer(
1129
+ self, wx.ID_ANY, _("Total Distance"), wx.HORIZONTAL
1130
+ )
1131
+ sizer_travel_distance = StaticBoxSizer(
1132
+ self, wx.ID_ANY, _("Travel Distance"), wx.HORIZONTAL
1133
+ )
1134
+ sizer_laser_distance = StaticBoxSizer(
1135
+ self, wx.ID_ANY, _("Laser Distance"), wx.HORIZONTAL
1136
+ )
1137
+ # +--------+---+-------+
1138
+ # | P | | Optim |
1139
+ # | R | | |
1140
+ # | E | |Options|
1141
+ # | V | > | |
1142
+ # | I | | |
1143
+ # | E | +-------+
1144
+ # | W | |Refresh|
1145
+ # +--------+---+-------+
1146
+
1147
+ opt_sizer = wx.BoxSizer(wx.VERTICAL)
1148
+ self.options_optimize.Reparent(self.subpanel_optimize)
1149
+ self.checkbox_optimize.Reparent(self.subpanel_optimize)
1150
+ self.btn_redo_it.Reparent(self.subpanel_optimize)
1151
+
1152
+ self.checkbox_optimize.SetMinSize(dip_size(self, -1, 23))
1153
+ opt_sizer.Add(self.options_optimize, 1, wx.EXPAND, 0)
1154
+ opt_sizer.Add(self.checkbox_optimize, 0, wx.EXPAND, 0)
1155
+ opt_sizer.Add(self.btn_redo_it, 0, wx.EXPAND, 0)
1156
+ self.subpanel_optimize.SetSizer(opt_sizer)
1157
+ self.subpanel_optimize.Layout()
1158
+
1159
+ # Linux requires a minimum height / width to display a text inside a button
1160
+ system = platform.system()
1161
+ if system == "Darwin":
1162
+ mysize = 40
1163
+ elif system == "Windows":
1164
+ mysize = 23
1165
+ elif system == "Linux":
1166
+ mysize = 40
1167
+ else:
1168
+ mysize = 20
1169
+ self.btn_slide_options.SetMinSize(dip_size(self, mysize, -1))
1170
+ self.voption_sizer = wx.BoxSizer(wx.VERTICAL)
1171
+ self.voption_sizer.Add(self.panel_optimize, 1, wx.EXPAND, 0)
1172
+
1173
+ self.hscene_sizer = wx.BoxSizer(wx.HORIZONTAL)
1174
+ self.hscene_sizer.Add(self.view_pane, 2, wx.EXPAND, 0)
1175
+ self.hscene_sizer.Add(self.btn_slide_options, 0, wx.EXPAND, 0)
1176
+ self.hscene_sizer.Add(self.voption_sizer, 1, wx.EXPAND, 0)
1177
+
1178
+ h_sizer_scroll.Add(self.slider_progress, 1, wx.EXPAND, 0)
1179
+
1180
+ sizer_laser_distance.Add(self.text_distance_laser_step, 1, wx.EXPAND, 0)
1181
+ sizer_laser_distance.Add(self.text_distance_laser, 1, wx.EXPAND, 0)
1182
+ h_sizer_text_1.Add(sizer_laser_distance, 1, wx.EXPAND, 0)
1183
+
1184
+ sizer_travel_distance.Add(self.text_distance_travel_step, 1, wx.EXPAND, 0)
1185
+ sizer_travel_distance.Add(self.text_distance_travel, 1, wx.EXPAND, 0)
1186
+ h_sizer_text_1.Add(sizer_travel_distance, 1, wx.EXPAND, 0)
1187
+
1188
+ sizer_total_distance.Add(self.text_distance_total_step, 1, wx.EXPAND, 0)
1189
+ sizer_total_distance.Add(self.text_distance_total, 1, wx.EXPAND, 0)
1190
+ h_sizer_text_1.Add(sizer_total_distance, 1, wx.EXPAND, 0)
1191
+
1192
+ sizer_laser_time.Add(self.text_time_laser_step, 1, wx.EXPAND, 0)
1193
+ sizer_laser_time.Add(self.text_time_laser, 1, wx.EXPAND, 0)
1194
+ h_sizer_text_2.Add(sizer_laser_time, 1, wx.EXPAND, 0)
1195
+
1196
+ sizer_travel_time.Add(self.text_time_travel_step, 1, wx.EXPAND, 0)
1197
+ sizer_travel_time.Add(self.text_time_travel, 1, wx.EXPAND, 0)
1198
+ h_sizer_text_2.Add(sizer_travel_time, 1, wx.EXPAND, 0)
1199
+
1200
+ sizer_total_time.Add(self.text_time_total_step, 1, wx.EXPAND, 0)
1201
+ sizer_total_time.Add(self.text_time_total, 1, wx.EXPAND, 0)
1202
+ h_sizer_text_2.Add(sizer_total_time, 1, wx.EXPAND, 0)
1203
+
1204
+ sizer_extra_time.Add(self.text_time_extra_step, 1, wx.EXPAND, 0)
1205
+ sizer_extra_time.Add(self.text_time_extra, 1, wx.EXPAND, 0)
1206
+ h_sizer_text_2.Add(sizer_extra_time, 1, wx.EXPAND, 0)
1207
+
1208
+ h_sizer_buttons.Add(self.button_play, 0, 0, 0)
1209
+ sizer_speed_options.Add(self.slider_playbackspeed, 0, wx.EXPAND, 0)
1210
+
1211
+ label_playback_speed = wxStaticText(self, wx.ID_ANY, _("Playback Speed") + " ")
1212
+ sizer_pb_speed.Add(label_playback_speed, 2, wx.ALIGN_CENTER_VERTICAL, 0)
1213
+ sizer_pb_speed.Add(self.text_playback_speed, 1, wx.EXPAND, 0)
1214
+
1215
+ sizer_display = wx.BoxSizer(wx.HORIZONTAL)
1216
+ label_playback_mode = wxStaticText(self, wx.ID_ANY, _("Mode") + " ")
1217
+ sizer_display.Add(label_playback_mode, 1, wx.ALIGN_CENTER_VERTICAL, 0)
1218
+ # Make sure it has about textbox size, otherwise too narrow
1219
+ self.radio_cut.SetMinSize(dip_size(self, -1, 23))
1220
+ sizer_display.Add(self.radio_cut, 1, wx.ALIGN_CENTER_VERTICAL, 0)
1221
+ sizer_display.Add(self.radio_time_seconds, 1, wx.ALIGN_CENTER_VERTICAL, 0)
1222
+ sizer_display.Add(self.radio_time_minutes, 1, wx.ALIGN_CENTER_VERTICAL, 0)
1223
+ sizer_speed_options.Add(sizer_pb_speed, 0, wx.EXPAND, 0)
1224
+ sizer_speed_options.Add(sizer_display, 0, wx.EXPAND, 0)
1225
+ h_sizer_buttons.Add(sizer_speed_options, 1, wx.EXPAND, 0)
1226
+ # sizer_execute.Add(self.combo_device, 0, wx.EXPAND, 0)
1227
+ sizer_execute.Add(self.button_spool, 1, wx.EXPAND, 0)
1228
+ h_sizer_buttons.Add(sizer_execute, 1, wx.EXPAND, 0)
1229
+ v_sizer_main.Add(self.hscene_sizer, 1, wx.EXPAND, 0)
1230
+ v_sizer_main.Add(h_sizer_scroll, 0, wx.EXPAND, 0)
1231
+ v_sizer_main.Add(h_sizer_text_1, 0, wx.EXPAND, 0)
1232
+ v_sizer_main.Add(h_sizer_text_2, 0, wx.EXPAND, 0)
1233
+ v_sizer_main.Add(h_sizer_buttons, 0, wx.EXPAND, 0)
1234
+ self.SetSizer(v_sizer_main)
1235
+ self.slided_in = True # Hide initially
1236
+ self.Layout()
1237
+ # end wxGlade
1238
+
1239
+ def on_size(self, event):
1240
+ sz = event.GetSize()
1241
+ event.Skip()
1242
+ self.debug(f"Manually forwarding the size: {sz}")
1243
+ self.view_pane.SetSize(wx.Size(sz[0], int(2 / 3 * sz[1])))
1244
+ self.Layout()
1245
+ sz = self.view_pane.GetSize()
1246
+ self.debug(f"Now pane has: {sz}")
1247
+ self.fit_scene_to_panel()
1248
+
1249
+ # Manages the display / non-display of the optimisation-options
1250
+ @property
1251
+ def slided_in(self):
1252
+ return self._slided_in
1253
+
1254
+ @slided_in.setter
1255
+ def slided_in(self, newvalue):
1256
+ self._slided_in = newvalue
1257
+ try:
1258
+ if newvalue:
1259
+ # Slided in ->
1260
+ self.hscene_sizer.Show(sizer=self.voption_sizer, show=False, recursive=True)
1261
+ self.voption_sizer.Layout()
1262
+ self.btn_slide_options.SetLabel("<")
1263
+ else:
1264
+ # Slided out ->
1265
+ self.hscene_sizer.Show(sizer=self.voption_sizer, show=True, recursive=True)
1266
+ self.voption_sizer.Layout()
1267
+ self.btn_slide_options.SetLabel(">")
1268
+ self.hscene_sizer.Layout()
1269
+ self.Layout()
1270
+ except RuntimeError:
1271
+ return
1272
+
1273
+ def toggle_background(self, event):
1274
+ """
1275
+ Toggle the draw mode for the background
1276
+ """
1277
+ self.widget_scene.context.draw_mode ^= DRAW_MODE_BACKGROUND
1278
+ self.widget_scene.request_refresh()
1279
+
1280
+ def toggle_grid(self, gridtype):
1281
+ if gridtype == "primary":
1282
+ self.grid.draw_grid_primary = not self.grid.draw_grid_primary
1283
+ elif gridtype == "secondary":
1284
+ self.grid.draw_grid_secondary = not self.grid.draw_grid_secondary
1285
+ elif gridtype == "circular":
1286
+ self.grid.draw_grid_circular = not self.grid.draw_grid_circular
1287
+ elif gridtype == "offset":
1288
+ self.grid.draw_offset_lines = not self.grid.draw_offset_lines
1289
+ self.widget_scene.request_refresh()
1290
+
1291
+ def toggle_grid_p(self, event):
1292
+ self.toggle_grid("primary")
1293
+
1294
+ def toggle_grid_s(self, event):
1295
+ self.toggle_grid("secondary")
1296
+
1297
+ def toggle_grid_c(self, event):
1298
+ self.toggle_grid("circular")
1299
+
1300
+ def toggle_grid_o(self, event):
1301
+ self.toggle_grid("offset")
1302
+
1303
+ def toggle_travel_display(self, event):
1304
+ self.display_travel = not self.display_travel
1305
+ self.context.display_travel = self.display_travel
1306
+ self.sim_travel.display = self.display_travel
1307
+ self.widget_scene.request_refresh()
1308
+
1309
+ def toggle_raster_display(self, event):
1310
+ self.raster_as_image = not self.raster_as_image
1311
+ self.context.raster_as_image = self.raster_as_image
1312
+ self.sim_cutcode.raster_as_image = self.raster_as_image
1313
+ self.widget_scene.request_refresh()
1314
+
1315
+ def calc_laser_spot_width(self):
1316
+ if self.laserspot_display:
1317
+ spot_value = getattr(self.context.device, "laserspot", "0.3mm")
1318
+ try:
1319
+ scale = 0.5 * (self.context.device.view.native_scale_x + self.context.device.view.native_scale_y)
1320
+ spotwidth_in_scene = float(Length(spot_value))
1321
+ spot_width = spotwidth_in_scene / scale
1322
+ # print (f"Scale for device: {scale}, spot in scene: {spot_value} = {spotwidth_in_scene} -> {spot_width}")
1323
+ except ValueError:
1324
+ spot_width = None
1325
+ self.laserspot_width = spot_width
1326
+ else:
1327
+ self.laserspot_width = None
1328
+
1329
+ def toggle_laserspot(self, event):
1330
+ self.laserspot_display = not self.laserspot_display
1331
+ self.context.laserspot_display = self.laserspot_display
1332
+ self.calc_laser_spot_width()
1333
+ self.sim_cutcode.laserspot_width = self.laserspot_width
1334
+ self.widget_scene.request_refresh()
1335
+
1336
+ def remove_background(self, event):
1337
+ self.widget_scene._signal_widget(
1338
+ self.widget_scene.widget_root, "background", None
1339
+ )
1340
+ self.widget_scene.request_refresh()
1341
+
1342
+ def zoom_in(self):
1343
+ matrix = self.widget_scene.widget_root.matrix
1344
+ zoomfactor = 1.5 / 1.0
1345
+ matrix.post_scale(zoomfactor)
1346
+ self.widget_scene.request_refresh()
1347
+
1348
+ def zoom_out(self):
1349
+ matrix = self.widget_scene.widget_root.matrix
1350
+ zoomfactor = 1.0 / 1.5
1351
+ matrix.post_scale(zoomfactor)
1352
+ self.widget_scene.request_refresh()
1353
+
1354
+ def fit_scene_to_panel(self):
1355
+ bbox = self.context.device.view.source_bbox()
1356
+ winsize = self.view_pane.GetSize()
1357
+ if winsize[0] != 0 and winsize[1] != 0:
1358
+ self.widget_scene.widget_root.focus_viewport_scene(bbox, winsize, 0.1)
1359
+ self.widget_scene.request_refresh()
1360
+
1361
+ def set_cutcode_entry(self, cutcode):
1362
+ self.subpanel_cutcode.set_cutcode_entry(cutcode, self.plan_name)
1363
+
1364
+ def progress_to_idx(self, progress):
1365
+ residual = 0
1366
+ idx = progress
1367
+ if not self._playback_cuts:
1368
+ # progress is the time indicator
1369
+ idx = len(self.statistics) - 1
1370
+ prev_time = None
1371
+ while idx >= 0:
1372
+ item = self.statistics[idx]
1373
+ this_time = item["time_at_end_of_burn"]
1374
+ # print (f"{idx} {this_time} vs {progress} - {item}")
1375
+ if this_time <= progress:
1376
+ if prev_time is not None:
1377
+ # We compute a 0 to 1 ratio of the progress
1378
+ residual = (progress - this_time) / (prev_time - this_time)
1379
+ break
1380
+ prev_time = this_time
1381
+ idx -= 1
1382
+ idx += 1
1383
+ if idx == 0:
1384
+ item = self.statistics[idx]
1385
+ start_time = item["time_at_start"]
1386
+ this_time = item["time_at_end_of_burn"]
1387
+ residual = (progress - start_time) / (this_time - start_time)
1388
+
1389
+ if idx >= len(self.statistics):
1390
+ idx = len(self.statistics) - 1
1391
+ if idx < 0:
1392
+ idx = 0
1393
+ # print(
1394
+ # f"Cut-Mode={self._playback_cuts}, prog={progress}, idx={idx}, stats={len(self.statistics)}"
1395
+ # )
1396
+ return idx, residual
1397
+
1398
+ def on_mouse_right_down(self, event=None):
1399
+ def cut_before(event):
1400
+ step, residual = self.progress_to_idx(self.progress)
1401
+ self.context(f"plan{self.plan_name} sublist {step} -1\n")
1402
+
1403
+ def cut_after(event):
1404
+ step, residual = self.progress_to_idx(self.progress)
1405
+ self.context(f"plan{self.plan_name} sublist 0 {step}\n")
1406
+
1407
+ gui = self
1408
+ menu = wx.Menu()
1409
+ if self.radio_cut.GetValue():
1410
+ self.Bind(
1411
+ wx.EVT_MENU,
1412
+ cut_before,
1413
+ menu.Append(
1414
+ wx.ID_ANY,
1415
+ _("Delete cuts before"),
1416
+ _("Delete all cuts before the current position in Simulation"),
1417
+ ),
1418
+ )
1419
+ self.Bind(
1420
+ wx.EVT_MENU,
1421
+ cut_after,
1422
+ menu.Append(
1423
+ wx.ID_ANY,
1424
+ _("Delete cuts after"),
1425
+ _("Delete all cuts after the current position in Simulation"),
1426
+ ),
1427
+ )
1428
+ menu.AppendSeparator()
1429
+ id1 = menu.Append(
1430
+ wx.ID_ANY,
1431
+ _("Show Background"),
1432
+ _("Display the background picture in the Simulation pane"),
1433
+ wx.ITEM_CHECK,
1434
+ )
1435
+ self.Bind(wx.EVT_MENU, self.toggle_background, id=id1.GetId())
1436
+ menu.Check(
1437
+ id1.GetId(),
1438
+ (self.widget_scene.context.draw_mode & DRAW_MODE_BACKGROUND == 0),
1439
+ )
1440
+ id2 = menu.Append(
1441
+ wx.ID_ANY,
1442
+ _("Show Primary Grid"),
1443
+ _("Display the primary grid in the Simulation pane"),
1444
+ wx.ITEM_CHECK,
1445
+ )
1446
+ self.Bind(wx.EVT_MENU, self.toggle_grid_p, id=id2.GetId())
1447
+ menu.Check(id2.GetId(), self.grid.draw_grid_primary)
1448
+ id3 = menu.Append(
1449
+ wx.ID_ANY,
1450
+ _("Show Secondary Grid"),
1451
+ _("Display the secondary grid in the Simulation pane"),
1452
+ wx.ITEM_CHECK,
1453
+ )
1454
+ self.Bind(wx.EVT_MENU, self.toggle_grid_s, id=id3.GetId())
1455
+ menu.Check(id3.GetId(), self.grid.draw_grid_secondary)
1456
+ id4 = menu.Append(
1457
+ wx.ID_ANY,
1458
+ _("Show Circular Grid"),
1459
+ _("Display the circular grid in the Simulation pane"),
1460
+ wx.ITEM_CHECK,
1461
+ )
1462
+ self.Bind(wx.EVT_MENU, self.toggle_grid_c, id=id4.GetId())
1463
+ menu.Check(id4.GetId(), self.grid.draw_grid_circular)
1464
+ try:
1465
+ mx = float(Length(self.context.device.view.margin_x))
1466
+ my = float(Length(self.context.device.view.margin_y))
1467
+ except ValueError:
1468
+ mx = 0
1469
+ my = 0
1470
+ # print(self.context.device.view.margin_x, self.context.device.view.margin_y)
1471
+ if mx != 0.0 or my != 0.0:
1472
+ menu.AppendSeparator()
1473
+ id4b = menu.Append(
1474
+ wx.ID_ANY,
1475
+ _("Show physical dimensions"),
1476
+ _("Display the physical dimensions in the Simulation pane"),
1477
+ wx.ITEM_CHECK,
1478
+ )
1479
+ self.Bind(wx.EVT_MENU, self.toggle_grid_o, id=id4b.GetId())
1480
+ menu.Check(id4b.GetId(), self.grid.draw_offset_lines)
1481
+ if self.widget_scene.has_background:
1482
+ menu.AppendSeparator()
1483
+ id5 = menu.Append(wx.ID_ANY, _("Remove Background"), "")
1484
+ self.Bind(wx.EVT_MENU, self.remove_background, id=id5.GetId())
1485
+ menu.AppendSeparator()
1486
+ id6 = menu.Append(
1487
+ wx.ID_ANY,
1488
+ _("Show travel path"),
1489
+ _("Displays the laser travel when not burning"),
1490
+ wx.ITEM_CHECK,
1491
+ )
1492
+ self.Bind(wx.EVT_MENU, self.toggle_travel_display, id=id6.GetId())
1493
+ menu.Check(id6.GetId(), self.display_travel)
1494
+ id7 = menu.Append(
1495
+ wx.ID_ANY,
1496
+ _("Raster as Image"),
1497
+ _("Show picture as image / as all the lines needed"),
1498
+ wx.ITEM_CHECK,
1499
+ )
1500
+ self.Bind(wx.EVT_MENU, self.toggle_raster_display, id=id7.GetId())
1501
+ menu.Check(id7.GetId(), self.raster_as_image)
1502
+ id8 = menu.Append(
1503
+ wx.ID_ANY,
1504
+ _("Simulate laser width"),
1505
+ _("Show laser path as wide as laserspot width / as simple line"),
1506
+ wx.ITEM_CHECK,
1507
+ )
1508
+ self.Bind(wx.EVT_MENU, self.toggle_laserspot, id=id8.GetId())
1509
+ menu.Check(id8.GetId(), self.laserspot_display)
1510
+
1511
+ menu.AppendSeparator()
1512
+ self.Bind(
1513
+ wx.EVT_MENU,
1514
+ lambda e: self.zoom_out(),
1515
+ menu.Append(
1516
+ wx.ID_ANY,
1517
+ _("Zoom Out"),
1518
+ _("Make the scene smaller"),
1519
+ ),
1520
+ )
1521
+ self.Bind(
1522
+ wx.EVT_MENU,
1523
+ lambda e: self.zoom_in(),
1524
+ menu.Append(
1525
+ wx.ID_ANY,
1526
+ _("Zoom In"),
1527
+ _("Make the scene larger"),
1528
+ ),
1529
+ )
1530
+ self.Bind(
1531
+ wx.EVT_MENU,
1532
+ lambda e: self.fit_scene_to_panel(),
1533
+ menu.Append(
1534
+ wx.ID_ANY,
1535
+ _("Zoom to Bed"),
1536
+ _("View the whole laser bed"),
1537
+ ),
1538
+ )
1539
+
1540
+ if menu.MenuItemCount != 0:
1541
+ gui.PopupMenu(menu)
1542
+ menu.Destroy()
1543
+
1544
+ def _set_slider_dimensions(self):
1545
+ if self._playback_cuts:
1546
+ self.max = max(len(self.cutcode), 1)
1547
+ else:
1548
+ totalduration = 0
1549
+ maxidx = len(self.statistics)
1550
+ if maxidx > 0:
1551
+ totalduration = int(
1552
+ self.statistics[-1]["total_time_extra"]
1553
+ + self.statistics[-1]["total_time_travel"]
1554
+ + self.statistics[-1]["total_time_cut"]
1555
+ )
1556
+ self.max = max(totalduration, 1)
1557
+ self.progress = self.max
1558
+ self.slider_progress.SetMin(0)
1559
+ self.slider_progress.SetMax(self.max)
1560
+ self.slider_progress.SetValue(self.max)
1561
+ value = self.slider_playbackspeed.GetValue()
1562
+ value = int((10.0 ** (value // 90)) * (1.0 + float(value % 90) / 10.0))
1563
+ if self.radio_cut.GetValue():
1564
+ factor = 0.1 # steps
1565
+ else:
1566
+ factor = 1 # seconds
1567
+ self.interval = factor * 100.0 / float(value)
1568
+
1569
+ def _refresh_simulated_plan(self):
1570
+ self.debug(f"Refresh simulated: {perf_counter()-self.start_time}")
1571
+ # Stop animation
1572
+ if self.running:
1573
+ self._stop()
1574
+ return
1575
+ # Refresh cutcode
1576
+ if self.plan_name:
1577
+ self.cutplan = self.context.planner.get_or_make_plan(self.plan_name)
1578
+ else:
1579
+ self.cutplan = self.context.planner.default_plan
1580
+ self.plan_name = self.cutplan.name
1581
+ self.operations = self.cutplan.plan
1582
+ self.subpanel_cutcode.set_cutcode_entry(None, self.plan_name)
1583
+ self.subpanel_operations.set_cut_plan(self.cutplan)
1584
+ # for e in self.operations:
1585
+ # print(f"Refresh: {type(e).__name__} {e}")
1586
+ # try:
1587
+ # idx = 0
1588
+ # for n in e:
1589
+ # print(f"Entry {idx}#: {name_str(n)}")
1590
+ # idx += 1
1591
+ # except:
1592
+ # pass
1593
+
1594
+ self.cutcode = CutCode()
1595
+
1596
+ for c in self.operations:
1597
+ if isinstance(c, CutCode):
1598
+ self.cutcode.extend(c)
1599
+ self.cutcode = CutCode(self.cutcode.flat())
1600
+
1601
+ # self.reload_statistics()
1602
+
1603
+ # for idx, stat in enumerate(self.statistics):
1604
+ # print(f"#{idx}: {stat}")
1605
+ bb = self.cutplan._previous_bounds
1606
+ if bb is None or math.isinf(bb[0]):
1607
+ self.parent.SetTitle(_("Simulation"))
1608
+ else:
1609
+ wd = bb[2] - bb[0]
1610
+ ht = bb[3] - bb[1]
1611
+ sdimx = Length(
1612
+ wd, preferred_units=self.context.units_name, digits=2
1613
+ ).preferred_length
1614
+ sdimy = Length(
1615
+ ht, preferred_units=self.context.units_name, digits=2
1616
+ ).preferred_length
1617
+ self.parent.SetTitle(_("Simulation") + f" ({sdimx}x{sdimy})")
1618
+
1619
+ self.update_job.cancel()
1620
+ self.context.schedule(self.update_job)
1621
+
1622
+ self._startup()
1623
+ self.request_refresh()
1624
+
1625
+ @signal_listener("device;modified")
1626
+ @signal_listener("plan")
1627
+ def on_plan_change(self, origin, plan_name=None, status=None):
1628
+ def resend_signal():
1629
+ self.debug(f"Resending signal: {perf_counter()-self.start_time}")
1630
+ self.context.signal("plan", plan_name=self.plan_name, status=1)
1631
+
1632
+ winsize = self.view_pane.GetSize()
1633
+ winsize1 = self.hscene_sizer.GetSize()
1634
+ winsize2 = self.GetSize()
1635
+ self.debug(
1636
+ f"Plan called : {perf_counter()-self.start_time} (Pane: {winsize}, Sizer: {winsize1}, Window: {winsize2})"
1637
+ )
1638
+ if plan_name == self.plan_name:
1639
+ # This may come too early before all things have been done
1640
+ if (
1641
+ winsize[0] == 0 or winsize[1] == 0
1642
+ ) and self.retries > 3: # Still initialising
1643
+ self.Fit()
1644
+ self.hscene_sizer.Layout()
1645
+ self.view_pane.Show()
1646
+ interval = 0.25
1647
+ self.retries += 1
1648
+ self.debug(
1649
+ f"Need to resend signal due to invalid window-size, attempt {self.retries}/10, will wait for {interval:.2f} sec"
1650
+ )
1651
+
1652
+ _job = Job(
1653
+ process=resend_signal,
1654
+ job_name="resender",
1655
+ interval=interval,
1656
+ times=1,
1657
+ run_main=True,
1658
+ )
1659
+ self.context.schedule(_job)
1660
+ return
1661
+
1662
+ self.retries = 0
1663
+ self._refresh_simulated_plan()
1664
+
1665
+ @signal_listener("refresh_simulation")
1666
+ def on_request_refresh(self, origin, *args):
1667
+ self.widget_scene.request_refresh()
1668
+
1669
+ def on_radio_playback_mode(self, event):
1670
+ self._playback_cuts = self.radio_cut.GetValue()
1671
+ default = 0
1672
+ if self.radio_cut.GetValue():
1673
+ default = 0
1674
+ elif self.radio_time_seconds.GetValue():
1675
+ default = 1
1676
+ elif self.radio_time_minutes.GetValue():
1677
+ default = 2
1678
+ self.context.simulation_mode = default
1679
+ self._set_slider_dimensions()
1680
+
1681
+ def on_checkbox_optimize(self, event):
1682
+ if self.checkbox_optimize.GetValue():
1683
+ self.options_optimize.Enable(True)
1684
+ else:
1685
+ self.options_optimize.Enable(False)
1686
+
1687
+ def cache_updater(self):
1688
+ self.button_spool.Enable(False)
1689
+ msg = self.button_spool.GetLabel()
1690
+ self.button_spool.SetLabel(_("Calculating"))
1691
+ for cut in self.cutcode:
1692
+ if isinstance(cut, (RasterCut, PlotCut)):
1693
+ if hasattr(cut, "_plotcache") and cut._plotcache is not None:
1694
+ continue
1695
+ if isinstance(cut, RasterCut):
1696
+ cut._plotcache = list(cut.plot.plot())
1697
+ elif isinstance(cut, PlotCut):
1698
+ cut._plotcache = list(cut.plot)
1699
+ self.context.signal("refresh_scene", self.widget_scene.name)
1700
+ self.reload_statistics()
1701
+ try:
1702
+ self.button_spool.SetLabel(msg)
1703
+ self.button_spool.Enable(True)
1704
+ except RuntimeError:
1705
+ # No longer existing
1706
+ pass
1707
+
1708
+ def update_fields(self):
1709
+ def len_str(value):
1710
+ if abs(value) >= 1000000:
1711
+ result = f"{value / 1000000:.2f}km"
1712
+ elif abs(value) >= 1000:
1713
+ result = f"{value / 1000:.2f}m"
1714
+ else:
1715
+ result = f"{value:.0f}mm"
1716
+ return result
1717
+
1718
+ step, residual = self.progress_to_idx(self.progress)
1719
+ item = self.statistics[step - 1]
1720
+ partials = {
1721
+ "total_distance_travel": 0,
1722
+ "total_distance_cut": 0,
1723
+ "total_time_travel": 0,
1724
+ "total_internal_travel": 0,
1725
+ "total_time_cut": 0,
1726
+ "total_time_extra": 0,
1727
+ }
1728
+ if residual != 0 and step < len(self.statistics):
1729
+ itemnext = self.statistics[step]
1730
+ for entry in partials:
1731
+ partials[entry] = residual * (itemnext[entry] - item[entry])
1732
+
1733
+ ###################
1734
+ # UPDATE POSITIONAL
1735
+ ###################
1736
+
1737
+ mm = self.cutcode.settings.get("native_mm", 39.3701)
1738
+ # item = (i, distance_travel, distance_cut, extra, duration_travel, duration_cut)
1739
+ travel_mm = (
1740
+ item["total_distance_travel"] + partials["total_distance_travel"]
1741
+ ) / mm
1742
+ internal_mm = (
1743
+ item["total_internal_travel"] + partials["total_internal_travel"]
1744
+ ) / mm
1745
+ cuts_mm = (item["total_distance_cut"] + partials["total_distance_cut"]) / mm
1746
+ # travel_mm = self.cutcode.length_travel(stop_at=step) / mm
1747
+ # cuts_mm = self.cutcode.length_cut(stop_at=step) / mm
1748
+ info = len_str(travel_mm)
1749
+ if internal_mm != 0:
1750
+ info += f" ({len_str(internal_mm)})"
1751
+ self.text_distance_travel_step.SetValue(info)
1752
+ self.text_distance_laser_step.SetValue(len_str(cuts_mm))
1753
+ self.text_distance_total_step.SetValue(len_str(travel_mm + cuts_mm))
1754
+ try:
1755
+ time_travel = item["total_time_travel"] + partials["total_time_travel"]
1756
+ t_hours = int(time_travel // 3600)
1757
+ t_mins = int((time_travel % 3600) // 60)
1758
+ t_seconds = int(time_travel % 60)
1759
+ self.text_time_travel_step.SetValue(
1760
+ f"{int(t_hours)}:{int(t_mins):02d}:{int(t_seconds):02d}"
1761
+ )
1762
+ except ZeroDivisionError:
1763
+ time_travel = 0
1764
+ try:
1765
+ time_cuts = item["total_time_cut"] + partials["total_time_cut"]
1766
+ t_hours = int(time_cuts // 3600)
1767
+ t_mins = int((time_cuts % 3600) // 60)
1768
+ t_seconds = int(time_cuts % 60)
1769
+ self.text_time_laser_step.SetValue(
1770
+ f"{int(t_hours)}:{int(t_mins):02d}:{int(t_seconds):02d}"
1771
+ )
1772
+ except ZeroDivisionError:
1773
+ time_cuts = 0
1774
+ try:
1775
+ extra = item["total_time_extra"] + partials["total_time_extra"]
1776
+ t_hours = int(extra // 3600)
1777
+ t_mins = int((extra % 3600) // 60)
1778
+ t_seconds = int(extra % 60)
1779
+ self.text_time_extra_step.SetValue(
1780
+ f"{int(t_hours)}:{int(t_mins):02d}:{int(t_seconds):02d}"
1781
+ )
1782
+ if self._playback_cuts:
1783
+ time_total = time_travel + time_cuts + extra
1784
+ else:
1785
+ time_total = self.progress
1786
+ t_hours = int(time_total // 3600)
1787
+ t_mins = int((time_total % 3600) // 60)
1788
+ t_seconds = int(time_total % 60)
1789
+ self.text_time_total_step.SetValue(
1790
+ f"{int(t_hours)}:{int(t_mins):02d}:{int(t_seconds):02d}"
1791
+ )
1792
+ except ZeroDivisionError:
1793
+ pass
1794
+
1795
+ ###################
1796
+ # UPDATE TOTAL
1797
+ ###################
1798
+
1799
+ travel_mm = self.statistics[-1]["total_distance_travel"] / mm
1800
+ cuts_mm = self.statistics[-1]["total_distance_cut"] / mm
1801
+ self.text_distance_travel.SetValue(len_str(travel_mm))
1802
+ self.text_distance_laser.SetValue(len_str(cuts_mm))
1803
+ self.text_distance_total.SetValue(len_str(travel_mm + cuts_mm))
1804
+
1805
+ try:
1806
+ time_travel = self.statistics[-1]["total_time_travel"]
1807
+ t_hours = int(time_travel // 3600)
1808
+ t_mins = int((time_travel % 3600) // 60)
1809
+ t_seconds = int(time_travel % 60)
1810
+ self.text_time_travel.SetValue(f"{t_hours}:{t_mins:02d}:{t_seconds:02d}")
1811
+ except ZeroDivisionError:
1812
+ time_travel = 0
1813
+ try:
1814
+ time_cuts = self.statistics[-1]["total_time_cut"]
1815
+ t_hours = int(time_cuts // 3600)
1816
+ t_mins = int((time_cuts % 3600) // 60)
1817
+ t_seconds = int(time_cuts % 60)
1818
+ self.text_time_laser.SetValue(f"{t_hours}:{t_mins:02d}:{t_seconds:02d}")
1819
+ except ZeroDivisionError:
1820
+ time_cuts = 0
1821
+ try:
1822
+ extra = self.statistics[-1]["total_time_extra"]
1823
+ t_hours = int(extra // 3600)
1824
+ t_mins = int((extra % 3600) // 60)
1825
+ t_seconds = int(extra % 60)
1826
+ self.text_time_extra.SetValue(f"{t_hours}:{t_mins:02d}:{t_seconds:02d}")
1827
+ time_total = time_travel + time_cuts + extra
1828
+ t_hours = int(time_total // 3600)
1829
+ t_mins = int((time_total % 3600) // 60)
1830
+ t_seconds = int(time_total % 60)
1831
+ self.text_time_total.SetValue(f"{t_hours}:{t_mins:02d}:{t_seconds:02d}")
1832
+ except ZeroDivisionError:
1833
+ pass
1834
+
1835
+ def slide_out(self, event):
1836
+ self.slided_in = not self.slided_in
1837
+ event.Skip()
1838
+
1839
+ def on_redo_it(self, event):
1840
+ busy = self.context.kernel.busyinfo
1841
+ busy.start(msg=_("Preparing simulation..."))
1842
+
1843
+ plan = self.plan_name
1844
+ if self.checkbox_optimize.GetValue():
1845
+ opt = " preopt optimize"
1846
+ self.context.planner.do_optimization = True
1847
+ else:
1848
+ opt = ""
1849
+ self.context.planner.do_optimization = False
1850
+ self.context.signal("optimize", self.context.planner.do_optimization)
1851
+ self.context(
1852
+ f"plan{plan} clear\nplan{plan} copy preprocess validate blob{opt}\n"
1853
+ )
1854
+ busy.end()
1855
+ self._refresh_simulated_plan()
1856
+
1857
+ def pane_show(self):
1858
+ self.Layout()
1859
+ self.context.setting(str, "units_name", "mm")
1860
+
1861
+ bbox = self.context.device.view.source_bbox()
1862
+ self.widget_scene.widget_root.focus_viewport_scene(
1863
+ bbox, self.view_pane.Size, 0.1
1864
+ )
1865
+ self.update_fields()
1866
+ # self.panel_optimize.pane_show()
1867
+ self.panel_optimize.Show()
1868
+
1869
+ def pane_hide(self):
1870
+ if self.auto_clear:
1871
+ self.context(f"plan{self.plan_name} clear\n")
1872
+ self.context.close("SimScene")
1873
+ self.context.unschedule(self)
1874
+ self.running = False
1875
+ # self.panel_optimize.pane_hide()
1876
+ try:
1877
+ self.panel_optimize.Hide()
1878
+ except RuntimeError:
1879
+ pass
1880
+
1881
+ @signal_listener("refresh_scene")
1882
+ def on_refresh_scene(self, origin, scene_name=None, *args):
1883
+ """
1884
+ Called by 'refresh_scene' change. To refresh tree.
1885
+ @param origin: the path of the originating signal
1886
+ @param scene_name: Scene to refresh on if matching
1887
+ @param args:
1888
+ @return:
1889
+ """
1890
+ if scene_name == "SimScene":
1891
+ self.request_refresh()
1892
+
1893
+ def request_refresh(self, *args):
1894
+ self.widget_scene.request_refresh(*args)
1895
+
1896
+ def on_slider_progress(self, event=None): # wxGlade: Simulation.<event_handler>
1897
+ self.progress = min(self.slider_progress.GetValue(), self.max)
1898
+ self.update_fields()
1899
+ self.context.signal("refresh_scene", self.widget_scene.name)
1900
+
1901
+ def _start(self):
1902
+ self.button_play.SetBitmap(
1903
+ icons8_pause.GetBitmap(resize=get_default_icon_size(self.context))
1904
+ )
1905
+ self.button_play.SetToolTip(_("Stop the simulation replay"))
1906
+ self.context.schedule(self)
1907
+ self.running = True
1908
+
1909
+ def _stop(self):
1910
+ self.button_play.SetBitmap(
1911
+ icons8_circled_play.GetBitmap(resize=get_default_icon_size(self.context))
1912
+ )
1913
+ self.button_play.SetToolTip(_("Start the simulation replay"))
1914
+ self.context.unschedule(self)
1915
+ self.running = False
1916
+
1917
+ def on_button_play(self, event=None): # wxGlade: Simulation.<event_handler>
1918
+ if self.running:
1919
+ self._stop()
1920
+ return
1921
+ if self.progress >= self.max:
1922
+ self.progress = 0
1923
+ self.slider_progress.SetValue(self.progress)
1924
+ self.update_fields()
1925
+ self._start()
1926
+
1927
+ def animate_sim(self, event=None):
1928
+ if self.radio_time_minutes.GetValue():
1929
+ self.progress += 60
1930
+ else:
1931
+ self.progress += 1
1932
+ if self.progress >= self.max:
1933
+ self.progress = self.max
1934
+ self.slider_progress.SetValue(self.progress)
1935
+ self._stop()
1936
+ else:
1937
+ self.slider_progress.SetValue(self.progress)
1938
+ self.update_fields()
1939
+ self.context.signal("refresh_scene", self.widget_scene.name)
1940
+
1941
+ def on_slider_playback(self, event=None): # wxGlade: Simulation.<event_handler>
1942
+ # Slider is now pseudo logarithmic in scale varying from 1% to 5,000%.
1943
+
1944
+ value = self.slider_playbackspeed.GetValue()
1945
+ value = int((10.0 ** (value // 90)) * (1.0 + float(value % 90) / 10.0))
1946
+ if self.radio_cut.GetValue():
1947
+ factor = 0.1 # steps
1948
+ else:
1949
+ factor = 1 # seconds
1950
+ self.interval = factor * 100.0 / float(value)
1951
+
1952
+ self.text_playback_speed.SetValue(f"{value}%")
1953
+
1954
+ def on_button_spool(self, event=None): # wxGlade: Simulation.<event_handler>
1955
+ self.context(f"plan{self.plan_name} spool\n")
1956
+ self.context("window close Simulation\n")
1957
+ if self.context.auto_spooler:
1958
+ self.context("window open JobSpooler\n")
1959
+
1960
+
1961
+ class SimulationWidget(Widget):
1962
+ """
1963
+ The simulation widget is responsible for rendering the cutcode to the scene. This should be
1964
+ done such that both progress of 0 and 1 render nothing and items begin to draw at 2.
1965
+ """
1966
+
1967
+ def __init__(self, scene, sim):
1968
+ Widget.__init__(self, scene, all=False)
1969
+ self.renderer = LaserRender(self.scene.context)
1970
+ self.sim = sim
1971
+ self.matrix.post_cat(~scene.context.device.view.matrix)
1972
+ self.last_msg = None
1973
+ self.raster_as_image = True
1974
+ self.laserspot_width = None # 1 Pixel
1975
+
1976
+ def process_draw(self, gc: wx.GraphicsContext):
1977
+ if self.sim.progress < 0:
1978
+ return
1979
+ spot_width = self.laserspot_width
1980
+ residual = 0
1981
+ idx = 0
1982
+ if self.sim.progress < self.sim.max:
1983
+ idx, residual = self.sim.progress_to_idx(self.sim.progress)
1984
+ # print(f"SimWidget, idx={idx}, residual={residual:.3f}")
1985
+ sim_cut = self.sim.cutcode[:idx]
1986
+ else:
1987
+ sim_cut = self.sim.cutcode
1988
+ self.renderer.draw_cutcode(sim_cut, gc, 0, 0, self.raster_as_image, laserspot_width=spot_width)
1989
+ if residual <= 0:
1990
+ return
1991
+ # We draw interpolated lines to acknowledge we are in the middle of a cut operation
1992
+ starts = []
1993
+ ends = []
1994
+ cutstart = wx.Point2D(*self.sim.cutcode[idx].start)
1995
+ cutend = wx.Point2D(*self.sim.cutcode[idx].end)
1996
+ if self.sim.statistics[idx]["type"] == "RasterCut":
1997
+ if self.raster_as_image:
1998
+ # Rastercut object.
1999
+ x = 0
2000
+ y = 0
2001
+ cut = self.sim.cutcode[idx]
2002
+ image = cut.image
2003
+ gc.PushState()
2004
+ matrix = Matrix.scale(cut.step_x, cut.step_y)
2005
+ matrix.post_translate(cut.offset_x + x, cut.offset_y + y) # Adjust image xy
2006
+ gc.ConcatTransform(wx.GraphicsContext.CreateMatrix(gc, ZMatrix(matrix)))
2007
+ try:
2008
+ cache = cut._cache
2009
+ cache_id = cut._cache_id
2010
+ except AttributeError:
2011
+ cache = None
2012
+ cache_id = -1
2013
+ if cache_id != id(image):
2014
+ # Cached image is invalid.
2015
+ cache = None
2016
+ if cache is None:
2017
+ # No valid cache. Generate.
2018
+ cut._cache_width, cut._cache_height = image.size
2019
+ try:
2020
+ cut._cache = self.renderer.make_thumbnail(image, maximum=5000)
2021
+ except (MemoryError, RuntimeError):
2022
+ cut._cache = None
2023
+ cut._cache_id = id(image)
2024
+ # Set draw - constraint
2025
+ if cut.horizontal:
2026
+ if cut.start_minimum_y:
2027
+ # mode = "T2B"
2028
+ clip_w = cut._cache_width
2029
+ clip_h = int(residual * cut._cache_height)
2030
+ clip_x = 0
2031
+ clip_y = 0
2032
+ else:
2033
+ # mode = "B2T"
2034
+ clip_w = cut._cache_width
2035
+ clip_h = int(residual * cut._cache_height)
2036
+ clip_x = 0
2037
+ clip_y = cut._cache_height - clip_h
2038
+ else:
2039
+ if cut.start_minimum_x:
2040
+ # mode = "L2R"
2041
+ clip_w = int(residual * cut._cache_width)
2042
+ clip_h = cut._cache_height
2043
+ clip_x = 0
2044
+ clip_y = 0
2045
+ else:
2046
+ # mode = "R2L"
2047
+ clip_w = int(residual * cut._cache_width)
2048
+ clip_h = cut._cache_height
2049
+ clip_x = cut._cache_width - clip_w
2050
+ clip_y = 0
2051
+
2052
+ # msg = f"Mode: {mode}, Horiz: {cut.horizontal}, from left: {cut.start_on_left}, from top: {cut.start_on_top}"
2053
+ # if msg != self.last_msg:
2054
+ # print (msg)
2055
+ # self.last_msg = msg
2056
+ gc.Clip(clip_x, clip_y, clip_w, clip_h)
2057
+ if cut._cache is not None:
2058
+ # Cache exists and is valid.
2059
+ gc.DrawBitmap(cut._cache, 0, 0, cut._cache_width, cut._cache_height)
2060
+ # gc.SetBrush(wx.RED_BRUSH)
2061
+ # gc.DrawRectangle(0, 0, cut._cache_width, cut._cache_height)
2062
+ else:
2063
+ # Image was too large to cache, draw a red rectangle instead.
2064
+ gc.SetBrush(wx.RED_BRUSH)
2065
+ gc.DrawRectangle(0, 0, cut._cache_width, cut._cache_height)
2066
+ gc.DrawBitmap(
2067
+ icons8_image.GetBitmap(),
2068
+ 0,
2069
+ 0,
2070
+ cut._cache_width,
2071
+ cut._cache_height,
2072
+ )
2073
+ gc.ResetClip()
2074
+ gc.PopState()
2075
+ else:
2076
+ # We draw the cutcode up to a certain percentage
2077
+ simcut = (self.sim.cutcode[idx], )
2078
+ self.renderer.draw_cutcode(simcut, gc, 0, 0, self.raster_as_image, residual=residual, laserspot_width=spot_width)
2079
+
2080
+ return
2081
+ # # We draw a rectangle covering the raster area
2082
+ # spath = str(self.sim.cutcode[idx].path)
2083
+ # sparse = re.compile(" ([0-9,\.]*) ")
2084
+ # min_x = None
2085
+ # max_x = None
2086
+ # path_width = 0
2087
+ # for numpair in sparse.findall(spath):
2088
+ # comma_idx = numpair.find(",")
2089
+ # if comma_idx >= 0:
2090
+ # left_num = numpair[:comma_idx]
2091
+ # right_num = numpair[comma_idx + 1 :]
2092
+ # # print (f"'{numpair}' -> '{left_num}', '{right_num}'")
2093
+ # try:
2094
+ # c_x = float(left_num)
2095
+ # c_y = float(right_num)
2096
+ # if min_x is None:
2097
+ # min_x = c_x
2098
+ # max_x = c_x
2099
+ # else:
2100
+ # if c_x < min_x:
2101
+ # min_x = c_x
2102
+ # if c_x > max_x:
2103
+ # max_x = c_x
2104
+ # path_width = max_x - min_x
2105
+ # except ValueError:
2106
+ # pass
2107
+ # print(f"path={self.sim.cutcode[idx].path}")
2108
+ # print(f"Raster: ({cutstart[0]}, {cutstart[1]}) - ({cutend[0]}, {cutend[1]})")
2109
+ # print(f"w={abs(cutend[0] - cutstart[0])}, w-cutop = {2*self.sim.cutcode[idx].width}, w_path={path_width}")
2110
+ # c_vars = vars(self.sim.cutcode[idx])
2111
+ # for cv in c_vars:
2112
+ # print(f"{cv}={c_vars[cv]}")
2113
+ # rect_y = cutstart[1]
2114
+ # rect_x = self.sim.cutcode[idx].offset_x
2115
+ # rect_w = max(2 * self.sim.cutcode[idx].width, path_width)
2116
+ # rect_h = residual * (cutend[1] - cutstart[1])
2117
+ # interim_pen = wx.Pen(wx.GREEN, 1, wx.PENSTYLE_SOLID)
2118
+ # gc.SetPen(interim_pen)
2119
+ # gc.DrawRectangle(rect_x, rect_y, rect_w, rect_h)
2120
+ end = wx.Point2D(
2121
+ cutstart[0] + residual * (cutend[0] - cutstart[0]),
2122
+ cutstart[1] + residual * (cutend[1] - cutstart[1]),
2123
+ )
2124
+ starts.append(cutstart)
2125
+ ends.append(end)
2126
+ interim_pen = wx.Pen(wx.GREEN, 1, wx.PENSTYLE_SOLID)
2127
+ gc.SetPen(interim_pen)
2128
+ gc.StrokeLineSegments(starts, ends)
2129
+
2130
+
2131
+ class SimulationTravelWidget(Widget):
2132
+ """
2133
+ The simulation Travel Widget is responsible for the background of dotted lines and arrows
2134
+ within the simulation scene.
2135
+ """
2136
+
2137
+ def __init__(self, scene, sim):
2138
+ Widget.__init__(self, scene, all=False)
2139
+ self.sim_matrix = ~scene.context.device.view.matrix
2140
+ self.sim = sim
2141
+ self.matrix.post_cat(~scene.context.device.view.matrix)
2142
+ self.display = True
2143
+ self.initvars()
2144
+
2145
+ def initvars(self):
2146
+ self.starts = list()
2147
+ self.ends = list()
2148
+ self.pos = list()
2149
+ self.starts.append(wx.Point2D(0, 0))
2150
+ self.ends.append(wx.Point2D(0, 0))
2151
+ prev = None
2152
+ for i, curr in enumerate(list(self.sim.cutcode)):
2153
+ if prev is not None:
2154
+ if prev.end != curr.start:
2155
+ # This is a travel
2156
+ start = wx.Point2D(*prev.end)
2157
+ end = wx.Point2D(*curr.start)
2158
+ self.starts.append(start)
2159
+ self.ends.append(end)
2160
+ # print (f"Travel found at idx {i}, {start}->{end}")
2161
+ s = complex(start[0], start[1])
2162
+ e = complex(end[0], end[1])
2163
+ d = abs(s - e)
2164
+ if d >= 127:
2165
+ for p in [0.75]:
2166
+ m = p * (e - s) + s
2167
+ ang = math.atan2((s - e).imag, (s - e).real)
2168
+ # arrow_size = d / 10.0
2169
+ arrow_size = 50
2170
+ m0 = m + complex(
2171
+ math.cos(ang + math.tau / 10) * arrow_size,
2172
+ math.sin(ang + math.tau / 10) * arrow_size,
2173
+ )
2174
+ m1 = m + complex(
2175
+ math.cos(ang - math.tau / 10) * arrow_size,
2176
+ math.sin(ang - math.tau / 10) * arrow_size,
2177
+ )
2178
+ m = wx.Point2D(m.real, m.imag)
2179
+ self.starts.append(m)
2180
+ self.ends.append(wx.Point2D(m0.real, m0.imag))
2181
+ self.starts.append(m)
2182
+ self.ends.append(wx.Point2D(m1.real, m1.imag))
2183
+ else:
2184
+ end = wx.Point2D(*curr.start)
2185
+ self.starts = list()
2186
+ self.ends = list()
2187
+ self.starts.append(wx.Point2D(0, 0))
2188
+ self.ends.append(end)
2189
+ self.pos.append(len(self.starts))
2190
+ prev = curr
2191
+
2192
+ def process_draw(self, gc: wx.GraphicsContext):
2193
+ if not self.display:
2194
+ return
2195
+ if not len(self.pos):
2196
+ return
2197
+ residual = 0
2198
+ idx = 0
2199
+ if self.sim.progress < self.sim.max:
2200
+ idx, residual = self.sim.progress_to_idx(self.sim.progress)
2201
+ pos = self.pos[idx]
2202
+ # print(f"TravelWidget, idx={idx}, residual={residual:.3f}, pos={pos}")
2203
+ else:
2204
+ pos = self.pos[-1]
2205
+ if pos < 0:
2206
+ return
2207
+ gcscale = get_gc_scale(gc)
2208
+ if gcscale == 0:
2209
+ gcscale = 1
2210
+ linewidth = 1 / gcscale
2211
+
2212
+ starts = self.starts[:pos]
2213
+ ends = self.ends[:pos]
2214
+ if residual > 0 and idx > 0:
2215
+ p1 = self.sim.cutcode[idx - 1].end
2216
+ p2 = self.sim.cutcode[idx - 1].start
2217
+ # progress = time
2218
+ t1 = self.sim.statistics[idx - 1]
2219
+ t2 = self.sim.statistics[idx]
2220
+ end_time = t1["time_at_end_of_travel"]
2221
+ # Time after travel.
2222
+ new_time = t2["time_at_end_of_travel"]
2223
+ if t1["total_time_travel"] != t2["total_time_travel"]: # Travel time
2224
+ fact = (min(self.sim.progress, new_time) - end_time) / (
2225
+ new_time - end_time
2226
+ )
2227
+ newstart = wx.Point2D(p1[0], p1[1])
2228
+ newend = wx.Point2D(
2229
+ p1[0] + fact * (p2[0] - p1[0]),
2230
+ p1[1] + fact * (p2[1] - p1[1]),
2231
+ )
2232
+ mystarts = list()
2233
+ myends = list()
2234
+ mystarts.append(newstart)
2235
+ myends.append(newend)
2236
+ interim_pen = wx.Pen(wx.GREEN, 1, wx.PENSTYLE_DOT)
2237
+ try:
2238
+ interim_pen.SetWidth(linewidth)
2239
+ except TypeError:
2240
+ interim_pen.SetWidth(int(linewidth))
2241
+ gc.SetPen(interim_pen)
2242
+ gc.StrokeLineSegments(mystarts, myends)
2243
+ mypen = wx.Pen(wx.BLACK, 1, wx.PENSTYLE_LONG_DASH)
2244
+ try:
2245
+ mypen.SetWidth(linewidth)
2246
+ except TypeError:
2247
+ mypen.SetWidth(int(linewidth))
2248
+ gc.SetPen(mypen)
2249
+ gc.StrokeLineSegments(starts, ends)
2250
+ # for idx, pt_start in enumerate(starts):
2251
+ # pt_end = ends[idx]
2252
+ # print (f"#{idx}: ({pt_start[0]:.0f}, {pt_start[1]:.0f}) - ({pt_end[0]:.0f}, {pt_end[1]:.0f})")
2253
+ # starts = list()
2254
+ # ends = list()
2255
+ # starts.append(wx.Point2D(0, 0))
2256
+ # ends.append(wx.Point2D(10000, 10000))
2257
+ # starts.append(wx.Point2D(0, 10000))
2258
+ # ends.append(wx.Point2D(10000, 0))
2259
+ # gc.SetPen(wx.CYAN_PEN)
2260
+ # gc.StrokeLineSegments(starts, ends)
2261
+
2262
+
2263
+ class SimReticleWidget(Widget):
2264
+ """
2265
+ The simulation Reticle widget is responsible for rendering the three green circles.
2266
+ The position at 0 should be 0,0. At 1 the start position. And at all other positions
2267
+ the end of the current cut object.
2268
+ """
2269
+
2270
+ def __init__(self, scene, sim):
2271
+ Widget.__init__(self, scene, all=False)
2272
+ self.sim_matrix = ~scene.context.device.view.matrix
2273
+ self.sim = sim
2274
+
2275
+ def process_draw(self, gc):
2276
+ x = 0
2277
+ y = 0
2278
+ if (
2279
+ # self.sim.progress > 0 and
2280
+ self.sim.cutcode is not None
2281
+ and len(self.sim.cutcode)
2282
+ ):
2283
+ idx, residual = self.sim.progress_to_idx(self.sim.progress)
2284
+ dx = 0
2285
+ dy = 0
2286
+ if self.sim.progress != self.sim.max:
2287
+ if idx > 0:
2288
+ pos = self.sim.cutcode[idx - 1].end
2289
+ else:
2290
+ pos = self.sim.cutcode[idx].start
2291
+ if residual > 0:
2292
+ # We could still be traversing or already burning...
2293
+ # We have two time stamps one after travel,
2294
+ # one after burn
2295
+ item = self.sim.statistics[idx]
2296
+ # print(
2297
+ # f"Time stamp: {self.sim.progress}, "
2298
+ # + f"at start: {item['time_at_start']}, "
2299
+ # + f"after travel: {item['time_at_end_of_travel']}, "
2300
+ # + f"after burn: {item['time_at_end_of_burn']}"
2301
+ # )
2302
+ if self.sim.progress < item["time_at_end_of_travel"]:
2303
+ # All travel done...
2304
+ fraction = (self.sim.progress - item["time_at_start"]) / (
2305
+ item["time_at_end_of_travel"] - item["time_at_start"]
2306
+ )
2307
+ pos = self.sim.cutcode[idx - 1].end
2308
+ npos = self.sim.cutcode[idx].start
2309
+ else:
2310
+ # Still travelling, duration
2311
+ fraction = (
2312
+ self.sim.progress - item["time_at_end_of_travel"]
2313
+ ) / (
2314
+ item["time_at_end_of_burn"] - item["time_at_end_of_travel"]
2315
+ )
2316
+ pos = self.sim.cutcode[idx].start
2317
+ npos = self.sim.cutcode[idx].end
2318
+
2319
+ dx = fraction * (npos[0] - pos[0])
2320
+ dy = fraction * (npos[1] - pos[1])
2321
+ else:
2322
+ pos = self.sim.cutcode[idx].end
2323
+ x = pos[0] + dx
2324
+ y = pos[1] + dy
2325
+ x, y = self.sim_matrix.point_in_matrix_space((x, y))
2326
+
2327
+ try:
2328
+ # Draw Reticle
2329
+ gc.SetPen(wx.Pen(wx.Colour(0, 255, 0, alpha=127)))
2330
+ gc.SetBrush(wx.TRANSPARENT_BRUSH)
2331
+ x, y = self.scene.convert_scene_to_window([x, y])
2332
+ gc.DrawEllipse(x - 5, y - 5, 10, 10)
2333
+ gc.DrawEllipse(x - 10, y - 10, 20, 20)
2334
+ gc.DrawEllipse(x - 20, y - 20, 40, 40)
2335
+ except AttributeError:
2336
+ pass
2337
+
2338
+
2339
+ class Simulation(MWindow):
2340
+ def __init__(self, *args, **kwds):
2341
+ super().__init__(706, 755, *args, **kwds)
2342
+ # We do this very early to allow resizing events to do their thing...
2343
+ self.restore_aspect(honor_initial_values=True)
2344
+ if len(args) > 3:
2345
+ plan_name = args[3]
2346
+ else:
2347
+ plan_name = None
2348
+ if len(args) > 4:
2349
+ auto_clear = bool(int(args[4]))
2350
+ else:
2351
+ auto_clear = True
2352
+ if len(args) > 5:
2353
+ optimise = bool(int(args[5]))
2354
+ else:
2355
+ optimise = True
2356
+
2357
+ self.panel = SimulationPanel(
2358
+ self,
2359
+ wx.ID_ANY,
2360
+ context=self.context,
2361
+ plan_name=plan_name,
2362
+ auto_clear=auto_clear,
2363
+ optimise_at_start=optimise,
2364
+ )
2365
+ self.sizer.Add(self.panel, 1, wx.EXPAND, 0)
2366
+ _icon = wx.NullIcon
2367
+ _icon.CopyFromBitmap(icons8_laser_beam_hazard.GetBitmap())
2368
+ self.SetIcon(_icon)
2369
+ self.SetTitle(_("Simulation"))
2370
+ self.Layout()
2371
+
2372
+ @staticmethod
2373
+ def sub_register(kernel):
2374
+ def handler(opt):
2375
+ optpart = " preopt optimize" if opt else ""
2376
+
2377
+ busy = kernel.busyinfo
2378
+ busy.change(msg=_("Preparing simulation..."))
2379
+ busy.start()
2380
+
2381
+ kernel.console(
2382
+ f"planz copy preprocess validate blob{optpart}\nwindow toggle Simulation z\n"
2383
+ )
2384
+ busy.end()
2385
+
2386
+ def open_simulator(*args):
2387
+ opt = kernel.planner.do_optimization
2388
+ handler(opt)
2389
+
2390
+ def open_simulator_simple(*args):
2391
+ handler(False)
2392
+
2393
+ kernel.register(
2394
+ "button/jobstart/Simulation",
2395
+ {
2396
+ "label": _("Simulate"),
2397
+ "icon": icons8_laser_beam_hazard,
2398
+ "tip": _("Simulate the current laser job") + "\n" + _("(Right click: no optimisation)"),
2399
+ "action": open_simulator,
2400
+ "action_right": open_simulator_simple,
2401
+ "rule_enabled": lambda cond: kernel.elements.have_burnable_elements(),
2402
+ "size": STD_ICON_SIZE,
2403
+ "priority": 1,
2404
+ },
2405
+ )
2406
+
2407
+ def window_open(self):
2408
+ self.panel.pane_show()
2409
+
2410
+ def window_close(self):
2411
+ self.panel.pane_hide()
2412
+
2413
+ def delegates(self):
2414
+ yield self.panel
2415
+
2416
+ @signal_listener("background")
2417
+ def on_background_signal(self, origin, background):
2418
+ if background is not None:
2419
+ background = wx.Bitmap.FromBuffer(*background)
2420
+ self.panel.widget_scene._signal_widget(
2421
+ self.panel.widget_scene.widget_root, "background", background
2422
+ )
2423
+ self.panel.widget_scene.request_refresh()
2424
+
2425
+ @staticmethod
2426
+ def submenu():
2427
+ return "Burning", "Simulation"
2428
+
2429
+ @staticmethod
2430
+ def helptext():
2431
+ return _("Display the job simulation window to see what will happen...")