├── .editorconfig ├── .gitignore ├── .gitmodules ├── .vscode ├── launch.json └── settings.json ├── LICENSE ├── MD33ToMD34.py ├── README.md ├── __init__.py ├── cm ├── __init__.py ├── base.py ├── material.py └── projection.py ├── common.py ├── createChangeLog.py ├── im ├── __init__.py └── material.py ├── listOffsets.py ├── m3.py ├── m3ToXml.py ├── m3export.py ├── m3import.py ├── shared.py ├── structures.xml ├── transferAnimationIds.py ├── transferAnimations.py ├── ui ├── __init__.py ├── base.py └── projection.py └── xmlToM3.py /.editorconfig: -------------------------------------------------------------------------------- 1 | ; EditorConfig helps developers define and maintain consistent 2 | ; coding styles between different editors and IDEs. 3 | 4 | ; For more visit http://editorconfig.org. 5 | root = true 6 | 7 | ; Choose between lf or rf on "end_of_line" property 8 | [*] 9 | indent_style = space 10 | end_of_line = lf 11 | charset = utf-8 12 | trim_trailing_whitespace = true 13 | insert_final_newline = true 14 | 15 | [*.{py,xml}] 16 | indent_size = 4 17 | 18 | [*.md] 19 | trim_trailing_whitespace = false 20 | indent_size = 2 21 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # py 2 | *~ 3 | *.pyc 4 | __pycache__ 5 | 6 | # tmp test junk 7 | test/ 8 | logs/ 9 | 10 | # m3xml to exe 11 | build/ 12 | dist/ 13 | 14 | # working docs 15 | TODO.md 16 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "blender_autocomplete"] 2 | path = blender_autocomplete 3 | url = https://github.com/Korchy/blender_autocomplete.git 4 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "inputs": [ 7 | { 8 | "type": "promptString", 9 | "id": "modelFilename", 10 | "description": "filename of m3", 11 | "default": "test/model.m3" 12 | }, 13 | { 14 | "type": "pickString", 15 | "description": "script name", 16 | "id": "scriptName", 17 | "options": [ 18 | "m3ToXml", 19 | "xmlToM3", 20 | "MD33ToMD34", 21 | ] 22 | }, 23 | ], 24 | "configurations": [ 25 | { 26 | "name": "Launch: M3 to XML", 27 | "type": "python", 28 | "request": "launch", 29 | "program": "${workspaceFolder}/m3ToXml.py", 30 | "cwd": "${workspaceFolder}", 31 | "args": [ 32 | "${input:modelFilename}" 33 | ] 34 | }, 35 | { 36 | "name": "Launch: MD33ToMD34", 37 | "type": "python", 38 | "request": "launch", 39 | "program": "${workspaceFolder}/MD33ToMD34.py", 40 | "cwd": "${workspaceFolder}", 41 | "args": [ 42 | "${input:modelFilename}" 43 | ], 44 | }, 45 | { 46 | // Attach to running Blender using: 47 | // https://github.com/AlansCodeLog/blender-debugger-for-vscode 48 | "name": "Attach to Blender", 49 | "type": "python", 50 | "request": "attach", 51 | "port": 5678, 52 | "host": "localhost" 53 | }, 54 | ] 55 | } 56 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "python.autoComplete.extraPaths": [ 3 | "blender_autocomplete/2.91" 4 | ], 5 | "python.linting.pylintArgs": [ 6 | "--init-hook", 7 | "import sys; sys.path.append('blender_autocomplete/2.91')" 8 | ], 9 | // "python.analysis.logLevel": "Trace", 10 | "python.languageServer": "Microsoft", 11 | 12 | "python.linting.enabled": true, 13 | "python.linting.pylintEnabled": false, 14 | "python.linting.flake8Enabled": true, 15 | "python.linting.flake8CategorySeverity.F": "Warning", 16 | "python.linting.flake8CategorySeverity.E": "Warning", 17 | "python.linting.flake8CategorySeverity.W": "Hint", 18 | "python.linting.flake8Args": [ 19 | "--max-line-length=140", 20 | "--ignore=E501,", // pedanting stuff 21 | "--extend-ignore=F722,F821", // false positive bullshit 22 | ], 23 | 24 | "python.formatting.provider": "autopep8", 25 | "python.formatting.autopep8Args": [ 26 | "--max-line-length=160", 27 | ], 28 | 29 | "[python]": { 30 | "editor.formatOnSave": false, 31 | }, 32 | 33 | "files.exclude": { 34 | "**/build": true, 35 | "**/dist": true, 36 | "**/blender_autocomplete": true, 37 | }, 38 | "search.exclude": { 39 | "**/test": true, 40 | }, 41 | } 42 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /MD33ToMD34.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # -*- coding: utf-8 -*- 3 | 4 | # ##### BEGIN GPL LICENSE BLOCK ##### 5 | # 6 | # This program is free software; you can redistribute it and/or 7 | # modify it under the terms of the GNU General Public License 8 | # as published by the Free Software Foundation; either version 2 9 | # of the License, or (at your option) any later version. 10 | # 11 | # This program is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU General Public License for more details. 15 | # 16 | # You should have received a copy of the GNU General Public License 17 | # along with this program; if not, write to the Free Software Foundation, 18 | # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 19 | # 20 | # ##### END GPL LICENSE BLOCK ##### 21 | 22 | import m3 23 | import argparse 24 | import os.path 25 | from typing import Optional 26 | import os 27 | 28 | 29 | def structureToMD34(structure: m3.M3Structure): 30 | structure.structureDescription = m3.structures[structure.structureDescription.structureName].getVersion(structure.structureDescription.structureVersion) 31 | for field in structure.structureDescription.fields: 32 | value = getattr(structure, field.name) 33 | if isinstance(value, list) and len(value) > 0: 34 | for subValue in value: 35 | if isinstance(subValue, m3.M3Structure): 36 | structureToMD34(subValue) 37 | elif isinstance(subValue, (int, float, list, str, bytes, bytearray)) or subValue is None: 38 | pass 39 | else: 40 | raise Exception(field.name, type(subValue), subValue) 41 | elif isinstance(value, m3.M3Structure): 42 | structureToMD34(value) 43 | elif isinstance(value, (int, float, list, str, bytes, bytearray)) or value is None: 44 | pass 45 | else: 46 | raise Exception(field.name, type(value), value) 47 | 48 | 49 | def processModel(mSrc: str, mDest: Optional[str] = None, outDir: Optional[str] = None, skipExisting: bool = False): 50 | if not outDir: 51 | outDir = os.path.dirname(mSrc) 52 | if not mDest: 53 | tmp = os.path.basename(mSrc).split('.') 54 | name = ''.join(tmp[:-1]) if len(tmp) > 1 else tmp[0] 55 | mDest = os.path.join(outDir, name + '_MD34.m3') 56 | 57 | print("%s -> %s ... " % (mSrc, mDest), end='') 58 | 59 | if skipExisting and os.path.isfile(mDest): 60 | print("SKIPPED") 61 | return 62 | 63 | try: 64 | model = m3.loadModel(mSrc) 65 | structureToMD34(model) 66 | m3.saveAndInvalidateModel(model, mDest) 67 | print("OK") 68 | except Exception: 69 | print("FAIL") 70 | raise 71 | 72 | 73 | if __name__ == '__main__': 74 | parser = argparse.ArgumentParser(description='Convert Starcraft II Beta model (MD33) to its supported variant (MD34)') 75 | parser.add_argument('src', type=str, nargs='+', help='source .m3 file') 76 | parser.add_argument('-O', '--output-directory', type=str, help='output directory for converted m3 files') 77 | parser.add_argument('--skip-existing', action='store_true', default=False, help='skip conversion if target field already exists') 78 | args = parser.parse_args() 79 | for src in args.src: 80 | processModel(src, None, args.output_directory, args.skip_existing) 81 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | **⚠️ THIS SOFTWARE IS OBSOLETE AND NO LONGER MAINTAINED ⚠️** 2 | 3 | --- 4 | 5 | * 🚨 DOESN'T WORK WITH BLENDER VERSIONS NEWER THAN **BLENDER v3.6** \ 6 | *(was tested and developed on earlier releases of v3.x)* 7 | * 🔥 RECOMMENDED REPLACEMENT 🔗 [**M3Studio**](https://github.com/Solstice245/m3studio) \ 8 | *(keep in mind it *might* not work on a bleeding edge releaeses of Blender either - consult its docs or issues tab)* 9 | 10 | > If you wanna learn more, head to: [State of the development. And why you shouldn't use this addon anymore](https://github.com/SC2Mapster/m3addon/issues/48). 11 | 12 | --- 13 | 14 | **⚠️ THIS SOFTWARE IS OBSOLETE AND NO LONGER MAINTAINED ⚠️** 15 | 16 | # m3addon - Blender Import-Export for m3 file format. 17 | 18 | **Blender** addon to **import and export** models in **`.m3`** format, which is used in Blizzard's games: **StarCraft II** and **Heroes of the Storm**. 19 | 20 | >Originally made by: [Florian Köberle](https://github.com/flo/m3addon) *(aka "println")*. 21 | 22 | ## Installation 23 | 24 | 1. Download: 25 | * **[Most recent version](https://github.com/SC2Mapster/m3addon/archive/master.zip)** 26 | * Older versions, no longer maintained: 27 | * [Blender 2.7X](https://github.com/SC2Mapster/m3addon/archive/blender-2.7.zip) 28 | 2. Install addon using one of the methods: 29 | * __Option A__ (automatic): 30 | * From Blender menu, navigate to `Edit -> Preferences`. Then `Add-ons` tab. 31 | * Click on the `Install` button and point it to downloaded zipfile. 32 | * __Option B__ (manual): 33 | * Extract zipfile to `m3addon` directory which should be placed in following location: 34 | * Windows:\ 35 | `%APPDATA%\Blender Foundation\Blender\2.80\scripts\addons` 36 | * Linux: \ 37 | `~/.config/blender/2.80/scripts/addons` 38 | * *(If addon won't appear as a choice in the Blender's preferences, click `Refresh` button or restart the application.)* 39 | 3. Activate the addon in Blender preferences: toggle on the checkbox `[✓]` for `m3addon` entry in Add-ons tab. 40 | 41 | ![](https://i.imgur.com/Jpp075Q.png) 42 | 43 | ### Useful links 44 | 45 | * [Bug tracker](https://github.com/SC2Mapster/m3addon/issues): Encountered a bug? Feel free to report, but please include any relevant details. For general import/export related bugs, **provide a name of the model**. Assuming it comes from either StarCraft II or Heroes of the Storm, the filename is enough - we can obtain the file(s) from local installation directory to reproduce the issue. 46 | * [SC2Mapster Discord Server](https://discord.gg/fpY4exB): Gathers a small community of people familiar with this addon (channel `#artisttavern`). That's the place to go for some general guidance and support. 47 | 48 | ## Features 49 | 50 | The Python scripts can be used as a Blender addon. 51 | 52 | Currently, the following content can be exported and imported: 53 | 54 | * Animations 55 | * Meshes with up to 4 UV layers 56 | * The following known M3 materials: 57 | * standard materials 58 | * displacement materials 59 | * composite materials 60 | * terrain materials 61 | * volume materials 62 | * creep materials 63 | * volume noise materials 64 | * splat terrain bake materials 65 | * M3 particle systems 66 | * M3 forces 67 | * M3 attachment points and volumes 68 | * M3 cameras 69 | * M3 lights 70 | * M3 rigid bodies 71 | * M3 physics joints 72 | * M3 projections 73 | * M3 ribbons 74 | * M3 billboard behaviors 75 | * M3 turret behaviors 76 | * M3 inverse kinematic chains 77 | 78 | The script `m3ToXml.py` can also be used to convert an m3 file into an XML file. It 79 | takes an m3 file as an argument and prints the XML on the command line. 80 | 81 | The script `xmlToM3.py` can convert the XML files exported by `m3ToXml.py` 82 | back into an m3 file. 83 | 84 | The file structures.xml gets used by the `m3.py` library to parse the m3 files. 85 | Modifying this XML file will have an impact on the above scripts and the Blender addon. 86 | 87 | ## Usage 88 | 89 | The Blender addon adds panels to the scene tab of the properties editor. 90 | 91 | To create a particle system and preview it in the Starcraft 2 editor you can perform the following steps: 92 | 93 | 1. Add an animation sequence by clicking on `+` in the `M3 Animation Sequences` panel 94 | 2. Add a material by clicking on `+` in the `M3 Materials` panel 95 | 3. Select a diffuse image: 96 | 1. Select `Diffuse` in the `M3 Materials Layer` panel 97 | 1. Specify an image path like `Assets/Textures/Glow_Blue2.dds` in the `M3 Materials Layer` panel 98 | 4. Add a particle system by clicking on `+` in the `M3 Particle Systems` panel 99 | 5. Validate that your particle system has a valid material selected 100 | 6. Specify an absolute file path in the `M3 Quick Export` panel 101 | 7. Click on `Export As M3` in the `M3 Quick Export` panels 102 | 8. Open the previewer in the Starcraft 2 editor by using the menu `Window/Previewer` 103 | 9. Use the previewer menu "File/Add File" to preview the exported model in the SC2 Editor 104 | 105 | ## Some Blender Tipps: 106 | 107 | * You can right click on UI elements to view the source code which displays that element. 108 | * File/Save User Settings can be used to determine the default state of Blender. 109 | * You can save your export path this way! 110 | * You can make yourself a default view that shows SC2 properties panels where you want them 111 | 112 | ## About the Implementation 113 | 114 | * The `m3.py` file is a python library for reading and writing m3 files. It uses the structures.xml file to do so. 115 | * The file structures.xml specifies how the script should parse and export an m3 file 116 | * The importing of m3 files works like this: 117 | 1. The method loadModel of the `m3.py` file gets called to create a python data structure of the m3 file content. 118 | 2. This data structure gets then used to create corresponding Blender data structures 119 | * The exporting works the other way round: 120 | 1. The data structures of Blender get used to create `m3.py` data structures that represent an m3 file. 121 | 2. The method saveAndInvalidateModel of the `m3.py` file gets used to convert the latter data structure into an m3 file. 122 | 123 | ### About the m3 file format and the `structures.xml` file 124 | 125 | The m3 file format is a list of sections. Each section contains an array of a certain structure in a certain version. 126 | 127 | The first section of an m3 file contains always a single structure of type `MD34` in version 11. It is defined at the bottom of the `structures.xml` file: 128 | 129 | ```xml 130 | 131 | Header of a M3 file: Can be found at the start of the file. 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | ``` 143 | 144 | Structures may reference other sections via a data structure called Reference (or SmallReference in some exceptions). 145 | 146 | The `MD34` structure for example has a field called model, that is referencing a `MODL` structure within another section. To which structure type a reference is pointing is indicated by the refTo field. 147 | 148 | References typically do not however reference a single structure, but the whole section and thus an array of structures. Thus theoretically a `MD34` structure could reference multiple `MODL` structures but that has never been observed in a valid m3 file. 149 | 150 | The `m3.py` file requires all structures to be first defined in the `structures.xml` file before they get used/referenced by another structure. For this reason, the structure `MD34` is defined at the bottom. 151 | 152 | An m3 file contains also an index/overview about those sections it contains, which can be found at the location specified by indexOffset and indexSize. If you want to get a list of the sections in an m3 file programmatic wise you can use the `m3.py` method `loadSections(filename)`. 153 | 154 | However, it is usually easier to just work with a tree-like representation of the `MODL` structure in which all references to structure arrays have been replaced by a list of the section that got referenced. This is possible via the `m3.py` python function `loadModel(filename)`. 155 | 156 | ### Definition of structure elements in the `structures.xml` file 157 | 158 | A structure definition defines a structure for all versions that exist of it: 159 | 160 | For the creep material for example (structure name `CREP`) 2 versions exist that have different sizes. In the `structures.xml` file there is however just a single structure definition: 161 | 162 | ```xml 163 | 164 | Creep Material 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | ``` 176 | 177 | The `` block contains a `` element for all known versions of that structure. For each structure, the 178 | size needs to be known and defined in the `` element. When an m3 file contains a version of a structure that is not yet known, an exception will be thrown and information about the structure will be logged that contains also a guess on the size of the structure. 179 | 180 | A newer version of a structure might have additional fields. The attribute `since-version` can be used to indicate that a field exists since a certain version. The attribute `till-version` can be used to indicate that a field exists only till a certain version of the structure. 181 | 182 | The `m3.py` file checks that the defined fields have indeed the sizes specified in the `` elements. So when you add a new version you probably also need to find out what new fields got added and which fields stayed the same. 183 | 184 | A field needs either to have a size or type attribute. The type attribute can be one of the following primitive types: 185 | 186 | * uint32: a 32 bit unsigned integer 187 | * int32: a 32 bit signed integer 188 | * int16: a 16 bit signed integer 189 | * uint8: an 8 bit unsigned integer 190 | * uint8: an 8 bit signed integer 191 | * float: a classical floating point type that fits in 32 bit 192 | * tag: Up to 4 characters that are used to store structure names 193 | * fixed8: a fixed point value that gets stored in 8 bits 194 | 195 | In addition to that, all structures that got defined above the structure in the `structures.xml` file can be also be used as type. However, a Version suffix with V + version number needs to be added to the structure name. e.g. VEC3V0 to get version 0 of the structure VEC3. 196 | 197 | ### Common Errors and how to fix them 198 | 199 | > `Exception: XYZ_V4.unknown0 has value 42 instead of the expected value int(0)` 200 | 201 | In the `structures.xml` file, it's configured what structures exist, what fields those structures have, and what their default or expected value is. The exceptions mean that the field "unknown0" of the structure `XYZ_` has been configured in the `structures.xml` file to be 0, but it was actually 42. 202 | 203 | For each structure exists an XML element in the `structures.xml` file. Just search for the structure name (`XYZ_` in the example) to find it. In the structure xml element there are field elements. 204 | 205 | To fix the given error message we would search in the structure element for the field with the name attribute `unknown0` and would replace the attribute `expected-value="0"` with `default-value="0"`. 206 | 207 | --- 208 | 209 | > `Exception: There were 1 unknown sections` 210 | 211 | The error message means that the m3 file contained a structure that it is unknown to the script since it has not been defined in the `structures.xml` file. 212 | 213 | You can fix the error message by defining the unknown section. To do that have a look at the log, it will contain a message like this: 214 | 215 | `ERROR: Unknown section at offset 436124 with tag=XYZ_ version=1 repetitions=2 sectionLengthInBytes=32 guessedUnusedSectionBytes=4 guessedBytesPerEntry=14.0` 216 | 217 | The error message means that it found a section in the m3 file that contains two (repetitions=2) entries of type XYZ_. The script guesses that 4 bytes are unused and knowns that the section is 32 bytes long. So it calculates `2*X-4=32` where X is the number of guessed bytes per entry. 218 | 219 | The result of this calculation is printed at the end "guessedBytesPerEntry=14.0". So the script guesses that version 1 of the structure `XYZ_` is 14 bytes long. 220 | 221 | To fix this error you would have to define the structure `XYZ_` in version 1 in the `structures.xml` file. See the section about the `structures.xml` file to learn about how to do that. 222 | 223 | --- 224 | 225 | > `Field ABCDV7.xyz can be marked as a reference pointing to XYZ_V1`: 226 | 227 | To fix this example error message, we would search in the `structures.xml` file for a structure called "ABCD" with the attribute version="7". 228 | 229 | It will contain a xml element field with the attribute name="xyz". To this field we would add an attribute refTo="XYZ_V1". 230 | 231 | --- 232 | 233 | > `Exception: Unable to load all data: There were 1 unreferenced sections. View log for details` 234 | 235 | When this error occurs, you will find in the log a message like this: 236 | 237 | `WARNING: XYZ_V1 (2 repetitions) got 0 times referenced` 238 | 239 | Every section in an m3 file gets usually referenced exactly 1 time(except for the header). The error message means that there is a section that contains 2 structures of type XYZ_ in version 1, but which got not referenced from anywhere. Most likely there is actually a reference to this section, but it hasn't been configured as such in the `structures.xml` file. 240 | 241 | If you are lucky, then there will be exactly 1 line below the former warning which looks like this: 242 | 243 | `-> Found a reference at offset 56 in a section of type ABCDV7` 244 | 245 | To fix the error message we need to change the structure definition of ABCD in version 7 to contain a field definition like this: 246 | 247 | `` 248 | -------------------------------------------------------------------------------- /cm/__init__.py: -------------------------------------------------------------------------------- 1 | # ##### BEGIN GPL LICENSE BLOCK ##### 2 | # 3 | # This program is free software; you can redistribute it and/or 4 | # modify it under the terms of the GNU General Public License 5 | # as published by the Free Software Foundation; either version 2 6 | # of the License, or (at your option) any later version. 7 | # 8 | # This program is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | # GNU General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU General Public License 14 | # along with this program; if not, write to the Free Software Foundation, 15 | # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 16 | # 17 | # ##### END GPL LICENSE BLOCK ##### 18 | 19 | from .base import * 20 | from .material import * 21 | from .projection import * 22 | -------------------------------------------------------------------------------- /cm/base.py: -------------------------------------------------------------------------------- 1 | # ##### BEGIN GPL LICENSE BLOCK ##### 2 | # 3 | # This program is free software; you can redistribute it and/or 4 | # modify it under the terms of the GNU General Public License 5 | # as published by the Free Software Foundation; either version 2 6 | # of the License, or (at your option) any later version. 7 | # 8 | # This program is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | # GNU General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU General Public License 14 | # along with this program; if not, write to the Free Software Foundation, 15 | # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 16 | # 17 | # ##### END GPL LICENSE BLOCK ##### 18 | 19 | import bpy 20 | from .. import shared 21 | 22 | 23 | class ExportM3ContainerVersion: 24 | V23 = "23" 25 | V26 = "26" 26 | V29 = "29" 27 | 28 | 29 | ExportContainerM3VersionList = [ 30 | (ExportM3ContainerVersion.V23, "V23 (*stable*)", "Super old, but somewhat working. It was default export format till 2021."), 31 | (ExportM3ContainerVersion.V26, "V26 (beta)", "Semi old, but with more features available, however it hasn't been tested thoroughly."), 32 | (ExportM3ContainerVersion.V29, "V29 (alpha)", "Newest available for SC2. WIP.") 33 | ] 34 | 35 | animationExportAmount = [ 36 | (shared.exportAmountAllAnimations, "All animations", "All animations will be exported"), 37 | (shared.exportAmountCurrentAnimation, "Current animation", "Only the current animation will be exported"), 38 | # Possible future additions: CURRENT_FRAME or FIRST_FRAME 39 | (shared.exportAmountNoAnimations, "None", "No animations at all") 40 | ] 41 | 42 | 43 | class M3ExportOptions(bpy.types.PropertyGroup): 44 | path: bpy.props.StringProperty(name="path", default="ExportedModel.m3", options=set()) 45 | modlVersion: bpy.props.EnumProperty(name="M3 Version", default=ExportM3ContainerVersion.V26, items=ExportContainerM3VersionList, options=set()) 46 | animationExportAmount: bpy.props.EnumProperty(name="Animations", default=shared.exportAmountAllAnimations, items=animationExportAmount, options=set()) 47 | 48 | 49 | class M3ImportContentPreset: 50 | Everything = "EVERYTHING" 51 | MeshMaterialsRig = "MESH_MATERIALS_RIG" 52 | MeshMaterialsVG = "MESH_MATERIALS_VERTEX_GROUP" 53 | MeshMaterials = "MESH_MATERIALS" 54 | Custom = "CUSTOM" 55 | # CustomInteractive = "CUSTOM_INTERACTIVE" 56 | 57 | 58 | contentImportPresetList = [ 59 | (M3ImportContentPreset.Everything, "Everything", "Import everything included in the m3 file"), 60 | (M3ImportContentPreset.MeshMaterialsRig, "Mesh, vertex groups, rigging & materials", "Import the mesh, materials and rigging. When using this preset you'll likely want to merge imported rig with existing armature."), 61 | (M3ImportContentPreset.MeshMaterialsVG, "Mesh, vertex groups & materials", "Import the mesh with vertex groups and associated materials."), 62 | (M3ImportContentPreset.MeshMaterials, "Mesh with materials only", "Import just the mesh and associated materials."), 63 | # (M3ImportContentPreset.Custom, "Custom", "Customize what's being imported"), 64 | ] 65 | 66 | 67 | class M3ImportContent(bpy.types.PropertyGroup): 68 | mesh: bpy.props.BoolProperty( 69 | name="Mesh", 70 | default=True, 71 | options=set() 72 | ) 73 | materials: bpy.props.BoolProperty( 74 | name="Materials", 75 | default=True, 76 | options=set() 77 | ) 78 | bones: bpy.props.BoolProperty( 79 | name="Bones", 80 | default=True, 81 | options=set() 82 | ) 83 | rigging: bpy.props.BoolProperty( 84 | name="Rigging", 85 | description="Includes vertex groups & weight painting", 86 | default=True, 87 | options=set() 88 | ) 89 | cameras: bpy.props.BoolProperty( 90 | name="Cameras", 91 | default=True, 92 | options=set() 93 | ) 94 | fuzzyHitTests: bpy.props.BoolProperty( 95 | name="Fuzzy hit tests", 96 | default=True, 97 | options=set() 98 | ) 99 | tightHitTest: bpy.props.BoolProperty( 100 | name="Tight hit test", 101 | default=True, 102 | options=set() 103 | ) 104 | particleSystems: bpy.props.BoolProperty( 105 | name="Particle systems", 106 | default=True, 107 | options=set() 108 | ) 109 | ribbons: bpy.props.BoolProperty( 110 | name="Ribbons", 111 | default=True, 112 | options=set() 113 | ) 114 | forces: bpy.props.BoolProperty( 115 | name="Forces", 116 | default=True, 117 | options=set() 118 | ) 119 | rigidBodies: bpy.props.BoolProperty( 120 | name="Rigid bodies", 121 | default=True, 122 | options=set() 123 | ) 124 | lights: bpy.props.BoolProperty( 125 | name="Lights", 126 | default=True, 127 | options=set() 128 | ) 129 | billboardBehaviors: bpy.props.BoolProperty( 130 | name="Billboard behaviors", 131 | default=True, 132 | options=set() 133 | ) 134 | attachmentPoints: bpy.props.BoolProperty( 135 | name="Attachment points", 136 | default=True, 137 | options=set() 138 | ) 139 | projections: bpy.props.BoolProperty( 140 | name="Projections", 141 | default=True, 142 | options=set() 143 | ) 144 | warps: bpy.props.BoolProperty( 145 | name="Warps", 146 | default=True, 147 | options=set() 148 | ) 149 | 150 | 151 | def handleContentPresetChange(options, context: bpy.types.Context): 152 | options = options # type: M3ImportOptions 153 | content: M3ImportContent = options.content 154 | # content.mesh = True 155 | 156 | 157 | class M3ImportOptions(bpy.types.PropertyGroup): 158 | path: bpy.props.StringProperty(name="path", default="", options=set()) 159 | rootDirectory: bpy.props.StringProperty(name="rootDirectory", default="", options=set()) 160 | generateBlenderMaterials: bpy.props.BoolProperty(default=True, options=set()) 161 | applySmoothShading: bpy.props.BoolProperty(default=True, options=set()) 162 | markSharpEdges: bpy.props.BoolProperty(default=True, options=set()) 163 | recalculateRestPositionBones: bpy.props.BoolProperty(default=False, options=set()) 164 | teamColor: bpy.props.FloatVectorProperty( 165 | default=(1.0, 0.0, 0.0), min=0.0, max=1.0, name="team color", size=3, subtype="COLOR", options=set(), 166 | description="Team color place holder used for generated blender materials" 167 | ) 168 | contentPreset: bpy.props.EnumProperty( 169 | name="Import preset mode", 170 | description="Content import mode", 171 | default="EVERYTHING", 172 | items=contentImportPresetList, 173 | options=set(), 174 | update=handleContentPresetChange, 175 | ) 176 | content: bpy.props.PointerProperty( 177 | type=M3ImportContent, 178 | ) 179 | armatureObject: bpy.props.PointerProperty( 180 | type=bpy.types.Object, 181 | name="Armature", 182 | description="Defines which armature object should be used when importing rigging. If unset, a new one will be created.", 183 | options=set(), 184 | poll=lambda self, obj: obj.type == 'ARMATURE' and obj.data is not self 185 | ) 186 | -------------------------------------------------------------------------------- /cm/material.py: -------------------------------------------------------------------------------- 1 | # ##### BEGIN GPL LICENSE BLOCK ##### 2 | # 3 | # This program is free software; you can redistribute it and/or 4 | # modify it under the terms of the GNU General Public License 5 | # as published by the Free Software Foundation; either version 2 6 | # of the License, or (at your option) any later version. 7 | # 8 | # This program is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | # GNU General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU General Public License 14 | # along with this program; if not, write to the Free Software Foundation, 15 | # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 16 | # 17 | # ##### END GPL LICENSE BLOCK ##### 18 | 19 | import bpy 20 | from . import shared 21 | 22 | 23 | blenderMaterialsFieldNames = { 24 | shared.standardMaterialTypeIndex: "m3_standard_materials", 25 | shared.displacementMaterialTypeIndex: "m3_displacement_materials", 26 | shared.compositeMaterialTypeIndex: "m3_composite_materials", 27 | shared.terrainMaterialTypeIndex: "m3_terrain_materials", 28 | shared.volumeMaterialTypeIndex: "m3_volume_materials", 29 | shared.creepMaterialTypeIndex: "m3_creep_materials", 30 | shared.volumeNoiseMaterialTypeIndex: "m3_volume_noise_materials", 31 | shared.stbMaterialTypeIndex: "m3_stb_materials", 32 | # TODO: reflection material 33 | shared.lensFlareMaterialTypeIndex: "m3_lens_flare_materials", 34 | shared.bufferMaterialTypeIndex: "m3_buffer_materials", 35 | } 36 | 37 | uvSourceList = [ 38 | ("0", "Default", "First UV layer of mesh or generated whole image UVs for particles"), 39 | ("1", "UV Layer 2", "Second UV layer which can be used for decals"), 40 | ("2", "Ref Cubic Env", "For Env. Layer: Reflective Cubic Environment"), 41 | ("3", "Ref Spherical Env", "For Env. Layer: Reflective Spherical Environemnt"), 42 | ("4", "Planar Local z", "Planar Local z"), 43 | ("5", "Planar World z", "Planar World z"), 44 | ("6", "Animated Particle UV", "The flip book of the particle system is used to determine the UVs"), 45 | ("7", "Cubic Environment", "For Env. Layer: Cubic Environment"), 46 | ("8", "Spherical Environment", "For Env. Layer: Spherical Environment"), 47 | ("9", "UV Layer 3", "UV Layer 3"), 48 | ("10", "UV Layer 4", "UV Layer 4"), 49 | ("11", "Planar Local X", "Planar Local X"), 50 | ("12", "Planar Local Y", "Planar Local Y"), 51 | ("13", "Planar World X", "Planar World X"), 52 | ("14", "Planar World Y", "Planar World Y"), 53 | ("15", "Screen space", "Screen space"), 54 | ("16", "Tri Planar World", "Tri Planar World"), 55 | ("17", "Tri Planar World Local", "Tri Planar Local"), 56 | ("18", "Tri Planar World Local Z", "Tri Planar World Local Z") 57 | ] 58 | 59 | rttChannelList = [ 60 | ("-1", "None", "None"), 61 | ("0", "Layer 1", "Render To Texture Layer 1"), 62 | ("1", "Layer 2", "Render To Texture Layer 2"), 63 | ("2", "Layer 3", "Render To Texture Layer 3"), 64 | ("3", "Layer 4", "Render To Texture Layer 4"), 65 | ("4", "Layer 5", "Render To Texture Layer 5"), 66 | ("5", "Layer 6", "Render To Texture Layer 6"), 67 | ("6", "Layer 7", "Render To Texture Layer 7"), 68 | ] 69 | 70 | colorChannelSettingList = [ 71 | (shared.colorChannelSettingRGB, "RGB", "Use red, green and blue color channel"), 72 | (shared.colorChannelSettingRGBA, "RGBA", "Use red, green, blue and alpha channel"), 73 | (shared.colorChannelSettingA, "Alpha Only", "Use alpha channel only"), 74 | (shared.colorChannelSettingR, "Red Only", "Use red color channel only"), 75 | (shared.colorChannelSettingG, "Green Only", "Use green color channel only"), 76 | (shared.colorChannelSettingB, "Blue Only", "Use blue color channel only") 77 | ] 78 | 79 | fresnelTypeList = [ 80 | ("0", "Disabled", "Fresnel is disabled"), 81 | ("1", "Enabled", "Strength of layer is based on fresnel formula"), 82 | ("2", "Enabled; Inverted", "Strenth of layer is based on inverted fresnel formula") 83 | ] 84 | 85 | videoModeList = [ 86 | ("0", "Loop", "Loop"), 87 | ("1", "Hold", "Hold") 88 | ] 89 | 90 | 91 | materialTexmapType = [ 92 | ("0", "Bitmap", "Bitmap"), 93 | ("1", "Color", "Color") 94 | ] 95 | 96 | 97 | class M3Material(bpy.types.PropertyGroup): 98 | name: bpy.props.StringProperty(name="name", default="Material", options=set()) 99 | materialType: bpy.props.IntProperty(options=set()) 100 | materialIndex: bpy.props.IntProperty(options=set()) 101 | 102 | 103 | class M3MaterialLayer(bpy.types.PropertyGroup): 104 | name: bpy.props.StringProperty(default="Material Layer") 105 | imagePath: bpy.props.StringProperty(name="image path", default="", options=set()) 106 | unknownbd3f7b5d: bpy.props.IntProperty(name="unknownbd3f7b5d", default=-1, options=set()) 107 | color: bpy.props.FloatVectorProperty(name="color", default=(1.0, 1.0, 1.0, 1.0), min=0.0, max=1.0, size=4, subtype="COLOR", options={"ANIMATABLE"}) 108 | textureWrapX: bpy.props.BoolProperty(options=set(), default=True) 109 | textureWrapY: bpy.props.BoolProperty(options=set(), default=True) 110 | invertColor: bpy.props.BoolProperty(options=set(), default=False) 111 | clampColor: bpy.props.BoolProperty(options=set(), default=False) 112 | colorEnabled: bpy.props.EnumProperty(items=materialTexmapType) 113 | uvSource: bpy.props.EnumProperty(items=uvSourceList, options=set(), default="0") 114 | brightMult: bpy.props.FloatProperty(name="bright. mult.", options={"ANIMATABLE"}, default=1.0) 115 | uvOffset: bpy.props.FloatVectorProperty(name="uv offset", default=(0.0, 0.0), size=2, subtype="XYZ", options={"ANIMATABLE"}) 116 | uvAngle: bpy.props.FloatVectorProperty(name="uv offset", default=(0.0, 0.0, 0.0), size=3, subtype="XYZ", options={"ANIMATABLE"}) 117 | uvTiling: bpy.props.FloatVectorProperty(name="uv tiling", default=(1.0, 1.0), size=2, subtype="XYZ", options={"ANIMATABLE"}) 118 | triPlanarOffset: bpy.props.FloatVectorProperty(name="tri planer offset", default=(0.0, 0.0, 0.0), size=3, subtype="XYZ", options={"ANIMATABLE"}) 119 | triPlanarScale: bpy.props.FloatVectorProperty(name="tri planer scale", default=(1.0, 1.0, 1.0), size=3, subtype="XYZ", options={"ANIMATABLE"}) 120 | flipBookRows: bpy.props.IntProperty(name="flipBookRows", default=0, options=set()) 121 | flipBookColumns: bpy.props.IntProperty(name="flipBookColumns", default=0, options=set()) 122 | flipBookFrame: bpy.props.IntProperty(name="flipBookFrame", default=0, options={"ANIMATABLE"}) 123 | midtoneOffset: bpy.props.FloatProperty(name="midtone offset", options={"ANIMATABLE"}, description="Can be used to make dark areas even darker so that only the bright regions remain") 124 | brightness: bpy.props.FloatProperty(name="brightness", options={"ANIMATABLE"}, default=1.0) 125 | rttChannel: bpy.props.EnumProperty(items=rttChannelList, options=set(), default="-1") 126 | colorChannelSetting: bpy.props.EnumProperty(items=colorChannelSettingList, options=set(), default=shared.colorChannelSettingRGB) 127 | fresnelType: bpy.props.EnumProperty(items=fresnelTypeList, options=set(), default="0") 128 | invertedFresnel: bpy.props.BoolProperty(options=set()) 129 | fresnelExponent: bpy.props.FloatProperty(default=4.0, options=set()) 130 | fresnelMin: bpy.props.FloatProperty(default=0.0, options=set()) 131 | fresnelMax: bpy.props.FloatProperty(default=1.0, options=set()) 132 | fresnelMaskX: bpy.props.FloatProperty(options=set(), min=0.0, max=1.0) 133 | fresnelMaskY: bpy.props.FloatProperty(options=set(), min=0.0, max=1.0) 134 | fresnelMaskZ: bpy.props.FloatProperty(options=set(), min=0.0, max=1.0) 135 | fresnelRotationYaw: bpy.props.FloatProperty(subtype="ANGLE", options=set()) 136 | fresnelRotationPitch: bpy.props.FloatProperty(subtype="ANGLE", options=set()) 137 | fresnelLocalTransform: bpy.props.BoolProperty(options=set(), default=False) 138 | fresnelDoNotMirror: bpy.props.BoolProperty(options=set(), default=False) 139 | videoFrameRate: bpy.props.IntProperty(options=set(), default=24) 140 | videoStartFrame: bpy.props.IntProperty(options=set(), default=0) 141 | videoEndFrame: bpy.props.IntProperty(options=set(), default=-1) 142 | videoMode: bpy.props.EnumProperty(items=videoModeList, options=set(), default="0") 143 | videoSyncTiming: bpy.props.BoolProperty(options=set()) 144 | videoPlay: bpy.props.BoolProperty(name="videoPlay", options={"ANIMATABLE"}, default=True) 145 | videoRestart: bpy.props.BoolProperty(name="videoRestart", options={"ANIMATABLE"}, default=True) 146 | 147 | 148 | def getMaterial(scene, materialTypeIndex, materialIndex) -> M3Material: 149 | try: 150 | blenderFieldName = blenderMaterialsFieldNames[materialTypeIndex] 151 | except KeyError: 152 | # unsupported material 153 | return None 154 | materialsList = getattr(scene, blenderFieldName) 155 | return materialsList[materialIndex] 156 | -------------------------------------------------------------------------------- /cm/projection.py: -------------------------------------------------------------------------------- 1 | # ##### BEGIN GPL LICENSE BLOCK ##### 2 | # 3 | # This program is free software; you can redistribute it and/or 4 | # modify it under the terms of the GNU General Public License 5 | # as published by the Free Software Foundation; either version 2 6 | # of the License, or (at your option) any later version. 7 | # 8 | # This program is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | # GNU General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU General Public License 14 | # along with this program; if not, write to the Free Software Foundation, 15 | # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 16 | # 17 | # ##### END GPL LICENSE BLOCK ##### 18 | 19 | import bpy 20 | from .. import shared 21 | 22 | 23 | class ProjectionType: 24 | orthonormal = "1" 25 | perspective = "2" 26 | 27 | 28 | ProjectionTypeList = [ 29 | (ProjectionType.orthonormal, "Orthonormal", "Makes the Projector behave like a box. It will be the same width no matter how close the projector is to the target surface."), 30 | (ProjectionType.perspective, "Perspective", "Makes the Projector behave like a camera. The closer the projector is to the surface, the smaller the effect will be.") 31 | ] 32 | 33 | 34 | class SplatLayer: 35 | material = "8" 36 | power = "7" 37 | aoe = "6" 38 | building = "4" 39 | layer3 = "3" 40 | layer2 = "2" 41 | layer1 = "1" 42 | layer0 = "0" 43 | underCreep = "12" 44 | hardtile = "11" 45 | 46 | 47 | SplatLayerEnum = [ 48 | (SplatLayer.material, "Material UI Layer", "Used for in-world effects that are part of the user interface. This includes selection circles and similar effects."), 49 | (SplatLayer.power, "Power Layer", "contains rarely active effects such as the Protoss power grid that should be above most other splats, but below UI."), 50 | (SplatLayer.aoe, "AOE Layer", "conventionally holds AOE cursors and some special spell effects."), 51 | (SplatLayer.building, "Building Layer", "is most often used for the dark shadow that occurs under buildings."), 52 | (SplatLayer.layer3, "Layer 3", "Is a generic layer that occurs above creep, that is open for use as the user sees fit. Spell effects, blast marks, or any other general case splats usually occur on a generic layer, and are adjusted freely between them to correct visual artifacts."), 53 | (SplatLayer.layer2, "Layer 2", "Is a generic layer that occurs above creep, that is open for use as the user sees fit. Spell effects, blast marks, or any other general case splats usually occur on a generic layer, and are adjusted freely between them to correct visual artifacts."), 54 | (SplatLayer.layer1, "Layer 1", "Is a generic layer that occurs above creep, that is open for use as the user sees fit. Spell effects, blast marks, or any other general case splats usually occur on a generic layer, and are adjusted freely between them to correct visual artifacts."), 55 | (SplatLayer.layer0, "Layer 0", "Is a generic layer that occurs above creep, that is open for use as the user sees fit. Spell effects, blast marks, or any other general case splats usually occur on a generic layer, and are adjusted freely between them to correct visual artifacts."), 56 | (SplatLayer.underCreep, "Under Creep Layer", "Is a general use layer that occurs below creep. It is most often used for effects that appear above roads but below creep."), 57 | (SplatLayer.hardtile, "Hardtile Layer", "Is the most common layer for visual additions like paint, grunge, or damage that appear to be part of the terrain texture. Roads are also drawn on this layer."), 58 | ] 59 | 60 | 61 | def updateBoneShapeOfProjection(projection, bone, poseBone): 62 | if projection.projectionType == ProjectionType.orthonormal: 63 | untransformedPositions, faces = shared.createMeshDataForCuboid(projection.width, projection.height, projection.depth) 64 | else: 65 | # TODO create correct mesh for perspective projection 66 | untransformedPositions, faces = shared.createMeshDataForSphere(1.0) 67 | 68 | boneName = bone.name 69 | meshName = boneName + 'Mesh' 70 | shared.updateBoneShape(bone, poseBone, meshName, untransformedPositions, faces) 71 | 72 | 73 | def selectOrCreateBoneForProjection(scene, projection): 74 | scene.m3_bone_visiblity_options.showProjections = True 75 | bone, poseBone = shared.selectOrCreateBone(scene, projection.boneName) 76 | updateBoneShapeOfProjection(projection, bone, poseBone) 77 | 78 | 79 | def handleProjectionSizeChange(self, context): 80 | if not self.bl_update: 81 | return 82 | 83 | scene = context.scene 84 | if self.updateBlenderBone: 85 | selectOrCreateBoneForProjection(scene, self) 86 | 87 | 88 | def handleProjectionIndexChanged(self: bpy.types.Scene, context: bpy.types.Context): 89 | scene = context.scene 90 | if scene.m3_projection_index == -1: 91 | return 92 | projection = scene.m3_projections[scene.m3_projection_index] 93 | selectOrCreateBoneForProjection(scene, projection) 94 | 95 | 96 | def onUpdateName(self, context): 97 | if not self.bl_update: 98 | return 99 | 100 | scene = context.scene 101 | 102 | currentBoneName = self.boneName 103 | calculatedBoneName = shared.boneNameForProjection(self) 104 | 105 | if currentBoneName != calculatedBoneName: 106 | bone, armatureObject = shared.findBoneWithArmatureObject(scene, currentBoneName) 107 | if bone is not None: 108 | bone.name = calculatedBoneName 109 | self.boneName = bone.name 110 | else: 111 | self.boneName = calculatedBoneName 112 | 113 | selectOrCreateBoneForProjection(scene, self) 114 | 115 | 116 | class M3Projection(bpy.types.PropertyGroup): 117 | name: bpy.props.StringProperty( 118 | options=set(), update=onUpdateName, 119 | ) 120 | boneName: bpy.props.StringProperty( 121 | options=set(), 122 | ) 123 | bl_update: bpy.props.BoolProperty( 124 | default=True, 125 | ) 126 | materialName: bpy.props.StringProperty( 127 | options=set(), 128 | ) 129 | projectionType: bpy.props.EnumProperty( 130 | default=ProjectionType.orthonormal, items=ProjectionTypeList, options=set(), 131 | update=handleProjectionSizeChange, 132 | name='Type', 133 | ) 134 | fieldOfView: bpy.props.FloatProperty( 135 | default=45.0, options={'ANIMATABLE'}, 136 | name='FOV', 137 | description='Represents the angle (in degrees) that defines the vertical bounds of the projector', 138 | ) 139 | aspectRatio: bpy.props.FloatProperty( 140 | default=1.0, options={'ANIMATABLE'}, 141 | name='Aspect Ratio', 142 | ) 143 | near: bpy.props.FloatProperty( 144 | default=0.5, options={'ANIMATABLE'}, 145 | name='Near', 146 | ) 147 | far: bpy.props.FloatProperty( 148 | default=10.0, options={'ANIMATABLE'}, 149 | name='Far', 150 | ) 151 | depth: bpy.props.FloatProperty( 152 | default=10.0, options=set(), update=handleProjectionSizeChange, 153 | name='Depth', 154 | ) 155 | width: bpy.props.FloatProperty( 156 | default=10.0, options=set(), update=handleProjectionSizeChange, 157 | name='Width', 158 | ) 159 | height: bpy.props.FloatProperty( 160 | default=10.0, options=set(), update=handleProjectionSizeChange, 161 | name='Height', 162 | ) 163 | alphaOverTimeStart: bpy.props.FloatProperty( 164 | default=0.0, min=0.0, max=1.0, options=set(), subtype="FACTOR", 165 | name='Alpha over time start', 166 | ) 167 | alphaOverTimeMid: bpy.props.FloatProperty( 168 | default=1.0, min=0.0, max=1.0, options=set(), subtype="FACTOR", 169 | name='Alpha over time mid', 170 | ) 171 | alphaOverTimeEnd: bpy.props.FloatProperty( 172 | default=0.0, min=0.0, max=1.0, options=set(), subtype="FACTOR", 173 | name='Alpha over time end', 174 | ) 175 | splatLifeTimeAttack: bpy.props.FloatProperty( 176 | default=1.0, min=0.0, options=set(), 177 | name='Splat Lifetime: Attack', 178 | ) 179 | splatLifeTimeAttackTo: bpy.props.FloatProperty( 180 | default=0.0, min=0.0, options=set(), 181 | name='Splat Lifetime: Attack To', 182 | ) 183 | splatLifeTimeHold: bpy.props.FloatProperty( 184 | default=1.0, min=0.0, options=set(), 185 | name='Splat Lifetime: Hold', 186 | ) 187 | splatLifeTimeHoldTo: bpy.props.FloatProperty( 188 | default=0.0, min=0.0, options=set(), 189 | name='Splat Lifetime: Hold To', 190 | ) 191 | splatLifeTimeDecay: bpy.props.FloatProperty( 192 | default=1.0, min=0.0, options=set(), 193 | name='Splat Lifetime: Decay', 194 | ) 195 | splatLifeTimeDecayTo: bpy.props.FloatProperty( 196 | default=0.0, min=0.0, options=set(), 197 | name='Splat Lifetime: Decay To', 198 | ) 199 | attenuationPlaneDistance: bpy.props.FloatProperty( 200 | default=1.0, min=0.0, options=set(), 201 | name='Attenuation Plane:', 202 | description=f'''\ 203 | Makes it so that the splat will fade out as the surface gets further from the projection source. \ 204 | When off, the projector will be at full opacity across its entire length. \ 205 | Attenuation starts at % distance' pushes the start of the attenuation further from the projection source, \ 206 | making the splat display at full opacity for more of its range. 0 is a standard linear attenuation from the source. \ 207 | 100% would be equivalent to not using attenuation at all.\ 208 | ''', 209 | ) 210 | active: bpy.props.BoolProperty( 211 | default=True, options={'ANIMATABLE'}, 212 | name='Alive', 213 | description=f'''\ 214 | Makes the Projector on by default. Most static splats will have this enabled. 215 | This may be off in the case of dynamically generated splats. 216 | Turning off this value will trigger the splat to fade out as defined by "Decay" (Splat Lifetimes).\ 217 | ''', 218 | ) 219 | splatLayer: bpy.props.EnumProperty( 220 | default=SplatLayer.hardtile, items=SplatLayerEnum, options=set(), 221 | name='Splat Layer', 222 | description=f''' 223 | Denotes the general sorting group of the Projector. This is used to sort overlapping splats so that everything looks correct. \ 224 | Note that Projectors that use SC2. \ 225 | SplatTerrainBake respect relative ordering with other projectors using that material type, \ 226 | but all draw 'below' splats using any other material type. 227 | 228 | The sort order of projectors in one layer is undefined, but the sort order between layers is well defined. \ 229 | The descriptions for the values below show them in order, where the first entry draws on top of all others, \ 230 | and the last entry is below all others.\ 231 | ''', 232 | ) 233 | lodCut: bpy.props.EnumProperty( 234 | items=shared.lodEnum, 235 | options=set(), 236 | name='LOD Cut', 237 | description=f''' 238 | Denotes which graphical setting level the Projector will no longer be displayed at. \ 239 | If critical for gameplay, leaving this at "None" is prudent. Otherwise, it is useful for performance scaling.\ 240 | ''', 241 | ) 242 | lodReduce: bpy.props.EnumProperty( 243 | items=shared.lodEnum, 244 | options=set(), 245 | name='LOD Reduction', 246 | description=f''' 247 | Denotes which graphical setting the Projector can potentially be not shown at if there are too many splats on screen. \ 248 | It is more critical to be judicious with allowing splats to disappear here, \ 249 | as it is best to leave room available for gameplay-critical splats.\ 250 | ''', 251 | ) 252 | staticPosition: bpy.props.BoolProperty( 253 | options=set(), 254 | name='Static Position', 255 | ) 256 | unknownFlag0x2: bpy.props.BoolProperty( 257 | options=set(), 258 | ) 259 | unknownFlag0x4: bpy.props.BoolProperty( 260 | options=set(), 261 | ) 262 | unknownFlag0x8: bpy.props.BoolProperty( 263 | options=set(), 264 | ) 265 | -------------------------------------------------------------------------------- /common.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os 3 | import logging 4 | import importlib.util 5 | 6 | 7 | is_blender = importlib.util.find_spec('bpy') is not None 8 | 9 | 10 | def create_logger(): 11 | m3log = logging.getLogger('m3addon') 12 | m3log.setLevel(logging.DEBUG) 13 | form = logging.Formatter( 14 | fmt='%(asctime)-15s,%(msecs)-3d %(levelname)-6s %(filename)s:%(lineno)s %(message)s' 15 | ) 16 | 17 | console_handler = logging.StreamHandler(sys.stderr) 18 | console_handler.setFormatter(form) 19 | m3log.addHandler(console_handler) 20 | 21 | fname = os.path.join(os.path.dirname(__file__), 'logs', 'output.log') 22 | if is_blender: 23 | try: 24 | os.makedirs(os.path.dirname(fname), exist_ok=True) 25 | file_handler = logging.FileHandler(fname, mode='w') 26 | m3log.addHandler(file_handler) 27 | except PermissionError: 28 | pass 29 | 30 | return m3log 31 | 32 | 33 | mlog = create_logger() 34 | -------------------------------------------------------------------------------- /createChangeLog.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # -*- coding: utf-8 -*- 3 | 4 | # ##### BEGIN GPL LICENSE BLOCK ##### 5 | # 6 | # This program is free software; you can redistribute it and/or 7 | # modify it under the terms of the GNU General Public License 8 | # as published by the Free Software Foundation; either version 2 9 | # of the License, or (at your option) any later version. 10 | # 11 | # This program is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU General Public License for more details. 15 | # 16 | # You should have received a copy of the GNU General Public License 17 | # along with this program; if not, write to the Free Software Foundation, 18 | # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 19 | # 20 | # ##### END GPL LICENSE BLOCK ##### 21 | 22 | import m3 23 | import sys 24 | import os.path 25 | import argparse 26 | import time 27 | 28 | modelFileName = sys.argv[1] 29 | 30 | 31 | class ChangeLogCreator: 32 | 33 | def __init__(self, modelFileName, logFileName): 34 | self.modelFileName = modelFileName 35 | self.logFileName = logFileName 36 | 37 | def createChangeLog(self): 38 | self.logFile = open(self.logFileName, "w") 39 | try: 40 | previousModelModiticationTime = os.path.getmtime(self.modelFileName) 41 | self.log("Log file started at %s" % time.ctime(previousModelModiticationTime)) 42 | previousModel = m3.loadModel(self.modelFileName, checkExpectedValue=False) 43 | while True: 44 | currentModelModificationTime = os.path.getmtime(self.modelFileName) 45 | if currentModelModificationTime > previousModelModiticationTime: 46 | self.log("") 47 | self.log("File modified at %s" % time.ctime(currentModelModificationTime)) 48 | currentModel = m3.loadModel(self.modelFileName) 49 | self.changedAnimationIds = 0 50 | self.compareM3Structures(previousModel, currentModel, "model") 51 | if self.changedAnimationIds > 0: 52 | self.log("%d animation ids have changed!" % self.changedAnimationIds) 53 | previousModelModiticationTime = currentModelModificationTime 54 | previousModel = currentModel 55 | time.sleep(0.1) 56 | finally: 57 | self.logFile.close() 58 | 59 | def compareM3Structures(self, previous, current, structurePath): 60 | previousType = previous.structureDescription 61 | currentType = current.structureDescription 62 | if currentType.structureName != previousType.structureName: 63 | self.log("%s changed its structure type from %s to %s" % (structurePath, previousType.structureName, currentType.structureName)) 64 | return 65 | 66 | if currentType.structureVersion != previousType.structureVersion: 67 | self.log("%s changed its structure version from %s to %s" % (structurePath, previousType.structureVersion, currentType.structureVersion)) 68 | return 69 | 70 | for field in previousType.fields: 71 | fieldPath = structurePath + "." + field.name 72 | previousFieldContent = getattr(previous, field.name) 73 | currentFieldContent = getattr(current, field.name) 74 | if isinstance(field, m3.EmbeddedStructureField): 75 | self.compareM3Structures(previousFieldContent, currentFieldContent, fieldPath) 76 | elif isinstance(field, m3.StructureReferenceField): 77 | currentLength = len(currentFieldContent) 78 | previousLength = len(previousFieldContent) 79 | if len(currentFieldContent) != previousLength: 80 | self.log("The length of %s changed from %d to %d" % (fieldPath, previousLength, currentLength)) 81 | else: 82 | elementIndex = 0 83 | for previousElement, currentElement in zip(previousFieldContent, currentFieldContent): 84 | elementPath = "%s[%d]" % (fieldPath, elementIndex) 85 | self.compareM3Structures(previousElement, currentElement, elementPath) 86 | elementIndex += 1 87 | else: 88 | 89 | if currentFieldContent != previousFieldContent: 90 | if field.name != "animId" and field.name != "uniqueUnknownNumber": 91 | if isinstance(field, m3.IntField): 92 | previousFieldContentStr = hex(previousFieldContent) 93 | currentFieldContentStr = hex(currentFieldContent) 94 | else: 95 | previousFieldContentStr = str(previousFieldContent) 96 | currentFieldContentStr = str(currentFieldContent) 97 | self.log("%s changed from %s to %s" % (fieldPath, previousFieldContentStr, currentFieldContentStr)) 98 | else: 99 | self.changedAnimationIds += 1 100 | 101 | def log(self, message): 102 | self.logFile.write(str(message) + "\n") 103 | print(message) 104 | 105 | 106 | if __name__ == "__main__": 107 | parser = argparse.ArgumentParser() 108 | parser.add_argument('m3File', help="The m3 file for which a change log should be created") 109 | parser.add_argument('--log-file', '-l', help='Directory in which m3 files will be placed') 110 | args = parser.parse_args() 111 | modelFileName = args.m3File 112 | logFileName = args.log_file 113 | if logFileName is None: 114 | logFileName = modelFileName[:-3] + "-changelog.txt" 115 | changeLogCreator = ChangeLogCreator(modelFileName, logFileName) 116 | changeLogCreator.createChangeLog() 117 | -------------------------------------------------------------------------------- /im/__init__.py: -------------------------------------------------------------------------------- 1 | # ##### BEGIN GPL LICENSE BLOCK ##### 2 | # 3 | # This program is free software; you can redistribute it and/or 4 | # modify it under the terms of the GNU General Public License 5 | # as published by the Free Software Foundation; either version 2 6 | # of the License, or (at your option) any later version. 7 | # 8 | # This program is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | # GNU General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU General Public License 14 | # along with this program; if not, write to the Free Software Foundation, 15 | # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 16 | # 17 | # ##### END GPL LICENSE BLOCK ##### 18 | 19 | from . import material 20 | -------------------------------------------------------------------------------- /im/material.py: -------------------------------------------------------------------------------- 1 | # ##### BEGIN GPL LICENSE BLOCK ##### 2 | # 3 | # This program is free software; you can redistribute it and/or 4 | # modify it under the terms of the GNU General Public License 5 | # as published by the Free Software Foundation; either version 2 6 | # of the License, or (at your option) any later version. 7 | # 8 | # This program is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | # GNU General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU General Public License 14 | # along with this program; if not, write to the Free Software Foundation, 15 | # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 16 | # 17 | # ##### END GPL LICENSE BLOCK ##### 18 | 19 | import bpy 20 | import bpy.types as bt 21 | from .. import shared 22 | 23 | 24 | def createMaterialForMesh(scene: bt.Scene, mesh: bt.Mesh): 25 | standardMaterial = shared.getStandardMaterialOrNull(scene, mesh) 26 | if standardMaterial is None: 27 | return 28 | 29 | realMaterial = bpy.data.materials.new(standardMaterial.name) 30 | directoryList = shared.determineTextureDirectoryList(scene) 31 | 32 | realMaterial.use_nodes = True 33 | tree = realMaterial.node_tree 34 | tree.links.clear() 35 | tree.nodes.clear() 36 | 37 | # diffuse 38 | diffuseLayer = standardMaterial.layers[shared.getLayerNameFromFieldName("diffuseLayer")] 39 | diffuseTextureNode = shared.createTextureNodeForM3MaterialLayer(mesh, tree, diffuseLayer, directoryList) 40 | if diffuseTextureNode is not None: 41 | if diffuseLayer.colorChannelSetting == shared.colorChannelSettingRGBA: 42 | diffuseTeamColorMixNode = tree.nodes.new("ShaderNodeMixRGB") 43 | diffuseTeamColorMixNode.blend_type = "MIX" 44 | teamColor = scene.m3_import_options.teamColor 45 | diffuseTeamColorMixNode.inputs["Color1"].default_value = (teamColor[0], teamColor[1], teamColor[2], 1.0) 46 | tree.links.new(diffuseTextureNode.outputs["Alpha"], diffuseTeamColorMixNode.inputs["Fac"]) 47 | tree.links.new(diffuseTextureNode.outputs["Color"], diffuseTeamColorMixNode.inputs["Color2"]) 48 | finalDiffuseColorOutputSocket = diffuseTeamColorMixNode.outputs["Color"] 49 | else: 50 | finalDiffuseColorOutputSocket = diffuseTextureNode.outputs["Color"] 51 | else: 52 | rgbNode = tree.nodes.new("ShaderNodeRGB") 53 | rgbNode.outputs[0].default_value = (0, 0, 0, 1) 54 | finalDiffuseColorOutputSocket = rgbNode.outputs[0] 55 | 56 | # normal 57 | normalMapNode = shared.createNormalMapNode(mesh, tree, standardMaterial, directoryList) 58 | 59 | # specular 60 | specularLayer = standardMaterial.layers[shared.getLayerNameFromFieldName("specularLayer")] 61 | specularTextureNode = shared.createTextureNodeForM3MaterialLayer(mesh, tree, specularLayer, directoryList) 62 | 63 | # emissive 64 | emissiveLayer = standardMaterial.layers[shared.getLayerNameFromFieldName("emissiveLayer")] 65 | emissiveTextureNode = shared.createTextureNodeForM3MaterialLayer(mesh, tree, emissiveLayer, directoryList) 66 | 67 | # PrincipledBSDF 68 | shaderBSDF = tree.nodes.new("ShaderNodeBsdfPrincipled") 69 | shaderBSDF.inputs["Roughness"].default_value = 0.2 70 | 71 | tree.links.new(finalDiffuseColorOutputSocket, shaderBSDF.inputs["Base Color"]) 72 | if normalMapNode is not None: 73 | tree.links.new(normalMapNode.outputs["Normal"], shaderBSDF.inputs["Normal"]) 74 | if specularTextureNode is not None: 75 | tree.links.new(specularTextureNode.outputs["Color"], shaderBSDF.inputs["Specular"]) 76 | if emissiveTextureNode is not None: 77 | tree.links.new(emissiveTextureNode.outputs["Color"], shaderBSDF.inputs["Emission"]) 78 | 79 | # output 80 | outputNode = tree.nodes.new("ShaderNodeOutputMaterial") 81 | outputNode.location = (500.0, 000.0) 82 | tree.links.new(shaderBSDF.outputs["BSDF"], outputNode.inputs["Surface"]) 83 | 84 | shared.layoutInputNodesOf(tree) 85 | 86 | # Remove old materials: 87 | while len(mesh.materials) > 0: 88 | mesh.materials.pop(index=0, update_data=True) 89 | 90 | mesh.materials.append(realMaterial) 91 | -------------------------------------------------------------------------------- /listOffsets.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # -*- coding: utf-8 -*- 3 | 4 | import m3 5 | import sys 6 | 7 | 8 | structureName = sys.argv[1] 9 | structureVersion = int(sys.argv[2]) 10 | mdVersion = sys.argv[3] if len(sys.argv) > 3 else 'MD34' 11 | 12 | structureDescription = m3.structures[structureName].getVersion(structureVersion, mdVersion, True) # type: m3.M3StructureDescription 13 | if structureDescription is None: 14 | raise Exception("The structure %s hasn't been defined in version %d" % (structureName, structureVersion)) 15 | offset = 0 16 | for field in structureDescription.fields: 17 | print("0x%03X %04d %s" % (offset, offset, field.name)) 18 | offset += field.size 19 | 20 | -------------------------------------------------------------------------------- /m3.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # -*- coding: utf-8 -*- 3 | 4 | # ##### BEGIN GPL LICENSE BLOCK ##### 5 | # 6 | # This program is free software; you can redistribute it and/or 7 | # modify it under the terms of the GNU General Public License 8 | # as published by the Free Software Foundation; either version 2 9 | # of the License, or (at your option) any later version. 10 | # 11 | # This program is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU General Public License for more details. 15 | # 16 | # You should have received a copy of the GNU General Public License 17 | # along with this program; if not, write to the Free Software Foundation, 18 | # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 19 | # 20 | # ##### END GPL LICENSE BLOCK ##### 21 | 22 | import xml.dom.minidom 23 | from xml.dom.minidom import Node 24 | import re 25 | from sys import stderr 26 | import struct 27 | import copy 28 | import sys 29 | 30 | 31 | def increaseToValidSectionSize(size): 32 | blockSize = 16 33 | incompleteBlockBytes = (size % blockSize) 34 | if incompleteBlockBytes != 0: 35 | missingBytesToCompleteBlock = blockSize - incompleteBlockBytes 36 | return size + missingBytesToCompleteBlock 37 | else: 38 | return size 39 | 40 | 41 | class Section: 42 | """Has fields indexEntry and structureDescription and sometimes also the fields rawBytes and content """ 43 | 44 | def __init__(self): 45 | self.timesReferenced = 0 46 | 47 | def __str__(self): 48 | return 'Section %s timesReferenced=%d %sV%s' % ( 49 | self.indexEntry, 50 | self.timesReferenced, 51 | self.structureDescription.structureName, 52 | self.structureDescription.structureVersion 53 | ) 54 | 55 | def from_instances(self, content, tag=''): 56 | if tag: 57 | self.content = content 58 | self.structureDescription = structures[tag].structureDescription 59 | else: 60 | self.content = content 61 | self.structureDescription = content[0].structureDescription 62 | 63 | def determineContentField(self, checkExpectedValue): 64 | self.content = self.structureDescription.createInstances(buffer=self.rawBytes, count=self.indexEntry.repetitions, checkExpectedValue=checkExpectedValue) 65 | 66 | def determineFieldRawBytes(self): 67 | minRawBytes = self.determineRawBytesWithData() 68 | if len(minRawBytes) != self.bytesRequiredForContent(): 69 | raise Exception("Section size calculation failed: Expected %s but was %s for %s; content: %s" % (self.bytesRequiredForContent(), len(minRawBytes), self.structureDescription.structureName, minRawBytes)) 70 | sectionSize = increaseToValidSectionSize(len(minRawBytes)) 71 | if len(minRawBytes) == sectionSize: 72 | self.rawBytes = minRawBytes 73 | else: 74 | rawBytes = bytearray(sectionSize) 75 | rawBytes[0:len(minRawBytes)] = minRawBytes 76 | for i in range(len(minRawBytes), sectionSize): 77 | rawBytes[i] = 0xaa 78 | self.rawBytes = rawBytes 79 | 80 | def determineRawBytesWithData(self): 81 | return self.structureDescription.instancesToBytes(self.content) 82 | 83 | def bytesRequiredForContent(self): 84 | return self.structureDescription.countBytesRequiredForInstances(self.content) 85 | 86 | def resolveReferences(self, sections): 87 | if not self.structureDescription.isPrimitive: 88 | for object in self.content: 89 | object.resolveReferences(sections) 90 | 91 | 92 | primitiveFieldTypeSizes = {"uint32": 4, "int32": 4, "uint16": 2, "int16": 2, "uint8": 1, "int8": 1, "float": 4, "tag": 4, "fixed8": 1} 93 | primitiveFieldTypeFormats = {"uint32": "I", "int32": "i", "uint16": "H", "int16": "h", "uint8": "B", "int8": "b", "float": "f", "tag": "4s", "fixed8": "B"} 94 | intTypes = {"uint32", "int32", "uint16", "int16", "uint8", "int8"} 95 | 96 | structureNamesOfPrimitiveTypes = set(["CHAR", "U8__", "REAL", "I16_", "U16_", "I32_", "U32_", "FLAG"]) 97 | 98 | 99 | class M3StructureHistory: 100 | "Describes the history of a structure with a specific name" 101 | 102 | def __init__(self, name, versionToSizeMap, allFields): 103 | self.name = name 104 | self.versionToSizeMap = versionToSizeMap 105 | self.allFields = allFields 106 | self.versionToStructureDescriptionMap = {} 107 | self.isPrimitive = self.name in structureNamesOfPrimitiveTypes 108 | # Create all to check sizes: 109 | for version in versionToSizeMap: 110 | self.getVersion(version) 111 | 112 | def createStructureDescription(self, version, usedFields, specifiedSize, fmagic): 113 | finalFields = [] 114 | # dirty patching of all structures to make MD33 models work 115 | # - they use `SmallReference` instead of `Reference` across all structures 116 | if fmagic == 'MD33': 117 | for field in usedFields: 118 | if isinstance(field, ReferenceField): 119 | field = copy.copy(field) 120 | if field.referenceStructureDescription.structureName == 'Reference': 121 | newStructureHistory = structures['SmallReference'] 122 | newDescription = newStructureHistory.getVersion(0, fmagic) 123 | field.referenceStructureDescription = newDescription 124 | field.size = newDescription.size 125 | elif self.name == 'MODL' and field.name == 'tightHitTest': 126 | field = copy.copy(field) 127 | newStructureHistory = structures[field.structureDescription.structureName] 128 | newDescription = newStructureHistory.getVersion(1, fmagic) 129 | field.structureDescription = newDescription 130 | field.size = newDescription.size 131 | finalFields.append(field) 132 | else: 133 | finalFields = usedFields 134 | structure = M3StructureDescription(self.name, version, finalFields, specifiedSize, self, fmagic != 'MD33') 135 | return structure 136 | 137 | def getVersion(self, version, fmagic='MD34', force=False): 138 | structure = self.versionToStructureDescriptionMap.get(fmagic + '_' + str(version)) 139 | if structure is None: 140 | usedFields = [] 141 | for field in self.allFields: 142 | includeField = True 143 | if field.sinceVersion is not None and version < field.sinceVersion: 144 | includeField = False 145 | if field.tillVersion is not None and version > field.tillVersion: 146 | includeField = False 147 | if includeField: 148 | usedFields.append(field) 149 | specifiedSize = self.versionToSizeMap.get(version) 150 | if not force and specifiedSize is None: 151 | return None 152 | structure = self.createStructureDescription(version, usedFields, specifiedSize, fmagic) 153 | self.versionToStructureDescriptionMap[fmagic + '_' + str(version)] = structure 154 | return structure 155 | 156 | def getNewestVersion(self): 157 | newestVersion = None 158 | for version in self.versionToSizeMap.keys(): 159 | if newestVersion is None or version > newestVersion: 160 | newestVersion = version 161 | return self.getVersion(newestVersion) 162 | 163 | def createEmptyArray(self): 164 | if self.name == "CHAR": 165 | return None # even no terminating character 166 | elif self.name == "U8__": 167 | return bytearray(0) 168 | else: 169 | return [] 170 | 171 | def __str__(): 172 | return self.name 173 | 174 | 175 | class M3StructureDescription: 176 | 177 | def __init__(self, structureName, structureVersion, fields, specifiedSize, history, validateSize=True): 178 | self.structureName = structureName 179 | self.structureVersion = structureVersion 180 | self.fields = fields 181 | self.isPrimitive = self.structureName in structureNamesOfPrimitiveTypes 182 | self.history = history 183 | 184 | calculatedSize = 0 185 | for field in fields: 186 | calculatedSize += field.size 187 | self.size = calculatedSize 188 | 189 | # Validate the specified size: 190 | if validateSize and calculatedSize != specifiedSize: 191 | self.dumpOffsets() 192 | raise Exception("Size mismatch: %s in version %d has been specified to have size %d, but the calculated size was %d" % (structureName, structureVersion, specifiedSize, calculatedSize)) 193 | 194 | nameToFieldMap = {} 195 | for field in fields: 196 | if field.name in nameToFieldMap: 197 | raise Exception("%s contains in version %s multiple fields with the name %s" % (structureName, structureVersion, field.name)) 198 | nameToFieldMap[field.name] = field 199 | self.nameToFieldMap = nameToFieldMap 200 | 201 | def createInstance(self, buffer=None, offset=0, checkExpectedValue=True): 202 | return M3Structure(self, buffer, offset, checkExpectedValue) 203 | 204 | def createInstances(self, buffer, count, checkExpectedValue=True): 205 | if self.isPrimitive: 206 | if self.structureName == "CHAR": 207 | return buffer[:count - 1].decode("ASCII", "replace") 208 | elif self.structureName == "U8__": 209 | return bytearray(buffer[:count]) 210 | else: 211 | structFormat = self.fields[0].structFormat 212 | list = [] 213 | for offset in range(0, count * self.size, self.size): 214 | bytesOfOneEntry = buffer[offset:(offset + self.size)] 215 | intValue = structFormat.unpack(bytesOfOneEntry)[0] 216 | list.append(intValue) 217 | return list 218 | else: 219 | list = [] 220 | instanceOffset = 0 221 | for i in range(count): 222 | list.append(self.createInstance(buffer=buffer, offset=instanceOffset, checkExpectedValue=checkExpectedValue)) 223 | instanceOffset += self.size 224 | return list 225 | 226 | def dumpOffsets(self): 227 | offset = 0 228 | stderr.write("Offsets of %s in version %d:\n" % (self.structureName, self.structureVersion)) 229 | for field in self.fields: 230 | stderr.write("%s: %s\n" % (offset, field.name)) 231 | offset += field.size 232 | 233 | def countInstances(self, instances): 234 | if self.structureName == "CHAR": 235 | if instances is None: 236 | return 0 237 | return len(instances) + 1 # +1 terminating null character 238 | elif hasattr(instances, "__len__"): # either a list or an array of bytes 239 | return len(instances) 240 | else: 241 | raise Exception("Can't measure the length of %s which is a %s" % (instances, self.structureName)) 242 | 243 | def validateInstance(self, instance, instanceName): 244 | for field in self.fields: 245 | try: 246 | fieldContent = getattr(instance, field.name) 247 | except AttributeError: 248 | raise Exception("%s does not have a field called %s" % (instanceName, field.name)) 249 | raise 250 | field.validateContent(fieldContent, instanceName + "." + field.name) 251 | 252 | def hasField(self, fieldName): 253 | return fieldName in self.nameToFieldMap 254 | 255 | def instancesToBytes(self, instances): 256 | if self.structureName == "CHAR": 257 | if type(instances) != str: 258 | raise Exception("Expected a string but it was a %s" % type(instances)) 259 | return instances.encode("ASCII") + b'\x00' 260 | elif self.structureName == "U8__": 261 | if type(instances) != bytes and type(instances) != bytearray: 262 | raise Exception("Expected a byte array but it was a %s" % type(instances)) 263 | return instances 264 | else: 265 | rawBytes = bytearray(self.size * len(instances)) 266 | offset = 0 267 | 268 | if self.isPrimitive: 269 | structFormat = self.fields[0].structFormat 270 | for value in instances: 271 | structFormat.pack_into(rawBytes, offset, value) 272 | offset += self.size 273 | else: 274 | for value in instances: 275 | value.writeToBuffer(rawBytes, offset) 276 | offset += self.size 277 | return rawBytes 278 | 279 | def countBytesRequiredForInstances(self, instances): 280 | if self.structureName == "CHAR": 281 | return len(instances) + 1 # +1 for terminating character 282 | return self.size * self.countInstances(instances) 283 | 284 | 285 | class M3Structure: 286 | 287 | def __init__(self, structureDescription: M3StructureDescription, buffer=None, offset=0, checkExpectedValue=True): 288 | self.structureDescription = structureDescription 289 | 290 | if buffer is not None: 291 | self.readFromBuffer(buffer, offset, checkExpectedValue) 292 | else: 293 | for field in self.structureDescription.fields: 294 | field.setToDefault(self) 295 | 296 | def introduceIndexReferences(self, indexMaker): 297 | for field in self.structureDescription.fields: 298 | field.introduceIndexReferences(self, indexMaker) 299 | 300 | def resolveReferences(self, sections): 301 | for field in self.structureDescription.fields: 302 | field.resolveIndexReferences(self, sections) 303 | 304 | def readFromBuffer(self, buffer, offset, checkExpectedValue): 305 | fieldOffset = offset 306 | for field in self.structureDescription.fields: 307 | try: 308 | field.readFromBuffer(self, buffer, fieldOffset, checkExpectedValue) 309 | except struct.error as e: 310 | raise Exception('failed to unpack %sV%s %s' % (self.structureDescription.structureName, self.structureDescription.structureVersion, field.name), e) 311 | fieldOffset += field.size 312 | assert fieldOffset - offset == self.structureDescription.size 313 | 314 | def writeToBuffer(self, buffer, offset): 315 | fieldOffset = offset 316 | for field in self.structureDescription.fields: 317 | field.writeToBuffer(self, buffer, fieldOffset) 318 | fieldOffset += field.size 319 | assert fieldOffset - offset == self.structureDescription.size 320 | 321 | def __str__(self): 322 | fieldValueMap = {} 323 | for field in self.structureDescription.fields: 324 | fieldValueMap[field.name] = str(getattr(self, field.name)) 325 | return "%sV%s: {%s}" % (self.structureDescription.structureName, self.structureDescription.structureVersion, fieldValueMap) 326 | 327 | def getNamedBit(self, fieldName, bitName): 328 | field = self.structureDescription.nameToFieldMap[fieldName] 329 | return field.getNamedBit(self, bitName) 330 | 331 | def setNamedBit(self, fieldName, bitName, value): 332 | field = self.structureDescription.nameToFieldMap[fieldName] 333 | return field.setNamedBit(self, bitName, value) 334 | 335 | def getBitNameMaskPairs(self, fieldName): 336 | field = self.structureDescription.nameToFieldMap[fieldName] 337 | return field.getBitNameMaskPairs() 338 | 339 | 340 | class Field: 341 | def __init__(self, name, sinceVersion, tillVersion): 342 | self.name = name 343 | self.sinceVersion = sinceVersion 344 | self.tillVersion = tillVersion 345 | 346 | def introduceIndexReferences(self, owner, indexMaker): 347 | pass 348 | 349 | def resolveIndexReferences(self, owner, sections): 350 | pass 351 | 352 | 353 | class TagField(Field): 354 | 355 | def __init__(self, name, sinceVersion, tillVersion): 356 | Field.__init__(self, name, sinceVersion, tillVersion) 357 | self.structFormat = struct.Struct("<4B") 358 | self.size = 4 359 | 360 | def readFromBuffer(self, owner, buffer, offset, checkExpectedValue): 361 | b = self.structFormat.unpack_from(buffer, offset) 362 | if b[3] == 0: 363 | s = chr(b[2]) + chr(b[1]) + chr(b[0]) 364 | else: 365 | s = chr(b[3]) + chr(b[2]) + chr(b[1]) + chr(b[0]) 366 | 367 | setattr(owner, self.name, s) 368 | 369 | def writeToBuffer(self, owner, buffer, offset): 370 | s = getattr(owner, self.name) 371 | if len(s) == 4: 372 | b = (s[3] + s[2] + s[1] + s[0]).encode("ascii") 373 | else: 374 | b = (s[2] + s[1] + s[0]).encode("ascii") + b"\x00" 375 | return self.structFormat.pack_into(buffer, offset, b[0], b[1], b[2], b[3]) 376 | 377 | def setToDefault(self, owner): 378 | pass 379 | 380 | def validateContent(self, fieldContent, fieldPath): 381 | if (type(fieldContent) != str) or (len(fieldContent) != 4): 382 | raise Exception("%s is not a string with 4 characters" % (fieldPath)) 383 | 384 | 385 | class ReferenceField(Field): 386 | def __init__(self, name, referenceStructureDescription, historyOfReferencedStructures, sinceVersion, tillVersion): 387 | Field.__init__(self, name, sinceVersion, tillVersion) 388 | self.referenceStructureDescription = referenceStructureDescription 389 | self.historyOfReferencedStructures = historyOfReferencedStructures 390 | self.size = referenceStructureDescription.size 391 | 392 | def introduceIndexReferences(self, owner, indexMaker): 393 | referencedObjects = getattr(owner, self.name) 394 | structureDescription = self.getListContentStructureDefinition(referencedObjects, "while adding index ref") 395 | 396 | indexReference = indexMaker.getIndexReferenceTo(referencedObjects, self.referenceStructureDescription, structureDescription) 397 | isPrimitive = self.historyOfReferencedStructures is not None and self.historyOfReferencedStructures.isPrimitive 398 | if not isPrimitive: 399 | for referencedObject in referencedObjects: 400 | referencedObject.introduceIndexReferences(indexMaker) 401 | setattr(owner, self.name, indexReference) 402 | 403 | def resolveIndexReferences(self, owner, sections): 404 | ref = getattr(owner, self.name) 405 | ownerName = owner.structureDescription.structureName 406 | variable = "%(ownerName)s.%(fieldName)s" % {"ownerName": ownerName, "fieldName": self.name} 407 | if ref.entries == 0: 408 | if self.historyOfReferencedStructures is None: 409 | referencedObjects = [] 410 | else: 411 | referencedObjects = self.historyOfReferencedStructures.createEmptyArray() 412 | else: 413 | referencedSection = sections[ref.index] 414 | referencedSection.timesReferenced += 1 415 | indexEntry = referencedSection.indexEntry 416 | 417 | if indexEntry.repetitions < ref.entries: 418 | raise Exception("%s tries to reference %s elements in a %s section that contains just %s element(s)" % (variable, ref.entries, indexEntry.tag, indexEntry.repetitions)) 419 | 420 | referencedObjects = referencedSection.content 421 | if self.historyOfReferencedStructures is not None: 422 | expectedTagName = self.historyOfReferencedStructures.name 423 | actualTagName = indexEntry.tag 424 | if actualTagName != expectedTagName: 425 | raise Exception("Expected ref %s point to %s, but it points to %s" % (variable, expectedTagName, actualTagName)) 426 | else: 427 | raise Exception("Field %s can be marked as a reference pointing to %s" % (variable, indexEntry.tag)) 428 | 429 | setattr(owner, self.name, referencedObjects) 430 | 431 | def getListContentStructureDefinition(self, li, contextString): 432 | 433 | if self.historyOfReferencedStructures is None: 434 | if len(li) == 0: 435 | return None 436 | else: 437 | variable = "%(fieldName)s" % {"fieldName": self.name} 438 | raise Exception("%s: %s must be an empty list but wasn't" % (contextString, variable)) 439 | if self.historyOfReferencedStructures.isPrimitive: 440 | return self.historyOfReferencedStructures.getVersion(0) 441 | 442 | if type(li) != list: 443 | raise Exception("%s: Expected a list, but was a %s" % (contextString, type(li))) 444 | if len(li) == 0: 445 | return None 446 | 447 | firstElement = li[0] 448 | contentClass = type(firstElement) 449 | if contentClass != M3Structure: 450 | raise Exception("%s: Expected a list to contain an M3Structure object and not a %s" % (contextString, contentClass)) 451 | # Optional: Enable check: 452 | # if not contentClass.tagName == tagName: 453 | # raise Exception("Expected a list to contain a object of a class with tagName %s, but it contained a object of class %s with tagName %s" % (tagName, contentClass, contentClass.tagName)) 454 | return firstElement.structureDescription 455 | 456 | def readFromBuffer(self, owner, buffer, offset, checkExpectedValue): 457 | referenceObject = self.referenceStructureDescription.createInstance(buffer, offset, checkExpectedValue) 458 | setattr(owner, self.name, referenceObject) 459 | 460 | def writeToBuffer(self, owner, buffer, offset): 461 | referenceObject = getattr(owner, self.name) 462 | referenceObject.writeToBuffer(buffer, offset) 463 | 464 | def setToDefault(self, owner): 465 | 466 | if self.historyOfReferencedStructures is not None: 467 | defaultValue = self.historyOfReferencedStructures.createEmptyArray() 468 | else: 469 | defaultValue = [] 470 | setattr(owner, self.name, defaultValue) 471 | 472 | # The method validateContent is defined in subclasses 473 | 474 | 475 | class CharReferenceField(ReferenceField): 476 | 477 | def __init__(self, name, referenceStructureDescription, historyOfReferencedStructures, sinceVersion, tillVersion): 478 | ReferenceField.__init__(self, name, referenceStructureDescription, historyOfReferencedStructures, sinceVersion, tillVersion) 479 | 480 | def validateContent(self, fieldContent, fieldPath): 481 | if (fieldContent is not None) and (type(fieldContent) != str): 482 | raise Exception("%s is not a string but a %s" % (fieldPath, type(fieldContent))) 483 | 484 | 485 | class ByteReferenceField(ReferenceField): 486 | 487 | def __init__(self, name, referenceStructureDescription, historyOfReferencedStructures, sinceVersion, tillVersion): 488 | ReferenceField.__init__(self, name, referenceStructureDescription, historyOfReferencedStructures, sinceVersion, tillVersion) 489 | 490 | def validateContent(self, fieldContent, fieldPath): 491 | if (type(fieldContent) != bytearray): 492 | raise Exception("%s is not a bytearray but a %s" % (fieldPath, type(fieldContent))) 493 | 494 | 495 | class RealReferenceField(ReferenceField): 496 | 497 | def __init__(self, name, referenceStructureDescription, historyOfReferencedStructures, sinceVersion, tillVersion): 498 | ReferenceField.__init__(self, name, referenceStructureDescription, historyOfReferencedStructures, sinceVersion, tillVersion) 499 | 500 | def validateContent(self, fieldContent, fieldPath): 501 | if (type(fieldContent) != list): 502 | raise Exception("%s is not a list of float" % (fieldPath)) 503 | for itemIndex, item in enumerate(fieldContent): 504 | if type(item) != float: 505 | itemPath = "%s[%d]" % (fieldPath, itemIndex) 506 | raise Exception("%s is not an float" % (itemPath)) 507 | 508 | 509 | class IntReferenceField(ReferenceField): 510 | intRefToMinValue = {"I16_": (-(1 << 15)), "U16_": 0, "I32_": (-(1 << 31)), "U32_": 0, "FLAG": 0} 511 | intRefToMaxValue = {"I16_": ((1 << 15) - 1), "U16_": ((1 << 16) - 1), "I32_": ((1 << 31) - 1), "U32_": ((1 << 32) - 1), "FLAG": ((1 << 32) - 1)} 512 | 513 | def __init__(self, name, referenceStructureDescription, historyOfReferencedStructures, sinceVersion, tillVersion): 514 | ReferenceField.__init__(self, name, referenceStructureDescription, historyOfReferencedStructures, sinceVersion, tillVersion) 515 | self.minValue = IntReferenceField.intRefToMinValue[historyOfReferencedStructures.name] 516 | self.maxValue = IntReferenceField.intRefToMaxValue[historyOfReferencedStructures.name] 517 | 518 | def validateContent(self, fieldContent, fieldPath): 519 | if (type(fieldContent) != list): 520 | raise Exception("%s is not a list of integers" % (fieldPath)) 521 | for itemIndex, item in enumerate(fieldContent): 522 | itemPath = "%s[%d]" % (fieldPath, itemIndex) 523 | if type(item) != int: 524 | raise Exception("%s is not an integer" % (itemPath)) 525 | if (item < self.minValue) or (item > self.maxValue): 526 | raise Exception("%s has value %d which is not in range [%s, %s]" % (itemPath, item, self.minValue, self.maxValue)) 527 | 528 | 529 | class StructureReferenceField(ReferenceField): 530 | 531 | def __init__(self, name, referenceStructureDescription, historyOfReferencedStructures, sinceVersion, tillVersion): 532 | ReferenceField.__init__(self, name, referenceStructureDescription, historyOfReferencedStructures, sinceVersion, tillVersion) 533 | 534 | def validateContent(self, fieldContent, fieldPath): 535 | if (type(fieldContent) != list): 536 | raise Exception("%s is not a list, but a %s" % (fieldPath, type(fieldContent))) 537 | if len(fieldContent) > 0: 538 | structureDescription = self.getListContentStructureDefinition(fieldContent, fieldPath) 539 | if structureDescription.history != self.historyOfReferencedStructures: 540 | raise Exception("Expected that %s is a list of %s and not %s" % (fieldPath, self.historyOfReferencedStructures.name, structureDescription.history.name)) 541 | for itemIndex, item in enumerate(fieldContent): 542 | structureDescription.validateInstance(item, "%s[%d]" % (fieldPath, itemIndex)) 543 | 544 | 545 | class UnknownReferenceField(ReferenceField): 546 | 547 | def __init__(self, name, referenceStructureDescription, historyOfReferencedStructures, sinceVersion, tillVersion): 548 | ReferenceField.__init__(self, name, referenceStructureDescription, historyOfReferencedStructures, sinceVersion, tillVersion) 549 | 550 | def validateContent(self, fieldContent, fieldPath): 551 | if (type(fieldContent) != list) or (len(fieldContent) != 0): 552 | raise Exception("%s is not an empty list" % (fieldPath)) 553 | 554 | 555 | class EmbeddedStructureField(Field): 556 | 557 | def __init__(self, name, structureDescription, sinceVersion, tillVersion): 558 | Field.__init__(self, name, sinceVersion, tillVersion) 559 | self.structureDescription = structureDescription 560 | self.size = structureDescription.size 561 | 562 | def introduceIndexReferences(self, owner, indexMaker): 563 | emeddedStructure = getattr(owner, self.name) 564 | emeddedStructure.introduceIndexReferences(indexMaker) 565 | 566 | def resolveIndexReferences(self, owner, sections): 567 | emeddedStructure = getattr(owner, self.name) 568 | emeddedStructure.resolveReferences(sections) 569 | 570 | def toBytes(self, owner): 571 | emeddedStructure = getattr(owner, self.name) 572 | return emeddedStructure.toBytes() 573 | 574 | def readFromBuffer(self, owner, buffer, offset, checkExpectedValue): 575 | 576 | referenceObject = self.structureDescription.createInstance(buffer, offset, checkExpectedValue) 577 | setattr(owner, self.name, referenceObject) 578 | 579 | def writeToBuffer(self, owner, buffer, offset): 580 | emeddedStructure = getattr(owner, self.name) 581 | emeddedStructure.writeToBuffer(buffer, offset) 582 | 583 | def setToDefault(self, owner): 584 | v = self.structureDescription.createInstance() 585 | setattr(owner, self.name, v) 586 | 587 | def validateContent(self, fieldContent, fieldPath): 588 | self.structureDescription.validateInstance(fieldContent, fieldPath) 589 | 590 | 591 | class PrimitiveField(Field): 592 | """ Base class for IntField and FloatField """ 593 | 594 | def __init__(self, name, typeString, sinceVersion, tillVersion, defaultValue, expectedValue): 595 | Field.__init__(self, name, sinceVersion, tillVersion) 596 | self.size = primitiveFieldTypeSizes[typeString] 597 | self.structFormat = struct.Struct("<" + primitiveFieldTypeFormats[typeString]) 598 | self.typeString = typeString 599 | self.defaultValue = defaultValue 600 | self.expectedValue = expectedValue 601 | 602 | def readFromBuffer(self, owner, buffer, offset, checkExpectedValue): 603 | value = self.structFormat.unpack_from(buffer, offset)[0] 604 | if self.expectedValue is not None and value != self.expectedValue: 605 | structureName = owner.structureDescription.structureName 606 | structureVersion = owner.structureDescription.structureVersion 607 | raise Exception("Expected that field %s of %s (V. %d) has always the value %s, but it was %s" % (self.name, structureName, structureVersion, self.expectedValue, value)) 608 | setattr(owner, self.name, value) 609 | 610 | def writeToBuffer(self, owner, buffer, offset): 611 | value = getattr(owner, self.name) 612 | return self.structFormat.pack_into(buffer, offset, value) 613 | 614 | def setToDefault(self, owner): 615 | setattr(owner, self.name, self.defaultValue) 616 | 617 | 618 | class IntField(PrimitiveField): 619 | intTypeToMinValue = {"int16": (-(1 << 15)), "uint16": 0, "int32": (-(1 << 31)), "uint32": 0, "int8": -(1 << 7), "uint8": 0} 620 | intTypeToMaxValue = {"int16": ((1 << 15) - 1), "uint16": ((1 << 16) - 1), "int32": ((1 << 31) - 1), "uint32": ((1 << 32) - 1), "int8": ((1 << 7) - 1), "uint8": ((1 << 8) - 1)} 621 | 622 | def __init__(self, name, typeString, sinceVersion, tillVersion, defaultValue, expectedValue, bitMaskMap): 623 | PrimitiveField.__init__(self, name, typeString, sinceVersion, tillVersion, defaultValue, expectedValue) 624 | self.minValue = IntField.intTypeToMinValue[typeString] 625 | self.maxValue = IntField.intTypeToMaxValue[typeString] 626 | self.bitMaskMap = bitMaskMap 627 | 628 | def validateContent(self, fieldContent, fieldPath): 629 | if (type(fieldContent) != int): 630 | raise Exception("%s is not an int but a %s!" % (fieldPath, type(fieldContent))) 631 | if (fieldContent < self.minValue) or (fieldContent > self.maxValue): 632 | raise Exception("%s has value %d which is not in range [%d, %d]" % (fieldPath, fieldContent, self.minValue, self.maxValue)) 633 | 634 | def getNamedBit(self, owner, bitName): 635 | mask = self.bitMaskMap[bitName] 636 | intValue = getattr(owner, self.name) 637 | return ((intValue & mask) != 0) 638 | 639 | def setNamedBit(self, owner, bitName, value): 640 | mask = self.bitMaskMap[bitName] 641 | intValue = getattr(owner, self.name) 642 | if value: 643 | setattr(owner, self.name, intValue | mask) 644 | else: 645 | if (intValue & mask) != 0: 646 | setattr(owner, self.name, intValue ^ mask) 647 | 648 | def getBitNameMaskPairs(self): 649 | return self.bitMaskMap.items() 650 | 651 | 652 | class FloatField(PrimitiveField): 653 | 654 | def __init__(self, name, typeString, sinceVersion, tillVersion, defaultValue, expectedValue): 655 | PrimitiveField.__init__(self, name, typeString, sinceVersion, tillVersion, defaultValue, expectedValue) 656 | 657 | def validateContent(self, fieldContent, fieldPath): 658 | if (type(fieldContent) != float): 659 | raise Exception("%s is not a float but a %s!" % (fieldPath, type(fieldContent))) 660 | 661 | 662 | class Fixed8Field(PrimitiveField): 663 | 664 | def __init__(self, name, typeString, sinceVersion, tillVersion, defaultValue, expectedValue): 665 | PrimitiveField.__init__(self, name, typeString, sinceVersion, tillVersion, defaultValue, expectedValue) 666 | 667 | def readFromBuffer(self, owner, buffer, offset, checkExpectedValue): 668 | intValue = self.structFormat.unpack_from(buffer, offset)[0] 669 | floatValue = ((intValue / 255.0 * 2.0) - 1) 670 | 671 | if checkExpectedValue and self.expectedValue is not None and floatValue != self.expectedValue: 672 | structureName = owner.structureDescription.structureName 673 | structureVersion = owner.structureDescription.structureVersion 674 | raise Exception("Expected that field %s of %s (V. %d) has always the value %s, but it was %s" % (self.name, structureName, structureVersion, self.expectedValue, intValue)) 675 | setattr(owner, self.name, floatValue) 676 | 677 | def writeToBuffer(self, owner, buffer, offset): 678 | floatValue = getattr(owner, self.name) 679 | intValue = round((floatValue + 1) / 2.0 * 255.0) 680 | return self.structFormat.pack_into(buffer, offset, intValue) 681 | 682 | def validateContent(self, fieldContent, fieldPath): 683 | if (type(fieldContent) != float): 684 | raise Exception("%s is not a float but a %s!" % (fieldPath, type(fieldContent))) 685 | 686 | 687 | class UnknownBytesField(Field): 688 | 689 | def __init__(self, name, size, sinceVersion, tillVersion, defaultValue, expectedValue): 690 | Field.__init__(self, name, sinceVersion, tillVersion) 691 | self.size = size 692 | self.structFormat = struct.Struct("<%ss" % size) 693 | self.defaultValue = defaultValue 694 | self.expectedValue = expectedValue 695 | assert self.structFormat.size == self.size 696 | 697 | def readFromBuffer(self, owner, buffer, offset, checkExpectedValue): 698 | value = self.structFormat.unpack_from(buffer, offset)[0] 699 | if checkExpectedValue and self.expectedValue is not None and value != self.expectedValue: 700 | raise Exception("Expected that %sV%s.%s has always the value %s, but it was %s" % (owner.structureDescription.structureName, owner.structureDescription.structureVersion, self.name, self.expectedValue, value)) 701 | 702 | setattr(owner, self.name, value) 703 | 704 | def writeToBuffer(self, owner, buffer, offset): 705 | value = getattr(owner, self.name) 706 | return self.structFormat.pack_into(buffer, offset, value) 707 | 708 | def setToDefault(self, owner): 709 | setattr(owner, self.name, self.defaultValue) 710 | 711 | def validateContent(self, fieldContent, fieldPath): 712 | if (type(fieldContent) != bytes) or (len(fieldContent) != self.size): 713 | raise Exception("%s is not an bytes object of size %s" % (fieldPath, self.size)) 714 | 715 | 716 | class Visitor: 717 | def visitStart(self, generalDataMap): 718 | pass 719 | 720 | def visitClassStart(self, generalDataMap, classDataMap): 721 | pass 722 | 723 | def visitVersion(self, generalDataMap, classDataMap, versionDataMap): 724 | pass 725 | 726 | def visitFieldStart(self, generalDataMap, classDataMap, fieldDataMap): 727 | pass 728 | 729 | def visitFieldBit(self, generalDataMap, classDataMap, fieldDataMap, bitDataMap): 730 | pass 731 | 732 | def visitFieldEnd(self, generalDataMap, classDataMap, fieldDataMap): 733 | pass 734 | 735 | def visitClassEnd(self, generalDataMap, classDataMap): 736 | pass 737 | 738 | def visitEnd(self, generalDataMap): 739 | pass 740 | 741 | 742 | class StructureAttributesReader(Visitor): 743 | def visitClassStart(self, generalDataMap, classDataMap): 744 | xmlNode = classDataMap["xmlNode"] 745 | if xmlNode.hasAttribute("name"): 746 | classDataMap["structureName"] = xmlNode.getAttribute("name") 747 | else: 748 | raise Exception("There is a structure without a name attribute") 749 | classDataMap["versionToSizeMap"] = {} 750 | 751 | def visitVersion(self, generalDataMap, classDataMap, versionDataMap): 752 | xmlNode = versionDataMap["xmlNode"] 753 | if xmlNode.hasAttribute("number"): 754 | version = int(xmlNode.getAttribute("number")) 755 | else: 756 | raise Exception("The structure %s has a version element without a number attribute" % classDataMap["tagName"]) 757 | if xmlNode.hasAttribute("size"): 758 | sizeString = xmlNode.getAttribute("size") 759 | try: 760 | size = int(sizeString) 761 | except ValueError: 762 | structureName = classDataMap["structureName"] 763 | raise Exception("The size specified for version %d of structure %s is not an int" % (version, structureName)) 764 | else: 765 | raise Exception("The structure %s has a version element without a size attribute" % classDataMap["tagName"]) 766 | versionToSizeMap = classDataMap["versionToSizeMap"] 767 | if version in versionToSizeMap: 768 | raise Exception(("The structure %s has two times the same version" % classDataMap["tagName"])) 769 | versionToSizeMap[version] = size 770 | 771 | 772 | class StructureDescriptionReader(Visitor): 773 | def visitClassStart(self, generalDataMap, classDataMap): 774 | xmlNode = classDataMap["xmlNode"] 775 | tagDescriptionNodes = xmlNode.getElementsByTagName("description") 776 | if len(tagDescriptionNodes) != 1: 777 | fullName = classDataMap["fullName"] 778 | raise Exception("Tag %s has not exactly one description node", fullName) 779 | tagDescriptionNode = tagDescriptionNodes[0] 780 | tagDescription = "" 781 | for descriptionChild in tagDescriptionNode.childNodes: 782 | if descriptionChild.nodeType == Node.TEXT_NODE: 783 | tagDescription += descriptionChild.data 784 | classDataMap["description"] = tagDescription 785 | 786 | 787 | class FieldAttributesReader(Visitor): 788 | def visitFieldStart(self, generalDataMap, classDataMap, fieldDataMap): 789 | xmlNode = fieldDataMap["xmlNode"] 790 | if xmlNode.hasAttribute("name"): 791 | fieldDataMap["fieldName"] = xmlNode.getAttribute("name") 792 | else: 793 | fullName = classDataMap["fullName"] 794 | raise Exception("There is a field in %s without a name attribute" % fullName) 795 | 796 | if xmlNode.hasAttribute("type"): 797 | fieldDataMap["typeString"] = xmlNode.getAttribute("type") 798 | else: 799 | fieldDataMap["typeString"] = None 800 | 801 | if xmlNode.hasAttribute("refTo"): 802 | fieldDataMap["refTo"] = xmlNode.getAttribute("refTo") 803 | else: 804 | fieldDataMap["refTo"] = None 805 | 806 | if xmlNode.hasAttribute("size"): 807 | fieldDataMap["specifiedFieldSize"] = int(xmlNode.getAttribute("size")) 808 | else: 809 | fieldDataMap["specifiedFieldSize"] = None 810 | 811 | if xmlNode.hasAttribute("expected-value"): 812 | fieldDataMap["expectedValueString"] = xmlNode.getAttribute("expected-value") 813 | else: 814 | fieldDataMap["expectedValueString"] = None 815 | 816 | if xmlNode.hasAttribute("default-value"): 817 | fieldDataMap["defaultValueString"] = xmlNode.getAttribute("default-value") 818 | else: 819 | fieldDataMap["defaultValueString"] = None 820 | 821 | if xmlNode.hasAttribute("till-version"): 822 | fieldDataMap["tillVersion"] = int(xmlNode.getAttribute("till-version")) 823 | else: 824 | fieldDataMap["tillVersion"] = None 825 | 826 | if xmlNode.hasAttribute("since-version"): 827 | fieldDataMap["sinceVersion"] = int(xmlNode.getAttribute("since-version")) 828 | else: 829 | fieldDataMap["sinceVersion"] = None 830 | 831 | 832 | class BitAttributesReader(Visitor): 833 | 834 | def visitFieldBit(self, generalDataMap, classDataMap, fieldDataMap, bitDataMap): 835 | xmlNode = bitDataMap["xmlNode"] 836 | if xmlNode.hasAttribute("name"): 837 | bitDataMap["name"] = xmlNode.getAttribute("name") 838 | else: 839 | structureName = classDataMap["structureName"] 840 | fieldName = fieldDataMap["fieldName"] 841 | raise Exception("There is bit xml node in field %(fieldName)s of structure %(structureName)s without a name attribute" % {"fieldName": fieldName, "structureName": structureName}) 842 | 843 | if xmlNode.hasAttribute("mask"): 844 | maskString = xmlNode.getAttribute("mask") 845 | if not re.match("0x[0-9]+", maskString): 846 | structureName = classDataMap["structureName"] 847 | fieldName = fieldDataMap["fieldName"] 848 | bitName = bitDataMap["name"] 849 | raise Exception("The bit %(bitName)s of %(structureName)s.%(fieldName)s has an invalid mask attribute" % {"fieldName": fieldName, "structureName": structureName, "bitName": bitName}) 850 | 851 | bitDataMap["mask"] = int(maskString, 0) 852 | else: 853 | structureName = classDataMap["structureName"] 854 | fieldName = fieldDataMap["fieldName"] 855 | raise Exception("There is bit xml node in field %(fieldName)s of structure %(structureName)s without a mask attribute" % {"fieldName": fieldName, "structureName": structureName}) 856 | 857 | 858 | class ExpectedAndDefaultConstantsDeterminer(Visitor): 859 | def parseHex(self, hexString): 860 | hexString = hexString[2:] 861 | return bytes([int(hexString[x:x + 2], 16) for x in range(0, len(hexString), 2)]) 862 | 863 | def visitFieldStart(self, generalDataMap, classDataMap, fieldDataMap): 864 | structureName = classDataMap["structureName"] 865 | fieldName = fieldDataMap["fieldName"] 866 | fieldType = fieldDataMap["typeString"] 867 | expectedValueString = fieldDataMap["expectedValueString"] 868 | defaultValueString = fieldDataMap["defaultValueString"] 869 | variableName = "%s.%s" % (structureName, fieldName) 870 | expectedValue = None 871 | defaultValue = None 872 | if fieldType in ("int32", "int16", "int8", "uint8", "uint16", "uint32"): 873 | if expectedValueString is not None: 874 | try: 875 | expectedValue = int(expectedValueString, 0) 876 | except ValueError: 877 | raise Exception("The specified expected value for %s is not an integer" % variableName) 878 | 879 | if defaultValueString is not None: 880 | try: 881 | defaultValue = int(defaultValueString, 0) 882 | except ValueError: 883 | raise Exception("The specified default value for %s is not an integer" % variableName) 884 | else: 885 | if expectedValue is not None: 886 | defaultValue = expectedValue 887 | else: 888 | defaultValue = 0 889 | elif fieldType == "float" or fieldType == "fixed8": 890 | if expectedValueString is not None: 891 | try: 892 | expectedValue = float(expectedValueString) 893 | except ValueError: 894 | raise Exception("The specified expected value for %s is not a float" % variableName) 895 | 896 | if defaultValueString is not None: 897 | try: 898 | defaultValue = float(defaultValueString) 899 | except ValueError: 900 | raise Exception("The specified default value for %s is not a a float" % variableName) 901 | else: 902 | if expectedValue is not None: 903 | defaultValue = expectedValue 904 | else: 905 | defaultValue = 0.0 906 | elif fieldType is None: 907 | specifiedFieldSize = fieldDataMap["specifiedFieldSize"] 908 | defaultValue = None 909 | if expectedValueString is not None: 910 | if not expectedValueString.startswith("0x"): 911 | hexString = None # * ??? 912 | raise Exception('The expected-value "%s" of field %s does not start with 0x' % (hexString, variableName)) 913 | expectedValue = self.parseHex(expectedValueString) 914 | defaultValue = expectedValue 915 | 916 | if defaultValueString is not None: 917 | if not defaultValueString.startswith("0x"): 918 | raise Exception('The expected-value "%s" of field %s does not start with 0x' % (hexString, variableName)) 919 | defaultValue = self.parseHex(defaultValueString) 920 | 921 | if defaultValue is None: 922 | defaultValue = bytes(specifiedFieldSize) 923 | 924 | fieldDataMap["expectedValue"] = expectedValue 925 | fieldDataMap["defaultValue"] = defaultValue 926 | 927 | 928 | class BitMaskMapDeterminer(Visitor): 929 | def visitFieldStart(self, generalDataMap, classDataMap, fieldDataMap): 930 | fieldDataMap["bitMaskMap"] = {} 931 | 932 | def visitFieldBit(self, generalDataMap, classDataMap, fieldDataMap, bitDataMap): 933 | bitName = bitDataMap["name"] 934 | bitMask = bitDataMap["mask"] 935 | bitMaskMap = fieldDataMap["bitMaskMap"] 936 | bitMaskMap[bitName] = bitMask 937 | 938 | 939 | class FieldListCreator(Visitor): 940 | def visitClassStart(self, generalDataMap, classDataMap): 941 | classDataMap["fields"] = [] 942 | 943 | def visitFieldEnd(self, generalDataMap, classDataMap, fieldDataMap): 944 | fields = classDataMap["fields"] 945 | structureName = classDataMap["structureName"] 946 | fieldName = fieldDataMap["fieldName"] 947 | typeString = fieldDataMap["typeString"] 948 | sinceVersion = fieldDataMap["sinceVersion"] 949 | tillVersion = fieldDataMap["tillVersion"] 950 | defaultValue = fieldDataMap["defaultValue"] 951 | expectedValue = fieldDataMap["expectedValue"] 952 | specifiedFieldSize = fieldDataMap["specifiedFieldSize"] 953 | structures = generalDataMap["structures"] 954 | bitMaskMap = fieldDataMap["bitMaskMap"] 955 | 956 | # TODO validate field size 957 | if typeString == "tag": 958 | field = TagField(fieldName, sinceVersion, tillVersion) 959 | elif typeString in intTypes: 960 | field = IntField(fieldName, typeString, sinceVersion, tillVersion, defaultValue, expectedValue, bitMaskMap) 961 | elif typeString == "float": 962 | field = FloatField(fieldName, typeString, sinceVersion, tillVersion, defaultValue, expectedValue) 963 | elif typeString == "fixed8": 964 | field = Fixed8Field(fieldName, typeString, sinceVersion, tillVersion, defaultValue, expectedValue) 965 | elif typeString is None: 966 | field = UnknownBytesField(fieldName, specifiedFieldSize, sinceVersion, tillVersion, defaultValue, expectedValue) 967 | else: 968 | vPos = typeString.rfind("V") 969 | if vPos != -1: 970 | fieldStructureName = typeString[:vPos] 971 | fieldStructureVersion = int(typeString[vPos + 1:]) 972 | 973 | else: 974 | fieldStructureName = typeString 975 | fieldStructureVersion = 0 976 | if fieldStructureName == "Reference" or fieldStructureName == "SmallReference": 977 | refTo = fieldDataMap["refTo"] 978 | if (refTo is not None) and (not (refTo in structures)): 979 | raise Exception("The structure with name %s referenced by %s.%s is not defined" % (refTo, structureName, fieldName)) 980 | if refTo is not None: 981 | historyOfReferencedStructures = structures[refTo] 982 | else: 983 | historyOfReferencedStructures = None 984 | referenceStructureDescription = structures[fieldStructureName].getVersion(fieldStructureVersion) 985 | 986 | if refTo is None: 987 | field = UnknownReferenceField(fieldName, referenceStructureDescription, historyOfReferencedStructures, sinceVersion, tillVersion) 988 | elif refTo == "CHAR": 989 | field = CharReferenceField(fieldName, referenceStructureDescription, historyOfReferencedStructures, sinceVersion, tillVersion) 990 | elif refTo == "U8__": 991 | field = ByteReferenceField(fieldName, referenceStructureDescription, historyOfReferencedStructures, sinceVersion, tillVersion) 992 | elif refTo == "REAL": 993 | field = RealReferenceField(fieldName, referenceStructureDescription, historyOfReferencedStructures, sinceVersion, tillVersion) 994 | elif refTo in ["I16_", "U16_", "I32_", "U32_", "FLAG"]: 995 | field = IntReferenceField(fieldName, referenceStructureDescription, historyOfReferencedStructures, sinceVersion, tillVersion) 996 | else: 997 | field = StructureReferenceField(fieldName, referenceStructureDescription, historyOfReferencedStructures, sinceVersion, tillVersion) 998 | else: 999 | fieldStructureHistory = structures.get(fieldStructureName) 1000 | if fieldStructureHistory is None: 1001 | raise Exception("The structure %s has not been defined before structure %s" % (fieldStructureName, structureName)) 1002 | fieldStructureDescription = fieldStructureHistory.getVersion(fieldStructureVersion) 1003 | field = EmbeddedStructureField(fieldName, fieldStructureDescription, sinceVersion, tillVersion) 1004 | fields.append(field) 1005 | 1006 | 1007 | class StructureHistoryListCreator(Visitor): 1008 | def visitStart(self, generalDataMap): 1009 | generalDataMap["structures"] = {} 1010 | pass 1011 | 1012 | def visitClassEnd(self, generalDataMap, classDataMap): 1013 | fields = classDataMap["fields"] 1014 | structureName = classDataMap["structureName"] 1015 | versionToSizeMap = classDataMap["versionToSizeMap"] 1016 | structures = generalDataMap["structures"] 1017 | 1018 | structureHistory = M3StructureHistory(structureName, versionToSizeMap, fields) 1019 | structures[structureName] = structureHistory 1020 | 1021 | def visitEnd(self, generalDataMap): 1022 | pass 1023 | 1024 | 1025 | def foreachChildWithName(parentNode, childName): 1026 | for childNode in parentNode.childNodes: 1027 | if childNode.nodeName == childName: 1028 | yield childNode 1029 | 1030 | 1031 | def firstNodeWithName(parentNode, childName): 1032 | for childNode in parentNode.childNodes: 1033 | if childNode.nodeName == childName: 1034 | return childNode 1035 | return None 1036 | 1037 | 1038 | def visitStructresDomWith(structuresDom, visitors, generalDataMap): 1039 | for visitor in visitors: 1040 | visitor.visitStart(generalDataMap) 1041 | 1042 | structuresNode = structuresDom.documentElement 1043 | for structureNode in foreachChildWithName(structuresNode, "structure"): 1044 | classDataMap = {} 1045 | classDataMap["xmlNode"] = structureNode 1046 | 1047 | for visitor in visitors: 1048 | visitor.visitClassStart(generalDataMap, classDataMap) 1049 | 1050 | versionsNode = firstNodeWithName(structureNode, "versions") 1051 | for versionNode in foreachChildWithName(versionsNode, "version"): 1052 | versionDataMap = {} 1053 | versionDataMap["xmlNode"] = versionNode 1054 | for visitor in visitors: 1055 | 1056 | visitor.visitVersion(generalDataMap, classDataMap, versionDataMap) 1057 | 1058 | fieldsNode = firstNodeWithName(structureNode, "fields") 1059 | for fieldNode in foreachChildWithName(fieldsNode, "field"): 1060 | fieldDataMap = {} 1061 | fieldDataMap["xmlNode"] = fieldNode 1062 | for visitor in visitors: 1063 | visitor.visitFieldStart(generalDataMap, classDataMap, fieldDataMap) 1064 | 1065 | bitsNode = firstNodeWithName(fieldNode, "bits") 1066 | if bitsNode is not None: 1067 | for bitNode in foreachChildWithName(bitsNode, "bit"): 1068 | bitDataMap = {} 1069 | bitDataMap["xmlNode"] = bitNode 1070 | 1071 | for visitor in visitors: 1072 | visitor.visitFieldBit(generalDataMap, classDataMap, fieldDataMap, bitDataMap) 1073 | 1074 | for visitor in visitors: 1075 | visitor.visitFieldEnd(generalDataMap, classDataMap, fieldDataMap) 1076 | 1077 | for visitor in visitors: 1078 | visitor. visitClassEnd(generalDataMap, classDataMap) 1079 | 1080 | for visitor in visitors: 1081 | visitor.visitEnd(generalDataMap) 1082 | 1083 | 1084 | def readStructureDefinitions(structuresXmlFile): 1085 | doc = xml.dom.minidom.parse(structuresXmlFile) 1086 | generalDataMap = {} 1087 | 1088 | # first run is only for determing the complete list of known structures 1089 | # firstRunVisitors = [ 1090 | # StructureAttributesReader(), 1091 | # KnownStructuresListDeterminer(), 1092 | # KnownTagsListDeterminer() 1093 | # ] 1094 | # visitStructresDomWith(doc, firstRunVisitors, generalDataMap) 1095 | 1096 | secondRunVisitors = [ 1097 | StructureAttributesReader(), 1098 | StructureDescriptionReader(), 1099 | FieldAttributesReader(), 1100 | ExpectedAndDefaultConstantsDeterminer(), 1101 | BitAttributesReader(), 1102 | BitMaskMapDeterminer(), 1103 | FieldListCreator(), 1104 | StructureHistoryListCreator() 1105 | ] 1106 | 1107 | visitStructresDomWith(doc, secondRunVisitors, generalDataMap) 1108 | 1109 | return generalDataMap["structures"] 1110 | 1111 | 1112 | def resolveAllReferences(list, sections): 1113 | ListType = type([]) 1114 | for sublist in list: 1115 | if type(sublist) == ListType: 1116 | for entry in sublist: 1117 | entry.resolveReferences(sections) 1118 | 1119 | 1120 | def loadSections(filename, checkExpectedValue=True): 1121 | source = open(filename, "rb") 1122 | try: 1123 | fmagic = source.read(4)[::-1].decode('ascii') 1124 | source.seek(0) 1125 | 1126 | m3Header = structures[fmagic].getVersion(11) 1127 | headerBytes = source.read(m3Header.size) 1128 | header = m3Header.createInstance(headerBytes, checkExpectedValue=checkExpectedValue) 1129 | 1130 | source.seek(header.indexOffset) 1131 | MD34IndexEntryV0 = structures["MD34IndexEntry"].getVersion(0) 1132 | sections = [] 1133 | for i in range(header.indexSize): 1134 | section = Section() 1135 | indexEntryBytes = source.read(MD34IndexEntryV0.size) 1136 | section.indexEntry = MD34IndexEntryV0.createInstance(indexEntryBytes, checkExpectedValue=checkExpectedValue) 1137 | sections.append(section) 1138 | 1139 | offsets = [] 1140 | for section in sections: 1141 | indexEntry = section.indexEntry 1142 | offsets.append(indexEntry.offset) 1143 | offsets.append(header.indexOffset) 1144 | offsets.sort() 1145 | previousOffset = offsets[0] 1146 | offsetToSizeMap = {} 1147 | for offset in offsets[1:]: 1148 | offsetToSizeMap[previousOffset] = offset - previousOffset 1149 | previousOffset = offset 1150 | 1151 | unknownSections = set() 1152 | for section in sections: 1153 | indexEntry = section.indexEntry 1154 | source.seek(indexEntry.offset) 1155 | numberOfBytes = offsetToSizeMap[indexEntry.offset] 1156 | section.rawBytes = source.read(numberOfBytes) 1157 | 1158 | structureHistory = structures.get(indexEntry.tag) 1159 | if structureHistory is not None: 1160 | structureDescription = structureHistory.getVersion(indexEntry.version, fmagic) 1161 | else: 1162 | structureDescription = None 1163 | 1164 | if structureDescription is not None: 1165 | section.structureDescription = structureDescription 1166 | section.determineContentField(checkExpectedValue) 1167 | else: 1168 | guessedUnusedSectionBytes = 0 1169 | for i in range(1, 16): 1170 | if section.rawBytes[len(section.rawBytes) - i] == 0xaa: 1171 | guessedUnusedSectionBytes += 1 1172 | else: 1173 | break 1174 | guessedBytesPerEntry = float(len(section.rawBytes) - guessedUnusedSectionBytes) / indexEntry.repetitions 1175 | message = "ERROR: Unknown section at offset %s with tag=%s version=%s repetitions=%s sectionLengthInBytes=%s guessedUnusedSectionBytes=%s guessedBytesPerEntry=%s\n" % (indexEntry.offset, indexEntry.tag, indexEntry.version, indexEntry.repetitions, len(section.rawBytes), guessedUnusedSectionBytes, guessedBytesPerEntry) 1176 | stderr.write(message) 1177 | if sys.stderr.isatty(): 1178 | for entryNum in range(indexEntry.repetitions): 1179 | stderr.write('Entry %d\n' % entryNum) 1180 | offset = 0 1181 | while offset < int(guessedBytesPerEntry): 1182 | val_u32 = struct.unpack_from(' %04X:%04d = 0x%08X %15d %20.5f\n' % ( 1185 | indexEntry.tag, 1186 | indexEntry.version, 1187 | entryNum, 1188 | offset, 1189 | offset, 1190 | val_u32, 1191 | val_u32, 1192 | val_float, 1193 | )) 1194 | offset += 4 1195 | unknownSections.add("%sV%s" % (indexEntry.tag, indexEntry.version)) 1196 | if len(unknownSections) != 0: 1197 | raise Exception("There were %s unknown sections: %s (see console log for more details)" % (len(unknownSections), unknownSections)) 1198 | finally: 1199 | source.close() 1200 | return sections 1201 | 1202 | 1203 | def resolveReferencesOfSections(sections): 1204 | for section in sections: 1205 | section.resolveReferences(sections) 1206 | 1207 | 1208 | def checkThatAllSectionsGotReferenced(sections): 1209 | numberOfUnreferencedSections = 0 1210 | referenceStructureDescription = reference = structures["SmallReference"].getVersion(0) 1211 | for sectionIndex, section in enumerate(sections): 1212 | 1213 | if (section.timesReferenced == 0) and (sectionIndex != 0): 1214 | numberOfUnreferencedSections += 1 1215 | stderr.write("WARNING: %sV%s (%d repetitions) got %d times referenced\n" % (section.indexEntry.tag, section.indexEntry.version, section.indexEntry.repetitions, section.timesReferenced)) 1216 | reference = referenceStructureDescription.createInstance() 1217 | reference.entries = section.indexEntry.repetitions 1218 | reference.index = sectionIndex 1219 | bytesToSearch = referenceStructureDescription.instancesToBytes([reference]) 1220 | for sectionToCheck in sections: 1221 | positionInSection = sectionToCheck.rawBytes.find(bytesToSearch) 1222 | if positionInSection != -1: 1223 | flagBytes = sectionToCheck.rawBytes[positionInSection + 8:positionInSection + 12] 1224 | flagsAsHex = ''.join(["%02x" % x for x in flagBytes]) 1225 | stderr.write(" -> Found possible reference at offset %d in a section of type %sV%s with flag %s\n" % ( 1226 | positionInSection % sectionToCheck.structureDescription.size, 1227 | sectionToCheck.indexEntry.tag, 1228 | sectionToCheck.indexEntry.version, 1229 | flagsAsHex 1230 | )) 1231 | sectionToCheck.structureDescription.dumpOffsets() 1232 | 1233 | if numberOfUnreferencedSections > 0: 1234 | raise Exception("Unable to load all data: There were %d unreferenced sections. View log for details" % numberOfUnreferencedSections) 1235 | 1236 | 1237 | def loadModel(filename, checkExpectedValue=True): 1238 | sections = loadSections(filename, checkExpectedValue) 1239 | resolveReferencesOfSections(sections) 1240 | checkThatAllSectionsGotReferenced(sections) 1241 | header = sections[0].content[0] 1242 | model = header.model[0] 1243 | modelDescription = model.structureDescription 1244 | modelDescription.validateInstance(model, "model") 1245 | return model 1246 | 1247 | 1248 | class IndexReferenceSourceAndSectionListMaker: 1249 | """ Creates a list of sections which are needed to store the objects for which index references are requested""" 1250 | def __init__(self): 1251 | self.objectsIdToIndexReferenceMap = {} 1252 | self.offset = 0 1253 | self.nextFreeIndexPosition = 0 1254 | self.sections = [] 1255 | self.MD34IndexEntry = structures["MD34IndexEntry"].getVersion(0) 1256 | 1257 | def getIndexReferenceTo(self, objectsToSave, referenceStructureDescription, structureDescription): 1258 | if id(objectsToSave) in self.objectsIdToIndexReferenceMap.keys(): 1259 | return self.objectsIdToIndexReferenceMap[id(objectsToSave)] 1260 | 1261 | if structureDescription is None: 1262 | repetitions = 0 1263 | else: 1264 | repetitions = structureDescription.countInstances(objectsToSave) 1265 | 1266 | indexReference = referenceStructureDescription.createInstance() 1267 | if repetitions > 0: 1268 | indexReference.entries = repetitions 1269 | indexReference.index = self.nextFreeIndexPosition 1270 | 1271 | if (repetitions > 0): 1272 | indexEntry = self.MD34IndexEntry.createInstance() 1273 | indexEntry.tag = structureDescription.structureName 1274 | indexEntry.offset = self.offset 1275 | indexEntry.repetitions = repetitions 1276 | indexEntry.version = structureDescription.structureVersion 1277 | 1278 | section = Section() 1279 | section.indexEntry = indexEntry 1280 | section.content = objectsToSave 1281 | section.structureDescription = structureDescription 1282 | self.sections.append(section) 1283 | self.objectsIdToIndexReferenceMap[id(objectsToSave)] = indexReference 1284 | totalBytes = section.bytesRequiredForContent() 1285 | totalBytes = increaseToValidSectionSize(totalBytes) 1286 | self.offset += totalBytes 1287 | self.nextFreeIndexPosition += 1 1288 | return indexReference 1289 | 1290 | 1291 | def modelToSections(model): 1292 | MD34V11 = structures["MD34"].getVersion(11) 1293 | header = MD34V11.createInstance() 1294 | header.tag = "MD34" 1295 | header.model = [model] 1296 | ReferenceV0 = structures["Reference"].getVersion(0) 1297 | indexMaker = IndexReferenceSourceAndSectionListMaker() 1298 | indexMaker.getIndexReferenceTo([header], ReferenceV0, MD34V11) 1299 | header.introduceIndexReferences(indexMaker) 1300 | sections = indexMaker.sections 1301 | header.indexOffset = indexMaker.offset 1302 | header.indexSize = len(sections) 1303 | 1304 | for section in sections: 1305 | section.determineFieldRawBytes() 1306 | return sections 1307 | 1308 | 1309 | def saveSections(sections, filename): 1310 | fileObject = open(filename, "w+b") 1311 | try: 1312 | previousSection = None 1313 | for section in sections: 1314 | if section.indexEntry.offset != fileObject.tell(): 1315 | raise Exception("Section length problem: Section with index entry %(previousIndexEntry)s has length %(previousLength)s and gets followed by section with index entry %(currentIndexEntry)s" % {"previousIndexEntry": previousSection.indexEntry, "previousLength": len(previousSection.rawBytes), "currentIndexEntry": section.indexEntry}) 1316 | fileObject.write(section.rawBytes) 1317 | previousSection = section 1318 | header = sections[0].content[0] 1319 | if fileObject.tell() != header.indexOffset: 1320 | raise Exception("Not at expected write position %s after writing sections, but %s" % (header.indexOffset, fileObject.tell())) 1321 | for section in sections: 1322 | indexEntryBytesBuffer = bytearray(section.indexEntry.structureDescription.size) 1323 | section.indexEntry.writeToBuffer(indexEntryBytesBuffer, 0) 1324 | fileObject.write(indexEntryBytesBuffer) 1325 | finally: 1326 | fileObject.close() 1327 | 1328 | 1329 | def saveAndInvalidateModel(model, filename): 1330 | '''Do not use the model object after calling this method since it gets modified''' 1331 | model.structureDescription.validateInstance(model, "model") 1332 | sections = modelToSections(model) 1333 | saveSections(sections, filename) 1334 | 1335 | 1336 | def readStructures(): 1337 | from os import path 1338 | directory = path.dirname(__file__) 1339 | structuresXmlPath = path.join(directory, "structures.xml") 1340 | return readStructureDefinitions(structuresXmlPath) 1341 | 1342 | 1343 | structures = readStructures() 1344 | -------------------------------------------------------------------------------- /m3ToXml.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # -*- coding: utf-8 -*- 3 | 4 | # ##### BEGIN GPL LICENSE BLOCK ##### 5 | # 6 | # This program is free software; you can redistribute it and/or 7 | # modify it under the terms of the GNU General Public License 8 | # as published by the Free Software Foundation; either version 2 9 | # of the License, or (at your option) any later version. 10 | # 11 | # This program is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU General Public License for more details. 15 | # 16 | # You should have received a copy of the GNU General Public License 17 | # along with this program; if not, write to the Free Software Foundation, 18 | # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 19 | # 20 | # ##### END GPL LICENSE BLOCK ##### 21 | 22 | import sys 23 | import m3 24 | import argparse 25 | import os.path 26 | import os 27 | import io 28 | import time 29 | import traceback 30 | import re 31 | from xml.sax.saxutils import escape 32 | 33 | 34 | def byteDataToHex(byteData): 35 | return '0x' + ''.join(["%02x" % x for x in byteData]) 36 | 37 | 38 | def indent(level): 39 | return "\t" * level 40 | 41 | 42 | def openTag(name): 43 | return "<%s>" % name 44 | 45 | 46 | def closeTag(name): 47 | return "\n" % name 48 | 49 | 50 | def openCloseTag(name): 51 | return "<%s />\n" % name 52 | 53 | 54 | def printXmlElement(out, level, name, value): 55 | out.write(indent(level) + openTag(name) + value + closeTag(name)) 56 | 57 | 58 | def printObject(out, level, name, value): 59 | valueType = type(value) 60 | if value is None: 61 | out.write(indent(level) + openCloseTag(name)) 62 | return 63 | 64 | elif valueType == int: 65 | value = hex(value) 66 | printXmlElement(out, level, name, value) 67 | return 68 | 69 | elif valueType == bytearray or valueType == bytes: 70 | value = byteDataToHex(value) 71 | printXmlElement(out, level, name, value) 72 | return 73 | 74 | elif valueType == str: 75 | # get rid of non ASCII characters 76 | value = re.sub('[^\x20-\x7F]', '.', str(value)) 77 | # escape special XML characters (such as "&" -> "&") 78 | value = escape(value) 79 | printXmlElement(out, level, name, value) 80 | return 81 | 82 | elif valueType == list: 83 | if len(value) == 0: 84 | out.write(indent(level) + openTag(name) + closeTag(name)) 85 | return 86 | firstObject = value[0] 87 | if isinstance(firstObject, m3.M3Structure): 88 | structureName = firstObject.structureDescription.structureName 89 | structureVersion = firstObject.structureDescription.structureVersion 90 | out.write(('%s<%s structureName="%s" structureVersion="%s" >\n' % (indent(level), name, structureName, structureVersion))) 91 | else: 92 | out.write(indent(level) + openTag(name) + "\n") 93 | for entry in value: 94 | printObject(out, level + 1, name + "-element", entry) 95 | 96 | out.write(indent(level) + closeTag(name)) 97 | return 98 | 99 | elif valueType == m3.M3Structure: 100 | out.write(indent(level) + openTag(name) + "\n") 101 | 102 | for field in value.structureDescription.fields: 103 | v = getattr(value, field.name) 104 | printObject(out, level + 1, field.name, v) 105 | 106 | out.write(indent(level) + closeTag(name)) 107 | return 108 | 109 | else: 110 | printXmlElement(out, level, name, str(value)) 111 | return 112 | 113 | 114 | def printModel(model, outputFilePath): 115 | outputStream = io.StringIO() 116 | 117 | outputFile = open(outputFilePath, "w") 118 | modelDescription = model.structureDescription 119 | outputStream.write('\n' % (modelDescription.structureName, modelDescription.structureVersion)) 120 | 121 | for field in modelDescription.fields: 122 | value = getattr(model, field.name) 123 | printObject(outputStream, 0, field.name, value) 124 | 125 | outputStream.write(closeTag("model")) 126 | 127 | outputFile.write(outputStream.getvalue()) 128 | outputFile.close() 129 | 130 | outputStream.close() 131 | 132 | 133 | def convertFile(inputFilePath, outputFilePath, continueAtErrors): 134 | model = None 135 | try: 136 | model = m3.loadModel(inputFilePath) 137 | except Exception as e: 138 | if continueAtErrors: 139 | sys.stderr.write("\nError: %s\n" % e) 140 | sys.stderr.write("\nFile: %s\n" % inputFilePath) 141 | sys.stderr.write("Trace: %s\n" % traceback.format_exc()) 142 | else: 143 | raise e 144 | return False 145 | 146 | printModel(model, outputFilePath) 147 | return True 148 | 149 | 150 | def processFile(inputPath, outputDirectory, inputFilePath, continueAtErrors): 151 | relativeInputPath = os.path.relpath(inputFilePath, inputPath) 152 | relativeOutputPath = relativeInputPath + ".xml" 153 | 154 | if outputDirectory: 155 | if outputDirectory and not os.path.exists(outputDirectory): 156 | os.makedirs(outputDirectory) 157 | outputFilePath = os.path.join(outputDirectory, relativeOutputPath) 158 | else: 159 | outputFilePath = inputFilePath + ".xml" 160 | 161 | print("%s -> %s" % (inputFilePath, outputFilePath)) 162 | 163 | return convertFile(inputFilePath, outputFilePath, continueAtErrors) 164 | 165 | 166 | def processDirectory(inputPath, outputPath, recurse, continueAtErrors): 167 | 168 | count, succeeded, failed = 0, 0, 0 169 | 170 | for path, dirs, files in os.walk(inputPath): 171 | 172 | for file in files: 173 | if file.endswith(".m3"): 174 | 175 | inputFilePath = os.path.join(path, file) 176 | success = processFile(inputPath, outputPath, inputFilePath, continueAtErrors) 177 | 178 | succeeded += success 179 | failed += not success 180 | count += 1 181 | 182 | if not recurse: 183 | break 184 | 185 | return count, succeeded, failed 186 | 187 | 188 | if __name__ == "__main__": 189 | parser = argparse.ArgumentParser(description='Convert Starcraft II m3 models to xml format.') 190 | parser.add_argument('path', nargs='+', help="Either a *.m3 file or a directory with *.m3 files") 191 | parser.add_argument( 192 | '--output-directory', 193 | '-o', 194 | help='Directory in which m3 files will be placed') 195 | parser.add_argument( 196 | '-r', '--recurse', 197 | action='store_true', default=False, 198 | help='Recurse input directory and convert all m3 files found.') 199 | parser.add_argument( 200 | '-c', '--continue-at-errors', 201 | action='store_true', default=False, 202 | help='Continue if there are errors in the files') 203 | args = parser.parse_args() 204 | 205 | outputDirectory = args.output_directory 206 | if outputDirectory is not None and not os.path.isdir(outputDirectory): 207 | sys.stderr.write("%s is not a directory" % outputDirectory) 208 | sys.exit(2) 209 | 210 | for path in args.path: 211 | if not os.path.isdir(path) and not os.path.isfile(path): 212 | sys.stderr.write("Path %s is not a valid directory or file" % path) 213 | sys.exit(2) 214 | 215 | recurse = args.recurse 216 | 217 | continueAtErrors = args.continue_at_errors 218 | 219 | t0 = time.time() 220 | print("Converting files.. %d" % len(args.path)) 221 | for path in args.path: 222 | total, succeeded, failed = (0, 0, 0) 223 | if os.path.isfile(path): 224 | inputFilePath = path 225 | path = os.path.dirname(path) 226 | success = processFile(path, outputDirectory, inputFilePath, continueAtErrors) 227 | totalDelta, succeededDelta, failedDelta = 1, success, not success 228 | else: 229 | totalDelta, succeededDelta, failedDelta = processDirectory(path, outputDirectory, recurse, continueAtErrors) 230 | total += totalDelta 231 | succeeded += succeededDelta 232 | failed += failedDelta 233 | 234 | t1 = time.time() 235 | print("%d files found, %d converted, %d failed in %.2f s" % (total, succeeded, failed, (t1 - t0))) 236 | if failed > 0: 237 | sys.exit(1) 238 | -------------------------------------------------------------------------------- /transferAnimationIds.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # -*- coding: utf-8 -*- 3 | 4 | # ##### BEGIN GPL LICENSE BLOCK ##### 5 | # 6 | # This program is free software; you can redistribute it and/or 7 | # modify it under the terms of the GNU General Public License 8 | # as published by the Free Software Foundation; either version 2 9 | # of the License, or (at your option) any later version. 10 | # 11 | # This program is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU General Public License for more details. 15 | # 16 | # You should have received a copy of the GNU General Public License 17 | # along with this program; if not, write to the Free Software Foundation, 18 | # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 19 | # 20 | # ##### END GPL LICENSE BLOCK ##### 21 | 22 | 23 | import m3 24 | import argparse 25 | 26 | 27 | if __name__ == "__main__": 28 | parser = argparse.ArgumentParser(description='Make a model use the same animation ids like another model(works only for bones with the same name yet)') 29 | parser.add_argument('animIdFile', help="m3 with the wanted animation ids") 30 | parser.add_argument('modelToFix', help="m3 which has the wrong animation ids") 31 | parser.add_argument('outputFile', help="name of the new m3 file to create") 32 | args = parser.parse_args() 33 | 34 | animIdModel = m3.loadModel(args.animIdFile) 35 | modelToFix = m3.loadModel(args.modelToFix) 36 | outputFile = args.outputFile 37 | 38 | boneNameToAnimIdBoneMap = {} 39 | for bone in animIdModel.bones: 40 | boneNameToAnimIdBoneMap[bone.name] = bone 41 | 42 | oldAnimIdToNewAnimIdMap = {} 43 | for boneToFix in modelToFix.bones: 44 | boneWithAnimId = boneNameToAnimIdBoneMap[boneToFix.name] 45 | oldAnimId = boneToFix.location.header.animId 46 | newAnimId = boneWithAnimId.location.header.animId 47 | boneToFix.location.header.animId = newAnimId 48 | oldAnimIdToNewAnimIdMap[oldAnimId] = newAnimId 49 | 50 | oldAnimId = boneToFix.rotation.header.animId 51 | newAnimId = boneWithAnimId.rotation.header.animId 52 | boneToFix.rotation.header.animId = newAnimId 53 | oldAnimIdToNewAnimIdMap[oldAnimId] = newAnimId 54 | 55 | oldAnimId = boneToFix.scale.header.animId 56 | newAnimId = boneWithAnimId.scale.header.animId 57 | boneToFix.scale.header.animId = newAnimId 58 | oldAnimIdToNewAnimIdMap[oldAnimId] = newAnimId 59 | 60 | def assertModelContainsOneDivisionAndMSec(model): 61 | if len(model.divisions) != 1 or len(model.divisions[0].msec) != 1: 62 | raise Exception("Model contains %d divisions and the first division has %d msec" % (len(model.divisions), len(model.divisions[0].msec))) 63 | 64 | assertModelContainsOneDivisionAndMSec(modelToFix) 65 | assertModelContainsOneDivisionAndMSec(animIdModel) 66 | msecToFix = modelToFix.divisions[0].msec[0] 67 | msecWithAnimId = animIdModel.divisions[0].msec[0] 68 | oldAnimId = msecToFix.boundingsAnimation.header.animId 69 | newAnimId = msecWithAnimId.boundingsAnimation.header.animId 70 | msecToFix.boundingsAnimation.header.animId = newAnimId 71 | oldAnimIdToNewAnimIdMap[oldAnimId] = newAnimId 72 | 73 | for stc in modelToFix.sequenceTransformationCollections: 74 | animIds = stc.animIds 75 | for i in range(len(animIds)): 76 | newAnimId = oldAnimIdToNewAnimIdMap.get(animIds[i]) 77 | if newAnimId is not None: 78 | animIds[i] = newAnimId 79 | 80 | for sts in modelToFix.sts: 81 | animIds = sts.animIds 82 | for i in range(len(animIds)): 83 | newAnimId = oldAnimIdToNewAnimIdMap.get(animIds[i]) 84 | if newAnimId is not None: 85 | animIds[i] = newAnimId 86 | 87 | m3.saveAndInvalidateModel(modelToFix, outputFile) 88 | 89 | -------------------------------------------------------------------------------- /transferAnimations.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # -*- coding: utf-8 -*- 3 | 4 | # ##### BEGIN GPL LICENSE BLOCK ##### 5 | # 6 | # This program is free software; you can redistribute it and/or 7 | # modify it under the terms of the GNU General Public License 8 | # as published by the Free Software Foundation; either version 2 9 | # of the License, or (at your option) any later version. 10 | # 11 | # This program is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU General Public License for more details. 15 | # 16 | # You should have received a copy of the GNU General Public License 17 | # along with this program; if not, write to the Free Software Foundation, 18 | # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 19 | # 20 | # ##### END GPL LICENSE BLOCK ##### 21 | 22 | 23 | import m3 24 | import sys 25 | import argparse 26 | 27 | 28 | if __name__ == "__main__": 29 | parser = argparse.ArgumentParser(description='Combines an m3 and m3a file') 30 | parser.add_argument('m3File', help="m3 file") 31 | parser.add_argument('m3aFile', help="m3a files with extra animations for the m3 file") 32 | parser.add_argument('outputFile', help="name of the new m3 file to create") 33 | args = parser.parse_args() 34 | 35 | m3Model = m3.loadModel(args.m3File) 36 | m3aModel = m3.loadModel(args.m3aFile) 37 | outputFile = args.outputFile 38 | sameFormat = True 39 | 40 | if (len(m3Model.sequences) > 0 and len(m3aModel.sequences) > 0): 41 | if m3Model.sequences[0].structureDescription != m3aModel.sequences[0].structureDescription: 42 | sameFormat = False 43 | if (len(m3Model.sequenceTransformationCollections) > 0 and len(m3aModel.sequenceTransformationCollections) > 0): 44 | if m3Model.sequenceTransformationCollections[0].structureDescription != m3aModel.sequenceTransformationCollections[0].structureDescription: 45 | sameFormat = False 46 | if (len(m3Model.sequenceTransformationGroups) > 0 and len(m3aModel.sequenceTransformationGroups) > 0): 47 | if m3Model.sequenceTransformationGroups[0].structureDescription != m3aModel.sequenceTransformationGroups[0].structureDescription: 48 | sameFormat = False 49 | if (len(m3Model.sts) > 0 and len(m3aModel.sts) > 0): 50 | if m3Model.sts[0].structureDescription != m3aModel.sts[0].structureDescription: 51 | sameFormat = False 52 | 53 | if not sameFormat: 54 | sys.stderr.write("The animation data has been stored in differnt formats\n") 55 | sys.exit(1) 56 | 57 | if m3Model.uniqueUnknownNumber != m3aModel.uniqueUnknownNumber: 58 | sys.stderr.write("The animations / the m3a file has not been made for the m3 file\n") 59 | sys.exit(1) 60 | 61 | m3aAnimationNames = set() 62 | for seq in m3aModel.sequences: 63 | m3aAnimationNames.add(seq.name) 64 | 65 | m3AnimationNames = set() 66 | for seq in m3Model.sequences: 67 | m3AnimationNames.add(seq.name) 68 | 69 | animationNameConflicts = m3AnimationNames.intersection(m3aAnimationNames) 70 | if len(animationNameConflicts) > 0: 71 | sys.stderr.write("Animation name conflict detected: %s\n" % animationNameConflicts) 72 | sys.exit(1) 73 | 74 | numberOfSequences = len(m3aModel.sequences) 75 | if len(m3aModel.sequenceTransformationGroups) != numberOfSequences: 76 | raise Exception("Script or model incorrect: The model has not the same amounth of stg elements as it has sequences.") 77 | for sequenceIndex in range(numberOfSequences): 78 | sequence = m3aModel.sequences[sequenceIndex] 79 | stg = m3aModel.sequenceTransformationGroups[sequenceIndex] 80 | newSTCIndices = [] 81 | for oldSTCIndex in stg.stcIndices: 82 | stc = m3aModel.sequenceTransformationCollections[oldSTCIndex] 83 | if stc.stsIndex != stc.stsIndexCopy: 84 | raise Exception("Script or model incorrect: stsIndex != stsIndexCopy.") 85 | sts = m3aModel.sts[stc.stsIndex] 86 | stc.stsIndex = len(m3Model.sts) 87 | stc.stsIndexCopy = stc.stsIndex 88 | m3Model.sts.append(sts) 89 | newSTCIndex = len(m3Model.sequenceTransformationCollections) 90 | m3Model.sequenceTransformationCollections.append(stc) 91 | newSTCIndices.append(newSTCIndex) 92 | stg.stcIndices = newSTCIndices 93 | m3Model.sequences.append(sequence) 94 | m3Model.sequenceTransformationGroups.append(stg) 95 | 96 | m3.saveAndInvalidateModel(m3Model, outputFile) 97 | 98 | -------------------------------------------------------------------------------- /ui/__init__.py: -------------------------------------------------------------------------------- 1 | # ##### BEGIN GPL LICENSE BLOCK ##### 2 | # 3 | # This program is free software; you can redistribute it and/or 4 | # modify it under the terms of the GNU General Public License 5 | # as published by the Free Software Foundation; either version 2 6 | # of the License, or (at your option) any later version. 7 | # 8 | # This program is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | # GNU General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU General Public License 14 | # along with this program; if not, write to the Free Software Foundation, 15 | # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 16 | # 17 | # ##### END GPL LICENSE BLOCK ##### 18 | 19 | from .base import * 20 | from .projection import * 21 | -------------------------------------------------------------------------------- /ui/base.py: -------------------------------------------------------------------------------- 1 | # ##### BEGIN GPL LICENSE BLOCK ##### 2 | # 3 | # This program is free software; you can redistribute it and/or 4 | # modify it under the terms of the GNU General Public License 5 | # as published by the Free Software Foundation; either version 2 6 | # of the License, or (at your option) any later version. 7 | # 8 | # This program is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | # GNU General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU General Public License 14 | # along with this program; if not, write to the Free Software Foundation, 15 | # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 16 | # 17 | # ##### END GPL LICENSE BLOCK ##### 18 | 19 | import bpy 20 | import bpy_extras 21 | from ..common import mlog 22 | from ..cm import M3ImportContentPreset 23 | from .. import m3export 24 | from .. import m3import 25 | 26 | 27 | class ExportPanel(bpy.types.Panel): 28 | bl_idname = "OBJECT_PT_M3_quickExport" 29 | bl_label = "M3 Quick Export" 30 | bl_space_type = "PROPERTIES" 31 | bl_region_type = "WINDOW" 32 | bl_context = "scene" 33 | 34 | def draw(self, context): 35 | scene = context.scene 36 | self.layout.prop(scene.m3_export_options, "path", text="") 37 | self.layout.operator("m3.quick_export", text="Export As M3") 38 | ExportPanel.draw_layout(self.layout, scene) 39 | 40 | @classmethod 41 | def draw_layout(cls, layout: bpy.types.UILayout, scene: bpy.types.Scene): 42 | layout.prop(scene.m3_export_options, "modlVersion") 43 | layout.prop(scene.m3_export_options, "animationExportAmount") 44 | 45 | 46 | class M3_OT_export(bpy.types.Operator, bpy_extras.io_utils.ExportHelper): 47 | """Export a M3 file""" 48 | bl_idname = "m3.export" 49 | bl_label = "Export M3 Model" 50 | bl_options = {"UNDO"} 51 | 52 | filename_ext = ".m3" 53 | filter_glob: bpy.props.StringProperty(default="*.m3", options={"HIDDEN"}) 54 | 55 | filepath: bpy.props.StringProperty( 56 | name="File Path", 57 | description="Path of the file that should be created", 58 | maxlen=1024, default="" 59 | ) 60 | 61 | def execute(self, context): 62 | scene = context.scene 63 | scene.m3_export_options.path = self.properties.filepath 64 | return m3export.export(scene, self, self.properties.filepath) 65 | 66 | def invoke(self, context, event): 67 | context.window_manager.fileselect_add(self) 68 | return {"RUNNING_MODAL"} 69 | 70 | def draw(self, context): 71 | ExportPanel.draw_layout(self.layout, context.scene) 72 | 73 | 74 | class M3_OT_quickExport(bpy.types.Operator): 75 | bl_idname = "m3.quick_export" 76 | bl_label = "Quick Export" 77 | bl_description = "Exports the model to the specified m3 path without asking further questions" 78 | 79 | def invoke(self, context, event): 80 | scene = context.scene 81 | fileName = scene.m3_export_options.path 82 | return m3export.export(scene, self, fileName) 83 | 84 | 85 | class ImportPanel(bpy.types.Panel): 86 | bl_idname = "OBJECT_PT_M3_quickImport" 87 | bl_label = "M3 Import" 88 | bl_space_type = "PROPERTIES" 89 | bl_region_type = "WINDOW" 90 | bl_context = "scene" 91 | 92 | def draw(self, context): 93 | layout = self.layout 94 | scene = context.scene 95 | 96 | layout.prop(scene.m3_import_options, "path", text="M3 File") 97 | ImportPanel.draw_layout(layout, scene) 98 | layout.operator("m3.quick_import", text="Import M3") 99 | layout.operator("m3.generate_blender_materials", text="Generate Blender Materials") 100 | 101 | @classmethod 102 | def draw_content_import(cls, layout: bpy.types.UILayout, scene: bpy.types.Scene): 103 | layout.prop(scene.m3_import_options.content, "mesh") 104 | layout.prop(scene.m3_import_options.content, "materials") 105 | layout.prop(scene.m3_import_options.content, "bones") 106 | layout.prop(scene.m3_import_options.content, "rigging") 107 | layout.prop(scene.m3_import_options.content, "cameras") 108 | layout.prop(scene.m3_import_options.content, "fuzzyHitTests") 109 | layout.prop(scene.m3_import_options.content, "tightHitTest") 110 | layout.prop(scene.m3_import_options.content, "particleSystems") 111 | layout.prop(scene.m3_import_options.content, "ribbons") 112 | layout.prop(scene.m3_import_options.content, "forces") 113 | layout.prop(scene.m3_import_options.content, "rigidBodies") 114 | layout.prop(scene.m3_import_options.content, "lights") 115 | layout.prop(scene.m3_import_options.content, "billboardBehaviors") 116 | layout.prop(scene.m3_import_options.content, "attachmentPoints") 117 | layout.prop(scene.m3_import_options.content, "projections") 118 | layout.prop(scene.m3_import_options.content, "warps") 119 | 120 | @classmethod 121 | def draw_layout(cls, layout: bpy.types.UILayout, scene: bpy.types.Scene): 122 | layout.prop(scene.m3_import_options, "contentPreset") 123 | if scene.m3_import_options.contentPreset == M3ImportContentPreset.Custom: 124 | ImportPanel.draw_content_import(layout.box().column(heading="Content to import"), scene) 125 | if scene.m3_import_options.contentPreset not in [M3ImportContentPreset.MeshMaterials, M3ImportContentPreset.MeshMaterialsVG]: 126 | layout.prop(scene.m3_import_options, "armatureObject") 127 | 128 | layout.prop(scene.m3_import_options, "rootDirectory", text="Root Directory") 129 | layout.prop(scene.m3_import_options, "generateBlenderMaterials", text="Generate Blender Materials At Import") 130 | layout.prop(scene.m3_import_options, "applySmoothShading", text="Apply Smooth Shading") 131 | layout.prop(scene.m3_import_options, "markSharpEdges", text="Mark sharp edges") 132 | layout.prop(scene.m3_import_options, "teamColor", text="Team Color") 133 | 134 | 135 | class M3_OT_import(bpy.types.Operator, bpy_extras.io_utils.ImportHelper): 136 | """Load a M3 file""" 137 | bl_idname = "m3.import" 138 | bl_label = "Import M3" 139 | bl_options = {"UNDO"} 140 | 141 | filename_ext = ".m3" 142 | filter_glob: bpy.props.StringProperty(default="*.m3;*.m3a", options={"HIDDEN"}) 143 | 144 | filepath: bpy.props.StringProperty( 145 | name="File Path", 146 | description="File path used for importing the simple M3 file", 147 | maxlen=1024, 148 | default="" 149 | ) 150 | 151 | def execute(self, context): 152 | mlog.debug("Import %s" % self.properties.filepath) 153 | scene = context.scene 154 | scene.m3_import_options.path = self.properties.filepath 155 | m3import.importM3BasedOnM3ImportOptions(scene) 156 | return {"FINISHED"} 157 | 158 | def invoke(self, context, event): 159 | context.window_manager.fileselect_add(self) 160 | return {"RUNNING_MODAL"} 161 | 162 | def draw(self, context): 163 | ImportPanel.draw_layout(self.layout, context.scene) 164 | 165 | 166 | class M3_OT_quickImport(bpy.types.Operator): 167 | bl_idname = "m3.quick_import" 168 | bl_label = "Quick Import" 169 | bl_description = "Imports the model to the specified m3 path without asking further questions" 170 | 171 | def invoke(self, context, event): 172 | scene = context.scene 173 | m3import.importM3BasedOnM3ImportOptions(scene) 174 | return {"FINISHED"} 175 | -------------------------------------------------------------------------------- /ui/projection.py: -------------------------------------------------------------------------------- 1 | # ##### BEGIN GPL LICENSE BLOCK ##### 2 | # 3 | # This program is free software; you can redistribute it and/or 4 | # modify it under the terms of the GNU General Public License 5 | # as published by the Free Software Foundation; either version 2 6 | # of the License, or (at your option) any later version. 7 | # 8 | # This program is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | # GNU General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU General Public License 14 | # along with this program; if not, write to the Free Software Foundation, 15 | # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 16 | # 17 | # ##### END GPL LICENSE BLOCK ##### 18 | 19 | import bpy 20 | from .. import cm 21 | from .. import shared 22 | 23 | 24 | class ProjectionMenu(bpy.types.Menu): 25 | bl_idname = "OBJECT_MT_M3_projections" 26 | bl_label = "Select" 27 | 28 | def draw(self, context): 29 | layout = self.layout 30 | shared.draw_collection_op_generic(layout, 'duplicate', 'm3_projections', 'm3_projection_index', text='Duplicate') 31 | 32 | 33 | class ProjectionPanel(bpy.types.Panel): 34 | bl_idname = "OBJECT_PT_M3_projections" 35 | bl_label = "M3 Projections" 36 | bl_space_type = 'PROPERTIES' 37 | bl_region_type = 'WINDOW' 38 | bl_context = "scene" 39 | bl_options = {'DEFAULT_CLOSED'} 40 | 41 | def draw(self, context): 42 | layout = self.layout 43 | scene = context.scene 44 | 45 | shared.draw_collection_list(layout, 'm3_projections', 'm3_projection_index', menu_id=ProjectionMenu.bl_idname) 46 | 47 | if scene.m3_projection_index < 0: 48 | return 49 | 50 | projection = scene.m3_projections[scene.m3_projection_index] 51 | layout.separator() 52 | layout.prop(projection, 'name') 53 | layout.prop_search(projection, 'materialName', scene, 'm3_material_references', text="Material", icon='NONE') 54 | col = layout.column(align=True) 55 | col.prop(projection, "projectionType", text="Type") 56 | box = col.box() 57 | bcol = box.column(align=True) 58 | if projection.projectionType == cm.ProjectionType.orthonormal: 59 | bcol.prop(projection, 'depth', text="Depth") 60 | bcol.prop(projection, 'width', text="Width") 61 | bcol.prop(projection, 'height', text="Height") 62 | elif projection.projectionType == cm.ProjectionType.perspective: 63 | bcol.prop(projection, 'fieldOfView') 64 | bcol.prop(projection, 'aspectRatio', text="Aspect Ratio") 65 | bcol.prop(projection, 'near', text="Near") 66 | bcol.prop(projection, 'far', text="Far") 67 | 68 | row = layout.row() 69 | row.label(text='Splat Layer:') 70 | row.prop(projection, 'splatLayer', text='') 71 | 72 | row = layout.row(align=True) 73 | row.label(text='LOD Reduce/Cutoff:') 74 | row.prop(projection, 'lodReduce', text='') 75 | row.prop(projection, 'lodCut', text='') 76 | 77 | row = layout.row() 78 | col = row.column(align=True) 79 | col.label(text="Alpha Over Time:") 80 | col.prop(projection, 'alphaOverTimeStart', text="Start") 81 | col.prop(projection, 'alphaOverTimeMid', text="Middle") 82 | col.prop(projection, 'alphaOverTimeEnd', text="End") 83 | 84 | row = layout.row(align=True) 85 | row.label(text='Lifetime (Attack):') 86 | row.prop(projection, 'splatLifeTimeAttack', text='From') 87 | row.prop(projection, 'splatLifeTimeAttackTo', text='To') 88 | 89 | row = layout.row(align=True) 90 | row.label(text='Lifetime (Hold):') 91 | row.prop(projection, 'splatLifeTimeHold', text='From') 92 | row.prop(projection, 'splatLifeTimeHoldTo', text='To') 93 | 94 | row = layout.row(align=True) 95 | row.label(text='Lifetime (Decay):') 96 | row.prop(projection, 'splatLifeTimeDecay', text='From') 97 | row.prop(projection, 'splatLifeTimeDecayTo', text='To') 98 | 99 | row = layout.row() 100 | row.label(text=cm.M3Projection.bl_rna.properties['attenuationPlaneDistance'].name) 101 | row.prop(projection, 'attenuationPlaneDistance', text='Start at') 102 | 103 | layout.label(text="Flags:") 104 | box = layout.box() 105 | col = box.column_flow() 106 | col.prop(projection, 'active') 107 | col.prop(projection, 'staticPosition') 108 | col.prop(projection, 'unknownFlag0x2') 109 | col.prop(projection, 'unknownFlag0x4') 110 | col.prop(projection, 'unknownFlag0x8') 111 | -------------------------------------------------------------------------------- /xmlToM3.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # -*- coding: utf-8 -*- 3 | 4 | # ##### BEGIN GPL LICENSE BLOCK ##### 5 | # 6 | # This program is free software; you can redistribute it and/or 7 | # modify it under the terms of the GNU General Public License 8 | # as published by the Free Software Foundation; either version 2 9 | # of the License, or (at your option) any later version. 10 | # 11 | # This program is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU General Public License for more details. 15 | # 16 | # You should have received a copy of the GNU General Public License 17 | # along with this program; if not, write to the Free Software Foundation, 18 | # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 19 | # 20 | # ##### END GPL LICENSE BLOCK ##### 21 | 22 | import sys 23 | import m3 24 | import xml.dom.minidom 25 | from xml.dom.minidom import Node 26 | import argparse 27 | import os 28 | import time 29 | 30 | 31 | def forElementsIn(xmlNode): 32 | for child in xmlNode.childNodes: 33 | if type(child) == xml.dom.minidom.Text: 34 | if not child.wholeText.isspace(): 35 | raise Exception("Unexpected content \"%s\" within element %s" % (child.wholeText, xmlNode.nodeName)) 36 | else: 37 | yield child 38 | 39 | 40 | def createSingleStructureElement(xmlNode, structureDescription): 41 | createdObject = structureDescription.createInstance() 42 | fieldIndex = 0 43 | for child in forElementsIn(xmlNode): 44 | fieldName = child.nodeName 45 | if fieldIndex >= len(structureDescription.fields): 46 | raise Exception("XML file is incompatible: too many fields") 47 | field = structureDescription.fields[fieldIndex] 48 | if field.name != fieldName: 49 | raise Exception("XML file is incompatible: Expected field %s but found field %s" % (field.name, fieldName)) 50 | 51 | fieldContent = createFieldContent(child, field) 52 | setattr(createdObject, field.name, fieldContent) 53 | fieldIndex += 1 54 | 55 | missingFields = len(structureDescription.fields) - fieldIndex 56 | if missingFields > 0: 57 | raise Exception("XML file is incompatible: %d fields are missing in %s" % (missingFields, structureDescription.structureName)) 58 | 59 | return createdObject 60 | 61 | 62 | intTypeStrings = set(["int32", "int16", "int8", "uint32", "uint16", "uint8"]) 63 | 64 | 65 | def createFieldContent(xmlNode, field): 66 | if isinstance(field, m3.ReferenceField): 67 | if field.historyOfReferencedStructures is None: 68 | return [] # TODO check if that's correct 69 | else: 70 | referencedStructureName = field.historyOfReferencedStructures.name 71 | if referencedStructureName == "CHAR": 72 | if len(xmlNode.childNodes) == 0: 73 | return None 74 | return stringContentOf(xmlNode) 75 | elif referencedStructureName == "U8__": 76 | return bytearray(hexToBytes(stringContentOf(xmlNode), xmlNode)) 77 | else: 78 | if field.historyOfReferencedStructures is not None: 79 | return createElementList(xmlNode, field.name, field.historyOfReferencedStructures) 80 | else: 81 | return createElementList(xmlNode, field.name, None) 82 | 83 | elif isinstance(field, m3.UnknownBytesField): 84 | return hexToBytes(stringContentOf(xmlNode), xmlNode) 85 | elif isinstance(field, m3.PrimitiveField): 86 | if field.typeString == "float": 87 | return float(stringContentOf(xmlNode)) 88 | elif field.typeString in intTypeStrings: 89 | return int(stringContentOf(xmlNode), 0) 90 | else: 91 | raise Exception("Unsupported primtive: %s" % field.typeString) 92 | elif isinstance(field, m3.EmbeddedStructureField): 93 | return createSingleStructureElement(xmlNode, field.structureDescription) 94 | else: # TagField 95 | raise Exception("Unsupported field type %s" % type(field)) 96 | 97 | 98 | def removeWhitespace(s): 99 | return s.translate({ord(" "): None, ord("\t"): None, ord("\r"): None, ord("\n"): None}) 100 | 101 | 102 | def hexToBytes(hexString, xmlNode): 103 | hexString = removeWhitespace(hexString) 104 | if hexString == "": 105 | return bytearray(0) 106 | if not hexString.startswith("0x"): 107 | raise Exception('hex string "%s" of node %s does not start with 0x' % (hexString, xmlNode.nodeName)) 108 | hexString = hexString[2:] 109 | return bytes([int(hexString[x: x + 2], 16) for x in range(0, len(hexString), 2)]) 110 | 111 | 112 | def stringContentOf(xmlNode): 113 | content = "" 114 | for child in xmlNode.childNodes: 115 | if child.nodeType == Node.TEXT_NODE: 116 | content += child.data 117 | else: 118 | raise Exception("Element %s contained childs of xml node type %s." % (xmlNode.nodeName, type(xmlNode))) 119 | return content 120 | 121 | 122 | def createListElement(xmlNode, structureDescription): 123 | if structureDescription.structureName in ["I32_", "I16_", "I8__", "U32_", "U16_", "U8__", "FLAG"]: 124 | return int(stringContentOf(xmlNode), 0) 125 | elif structureDescription.structureName in ["REAL"]: 126 | return float(stringContentOf(xmlNode)) 127 | else: 128 | return createSingleStructureElement(xmlNode, structureDescription) 129 | 130 | 131 | def childElementsOf(parentName, xmlNode): 132 | expectedChildNames = parentName + "-element" 133 | for child in xmlNode.childNodes: 134 | if type(child) == xml.dom.minidom.Text: 135 | if not child.data.isspace(): 136 | raise Exception("Unexpected content \"%s\" within element %s" % (child.wholeText, xmlNode.nodeName)) 137 | else: 138 | if (child.nodeName != expectedChildNames): 139 | raise Exception("Unexpected child \"%s\" within element %s", (child.nodeName, xmlNode.nodeName)) 140 | yield child 141 | 142 | 143 | def createElementList(xmlNode, parentName, historyOfReferencedStructure): 144 | xmlElements = list(childElementsOf(parentName, xmlNode)) 145 | if historyOfReferencedStructure.name in ["CHAR", "I32_", "I16_", "I8__", "U32_", "U16_", "U8__", "REAL", "FLAG"]: 146 | structVersion = 0 147 | else: 148 | if len(xmlElements) == 0: 149 | return [] 150 | 151 | child = xmlNode.firstChild 152 | structVersion = int(xmlNode.getAttribute("structureVersion")) 153 | structName = xmlNode.getAttribute("structureName") 154 | if structName == "" or structVersion == "": 155 | raise Exception("Incompatible format: Require now a strutureName and structureVerson attribute for the list %s" % parentName) 156 | if structName != historyOfReferencedStructure.name: 157 | raise Exception("Expected a %s to have the structure name %s instead of %s" % (parentName, historyOfReferencedStructure.name, structName)) 158 | structureDescription = historyOfReferencedStructure.getVersion(structVersion) 159 | createdList = [] 160 | for child in xmlElements: 161 | o = createListElement(child, structureDescription) 162 | createdList.append(o) 163 | 164 | return createdList 165 | 166 | 167 | def convertFile(inputFilePath, outputDirectory): 168 | if outputDirectory is not None: 169 | fileName = os.path.basename(inputFilePath) 170 | outputFilePath = os.path.join(outputDirectory, fileName[:-4]) 171 | else: 172 | outputFilePath = inputFilePath[:-4] 173 | print("Converting %s -> %s" % (inputFilePath, outputFilePath)) 174 | doc = xml.dom.minidom.parse(inputFilePath) 175 | modelElement = doc.firstChild 176 | structVersion = int(modelElement.getAttribute("structureVersion")) 177 | structName = modelElement.getAttribute("structureName") 178 | modelDescription = m3.structures[structName].getVersion(structVersion) 179 | model = createSingleStructureElement(modelElement, modelDescription) 180 | m3.saveAndInvalidateModel(model, outputFilePath) 181 | 182 | 183 | if __name__ == "__main__": 184 | parser = argparse.ArgumentParser() 185 | parser.add_argument('path', nargs='+', help="Either a *.m3.xml file or a directory with *.m3.xml files generated with m3ToXml.py") 186 | parser.add_argument('--output-directory', '-o', help='Directory in which m3 files will be placed') 187 | parser.add_argument('--watch', action='store_const', const=True, default=False) 188 | args = parser.parse_args() 189 | outputDirectory = args.output_directory 190 | if outputDirectory is not None and not os.path.isdir(outputDirectory): 191 | sys.stderr.write("%s is not a directory" % outputDirectory) 192 | sys.exit(2) 193 | for filePath in args.path: 194 | if not (filePath.endswith(".m3.xml") or os.path.isdir(filePath)): 195 | sys.stderr.write("%s neither a directory nor does it end with '.m3.xml'\n" % filePath) 196 | sys.exit(2) 197 | 198 | if args.watch: 199 | if ((len(args.path) == 0) or os.path.isdir(filePath)): 200 | sys.stderr.write("Watch option is only supported for a single file") 201 | sys.exit(2) 202 | 203 | previousModelModiticationTime = os.path.getmtime(filePath) 204 | convertFile(filePath, outputDirectory) 205 | print("Converted %s to an m3 file. Will convert it again if it changes" % filePath) 206 | while True: 207 | currentModelModificationTime = os.path.getmtime(filePath) 208 | if currentModelModificationTime > previousModelModiticationTime: 209 | print("File modified at %s, converting again" % time.ctime(currentModelModificationTime)) 210 | convertFile(filePath, outputDirectory) 211 | print("converted file") 212 | previousModelModiticationTime = currentModelModificationTime 213 | time.sleep(0.1) 214 | else: 215 | counter = 0 216 | for filePath in args.path: 217 | if os.path.isdir(filePath): 218 | for fileName in os.listdir(filePath): 219 | inputFilePath = os.path.join(filePath, fileName) 220 | if fileName.endswith(".m3.xml"): 221 | convertFile(inputFilePath, outputDirectory) 222 | counter += 1 223 | else: 224 | convertFile(filePath, outputDirectory) 225 | counter += 1 226 | if counter == 1: 227 | print("Converted %d file from .m3.xml to .m3" % counter) 228 | else: 229 | print("Converted %d files from .m3.xml to .m3" % counter) 230 | --------------------------------------------------------------------------------