├── .gitignore
├── LICENSE.txt
├── README.rst
├── hornwitser
└── factorio_tools
│ ├── __init__.py
│ ├── __main__.py
│ ├── desync.py
│ ├── disown.py
│ ├── multi.py
│ ├── parse.py
│ └── ping.py
├── pyproject.toml
└── setup.cfg
/.gitignore:
--------------------------------------------------------------------------------
1 | # Python build and cache files
2 | /build/
3 | /dist/
4 | *.egg-info/
5 | __pycache__/
6 |
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.rst:
--------------------------------------------------------------------------------
1 | Factorio Tools
2 | ==============
3 |
4 | A collection of command-line tools for debugging and inspecting Factorio
5 | related things, written in Python.
6 |
7 |
8 | Installation
9 | ------------
10 |
11 | Factorio Tools is available on PyPi, you can install/update it using the
12 | ``pip`` module with the following command.
13 |
14 | .. code ::
15 |
16 | > py -m pip install --user --upgrade hornwitser.factorio_tools
17 |
18 | .. note ::
19 |
20 | Python 3.7 or higher is required to install and run this package.
21 |
22 | desync tool
23 | -----------
24 |
25 | Automatically parse and diff Factorio desync reports, takes a single
26 | parameter ``path`` to the desync report to analyze. If the report is in
27 | a .zip file it will be exacted first. For example:
28 |
29 | .. code ::
30 |
31 | > py -m hornwitser.factorio_tools desync desync-report-2020-07-01_10-00-00.zip
32 |
33 | The output shows differences found in the script.dat, level-heuristics
34 | and level_with_tags files between the reference and desynced level
35 | contained in the desync report.
36 |
37 | This tool is rather slow and may take a long time to run.
38 |
39 |
40 | dat2json tool
41 | -------------
42 |
43 | Decode some of Factorio's .dat files into pretty formatted JSON. The
44 | decoding is a work in progress and the meaning of fields ending with an
45 | underscore is not know. For example:
46 |
47 | .. code ::
48 |
49 | > py -m hornwitser.factorio_tools dat2json -i script.dat -o script.json
50 |
51 | Takes 3 options, ``--input`` for setting the input .dat file,
52 | ``--output`` for setting the output file, both of which accept ``-`` for
53 | stdin/stdout (the default), and ``--input-format`` which is needed in
54 | case the format can not be deduced from name of the file. The format
55 | should be the name Factorio gives the .dat file without the .dat suffix.
56 |
57 | Currently acheivements, mod-dettings and script data can be decoded
58 | using this tool.
59 |
60 |
61 | ping tool
62 | ---------
63 |
64 | Ping Factorio servers via UDP. Takes a hostname and an optional port
65 | and sends Ping messages to the given address and listens for PingReply
66 | responses. For example:
67 |
68 | .. code ::
69 |
70 | > py -m hornwitser.factorio_tools ping example.com --count 4
71 | PingReply from 203.0.113.51:34197: seq=0 time=43.0102ms
72 | PingReply from 203.0.113.51:34197: seq=1 time=42.6973ms
73 | PingReply from 203.0.113.51:34197: seq=2 time=42.6778ms
74 | PingReply from 203.0.113.51:34197: seq=3 time=42.6496ms
75 |
76 | --- example.com:34197 ping statistics ---
77 | 4 packets sent, 4 received, 0.0% loss, time 3537.53ms
78 | rtt min/avg/max/mdev 42.65/42.76/43.01/0.15
79 |
80 | Will keep pinging until interrupted by Ctrl+C if ``--count`` is not
81 | provided. The ``--punch`` option will relay a Nat punch requests
82 | through the Factorio matchmaking servers in order to attempt to traverse
83 | through Nat and/or firewalls. See ``--help`` for all options.
84 |
85 |
86 | multi tool
87 | ----------
88 |
89 | .. note :: This tool is only available on Windows.
90 |
91 | Automate spawning, arranging, and interacting with many Factorio clients
92 | at the same time. It works by arranging the client windows on a grid
93 | using the Windows API, and has a mode that clicks a specific location
94 | in every Factorio window on the desktop. To make it work you'll have to
95 | do the following steps:
96 |
97 | 1. Open a command propmt and navigate/create a new directory to store
98 | the write directories for all of the client instances. If you place
99 | this new directory inside the Factorio installation directory then
100 | the Factorio executable will be auto detected, otherwise you will
101 | need to pass it with the ``--factorio`` when spawning instances or
102 | by setting the FACTORIO environment variable to the path to the exe.
103 |
104 | 2. Generate a base write dir for the instances to be based on.
105 |
106 | .. code ::
107 |
108 | > py -m hornwitser.factorio_tools multi generate-base
109 |
110 | This creates a new directory named base by default (can be changed
111 | with the ``--base`` option.)
112 |
113 | 3. Start the base instance
114 |
115 | .. code ::
116 |
117 | > py -m hornwitser.factorio_tools multi spawn
118 |
119 | This should launch Factorio in windowed mode with music and updates
120 | disabled. You should consider changing the following settings in
121 | order to make the management of the instances less annoying and use
122 | less resources:
123 |
124 | - Disable minimap.
125 | - Disable show tips and tricks.
126 | - Disable show tutorial notifications.
127 | - Disable play sound for chat messages.
128 | - Disable entity tooltip on the side.
129 | - Set shortcut bar rows and active quickbars to 1.
130 | - Set a player name.
131 | - Disable all show ... graphics settings.
132 | - Set sprite resoultion to normal.
133 | - Disable high quality animations.
134 | - Set Video memory usage to low.
135 | - Set Texture compression to low quality.
136 | - Disable full color depth.
137 |
138 | After making the setting changes exit Factorio.
139 |
140 | 4. Generate instance write directories.
141 |
142 | .. code ::
143 |
144 | > py -m hornwitser.factorio_tools multi generate-instances 8
145 |
146 | This generates 8 instance directories named instance1 to instance8
147 | in the current directory based on the base instance. You can
148 | change the base instance, name of the output instances and where
149 | they are output with the ``--base``, ``--output`` and ``--prefix``
150 | options.
151 |
152 | 5. Spawn instances using the spawn-multi command
153 |
154 | .. code ::
155 |
156 | > py -m hornwitser.factorio_tools multi spawn-multi --count 8
157 |
158 | This will spawn and arrange Factorio clients in a 5x4 grid starting
159 | from the top right and going down. There are numerous options to
160 | control the behaviour, including how many rows and columns to use
161 | and the delay between each spawn.
162 |
163 | You can add arguments that are passed to factorio with the
164 | ``--args`` option. This is useful to have the clients auto connect
165 | to a server by passing ``--args "--mp-connect example.com"``.
166 |
167 | Once you've generated the instances you only need to perform step 5 to
168 | start instances. If you want to change the config for all of the
169 | instances perform step 3 followed step 4 again.
170 |
171 | Finally there's a ``click`` tool that's invoked with
172 |
173 | .. code ::
174 |
175 | > py -m hornwitser.factorio_tools multi click 200 180
176 |
177 | and clicks on the given x, y coordinate on every window who's title
178 | starts with "Factorio". Taking a screenshot of one of the Factorio
179 | windows with Alt+PrtScn and then pasting it into MS Paint is useful
180 | to figure out what coordinate a button is on.
181 |
182 | There's also a ``type`` tool that does keyboard input on each window
183 | and is invoked like this
184 |
185 | .. code ::
186 |
187 | > py -m hornwitser.factorio_tools multi type control-v backspace enter
188 |
189 | Separate each keypress with a space and ``-`` to combine multiple keys
190 | into one stroke. For a list of recognized keys see the `virtual key
191 | codes`_ table.
192 |
193 | .. _virtual key codes: https://docs.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes
194 |
--------------------------------------------------------------------------------
/hornwitser/factorio_tools/__init__.py:
--------------------------------------------------------------------------------
1 | # factorio_tools - Debugging utilities for Factorio
2 | # Copyright (C) 2020 Hornwitser
3 | #
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 | #
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU General Public License for more details.
13 | #
14 | # You should have received a copy of the GNU General Public License
15 | # along with this program. If not, see .
16 |
--------------------------------------------------------------------------------
/hornwitser/factorio_tools/__main__.py:
--------------------------------------------------------------------------------
1 | # factorio_tools - Debugging utilities for Factorio
2 | # Copyright (C) 2020 Hornwitser
3 | #
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 | #
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU General Public License for more details.
13 | #
14 | # You should have received a copy of the GNU General Public License
15 | # along with this program. If not, see .
16 |
17 | import argparse
18 | import sys
19 |
20 | from . import desync
21 | if sys.platform == "win32":
22 | from . import multi
23 | from . import parse
24 | from . import ping
25 |
26 |
27 | def main():
28 | parser = argparse.ArgumentParser(
29 | prog="factorio_tools",
30 | description="Debugging utilities for Factorio",
31 | )
32 | parser.set_defaults(func=lambda args: parser.print_help())
33 | subparsers = parser.add_subparsers(help="Tool to run")
34 |
35 | desync_parser(subparsers)
36 | dat2json_parser(subparsers)
37 | ping_parser(subparsers)
38 | if sys.platform == "win32":
39 | multi_parser(subparsers)
40 | args = parser.parse_args()
41 | args.func(args)
42 |
43 | def dat2json_parser(subparsers):
44 | parser = subparsers.add_parser(
45 | 'dat2json', help="Convert Factorio dat files to json",
46 | description=
47 | "Converts the binary formats used in Factorio to json. "
48 | "The format options are only necessary if the format cannot be deduced from filename."
49 | )
50 |
51 | parser.add_argument('--input', '-i', default='-', type=argparse.FileType('rb'), help="input file to convert")
52 | parser.add_argument('--input-format', help="format of input file")
53 | parser.add_argument('--output', '-o', default='-', type=argparse.FileType('w'), help="file to output to")
54 | parser.set_defaults(func=parse.dat2json)
55 |
56 | def desync_parser(subparsers):
57 | parser = subparsers.add_parser(
58 | 'desync', help="Analyze desync reports",
59 | description=
60 | "Automated parsing and diffing of desync reports from Factorio"
61 | )
62 |
63 | parser.add_argument('path', help="Path to desync report, will be extracted if in the .zip file")
64 | parser.set_defaults(func=desync.analyze)
65 |
66 | def ping_parser(subparsers):
67 | parser = subparsers.add_parser(
68 | 'ping', help="Ping Factorio server",
69 | description="Pings a Factorio server and display statistics."
70 | )
71 |
72 | parser.add_argument('--count', '-c', type=int, help="Stop after COUNT pings sent")
73 | parser.add_argument('--interval', '-i', type=float, default=1.0, help="Interval to send pings at in seconds")
74 | parser.add_argument('--ipv4', '-4', action='store_true', help="Use IPv4")
75 | parser.add_argument('--ipv6', '-6', action='store_true', help="Use IPv6")
76 | parser.add_argument('--punch', '-p', action='store_true', help="Send NAT punch request to server")
77 | parser.add_argument('--quiet', '-q', action='store_true', help="Suppress ping reply output")
78 | parser.add_argument('target', help="IP of server to ping")
79 | parser.add_argument('port', nargs='?', type=int, default=34197, help="Port of server to ping")
80 | parser.set_defaults(func=ping.ping)
81 |
82 | def multi_parser(subparsers):
83 | parser = subparsers.add_parser('multi', help="Handle multiple Factorio clients")
84 | parser.set_defaults(func=lambda args: parser.print_help())
85 | subparsers = parser.add_subparsers()
86 |
87 | parser_generate_base = subparsers.add_parser('generate-base', help="Generate write dir to base instances on")
88 | parser_generate_base.add_argument('--base', default="base", help="Name of write dir to generate")
89 | parser_generate_base.add_argument('--data', help="Path to Factorio data directory")
90 | parser_generate_base.set_defaults(func=multi.generate_base)
91 |
92 | parser_generate_instances = subparsers.add_parser('generate-instances', help="Generate instances write dirs")
93 | parser_generate_instances.add_argument('count', type=int, help="Number of instances to generate")
94 | parser_generate_instances.add_argument('--base', default="base", help="Write dir to base instances on")
95 | parser_generate_instances.add_argument('--output', default="", help="Path to put generated instances into")
96 | parser_generate_instances.add_argument('--prefix', default="instance", help="Prefix to name of instance dirs")
97 | parser_generate_instances.set_defaults(func=multi.generate_instances)
98 |
99 | parser_spawn = subparsers.add_parser('spawn', help="Spawn single client")
100 | parser_spawn.add_argument('--path', default="base", help="Path to write dir to spawn from")
101 | parser_spawn.add_argument('--factorio', help="Path to Factorio executable")
102 | parser_spawn.add_argument('--args', '-a', help="Additional args to pass to Factorio")
103 | parser_spawn.add_argument('--title', help="Set window title to given text")
104 | parser_spawn.set_defaults(func=multi.spawn)
105 |
106 | parser_spawn_multi = subparsers.add_parser('spawn-multi', help="Spawn multiple clients")
107 | parser_spawn_multi.add_argument('--count', '-c', type=int, default=1, help="Clients to spawn")
108 | parser_spawn_multi.add_argument('--delay', '-d', type=float, default=2.0, help="Deleay between spawns")
109 | parser_spawn_multi.add_argument('--monitor', '-m', type=int, default=None, help="Monitor to move window to")
110 | parser_spawn_multi.add_argument('--rows', '-R', type=int, default=4, help="Positioning rows")
111 | parser_spawn_multi.add_argument('--cols', '-C', type=int, default=5, help="Positioning columns")
112 | parser_spawn_multi.add_argument('--instance-dirs', default="", help="Location of instance dirs")
113 | parser_spawn_multi.add_argument('--prefix', default="instance", help="Prefix to name of instance dirs")
114 | parser_spawn_multi.add_argument('--factorio', help="Path to Factorio executable")
115 | parser_spawn_multi.add_argument('--args', '-a', help="Additional args to pass to Factorio")
116 | parser_spawn_multi.add_argument('--title', help="Set window title to given text")
117 | parser_spawn_multi.set_defaults(func=multi.spawn_multi)
118 |
119 | parser_click = subparsers.add_parser('click', help="Click coordinate on all clients")
120 | parser_click.add_argument('x', type=int, help="x coordinate")
121 | parser_click.add_argument('y', type=int, help="y coordinate")
122 | parser_click.set_defaults(func=multi.click)
123 |
124 | parser_type = subparsers.add_parser('type', help="Type keys on all clients")
125 | parser_type.add_argument("keys", type=str, nargs='+', help="keys to input")
126 | parser_type.set_defaults(func=multi.key)
127 |
128 | if __name__ == '__main__':
129 | main()
130 |
--------------------------------------------------------------------------------
/hornwitser/factorio_tools/desync.py:
--------------------------------------------------------------------------------
1 | # factorio_tools - Debugging utilities for Factorio
2 | # Copyright (C) 2020 Hornwitser
3 | #
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 | #
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU General Public License for more details.
13 | #
14 | # You should have received a copy of the GNU General Public License
15 | # along with this program. If not, see .
16 |
17 | '''
18 | desync.py - Automated analyzis of desync reports
19 | '''
20 |
21 | import collections
22 | import difflib
23 | import enum
24 | import itertools
25 | import json
26 | from os import path
27 | import re
28 | import zipfile
29 |
30 | from . import parse
31 |
32 |
33 | BUFFER_SIZE = 2**20
34 | class TokenKind(enum.IntEnum):
35 | OPEN_TAG = 1
36 | CLOSE_TAG = 2
37 | DATA = 3
38 | COLLAPSED = 4
39 |
40 | class Token(collections.namedtuple('Token', 'kind content tag parent pos')):
41 | def __eq__(self, other):
42 | return (
43 | self.kind == other.kind
44 | and self.content == other.content
45 | and self.tag == other.tag
46 | )
47 |
48 | def __ne__(self, other):
49 | return (
50 | self.kind != other.kind
51 | or self.content != other.content
52 | or self.tag != other.tag
53 | )
54 |
55 | def __hash__(self):
56 | return hash((self.kind, self.content, self.tag))
57 |
58 |
59 | token_spec = [
60 | (b'OPEN_TAG', br'<(?P[a-z-]{2,})( ([^\x00-\x1f<>\x80-\xff]|<[a-zA-Z]+>)*)?>'),
61 | (b'CLOSE_TAG', br'(?P[a-z-]{2,})>'),
62 | ]
63 |
64 | tag = re.compile(b'|'.join(b'(?P<%s>%s)' % pair for pair in token_spec))
65 |
66 | def tokenize_tagged_file(tagged_file):
67 | parent = None
68 | pos = 0
69 | offset = 0
70 | buffer = tagged_file.read(BUFFER_SIZE)
71 | while True:
72 | match = tag.search(buffer, pos)
73 | if not match:
74 | more = tagged_file.read(BUFFER_SIZE)
75 | if not more:
76 | yield Token(TokenKind.DATA, buffer[pos:], None, parent, offset + pos)
77 | break
78 |
79 | buffer += more
80 | continue
81 |
82 | if match.start() > pos:
83 | yield Token(TokenKind.DATA, buffer[pos:match.start()], None, parent, offset + pos)
84 |
85 | if match.lastgroup == 'CLOSE_TAG':
86 | new_parent = parent
87 | tag_name = match['CLOSE_TAG_NAME']
88 | while new_parent is not None:
89 | if new_parent.tag == tag_name:
90 | parent = new_parent.parent
91 | break
92 |
93 | new_parent = new_parent.parent
94 |
95 | else:
96 | print(f"Unmatched close tag {tag_name}>")
97 |
98 | token = Token(TokenKind[match.lastgroup], match[0], match[f'{match.lastgroup}_NAME'], parent, offset + pos)
99 | yield token
100 | if match.lastgroup == 'OPEN_TAG':
101 | parent = token
102 |
103 | pos = match.end()
104 | if pos > BUFFER_SIZE // 2:
105 | offset += pos
106 | buffer = buffer[pos:]
107 | pos = 0
108 |
109 | def token_path(token):
110 | path = []
111 | parent = token.parent
112 | while parent is not None:
113 | path[0:0] = [parent]
114 | parent = parent.parent
115 |
116 | formatted = []
117 | for i, ancestor in enumerate(path):
118 | formatted.append(f"{' '*i}{ancestor.content.decode('utf-8')} pos={ancestor.pos}")
119 | return '\n'.join(formatted)
120 |
121 | def collapse(iterator):
122 | curr = next(iterator, None)
123 | next1 = next(iterator, None)
124 | next2 = next(iterator, None)
125 |
126 | def advance():
127 | nonlocal curr, next1, next2
128 | curr = next1
129 | next1 = next2
130 | next2 = next(iterator, None)
131 |
132 | while curr is not None:
133 | if (
134 | curr.kind == TokenKind.OPEN_TAG
135 | and next1.kind == TokenKind.DATA
136 | and next2.kind == TokenKind.CLOSE_TAG
137 | and curr.tag == next2.tag
138 | ):
139 | content = curr.content + next1.content + next2.content
140 | yield Token(TokenKind.COLLAPSED, content, curr.tag, curr.pos)
141 | advance()
142 | advance()
143 |
144 | elif (
145 | curr.kind == TokenKind.OPEN_TAG
146 | and next1.kind == TokenKind.CLOSE_TAG
147 | and curr.tag == next1.tag
148 | ):
149 | content = curr.content + next1.content
150 | yield Token(TokenKind.COLLAPSED, content, curr.tag, curr.pos)
151 | advance()
152 |
153 | else:
154 | yield curr
155 |
156 | advance()
157 |
158 | def find_files(level_zip):
159 | files = {}
160 | for name in level_zip.namelist():
161 | if 'root' not in files:
162 | files['root'] = name[:name.find('/')]
163 |
164 | if re.match(r'.*/level-heuristic-\d+', name):
165 | files['heuristic'] = level_zip.open(name)
166 |
167 | if re.match(r'.*/level_with_tags_tick_\d+\.dat', name):
168 | files['level_with_tags'] = level_zip.open(name)
169 |
170 | files['script'] = level_zip.open(f'{files["root"]}/script.dat')
171 | return files
172 |
173 | def file_differs(a, b):
174 | try:
175 | bytes_a = None
176 | while bytes_a != b'':
177 | bytes_a = a.read(1024)
178 | if bytes_a != b.read(1024):
179 | return True
180 |
181 | return False
182 |
183 | finally:
184 | a.seek(0)
185 | b.seek(0)
186 |
187 | def diff_script_objects(a, b, path=[]):
188 | if type(a) is not type(b):
189 | yield (path, a, b)
190 |
191 | elif type(a) is list:
192 | for i in range(max(len(a), len(b))):
193 | sub_path = path + [i] if path != ['data'] else path + [a[i]['name']]
194 | if i < len(a) and i < len(b):
195 | yield from diff_script_objects(a[i], b[i], sub_path)
196 | elif i < len(a):
197 | yield (sub_path, a[i], None)
198 | else:
199 | yield (sub_path, None, b[i])
200 |
201 | elif type(a) is dict:
202 | shared_keys = {*a.keys(), *b.keys()}
203 | if shared_keys == {'key', 'value'}:
204 | path = path[:-1] + [a['key']]
205 | for k in shared_keys:
206 | if k in a and k in b:
207 | yield from diff_script_objects(a[k], b[k], path + [k])
208 | elif k in a:
209 | yield (path + [k], a[k], None)
210 | else:
211 | yield (path + [k], None, b[k])
212 |
213 | elif a != b:
214 | yield (path, a, b)
215 |
216 |
217 | def script_dat_to_object(level_files):
218 | print(f"parsing {level_files['root']}/script.dat")
219 | decoded = parse.ScriptDat.parse_stream(level_files['script'])
220 | level_files['script'].seek(0)
221 | return parse.container_to_object(decoded)
222 |
223 | def diff_tagged_files(a_file, b_file):
224 |
225 | # SequenceMatcher is too slow to work on an entire parsed level
226 | # so we will instead diff top level tags one by one
227 | def top_level_tags(generator):
228 | chunk = []
229 | for token in generator:
230 | chunk.append(token)
231 | if token.parent is None and token.kind != TokenKind.OPEN_TAG:
232 | yield chunk
233 | chunk = []
234 |
235 | if chunk:
236 | yield chunk
237 |
238 | a_generator = top_level_tags(tokenize_tagged_file(a_file))
239 | b_generator = top_level_tags(tokenize_tagged_file(b_file))
240 |
241 | # For now it's assumed two levels have the same number of chunks
242 | # and have them in the same order. This may not actually hold true
243 | combined = itertools.zip_longest(a_generator, b_generator)
244 | for a_chunk, b_chunk in combined:
245 | if a_chunk == b_chunk:
246 | continue
247 |
248 | if a_chunk is None:
249 | print()
250 | print("add to end")
251 | print("des:", b''.join(c.content for c in b_chunk))
252 | continue
253 | if b_chunk is None:
254 | print("delete from end")
255 | print("ref:", b''.join(c.content for c in a_chunk))
256 | continue
257 |
258 | if max(len(a_chunk), len(b_chunk)) > 200000:
259 | print(f"diffing <{a_chunk[0].tag}> {len(a_chunk)}/{len(b_chunk)} tokens, this may take a long time")
260 |
261 | matcher = difflib.SequenceMatcher(None, a_chunk, b_chunk)
262 | for op, i1, i2, j1, j2 in matcher.get_opcodes():
263 | if op == 'equal': continue
264 | print()
265 | print(f"{op:7} ref[{i1}:{i2}] -> des[{j1}:{j2}]")
266 | if i1 != i2:
267 | print(token_path(a_chunk[i1]))
268 | print(f"ref: {b''.join(map(lambda t: t.content, a_chunk[i1:i2]))!r}")
269 | if j1 != j2:
270 | print(token_path(b_chunk[j1]))
271 | print(f"des: {b''.join(map(lambda t: t.content, b_chunk[j1:j2]))}")
272 |
273 | def analyze(args):
274 | if args.path.endswith('.zip'):
275 | print(f"Unzipping {args.path}")
276 | report = zipfile.ZipFile(args.path)
277 | report.extractall(path.dirname(args.path))
278 | args.path = args.path[:-4]
279 |
280 | ref_zip = zipfile.ZipFile(path.join(args.path, 'reference-level.zip'))
281 | des_zip = zipfile.ZipFile(path.join(args.path, 'desynced-level.zip'))
282 |
283 | ref_files = find_files(ref_zip)
284 | des_files = find_files(des_zip)
285 |
286 | if file_differs(ref_files['heuristic'], des_files['heuristic']):
287 | print()
288 | print("level-heuristic differs")
289 | print("-----------------------")
290 | diff_tagged_files(ref_files['heuristic'], des_files['heuristic'])
291 |
292 | if file_differs(ref_files['script'], des_files['script']):
293 | print()
294 | print("script.dat differs")
295 | print("------------------")
296 |
297 | des_script = script_dat_to_object(des_files)
298 | ref_script = script_dat_to_object(ref_files)
299 | for diff in diff_script_objects(ref_script, des_script):
300 | print(f"Path: {diff[0]}")
301 | print(f"Reference value: {json.dumps(diff[1])}")
302 | print(f"Desynced value: {json.dumps(diff[2])}")
303 |
304 | if file_differs(ref_files['level_with_tags'], des_files['level_with_tags']):
305 | print()
306 | print("level_with_tags.dat differs")
307 | print("---------------------------")
308 | diff_tagged_files(ref_files['level_with_tags'], des_files['level_with_tags'])
309 |
--------------------------------------------------------------------------------
/hornwitser/factorio_tools/disown.py:
--------------------------------------------------------------------------------
1 | # factorio_tools - Debugging utilities for Factorio
2 | # Copyright (C) 2020 Hornwitser
3 | #
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 | #
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU General Public License for more details.
13 | #
14 | # You should have received a copy of the GNU General Public License
15 | # along with this program. If not, see .
16 |
17 | """
18 | disown.py - Dumb Factorio console workaround
19 |
20 | Invokes the command specified as the first argument and prints back the
21 | the pid of the command launched over stdout. This is necessary because
22 | Factorio likes to hijack whatever console it finds in the process that
23 | spawns it.
24 | """
25 |
26 | import sys
27 | import subprocess
28 |
29 | if __name__ == '__main__':
30 | proc = subprocess.Popen(sys.argv[1])
31 | print(proc.pid, end='')
32 |
--------------------------------------------------------------------------------
/hornwitser/factorio_tools/multi.py:
--------------------------------------------------------------------------------
1 | # factorio_tools - Debugging utilities for Factorio
2 | # Copyright (C) 2020 Hornwitser
3 | #
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 | #
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU General Public License for more details.
13 | #
14 | # You should have received a copy of the GNU General Public License
15 | # along with this program. If not, see .
16 |
17 | """
18 | multi.py - Spawn and handle multiple Factorio clients
19 | """
20 |
21 | import collections
22 | import configparser
23 | import ctypes
24 | import json
25 | import os
26 | import platform
27 | import re
28 | import shutil
29 | import subprocess
30 | import sys
31 | import time
32 |
33 |
34 | def generate_base(args):
35 | config_dir = os.path.join(args.base, 'config')
36 | os.makedirs(config_dir, exist_ok=True)
37 |
38 | if not args.data:
39 | args.data = os.path.join('__PATH__executable__', '..', '..', 'data')
40 |
41 | config = configparser.ConfigParser()
42 | config['path'] = {
43 | 'read-data': args.data,
44 | 'write-data': os.path.abspath(args.base),
45 | }
46 | config['other'] = { 'check-updates': 'false' }
47 | config['sound'] = { 'music-volume': '0.000000' }
48 | config['graphics'] = { 'full-screen': 'false' }
49 |
50 | with open(os.path.join(config_dir, 'config.ini'), 'x', newline='\n') as f:
51 | f.write('; version=7\n')
52 | config.write(f, space_around_delimiters=False)
53 |
54 | def generate_instances(args):
55 | with open(os.path.join(args.base, 'player-data.json')) as f:
56 | player_data = json.load(f)
57 |
58 | base_name = player_data["service-username"]
59 |
60 | for i in range(1, args.count+1):
61 | dst = os.path.join(args.output, f'{args.prefix}{i}')
62 | shutil.copytree(args.base, dst, dirs_exist_ok=True)
63 |
64 | player_data["service-username"] = f"{base_name}{i}"
65 | with open(os.path.join(dst, 'player-data.json'), 'w') as f:
66 | json.dump(player_data, f, indent=2)
67 |
68 | config_path = os.path.join(dst, 'config', 'config.ini')
69 | with open(config_path, 'r', newline='\n') as f:
70 | config_content = f.read()
71 |
72 | def escape(string):
73 | return string.replace('\\', '\\\\')
74 |
75 | config_content = re.sub(
76 | r'^write-data=.*$',
77 | f'write-data={escape(os.path.abspath(dst))}',
78 | config_content,
79 | flags=re.MULTILINE
80 | )
81 |
82 | with open(config_path, 'w', newline='\n') as f:
83 | f.write(config_content)
84 |
85 | def find_factorio():
86 | """Look for the factorio executable"""
87 | if "FACTORIO" in os.environ:
88 | return os.environ["FACTORIO"]
89 |
90 | dir = os.getcwd()
91 | while True:
92 | exe = os.path.join(dir, 'bin', 'x64', 'factorio.exe')
93 | if os.path.exists(exe):
94 | return exe
95 |
96 | parent = os.path.normpath(os.path.join(dir, '..'))
97 | if parent == dir:
98 | break
99 | dir = parent
100 |
101 | raise RuntimeError(
102 | "Unable to locate factorio executable, specify it with --factorio"
103 | )
104 |
105 | def spawn(args):
106 | spawn_one(args.path, args)
107 |
108 | def spawn_multi(args):
109 | instance_index = spawn_instance(1, args)
110 | for i in range(args.count - 1):
111 | time.sleep(args.delay)
112 | instance_index = spawn_instance(instance_index, args)
113 |
114 | def spawn_instance(instance_index, args):
115 | while True:
116 | write_dir = os.path.join(args.instance_dirs, f'{args.prefix}{instance_index}')
117 | if not os.path.exists(os.path.join(write_dir, '.lock')):
118 | break
119 | instance_index += 1
120 |
121 | pid = spawn_one(write_dir, args)
122 | move_window(pid, instance_index, args.monitor, args.rows, args.cols)
123 | return instance_index + 1
124 |
125 | def spawn_one(write_dir, args):
126 | disown = 'pyw -m hornwitser.factorio_tools.disown'
127 | factorio = args.factorio if args.factorio else find_factorio()
128 | cfg_path = os.path.join(write_dir, 'config', 'config.ini')
129 | extra_args = '' if not args.args else f' {args.args}'
130 | spawn_result = subprocess.run(
131 | f'{disown} "{factorio} --config {cfg_path}{extra_args}"',
132 | capture_output=True, text=True
133 | )
134 | pid = int(spawn_result.stdout)
135 | if args.title:
136 | hWnd = find_main_window(pid, 20)
137 | if hWnd:
138 | set_title(hWnd, args.title)
139 |
140 | return pid
141 |
142 |
143 | # --- Windows API interactions -----------------------------------------
144 |
145 | DWORD = ctypes.c_ulong
146 | WORD = ctypes.c_short
147 | BOOL = ctypes.c_long
148 | ULONG = ctypes.c_ulong
149 | LONG = ctypes.c_long
150 | UINT = ctypes.c_uint
151 |
152 | HANDLE = ctypes.c_void_p
153 | HDC = HANDLE
154 | HMONITOR = HANDLE
155 |
156 | kernel32 = ctypes.windll.kernel32
157 | user32 = ctypes.windll.user32
158 |
159 | class RECT(ctypes.Structure):
160 | _fields_ = [
161 | ('left', LONG),
162 | ('top', LONG),
163 | ('right', LONG),
164 | ('bottom', LONG),
165 | ]
166 |
167 | class MONITORINFO(ctypes.Structure):
168 | _fields_ = [
169 | ('cbSize', DWORD),
170 | ('rcMonitor', RECT),
171 | ('rcWork', RECT),
172 | ('dwFlags', DWORD),
173 | ]
174 |
175 | MOUSEEVENTF_MOVE = 0x0001
176 | MOUSEEVENTF_LEFTDOWN = 0x0002
177 | MOUSEEVENTF_LEFTUP = 0x0004
178 | MOUSEEVENTF_RIGHTDOWN = 0x0008
179 | MOUSEEVENTF_RIGHTUP = 0x0010
180 | MOUSEEVENTF_MIDDLEDOWN = 0x0020
181 | MOUSEEVENTF_MIDDLEUP = 0x0040
182 | MOUSEEVENTF_VIRTUALDESK = 0x4000
183 | MOUSEEVENTF_ABSOLUTE = 0x8000
184 |
185 | class MOUSEINPUT(ctypes.Structure):
186 | _fields_ = [
187 | ('dx', LONG),
188 | ('dy', LONG),
189 | ('mouseData', DWORD),
190 | ('dwFlags', DWORD),
191 | ('time', DWORD),
192 | ('dwExtraInfo', ctypes.POINTER(ULONG)),
193 | ]
194 |
195 | KEYEVENTF_EXTENDEDKEY = 0x0001
196 | KEYEVENTF_KEYUP = 0x0002
197 | KEYEVENTF_SCANCODE = 0x0008
198 | KEYEVENT_UNICODE = 0x0004
199 |
200 | class KEYBDINPUT(ctypes.Structure):
201 | _fields_ = [
202 | ('wVk', WORD),
203 | ('wScan', WORD),
204 | ('dwFlags', DWORD),
205 | ('time', DWORD),
206 | ('dwExtraInfo', ctypes.POINTER(ULONG))
207 | ]
208 |
209 | INPUT_MOUSE = 0
210 | INPUT_KEYBOARD = 1
211 | INPUT_HARDWARE = 3
212 |
213 | class INPUT_I(ctypes.Union):
214 | _fields_ = [
215 | ('mi', MOUSEINPUT),
216 | ('ki', KEYBDINPUT),
217 | # ('hi', HARDWAREINPUT),
218 | ]
219 |
220 | class INPUT(ctypes.Structure):
221 | _anonymous_ = ("ii",)
222 | _fields_ = [
223 | ('type', DWORD),
224 | ('ii', INPUT_I),
225 | ]
226 |
227 | MONITOR_DEFAULTTONULL = 0x0
228 | MONITOR_DEFAULTTOPRIMARY = 0x1
229 |
230 | MONITORENUMPROC = ctypes.WINFUNCTYPE(BOOL, HMONITOR, HDC, ctypes.POINTER(RECT), ctypes.c_void_p)
231 |
232 | def get_monitor_handle(monitor):
233 | callback = MONITORENUMPROC(get_monitor_handle_callback)
234 | monitors = []
235 | user32.EnumDisplayMonitors(None, None, callback, ctypes.byref(ctypes.py_object(monitors)))
236 | clamped = max(1, min(len(monitors), monitor))
237 | if clamped != monitor:
238 | print(f"Warning: monitor index out of range [1-{len(monitors)}]")
239 | return monitors[clamped-1]
240 |
241 | def get_monitor_handle_callback(hMonitor, hdc, p_rect, p_void):
242 | monitors = ctypes.cast(p_void, ctypes.POINTER(ctypes.py_object))[0]
243 | monitors.append(hMonitor)
244 | return True
245 |
246 | def get_monitor_info(hMonitor):
247 | info = MONITORINFO(ctypes.sizeof(MONITORINFO))
248 | success = user32.GetMonitorInfoW(hMonitor, ctypes.byref(info))
249 | if not success:
250 | raise RuntimeError("Failed to get monitor info")
251 |
252 | return info
253 |
254 | # Ported from https://stackoverflow.com/a/21767578
255 | class MainWindowData(ctypes.Structure):
256 | _fields_ = [
257 | ('pid', DWORD),
258 | ('hWnd', DWORD),
259 | ]
260 |
261 | WNDENUMPROC = ctypes.WINFUNCTYPE(BOOL, DWORD, ctypes.c_void_p)
262 |
263 | def find_main_window(pid, tries):
264 | data = MainWindowData(pid, 0)
265 | callback = WNDENUMPROC(find_main_window_callback)
266 | for i in range(tries):
267 | user32.EnumWindows(callback, ctypes.byref(data))
268 | if data.hWnd:
269 | break
270 | time.sleep(0.1)
271 | return data.hWnd
272 |
273 | def find_main_window_callback(hWnd, p_void):
274 | p_data = ctypes.cast(p_void, ctypes.POINTER(MainWindowData))
275 | pid = DWORD()
276 | user32.GetWindowThreadProcessId(hWnd, ctypes.byref(pid))
277 | if (pid.value != p_data[0].pid or not is_main_window(hWnd)):
278 | return True
279 | p_data[0].hWnd = hWnd
280 | return False
281 |
282 | def is_main_window(hWnd):
283 | return user32.GetWindow(hWnd, 4) == 0 and user32.IsWindowVisible(hWnd)
284 |
285 | def set_title(hWnd, text):
286 | user32.SetWindowTextW(hWnd, text)
287 |
288 | FindWindowData = collections.namedtuple('FindWindowData', 'name hWnds')
289 |
290 | def find_windows(name):
291 | """Find Windows who's title starts with name"""
292 | data = FindWindowData(name, [])
293 | callback = WNDENUMPROC(find_windows_callback)
294 | user32.EnumWindows(callback, ctypes.byref(ctypes.py_object(data)))
295 | return data.hWnds
296 |
297 | def find_windows_callback(hWnd, p_void):
298 | data = ctypes.cast(p_void, ctypes.POINTER(ctypes.py_object))[0]
299 | if (not is_main_window(hWnd)):
300 | return True
301 |
302 | buffer = ctypes.create_unicode_buffer(200)
303 | user32.GetWindowTextW(hWnd, ctypes.byref(buffer), 200)
304 | name = ctypes.wstring_at(buffer)
305 | if (name.startswith(data.name)):
306 | data.hWnds.append(hWnd)
307 |
308 | return True
309 |
310 | class POINT(ctypes.Structure):
311 | _fields_ = [
312 | ('x', LONG),
313 | ('y', LONG),
314 | ]
315 |
316 | SW_MAXIMIZE = 3
317 | SW_RESTORE = 9
318 |
319 | class WINDOWPLACEMENT(ctypes.Structure):
320 | _fields_ = [
321 | ('length', UINT),
322 | ('flags', UINT),
323 | ('showCmd', UINT),
324 | ('ptMinPosition', POINT),
325 | ('ptMaxPosition', POINT),
326 | ('rcNormalPosition', RECT),
327 | ('rcDevice', RECT),
328 | ]
329 |
330 | WM_SYSCOMMAND = 0x0112
331 | SC_RESTORE = 0xf120
332 |
333 | def ensure_not_maximized(hWnd):
334 | window_placement = WINDOWPLACEMENT(ctypes.sizeof(WINDOWPLACEMENT))
335 | user32.GetWindowPlacement(hWnd, ctypes.byref(window_placement))
336 |
337 | if window_placement.showCmd == SW_MAXIMIZE:
338 | user32.SendMessageW(hWnd, WM_SYSCOMMAND, SC_RESTORE, 0)
339 |
340 | def move_window(pid, instance_index, monitor, rows, cols):
341 | hWnd = find_main_window(pid, 20)
342 | if not hWnd:
343 | raise RuntimeError("Unable to find Factorio window")
344 |
345 | ensure_not_maximized(hWnd)
346 | if monitor is None:
347 | hMonitor = user32.MonitorFromWindow(hWnd, MONITOR_DEFAULTTOPRIMARY)
348 | else:
349 | hMonitor = get_monitor_handle(monitor)
350 | rcWork = get_monitor_info(hMonitor).rcWork
351 | width = (rcWork.right - rcWork.left) // cols
352 | height = (rcWork.bottom - rcWork.top) // rows
353 | left = rcWork.right - (((instance_index - 1) // rows + 1) * width)
354 | top = rcWork.top + ((instance_index - 1) % rows * height)
355 |
356 | # No idea why, but this produced thighly spaced windows on Windows 7
357 | # but left 7 pixel borders 10.
358 | if platform.release() == '10':
359 | height += 7
360 | left -= 7
361 | width += 14
362 |
363 | user32.MoveWindow(hWnd, left, top, width, height, False)
364 |
365 |
366 | def window_to_virtual(hWnd, x, y):
367 | rect = RECT()
368 | if not user32.GetWindowRect(hWnd, ctypes.byref(rect)):
369 | raise RuntimeError("Unable to get size of window")
370 | return x + rect.left, y + rect.top
371 |
372 | def click_window(hWnd, x, y):
373 | flags = (
374 | MOUSEEVENTF_LEFTDOWN
375 | | MOUSEEVENTF_LEFTUP
376 | )
377 | x, y = window_to_virtual(hWnd, x, y)
378 | user32.SetCursorPos(x, y)
379 | user32.SetCursorPos(x, y) # Make sure it actually moves
380 | mi = MOUSEINPUT(0, 0, 0, flags, 0, None)
381 | input = INPUT(INPUT_MOUSE, mi=mi)
382 | user32.SendInput(1, ctypes.byref(input), ctypes.sizeof(INPUT))
383 |
384 | def click(args):
385 | factorio_windows = find_windows("Factorio")
386 | for hWnd in factorio_windows:
387 | click_window(hWnd, args.x, args.y)
388 | time.sleep(0.1)
389 |
390 | vk_codes = {
391 | 'LBUTTON': 0x01, 'RBUTTON': 0x02,
392 | 'CANCEL': 0x03,
393 | 'MBUTTON': 0x04,
394 | 'XBUTTON1': 0x05,
395 | 'XBUTTON2': 0x06,
396 | 'BACK': 0x08,
397 | 'TAB': 0x09,
398 | 'CLEAR': 0x0C,
399 | 'RETURN': 0x0D,
400 | 'SHIFT': 0x10,
401 | 'CONTROL': 0x11,
402 | 'MENU': 0x12,
403 | 'PAUSE': 0x13,
404 | 'CAPITAL': 0x14,
405 | 'KANA': 0x15,
406 | 'HANGUEL': 0x15,
407 | 'HANGUL': 0x15,
408 | 'IME_ON': 0x16,
409 | 'JUNJA': 0x17,
410 | 'FINAL': 0x18,
411 | 'HANJA': 0x19,
412 | 'KANJI': 0x19,
413 | 'IME_OFF': 0x1A,
414 | 'ESCAPE': 0x1B,
415 | 'CONVERT': 0x1C,
416 | 'NONCONVERT': 0x1D,
417 | 'ACCEPT': 0x1E,
418 | 'MODECHANGE': 0x1F,
419 | 'SPACE': 0x20,
420 | 'PRIOR': 0x21,
421 | 'NEXT': 0x22,
422 | 'END': 0x23,
423 | 'HOME': 0x24,
424 | 'LEFT': 0x25,
425 | 'UP': 0x26,
426 | 'RIGHT': 0x27,
427 | 'DOWN': 0x28,
428 | 'SELECT': 0x29,
429 | 'PRINT': 0x2A,
430 | 'EXECUTE': 0x2B,
431 | 'SNAPSHOT': 0x2C,
432 | 'INSERT': 0x2D,
433 | 'DELETE': 0x2E,
434 | 'HELP': 0x2F,
435 | '0': 0x30,
436 | '1': 0x31,
437 | '2': 0x32,
438 | '3': 0x33,
439 | '4': 0x34,
440 | '5': 0x35,
441 | '6': 0x36,
442 | '7': 0x37,
443 | '8': 0x38,
444 | '9': 0x39,
445 | 'A': 0x41,
446 | 'B': 0x42,
447 | 'C': 0x43,
448 | 'D': 0x44,
449 | 'E': 0x45,
450 | 'F': 0x46,
451 | 'G': 0x47,
452 | 'H': 0x48,
453 | 'I': 0x49,
454 | 'J': 0x4A,
455 | 'K': 0x4B,
456 | 'L': 0x4C,
457 | 'M': 0x4D,
458 | 'N': 0x4E,
459 | 'O': 0x4F,
460 | 'P': 0x50,
461 | 'Q': 0x51,
462 | 'R': 0x52,
463 | 'S': 0x53,
464 | 'T': 0x54,
465 | 'U': 0x55,
466 | 'V': 0x56,
467 | 'W': 0x57,
468 | 'X': 0x58,
469 | 'Y': 0x59,
470 | 'Z': 0x5A,
471 | 'LWIN': 0x5B,
472 | 'RWIN': 0x5C,
473 | 'APPS': 0x5D,
474 | '-': 0x5E,
475 | 'SLEEP': 0x5F,
476 | 'NUMPAD0': 0x60,
477 | 'NUMPAD1': 0x61,
478 | 'NUMPAD2': 0x62,
479 | 'NUMPAD3': 0x63,
480 | 'NUMPAD4': 0x64,
481 | 'NUMPAD5': 0x65,
482 | 'NUMPAD6': 0x66,
483 | 'NUMPAD7': 0x67,
484 | 'NUMPAD8': 0x68,
485 | 'NUMPAD9': 0x69,
486 | 'MULTIPLY': 0x6A,
487 | 'ADD': 0x6B,
488 | 'SEPARATOR': 0x6C,
489 | 'SUBTRACT': 0x6D,
490 | 'DECIMAL': 0x6E,
491 | 'DIVIDE': 0x6F,
492 | 'F1': 0x70,
493 | 'F2': 0x71,
494 | 'F3': 0x72,
495 | 'F4': 0x73,
496 | 'F5': 0x74,
497 | 'F6': 0x75,
498 | 'F7': 0x76,
499 | 'F8': 0x77,
500 | 'F9': 0x78,
501 | 'F10': 0x79,
502 | 'F11': 0x7A,
503 | 'F12': 0x7B,
504 | 'F13': 0x7C,
505 | 'F14': 0x7D,
506 | 'F15': 0x7E,
507 | 'F16': 0x7F,
508 | 'F17': 0x80,
509 | 'F18': 0x81,
510 | 'F19': 0x82,
511 | 'F20': 0x83,
512 | 'F21': 0x84,
513 | 'F22': 0x85,
514 | 'F23': 0x86,
515 | 'F24': 0x87,
516 | 'NUMLOCK': 0x90,
517 | 'SCROLL': 0x91,
518 | 'LSHIFT': 0xA0,
519 | 'RSHIFT': 0xA1,
520 | 'LCONTROL': 0xA2,
521 | 'RCONTROL': 0xA3,
522 | 'LMENU': 0xA4,
523 | 'RMENU': 0xA5,
524 | 'BROWSER_BACK': 0xA6,
525 | 'BROWSER_FORWARD': 0xA7,
526 | 'BROWSER_REFRESH': 0xA8,
527 | 'BROWSER_STOP': 0xA9,
528 | 'BROWSER_SEARCH': 0xAA,
529 | 'BROWSER_FAVORITES': 0xAB,
530 | 'BROWSER_HOME': 0xAC,
531 | 'VOLUME_MUTE': 0xAD,
532 | 'VOLUME_DOWN': 0xAE,
533 | 'VOLUME_UP': 0xAF,
534 | 'MEDIA_NEXT_TRACK': 0xB0,
535 | 'MEDIA_PREV_TRACK': 0xB1,
536 | 'MEDIA_STOP': 0xB2,
537 | 'MEDIA_PLAY_PAUSE': 0xB3,
538 | 'LAUNCH_MAIL': 0xB4,
539 | 'LAUNCH_MEDIA_SELECT': 0xB5,
540 | 'LAUNCH_APP1': 0xB6,
541 | 'LAUNCH_APP2': 0xB7,
542 | 'OEM_1': 0xBA,
543 | 'OEM_PLUS': 0xBB,
544 | 'OEM_COMMA': 0xBC,
545 | 'OEM_MINUS': 0xBD,
546 | 'OEM_PERIOD': 0xBE,
547 | 'OEM_2': 0xBF,
548 | 'OEM_3': 0xC0,
549 | 'OEM_4': 0xDB,
550 | 'OEM_5': 0xDC,
551 | 'OEM_6': 0xDD,
552 | 'OEM_7': 0xDE,
553 | 'OEM_8': 0xDF,
554 | 'OEM_102': 0xE2,
555 | 'PROCESSKEY': 0xE5,
556 | 'ATTN': 0xF6,
557 | 'CRSEL': 0xF7,
558 | 'EXSEL': 0xF8,
559 | 'EREOF': 0xF9,
560 | 'PLAY': 0xFA,
561 | 'ZOOM': 0xFB,
562 | 'NONAME': 0xFC,
563 | 'PA1': 0xFD,
564 | 'OEM_CLEAR': 0xFE,
565 | }
566 |
567 | def key_window(hWnd, vks, scans):
568 | this_id = kernel32.GetCurrentThreadId()
569 | target_id = user32.GetWindowThreadProcessId(hWnd, None)
570 | user32.AttachThreadInput(this_id, target_id, True)
571 | user32.SetForegroundWindow(hWnd)
572 | user32.AttachThreadInput(this_id, target_id, False)
573 |
574 | inputs = []
575 | for vk, scan in reversed(list(zip(vks, scans))):
576 | inputs.insert(0, INPUT(INPUT_KEYBOARD, ki=KEYBDINPUT(vk, scan)))
577 | inputs.append(INPUT(INPUT_KEYBOARD, ki=KEYBDINPUT(vk, scan, KEYEVENTF_KEYUP)))
578 |
579 | inputs = (INPUT * len(inputs))(*inputs)
580 | user32.SendInput(len(inputs), ctypes.byref(inputs), ctypes.sizeof(INPUT))
581 |
582 | def key(args):
583 | factorio_windows = find_windows("Factorio")
584 | for key in args.keys:
585 | vks = list(map(lambda k: vk_codes[k.upper()], key.split("-")))
586 | scans = list(map(lambda vk: user32.MapVirtualKeyW(vk, 0), vks))
587 | for hWnd in factorio_windows:
588 | key_window(hWnd, vks, scans)
589 | time.sleep(0.01)
590 |
--------------------------------------------------------------------------------
/hornwitser/factorio_tools/parse.py:
--------------------------------------------------------------------------------
1 | # factorio_tools - Debugging utilities for Factorio
2 | # Copyright (C) 2020 Hornwitser
3 | #
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 | #
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU General Public License for more details.
13 | #
14 | # You should have received a copy of the GNU General Public License
15 | # along with this program. If not, see .
16 |
17 | """
18 | parse.py - Parser for the binary formats to Factorio
19 | """
20 |
21 | import json
22 | import os
23 | import struct
24 | import sys
25 |
26 | from construct import \
27 | Construct, Container, ListContainer, Prefixed, PrefixedArray, Struct, \
28 | Sequence, Switch, Computed, Terminated, Int32ul, Int24ul, Int16ul, Int8ul, \
29 | Float64l, Float32l, PascalString, stream_read, stream_write, this
30 |
31 |
32 | def singleton(cls):
33 | return cls()
34 |
35 | @singleton
36 | class FactorioInt32ul(Construct):
37 | def _parse(self, stream, context, path):
38 | tiny = stream_read(stream, 1, path)[0]
39 | if tiny != 0xff:
40 | return tiny
41 |
42 | big = stream_read(stream, 4, path)
43 | return struct.unpack('.
16 |
17 | import asyncio
18 | import itertools
19 | import random
20 | import selectors
21 | import socket
22 | from statistics import mean, pstdev
23 | import struct
24 | import sys
25 | import time
26 |
27 | MESSAGE_TYPE = [
28 | 'Ping', # 0
29 | 'PingReply', # 1
30 | 'ConnectionRequest',
31 | 'ConnectionRequestReply',
32 | 'ConnectionRequestReplyConfirm',
33 | 'ConnectionAcceptOrDeny',
34 | 'ClientToServerHeartbeat',
35 | 'ServerToClientHeartbeat',
36 | 'GetOwnAddress',
37 | 'GetOwnAddressReply',
38 | 'NatPunchRequest', # 10
39 | 'NatPunch', # 11
40 | 'TransferBlockRequest',
41 | 'TransferBlock',
42 | 'RequestForHeartbeatWhenDisconnecting',
43 | 'LANBroadcast',
44 | 'GameInformationRequest',
45 | 'GameInformationRequestReply',
46 | 'Empty',
47 | ]
48 |
49 | PINGPONG_SERVERS = [
50 | ('pingpong1.factorio.com', 34197),
51 | ('pingpong2.factorio.com', 34197),
52 | ('pingpong3.factorio.com', 34197),
53 | ('pingpong4.factorio.com', 34197),
54 | ]
55 |
56 | def format_ip(ip):
57 | return ip if ':' not in ip else f'[{ip}]'
58 |
59 | def format_addr(addr):
60 | return f'{format_ip(addr[0])}:{addr[1]}'
61 |
62 | class PingClientProtocol:
63 | def __init__(self, addr, pingpong_servers, punch, quiet):
64 | self.transport = None
65 | self.sent = 0
66 | self.pings = {}
67 | self.in_flight = {}
68 | self.last_punch = 0
69 | self.addr = addr
70 | self.pingpong_servers = pingpong_servers
71 | self.send_punch = punch
72 | self.quiet = quiet
73 |
74 | def connection_made(self, transport):
75 | self.transport = transport
76 |
77 | def ping(self, seq):
78 | send_time = time.perf_counter_ns()
79 | if self.send_punch and (not self.last_punch or (send_time - self.last_punch) / 1e9 >= 1):
80 | self.last_punch = send_time
81 | self.punch()
82 | self.in_flight[seq & 0xffff] = (send_time, seq)
83 | self.transport.sendto(struct.pack("02}" for c in data)
112 | print(f"Uhandled message {MESSAGE_TYPE[net_type] if net_type < len(MESSAGE_TYPE) else 'Unknown'} ({net_type}):{packet_bytes}")
113 | return
114 |
115 | def error_received(self, exc):
116 | print(f"{type(exc).__name__}: {exc}")
117 |
118 | def connection_lost(self, exc):
119 | pass
120 |
121 |
122 | async def ping_server(host, port, family, addr, interval, count, punch, pingpong_servers, quiet):
123 | loop = asyncio.get_running_loop()
124 | sock = socket.socket(family, type=socket.SOCK_DGRAM)
125 | if family == socket.AF_INET:
126 | sock.bind(('0.0.0.0', 0))
127 | elif family == socket.AF_INET6:
128 | sock.bind(('::1', 0, 0, 0))
129 | else:
130 | sock.close()
131 | raise ValueError("invalid address family")
132 |
133 |
134 | transport, protocol = await loop.create_datagram_endpoint(
135 | lambda: PingClientProtocol(addr, pingpong_servers, punch, quiet),
136 | sock=sock,
137 | )
138 |
139 | # delays smaller than 0.02 gets rounded down to 0 by asyncio sleep.
140 | if not interval > 0.02:
141 | interval = 1 / 30
142 |
143 | start = time.perf_counter_ns()
144 | try:
145 | for seq in itertools.count(0):
146 | protocol.ping(seq)
147 | if protocol.sent == count:
148 | break
149 | await asyncio.sleep(interval)
150 | await asyncio.sleep(0.5)
151 | except asyncio.CancelledError:
152 | pass
153 |
154 | transport.close()
155 | received = len(protocol.pings)
156 | end = time.perf_counter_ns()
157 | times = [(p[1] - p[0]) / 1e6 for p in protocol.pings.values()]
158 | loss = round((protocol.sent - received) / protocol.sent * 100, 2)
159 | print()
160 | print(f"--- {host}:{port} ping statistics ---")
161 | print(f"{protocol.sent} packets sent, {received} received, {loss}% loss, time {(end - start) / 1e6:.2f}ms")
162 | if len(times):
163 | print(f"rtt min/avg/max/mdev {min(times):.2f}/{mean(times):.2f}/{max(times):.2f}/{pstdev(times):.2f}")
164 |
165 | def ping(args):
166 | if args.ipv4 and args.ipv6:
167 | print("--ipv4/-4 and --ipv6/-6 are mutually exclusive")
168 | sys.exit(1)
169 |
170 | if args.ipv4:
171 | family = socket.AF_INET
172 | elif args.ipv6:
173 | family = socket.AF_INET6
174 | else:
175 | family = 0
176 |
177 | try:
178 | addrs = socket.getaddrinfo(args.target, args.port, family=family)
179 | except socket.gaierror:
180 | print(f"Unable to resolve {args.target}")
181 | sys.exit(1)
182 |
183 | family, addr = addrs[0][0], addrs[0][4]
184 |
185 | pingpong_servers = []
186 | if args.punch:
187 | for pingpong_server in PINGPONG_SERVERS:
188 | try:
189 | result = socket.getaddrinfo(*pingpong_server, family=family)
190 | pingpong_servers.append(result[0][4])
191 | except socket.gaierror:
192 | print(f"Unable to resolve {pingpong_server[0]}")
193 | sys.exit(1)
194 |
195 | # The ProactorEventLoop gives some random nonsense error on IPv6 ping of localhost
196 | selector = selectors.SelectSelector()
197 | loop = asyncio.SelectorEventLoop(selector)
198 | task = asyncio.ensure_future(ping_server(
199 | args.target, args.port, family, addr, args.interval, args.count, args.punch, pingpong_servers, args.quiet
200 | ), loop=loop)
201 | try:
202 | loop.run_until_complete(task)
203 | except KeyboardInterrupt:
204 | task.cancel()
205 | loop.run_until_complete(task)
206 |
--------------------------------------------------------------------------------
/pyproject.toml:
--------------------------------------------------------------------------------
1 | [build-system]
2 | requires = ["setuptools"]
3 | build-backend = "setuptools.build_meta"
4 |
--------------------------------------------------------------------------------
/setup.cfg:
--------------------------------------------------------------------------------
1 | [metadata]
2 | name = hornwitser.factorio_tools
3 | version = 0.0.6
4 | url = https://github.com/Hornwitser/factorio_tools
5 | author = Hornwitser
6 | author_email = github@hornwitser.no
7 | description = Tools for Debugging Factorio
8 | long_description = file: README.rst
9 | classifiers =
10 | Development Status :: 3 - Alpha
11 | Intended Audience :: Developers
12 | Environment :: Console
13 | License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)
14 | Programming Language :: Python :: 3
15 | Operating System :: Microsoft :: Windows
16 | Topic :: Utilities
17 |
18 | [options]
19 | zip_safe = True
20 | packages = hornwitser.factorio_tools
21 | python_requires = >=3.7
22 | install_requires =
23 | construct>=2.10.53
24 |
25 |
--------------------------------------------------------------------------------