├── LICENSE ├── Makefile ├── README.md ├── blender2minecraft ├── __init__.py ├── export.py └── importer.py └── blender2minecraftTemplate.blend /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 | {description} 294 | Copyright (C) {year} {fullname} 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 | {signature of Ty Coon}, 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 | 341 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | all: blender2minecraft.zip 2 | 3 | blender2minecraft.zip: $(shell find blender2minecraft -type f -not -name '.*') 4 | zip -r blender2minecraft.zip blender2minecraft/ 5 | 6 | install: 7 | unzip -o blender2minecraft.zip -d ~/.config/blender/2.78/scripts/addons 8 | 9 | clean: 10 | rm blender2minecraft.zip 11 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | blender2minecraft - 1.9 2 | ======================= 3 | 4 | A Blender Add-on to create Minecraft 3D-Models inside Blender. 5 | 6 | Updated for Minecraft 1.9 7 | -------------------------------------------------------------------------------- /blender2minecraft/__init__.py: -------------------------------------------------------------------------------- 1 | bl_info = { 2 | "name": "Blender2Minecraft", 3 | "author": "freundTech", 4 | "version": (0, 3), 5 | "blender": (2, 6, 9), 6 | "location": "File > Export > Export to Minecraft", 7 | "description": "Export Scene as Minecraft Blockmodel", 8 | "wiki_url": "https://github.com/freundTech/blender2minecraft/wiki", 9 | "tracker_url": "https://github.com/freundTech/blender2minecraft/issues", 10 | "support": "COMMUNITY", 11 | "category": "Import-Export" 12 | } 13 | 14 | if "bpy" in locals(): 15 | import imp 16 | imp.reload(export) 17 | print("Reloaded multifiles") 18 | else: 19 | from . import export 20 | print("Imported multifiles") 21 | 22 | import bpy 23 | from bpy_extras.io_utils import ExportHelper 24 | from bpy.props import StringProperty, BoolProperty, EnumProperty, FloatProperty 25 | from bpy.types import Operator, Panel 26 | 27 | import math 28 | 29 | #pullrequests using pi will not be accepted. Learn to use tau ;) 30 | tau = 2*math.pi 31 | 32 | 33 | class ExportBlockModel(Operator, ExportHelper): 34 | """This appears in the tooltip of the operator and in the generated docs""" 35 | bl_idname = "export_mc.blockmodel" # important since its how bpy.ops.import_test.some_data is constructed 36 | bl_label = "Export Scene as Minecraft Blockmodel" 37 | 38 | filename_ext = ".json" 39 | 40 | filter_glob = StringProperty( 41 | default="*.json", 42 | options={'HIDDEN'}, 43 | ) 44 | include_textures = BoolProperty( 45 | name="Include Textures", 46 | description="Includes the texturepaths into the models", 47 | default=True, 48 | ) 49 | ambientocclusion = BoolProperty( 50 | name="Use Ambient Occlusion", 51 | description="Turns the Ambient Occlusion option on or off", 52 | default=True, 53 | ) 54 | minify = BoolProperty( 55 | name="Minify Json", 56 | description="Reduces size of exported .json by omitting redundant whitespaces", 57 | default=True, 58 | ) 59 | 60 | fplTransform = bpy.props.FloatVectorProperty( 61 | name = "First Person Left Hand Transform", 62 | description = "Translation, Rotation and Scale of first person (in left hand) rendering", 63 | size = 9, 64 | default=[0.0, 0.0, 0.0, 65 | 0.0, 45.0, 0.0, 66 | 0.4, 0.4, 0.4 67 | ] 68 | ) 69 | fprTransform = bpy.props.FloatVectorProperty( 70 | name = "First Person Right Hand Transform", 71 | description = "Translation, Rotation and Scale of first person (in right hand) rendering", 72 | size = 9, 73 | default=[0.0, 0.0, 0.0, 74 | 0.0, 45.0, 0.0, 75 | 0.4, 0.4, 0.4 76 | ] 77 | ) 78 | tplTransform = bpy.props.FloatVectorProperty( 79 | name = "Third Person Left Hand Transform", 80 | description = "Translation, Rotation and Scale of third person (in left hand) rendering", 81 | size = 9, 82 | default=[0.0, 2.5, 0.0, 83 | 75.0, 45.0, 0.0, 84 | 0.375, 0.375, 0.375 85 | ] 86 | ) 87 | tprTransform = bpy.props.FloatVectorProperty( 88 | name = "Third Person Right Hand Transform", 89 | description = "Translation, Rotation and Scale of third person (in right hand) rendering", 90 | size = 9, 91 | default=[0.0, 2.5, 0.0, 92 | 75.0, 45.0, 0.0, 93 | 0.375, 0.375, 0.375 94 | ] 95 | ) 96 | guiTransform = bpy.props.FloatVectorProperty( 97 | name = "GUI Transform", 98 | description = "Translation, Rotation and Scale in the GUI (Inventory)", 99 | size = 9, 100 | default=[0.0, 0.0, 0.0, 101 | 30.0, 225.0, 0.0, 102 | 0.35, 0.35, 0.35 103 | ] 104 | ) 105 | headTransform = bpy.props.FloatVectorProperty( 106 | name = "Head Transform", 107 | description = "Translation, Rotation and Scale when equipped as helmet", 108 | size = 9, 109 | default=[0.0, 0.0, 0.0, 110 | 0.0, 0.0, 0.0, 111 | 1.0, 1.0, 1.0]) 112 | groundTransform = bpy.props.FloatVectorProperty( 113 | name = "Ground Transform", 114 | description = "Translation, Rotation and Scale on the ground", 115 | size = 9, 116 | default=[0.0, 3.0, 0.0, 117 | 0.0, 0.0, 0.0, 118 | 0.25, 0.25, 0.25 119 | ] 120 | ) 121 | fixedTransform = bpy.props.FloatVectorProperty( 122 | name = "Item Frame Transform", 123 | description = "Translation, Rotation and Scale in Item Frames", 124 | size = 9, 125 | default=[0.0, 0.0, 0.0, 126 | 0.0, 0.0, 0.0, 127 | 0.5, 0.5, 0.5 128 | ] 129 | ) 130 | 131 | def draw(self, context): 132 | layout = self.layout 133 | 134 | scene = context.scene 135 | 136 | # Create a simple row. 137 | layout.label(text="Textures:") 138 | row = layout.row() 139 | row.prop(self, "include_textures") 140 | 141 | layout.label(text="Ambient Occlusion:") 142 | row = layout.row() 143 | row.prop(self, "ambientocclusion") 144 | 145 | layout.label(text="Minify Json:") 146 | row = layout.row() 147 | row.prop(self, "minify") 148 | 149 | def createTransform(name, value): 150 | layout.label() 151 | layout.label(text=name) 152 | split = layout.split() 153 | col = split.column(align=True) 154 | col.label(text="Translate:") 155 | col.prop(self, value, index=0, text="X") 156 | col.prop(self, value, index=1, text="Y") 157 | col.prop(self, value, index=2, text="Z") 158 | 159 | col = split.column(align=True) 160 | col.label(text="Rotate:") 161 | col.prop(self, value, index=3, text="X") 162 | col.prop(self, value, index=4, text="Y") 163 | col.prop(self, value, index=5, text="Z") 164 | 165 | col = split.column(align=True) 166 | col.label(text="Scale:") 167 | col.prop(self, value, index=6, text="X") 168 | col.prop(self, value, index=7, text="Y") 169 | col.prop(self, value, index=8, text="Z") 170 | 171 | createTransform("First Person - Left hand :", "fplTransform") 172 | createTransform("First Person - Right hand :", "fprTransform") 173 | createTransform("Third Person - Left hand:", "tplTransform") 174 | createTransform("Third Person - Right hand:", "tprTransform") 175 | createTransform("Inventory:", "guiTransform") 176 | createTransform("Head:", "headTransform") 177 | createTransform("Ground:", "groundTransform") 178 | createTransform("Item Frame:", "fixedTransform") 179 | 180 | def execute(self, context): 181 | #do the export 182 | #TODO: What was I thinking when writing that function signature 183 | return export.write_to_file(context, self.filepath, self.include_textures, self.ambientocclusion, self.minify, 184 | self.fplTransform[0:3], 185 | self.fplTransform[6:9], 186 | self.fplTransform[3:6], 187 | self.fprTransform[0:3], 188 | self.fprTransform[6:9], 189 | self.fprTransform[3:6], 190 | self.tplTransform[0:3], 191 | self.tplTransform[6:9], 192 | self.tplTransform[3:6], 193 | self.tprTransform[0:3], 194 | self.tprTransform[6:9], 195 | self.tprTransform[3:6], 196 | self.guiTransform[0:3], 197 | self.guiTransform[6:9], 198 | self.guiTransform[3:6], 199 | self.headTransform[0:3], 200 | self.headTransform[6:9], 201 | self.headTransform[3:6], 202 | self.groundTransform[0:3], 203 | self.groundTransform[6:9], 204 | self.groundTransform[3:6], 205 | self.fixedTransform[0:3], 206 | self.fixedTransform[6:9], 207 | self.fixedTransform[3:6]) 208 | 209 | 210 | def menu_func_export(self, context): 211 | self.layout.operator(ExportBlockModel.bl_idname, text="Minecraft model (.json)") 212 | 213 | bpy.types.Image.MinecraftCullface = EnumProperty( 214 | items=[("none", "None", "Don't use cullface"), 215 | ("auto", "Auto", "Use direction the face is facing"), 216 | ("x", "X", "Use X direction"), 217 | ("y", "Y", "Use Y direction"), 218 | ("z", "Z", "Use Z direction"), 219 | ("-x", "-X", "Use -X direction"), 220 | ("-y", "-Y", "Use -Y direction"), 221 | ("-z", "-Z", "Use -Z direction"), 222 | ], 223 | name="Cullface Direction", 224 | description="Hide this face if a block is placed in the given direction." 225 | ) 226 | 227 | bpy.types.Image.MinecraftTintindex = BoolProperty( 228 | name="Tintindex", 229 | description="Has to be activated on grass, leafes and similar to color them accoring to biome" 230 | ) 231 | 232 | def update_particle(self, context): 233 | if self["MinecraftParticle"] == 1: 234 | for image in bpy.data.images: 235 | if "MinecraftParticle" in image and image != self: 236 | image["MinecraftParticle"] = 0 237 | 238 | bpy.types.Image.MinecraftParticle = BoolProperty( 239 | name="Particle", 240 | description="Use this texure as block breaking particle. Can only be activated for one texture", 241 | update=update_particle 242 | ) 243 | 244 | class ModelFacePanel(Panel): 245 | bl_label = "Minecraft Block Face Settings" 246 | bl_space_type = 'IMAGE_EDITOR' 247 | bl_region_type = 'UI' 248 | 249 | @classmethod 250 | def poll(self, context): 251 | return context.area.spaces.active.image != None 252 | 253 | def draw(self, context): 254 | self.layout.prop(context.area.spaces.active.image, "MinecraftCullface") 255 | self.layout.prop(context.area.spaces.active.image, "MinecraftTintindex") 256 | self.layout.prop(context.area.spaces.active.image, "MinecraftParticle") 257 | 258 | class OBJECT_OT_MinecraftFixRotation(Operator): 259 | bl_idname = "object.minecraftfixrotation" 260 | bl_label = "Fix Rotation" 261 | bl_description = "Fix object rotation to be usable as a minecraft model" 262 | bl_options = {'REGISTER', 'UNDO'} 263 | 264 | def execute(self, context): 265 | for obj in context.selected_objects[:]: #We'll be changing the selection in this loop, so we have to copy the list 266 | bpy.ops.object.select_all(action='DESELECT') 267 | context.scene.objects.active = obj 268 | obj.select = True 269 | realrot = [None]*3 270 | for i, rot in enumerate(obj.rotation_euler): 271 | rot = round(rot/(tau/16))*(tau/16) #round to 1/16 rotation 272 | blockrot = round(rot/(tau/4))*(tau/4) #round to 1/4 to know which rotation to apply 273 | realrot[i] = rot - blockrot #rotation that can't be applied 274 | obj.rotation_euler[i] = blockrot 275 | bpy.ops.object.transform_apply(rotation=True) 276 | for i, rot in enumerate(realrot): 277 | if rot >= 0: 278 | rot %= 360 279 | else: 280 | rot %= -360 281 | if rot != 0: 282 | obj.rotation_euler[i] = rot 283 | break #Only one axis can be rotated. Just use the first one 284 | 285 | return {'FINISHED'} 286 | 287 | class ModelPanel(Panel): 288 | bl_label = "Minecraft Block Tools" 289 | bl_space_type = 'VIEW_3D' 290 | bl_region_type = 'TOOLS' 291 | 292 | @classmethod 293 | def poll(self, context): 294 | return len(context.selected_objects) 295 | 296 | def draw(self, context): 297 | self.layout.operator(OBJECT_OT_MinecraftFixRotation.bl_idname, text="Fix Rotation") 298 | 299 | addon_keymaps = [] 300 | 301 | def register(): 302 | global keymap 303 | 304 | bpy.utils.register_module(__name__) 305 | bpy.types.INFO_MT_file_export.append(menu_func_export) 306 | 307 | wm = bpy.context.window_manager 308 | if wm.keyconfigs.addon: 309 | km = wm.keyconfigs.addon.keymaps.new(name='Object Mode') 310 | kmi = km.keymap_items.new(OBJECT_OT_MinecraftFixRotation.bl_idname, 'F', 'PRESS') 311 | addon_keymaps.append(km) 312 | 313 | def unregister(): 314 | bpy.utils.unregister_module(__name__) 315 | bpy.types.INFO_MT_file_export.remove(menu_func_export) 316 | 317 | wm = bpy.context.window_manager 318 | for km in addon_keymaps: 319 | wm.keyconfigs.addon.keymaps.remove(km) 320 | 321 | del addon_keymaps[:] 322 | 323 | if __name__ == "__main__": 324 | register() 325 | 326 | # test call 327 | bpy.ops.export_mc.blockmodel('INVOKE_DEFAULT') 328 | -------------------------------------------------------------------------------- /blender2minecraft/export.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | import bmesh 3 | import os 4 | import math 5 | import json 6 | from collections import OrderedDict 7 | 8 | #Axis for better readability 9 | x = 0 10 | y = 1 11 | z = 2 12 | 13 | #Might contain errors. Not tested yet. 14 | cullfaceDirection = { 15 | 2: "east", 16 | 3: "north", 17 | 4: "up", 18 | 5: "west", 19 | 6: "south", 20 | 7: "bottom" 21 | } 22 | 23 | #Maybe make it configurable? 24 | #Number of decimal digits to be rounded to 25 | toRound = 2 26 | 27 | #Get Maximum and Minimum values form dict values for axis axis 28 | def getMaxMin(values, axis): 29 | max = [None]*len(axis) 30 | min = [None]*len(axis) 31 | for u in range(0, len(axis)): 32 | max[u] = float('-inf') 33 | min[u] = float('inf') 34 | 35 | for value in values: 36 | for u in range(0, len(axis)): 37 | if value[axis[u]] > max[u]: 38 | max[u] = value[axis[u]] 39 | if value[axis[u]] < min[u]: 40 | min[u] = value[axis[u]] 41 | 42 | for u in range(0, len(axis)): 43 | max[u] = round(max[u], toRound) 44 | min[u] = round(min[u], toRound) 45 | return max, min 46 | 47 | def getIndex(values, mask, axis): 48 | for value in values: 49 | if round(value[axis[0]], toRound) == mask[0] and round(value[axis[1]], toRound) == mask[1]: 50 | return values.index(value) 51 | raise Exception("Value not found") 52 | 53 | #Round value to the accuracy defined in toRound 54 | def roundValue(num): 55 | return round(num, toRound) 56 | 57 | #Get direction of a face by checking the normals 58 | def getDir(face): 59 | normals = [] 60 | for i in range(0, len(face.loops)): 61 | normals.append(list(face.loops[i].vert.normal)) 62 | 63 | top = 0 64 | bottom = 0 65 | north = 0 66 | south = 0 67 | east = 0 68 | west = 0 69 | 70 | for i in range(0, len(normals)): 71 | if normals[i][x] >= 0: 72 | east += 1 73 | else: 74 | west += 1 75 | if normals[i][y] >= 0: 76 | north += 1 77 | else: 78 | south += 1 79 | if normals[i][z] >= 0: 80 | top += 1 81 | else: 82 | bottom += 1 83 | 84 | if top == 4: 85 | return ["up", [x, y]] 86 | if bottom == 4: 87 | return ["down", [x, y]] 88 | if north == 4: 89 | return ["north", [x, z]] 90 | if south == 4: 91 | return ["south", [x, z]] 92 | if east == 4: 93 | return ["east", [y, z]] 94 | if west == 4: 95 | return ["west", [y, z]] 96 | raise Exception("This should never happen") 97 | 98 | #TODO: Use acctual image class? 99 | class attrdict(dict): 100 | def __init__(self, *args, **kwargs): 101 | dict.__init__(self, *args, **kwargs) 102 | __dict__ = self 103 | 104 | #Export the model 105 | #TODO: Fix signature 106 | def write_to_file(context, filepath, include_textures, ambientocclusion, minify, 107 | first_left_trans, first_left_scale, first_left_rot, 108 | first_right_trans, first_right_scale, first_right_rot, 109 | third_left_trans, third_left_scale, third_left_rot, 110 | third_right_trans, third_right_scale, third_right_rot, 111 | invtrans, invscale, invrot, 112 | headtrans, headscale, headrot, 113 | groundtrans, groundscale, groundrot, 114 | fixedtrans, fixedscale, fixedrot): 115 | textures = [] 116 | particle = "" 117 | scene = context.scene 118 | objects = scene.objects 119 | 120 | file = open(filepath,'w', encoding='utf-8') 121 | 122 | #TODO: Figure out how to make jsondump respect the OrderedDict order 123 | fileContent = OrderedDict() 124 | 125 | fileContent["__comment"] = "This model was created with freundTech's Blender2Minecraft converter (BETA)" 126 | fileContent["ambientocclusion"] = ambientocclusion 127 | fileContent["elements"] = [] 128 | 129 | if bpy.ops.object.mode_set.poll(): 130 | bpy.ops.object.mode_set(mode='OBJECT') 131 | 132 | for obj in objects: 133 | #TODO: Maybe assert or inverted if would be better than giant if 134 | if obj.type == 'MESH': 135 | data = obj.data 136 | bm = bmesh.new() 137 | bm.from_mesh(data) 138 | uv_layer = bm.loops.layers.uv.active 139 | 140 | if len(bm.faces) == 6: 141 | box = [] 142 | for i in range(0, len(obj.bound_box)): 143 | box.append([]) 144 | for j in range(0, len(obj.bound_box[i])): 145 | box[i].append(obj.bound_box[i][j]) 146 | pos = obj.location 147 | scale = obj.scale 148 | 149 | for co in box: 150 | for i in range(0, 3): 151 | co[i] *= scale[i] 152 | co[i] += pos[i] 153 | co[i] *= 16 154 | co[x] += 8 155 | co[y] = (co[y]) * -1 + 8 156 | 157 | toCoord, fromCoord = getMaxMin(box, [x, y, z]) 158 | 159 | objname = [""] 160 | for c in obj.name: 161 | if c != '.': 162 | objname[len(objname)-1] += c 163 | else: 164 | objname.append("") 165 | 166 | item = {} 167 | 168 | item["__comment"] = objname[0] 169 | item["from"] = [roundValue(fromCoord[x]), roundValue(fromCoord[z]), roundValue(fromCoord[y])] 170 | item["to"] = [roundValue(toCoord[x]), roundValue(toCoord[z]), roundValue(toCoord[y])] 171 | 172 | rotation = [round(math.degrees(a), 1) for a in obj.rotation_euler] 173 | numaxis = 0 174 | for i in range(0, len(rotation)): 175 | while rotation[i] >= 360: 176 | rotation[i] -= 360 177 | for r in rotation: 178 | if r != 0: 179 | numaxis += 1 180 | axis = rotation.index(r) 181 | if numaxis > 1: 182 | raise Exception("Only one Axis can be rotated at a time!") 183 | elif numaxis == 1: 184 | if rotation[axis] == -22.5 or rotation[axis] == 22.5 or rotation[axis] == -45 or rotation[axis] == 45: 185 | item["rotation"] = { "origin": [roundValue(pos[x]*16+8), roundValue(pos[z]*16), roundValue(pos[y]*-16+8)] } 186 | 187 | axisStr = "none" 188 | if axis == 0: 189 | axisStr = "x" 190 | elif axis == 1: 191 | axisStr = "z" 192 | rotation[axis] *= -1 193 | elif axis == 2: 194 | axisStr = "y" 195 | item["rotation"]["axis"] = axisStr 196 | item["rotation"]["angle"] = rotation[axis] 197 | 198 | for n in objname: 199 | if n[0:8] == "rescale:": 200 | item["rotation"]["rescale"] = n[8:].lower() == "true" 201 | else: 202 | raise Exception("You can only rotate by 22.5, -22.5, 45 or -45 degrees!") 203 | 204 | item["faces"] = {} 205 | 206 | for face in bm.faces: 207 | if len(face.loops) == 4: 208 | direction, toUse = getDir(face) 209 | 210 | try: 211 | uvs = [] 212 | for i in range(0, len(face.loops)): 213 | uvs.append([face.loops[i][uv_layer].uv[x] * 16, face.loops[i][uv_layer].uv[y] * 16]) 214 | except AttributeError: 215 | uvs = [[16, 16], [0, 16], [0, 0], [16, 0]] 216 | 217 | #TODO: Don't use builtin functions as variables 218 | max, min = getMaxMin(uvs, [x, y]) 219 | 220 | if min[x] != max[x] and min[y] != max[y]: 221 | 222 | verts = [] 223 | for i in range(0, len(face.loops)): 224 | verts.append([face.loops[i].vert.co[x] * 16, face.loops[i].vert.co[y] * 16, face.loops[i].vert.co[z] * 16]) 225 | maxr, minr = getMaxMin(verts, toUse) 226 | 227 | if direction == "south": 228 | bottom = minr 229 | elif direction == "east": 230 | bottom = minr 231 | elif direction == "up": 232 | bottom = minr 233 | elif direction == "down": 234 | bottom = [minr[0], maxr[1]] 235 | elif direction == "north": 236 | bottom = [maxr[0], minr[1]] 237 | elif direction == "west": 238 | bottom = [maxr[0], minr[1]] 239 | 240 | minI = getIndex(verts, bottom, toUse) 241 | 242 | minUv = list(uvs[minI]) 243 | for i in range(0, len(minUv)): 244 | minUv[i] = round(minUv[i], toRound) 245 | 246 | nextI = minI + 1 247 | while nextI >= 4: 248 | nextI -= 4 249 | 250 | nextUv = list(uvs[nextI]) 251 | for i in range(0, len(nextUv)): 252 | nextUv[i] = round(nextUv[i], toRound) 253 | 254 | if minUv == min and nextUv == [max[x], min[y]]: 255 | rot = 0 256 | mirror = False 257 | elif minUv == [max[x], min[y]] and nextUv == max: 258 | rot = 90 259 | mirror = False 260 | elif minUv == max and nextUv == [min[x], max[y]]: 261 | rot = 180 262 | mirror = False 263 | elif minUv == [min[x], max[y]] and nextUv == min: 264 | rot = 270 265 | mirror = False 266 | elif minUv == [max[x], min[y]] and nextUv == min: 267 | rot = 0 268 | mirror = True 269 | elif minUv == max and nextUv == [max[x], min[y]]: 270 | rot = 270 271 | mirror = True 272 | elif minUv == [min[x], max[y]] and nextUv == max: 273 | rot = 180 274 | mirror = True 275 | elif minUv == min and nextUv == [min[x], max[y]]: 276 | rot = 90 277 | mirror = True 278 | else: 279 | raise Exception("Your UV is messed up") 280 | 281 | try: 282 | image = data.uv_textures.active.data[face.index].image 283 | except AttributeError: 284 | image = attrdict(name=["texture"], filepath="") 285 | 286 | filepath = "" 287 | if image.filepath == "": 288 | print("Warning: Image %s not saved to disk. Can't get path!" % image.name) 289 | else: 290 | filepath = bpy.path.relpath(image.filepath) 291 | 292 | imagepath = bpy.path.abspath(image.filepath) 293 | imagepath = os.path.abspath(imagepath) 294 | path = imagepath.split(os.sep) 295 | for i, dir in enumerate(path): 296 | if dir == "assets" and path[i+1] == "minecraft" and path[i+2] == "textures": 297 | filepath = os.path.join(*path[i+3:]) 298 | 299 | filepath = os.path.splitext(filepath)[0] 300 | 301 | if not [image.name, filepath] in textures: 302 | textures.append([image.name, filepath]) 303 | 304 | s = max[y] 305 | 306 | max[y] = (min[y]- 8)*-1+8 307 | min[y] = (s- 8)*-1+8 308 | 309 | item["faces"][direction] = {} 310 | 311 | if not mirror: 312 | item["faces"][direction]["uv"] = [min[x], min[y], max[x], max[y]] 313 | item["faces"][direction]["texture"] = "#" + image.name 314 | item["faces"][direction]["rotation"] = rot 315 | else: 316 | item["faces"][direction]["uv"] = [max[x], min[y], min[x], max[y]] 317 | item["faces"][direction]["texture"] = "#" + image.name 318 | item["faces"][direction]["rotation"] = rot 319 | 320 | if "MinecraftParticle" in image and image["MinecraftParticle"] == 1: 321 | particle = filepath 322 | if "MinecraftTintindex" in image and image["MinecraftTintindex"] != 0: 323 | item["faces"][direction]["tintindex"] = image["MinecraftTintindex"] 324 | if "MinecraftCullface" in image and image["MinecraftCullface"] != 0: 325 | if image["MinecraftCullface"] == 1: 326 | item["faces"][direction]["cullface"] = direction 327 | else: 328 | item["faces"][direction]["cullface"] = cullfaceDirection[image["MinecraftCullface"]] 329 | else: 330 | print("Object \"" + data.name + "\" is not a cube!!!") 331 | 332 | fileContent["elements"].append(item) 333 | 334 | else: 335 | print("Object \"" + data.name + "\" is not a cube!") 336 | 337 | if include_textures: 338 | fileContent["textures"] = {} 339 | 340 | for texture in textures: 341 | fileContent["textures"][texture[0]] = texture[1] 342 | 343 | if particle != "": 344 | fileContent["textures"]["particle"] = particle 345 | 346 | fileContent["display"] = { 347 | "firstperson_lefthand": { 348 | "rotation": [roundValue(first_left_rot[x]), roundValue(first_left_rot[y]), roundValue(first_left_rot[z])], 349 | "translation": [roundValue(first_left_trans[x]), roundValue(first_left_trans[y]), roundValue(first_left_trans[z])], 350 | "scale": [roundValue(first_left_scale[x]), roundValue(first_left_scale[y]), roundValue(first_left_scale[z])] 351 | }, 352 | "firstperson_righthand": { 353 | "rotation": [roundValue(first_right_rot[x]), roundValue(first_right_rot[y]), roundValue(first_right_rot[z])], 354 | "translation": [roundValue(first_right_trans[x]), roundValue(first_right_trans[y]), roundValue(first_right_trans[z])], 355 | "scale": [roundValue(first_right_scale[x]), roundValue(first_right_scale[y]), roundValue(first_right_scale[z])] 356 | }, 357 | "thirdperson_righthand": { 358 | "rotation": [roundValue(third_right_rot[x]), roundValue(third_right_rot[y]), roundValue(third_right_rot[z])], 359 | "translation": [roundValue(third_right_trans[x]), roundValue(third_right_trans[y]), roundValue(third_right_trans[z])], 360 | "scale": [roundValue(third_right_scale[x]), roundValue(third_right_scale[y]), roundValue(third_right_scale[z])] 361 | }, 362 | "thirdperson_lefthand": { 363 | "rotation": [roundValue(third_left_rot[x]), roundValue(third_left_rot[y]), roundValue(third_left_rot[z])], 364 | "translation": [roundValue(third_left_trans[x]), roundValue(third_left_trans[y]), roundValue(third_left_trans[z])], 365 | "scale": [roundValue(third_left_scale[x]), roundValue(third_left_scale[y]), roundValue(third_left_scale[z])] 366 | }, 367 | "gui": { 368 | "rotation": [roundValue(invrot[x]), roundValue(invrot[y]), roundValue(invrot[z])], 369 | "translation": [roundValue(invtrans[x]), roundValue(invtrans[y]), roundValue(invtrans[z])], 370 | "scale": [roundValue(invscale[x]), roundValue(invscale[y]), roundValue(invscale[z])] 371 | }, 372 | "head": { 373 | "rotation": [roundValue(headrot[x]), roundValue(headrot[y]), roundValue(headrot[z])], 374 | "translation": [roundValue(headtrans[x]), roundValue(headtrans[y]), roundValue(headtrans[z])], 375 | "scale": [roundValue(headscale[x]), roundValue(headscale[y]), roundValue(headscale[z])] 376 | }, 377 | "ground": { 378 | "rotation": [roundValue(groundrot[x]), roundValue(groundrot[y]), roundValue(groundrot[z])], 379 | "translation": [roundValue(groundtrans[x]), roundValue(groundtrans[y]), roundValue(groundtrans[z])], 380 | "scale": [roundValue(groundscale[x]), roundValue(groundscale[y]), roundValue(groundscale[z])] 381 | }, 382 | "fixed": { 383 | "rotation": [roundValue(fixedrot[x]), roundValue(fixedrot[y]), roundValue(fixedrot[z])], 384 | "translation": [roundValue(fixedtrans[x]), roundValue(fixedtrans[y]), roundValue(fixedtrans[z])], 385 | "scale": [roundValue(fixedscale[x]), roundValue(fixedscale[y]), roundValue(fixedscale[z])] 386 | } 387 | } 388 | 389 | if(minify): 390 | file.write(json.dumps(fileContent, separators=(',', ':'), sort_keys=False)) 391 | else: 392 | file.write(json.dumps(fileContent, indent=4, sort_keys=False)) 393 | 394 | file.close() 395 | 396 | return {'FINISHED'} 397 | -------------------------------------------------------------------------------- /blender2minecraft/importer.py: -------------------------------------------------------------------------------- 1 | class ImportBlockModel(Operator, ImportHelper): 2 | """This appears in the tooltip of the operator and in the generated docs""" 3 | bl_idname = "import_mc.blockmodel" # important since its how bpy.ops.import_test.some_data is constructed 4 | bl_label = "Import a Minecraft Blockmodel in Scene" 5 | 6 | def execute(self, context): 7 | 8 | # import file 9 | readfile = open(self.filepath,'r', encoding='utf-8') 10 | data = json.load(readfile) 11 | readfile.close() 12 | 13 | # Make scene 14 | scene = bpy.data.scenes["Scene"] 15 | scene.render.resolution_x = 1000 16 | scene.render.resolution_y = 1000 17 | if scene.objects.active : 18 | bpy.ops.object.mode_set(mode='OBJECT') 19 | 20 | ## Light 21 | bpy.ops.object.lamp_add(type='SUN', view_align=False, location=(-0.0402176, 1.2157, 1.36071), layers=(True, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False)) 22 | light = context.object 23 | light.data.shadow_method = 'NOSHADOW' 24 | light.data.energy = 1.5 25 | light.location[0] = 4 26 | light.location[1] = -4 27 | light.location[2] = 12 28 | light.rotation_euler[0] = 0.035 29 | light.rotation_euler[1] = 0.192 30 | light.rotation_euler[2] = -0.838 31 | 32 | ## camera 33 | bpy.ops.object.camera_add(location=(1.38, -1.38, 1.86), rotation=(0.959931, 0, 0.785398)) 34 | cam = context.object 35 | cam.data.type = 'ORTHO' 36 | cam.data.ortho_scale = 1.96 37 | cam.name = "MinecraftView" 38 | scene.camera = cam 39 | 40 | ## grid 41 | for area in bpy.context.screen.areas : 42 | for space in area.spaces : 43 | if space.type == 'VIEW_3D' : 44 | space.grid_scale = 0.03125 45 | space.grid_subdivisions = 2 46 | space.grid_lines = 32 47 | 48 | ## Ambiant Occlusion 49 | if 'ambientocclusion' in data : 50 | print("ambientocclusion - " + str(data['ambientocclusion'])) 51 | else : 52 | data['ambientocclusion'] = True 53 | print("ambientocclusion force - " + str(data['ambientocclusion'])) 54 | 55 | scene.world.light_settings.use_ambient_occlusion = data['ambientocclusion'] 56 | 57 | ## texture 58 | if 'textures' in data : void = 0 59 | else : data['textures'] = [] 60 | 61 | for texture in data['textures'] : 62 | self.loadTextures(context, data['textures'][texture], texture) 63 | 64 | ## import element 65 | if 'elements' in data : void = 0 66 | else : data['elements'] = [] 67 | 68 | nbMake = 0 69 | nbTotal = len(data['elements']) 70 | for element in data['elements'] : 71 | if self.makeElement(context, element, nbMake) == True : 72 | nbMake += 1 73 | 74 | print( str(nbMake) + " elements make on " + str(nbTotal) ) 75 | 76 | return {'FINISHED'} 77 | 78 | def makeElement(self, context, data, id): 79 | 80 | if 'from' in data and 'to' in data : 81 | 82 | # cube 83 | print("cube" + str(id)) 84 | name = "Elem_%i" % id 85 | if '__comment' in data : 86 | name = data['__comment'] 87 | 88 | #mat = bpy.data.materials.new(name) 89 | #mat.diffuse_color = random.random(), random.random(), random.random() 90 | 91 | fromBL = MC2BL(data['from']) 92 | toBL = MC2BL(data['to']) 93 | 94 | size = [(toBL[x]-fromBL[x])/2, 95 | (toBL[y]-fromBL[y])/2, 96 | (toBL[z]-fromBL[z])/2] 97 | 98 | loca = [size[x]+fromBL[x], 99 | size[y]+fromBL[y], 100 | size[z]+fromBL[z]] 101 | 102 | bpy.ops.mesh.primitive_cube_add( radius=1, location=(loca[x], loca[y], loca[z])) 103 | 104 | bpy.ops.object.mode_set(mode='EDIT') 105 | bpy.ops.uv.unwrap(method='ANGLE_BASED', margin=0.001) 106 | bpy.ops.object.mode_set(mode='OBJECT') 107 | 108 | elem = context.object 109 | elem.scale = size 110 | #elem.data.materials.append(mat) 111 | elem.name = name 112 | 113 | # rotation 114 | 115 | if 'rotation' in data : 116 | if 'origin' in data['rotation'] and 'axis' in data['rotation'] and 'angle' in data['rotation'] : 117 | originBL = MC2BL(data['rotation']['origin']) 118 | context.scene.cursor_location = originBL 119 | bpy.types.SpaceView3D.pivot_point = 'CURSOR' 120 | 121 | if data['rotation']['axis'] == 'x' : 122 | axis = (1, 0, 0); 123 | rad = math.radians(data['rotation']['angle']) 124 | elif data['rotation']['axis'] == 'y' : 125 | axis = (0, 0, 1); 126 | rad = -math.radians(data['rotation']['angle']) 127 | else : 128 | axis = (0, 1, 0); 129 | rad = math.radians(data['rotation']['angle']) 130 | 131 | bpy.ops.transform.rotate(value=rad, axis=axis) 132 | 133 | # faces 134 | if 'faces' in data : void = 0 135 | else : data['faces'] = [] 136 | 137 | faceRef = {"down":4, "up":5, "north":3, "south":1, "west":0, "east":2} 138 | 139 | bpy.ops.object.mode_set(mode="EDIT") 140 | bpy.ops.mesh.select_mode(type="FACE") 141 | bpy.ops.mesh.select_all(action='TOGGLE') 142 | bpy.ops.object.mode_set(mode='OBJECT') 143 | 144 | nbMake = 0 145 | nbTotal = len(data['faces']) 146 | for face in faceRef : 147 | print(face) 148 | if face in data['faces'] : 149 | if self.makeFace(context, elem, data['faces'][face], faceRef[face]) == True : 150 | nbMake += 1 151 | else : 152 | poly = elem.data.polygons[faceRef[face]] 153 | poly.select = True # won't show in viewport 154 | 155 | bpy.ops.object.mode_set(mode="EDIT") 156 | bpy.ops.mesh.delete(type='FACE') # will be acted on. 157 | bpy.ops.object.mode_set(mode='OBJECT') 158 | 159 | 160 | print( str(nbMake) + " faces make on " + str(nbTotal) ) 161 | 162 | return True 163 | else : 164 | return False 165 | 166 | def makeFace(self, context, elem, data, id): 167 | 168 | if 'uv' in data and 'texture' in data : 169 | 170 | uv_layer = elem.data.uv_layers.active.data 171 | poly = elem.data.polygons[id] 172 | 173 | uvBL = uvMC2BL(data['uv']) 174 | uvref = collections.deque([[2,1],[0,1],[0,3],[2,3]]) 175 | if id == 4 : uvref.rotate(-1) #down 4 176 | if id == 5 : uvref.rotate(1) #up 5 177 | 178 | if 'rotation' in data : 179 | uvref.rotate(int(-data['rotation']/90)) 180 | 181 | index = -1 182 | for loop_index in range(poly.loop_start, poly.loop_start + poly.loop_total) : 183 | index += 1 184 | uv_layer[loop_index].uv[0] = uvBL[ uvref[index][0] ] 185 | uv_layer[loop_index].uv[1] = uvBL[ uvref[index][1] ] 186 | 187 | # Assign materials to faces 188 | if dataMat[data['texture']].name in elem.data.materials : void = 0 189 | else : elem.data.materials.append(dataMat[data['texture']]) 190 | 191 | index = -1 192 | for slot in elem.material_slots : 193 | index += 1 194 | if slot.material == dataMat[data['texture']] : 195 | break 196 | 197 | poly.material_index = index 198 | 199 | return True 200 | else : 201 | return False 202 | 203 | def loadTextures(self, context, data, id) : 204 | 205 | spl = data.split('/') 206 | name = spl[len(spl)-1] 207 | 208 | # if material existe 209 | if name in bpy.data.materials : 210 | dataMat['#'+id] = bpy.data.materials[name] 211 | else : 212 | 213 | # if texture existe 214 | if name in bpy.data.textures : 215 | cTex = bpy.data.textures[name] 216 | else : 217 | 218 | # if image existe 219 | if name + '.png' in bpy.data.images : 220 | img = bpy.data.images[name + '.png'] 221 | else : 222 | # Load image file. Change here if the snippet folder is 223 | realpath = self.filepath.split('/minecraft/')[0] 224 | realpath += '/minecraft/textures/' 225 | realpath += data + '.png' 226 | 227 | cTex = bpy.data.textures.new(name, type = 'IMAGE') 228 | 229 | try: 230 | cTex.image = bpy.data.images.load(realpath) 231 | except: 232 | bpy.ops.info.message('INVOKE_DEFAULT', 233 | title = "Loading image Error", 234 | type = "Message", 235 | message = "Cannot load image %s" % realpath) 236 | 237 | #raise NameError("Cannot load image %s" % realpath) 238 | 239 | dataMat['#'+id] = bpy.data.materials.new(name) 240 | dataMat['#'+id].use_transparency = True 241 | dataMat['#'+id].alpha = 0 242 | dataMat['#'+id].preview_render_type = 'CUBE' 243 | dataMat['#'+id].use_raytrace = False 244 | 245 | # Add texture slot for color texture 246 | mtex = dataMat['#'+id].texture_slots.add() 247 | mtex.texture = cTex 248 | mtex.texture_coords = 'UV' 249 | mtex.use_map_alpha = True 250 | 251 | cTex.use_interpolation = False 252 | cTex.filter_type = 'BOX' 253 | 254 | return True 255 | 256 | def MC2BL(mc): 257 | bl = [mc[x]*0.0625-0.5, -mc[z]*0.0625+0.5, mc[y]*0.0625] 258 | return bl 259 | 260 | def uvMC2BL(mc): 261 | bl = [mc[0]*0.0625, (16-mc[1])*0.0625, mc[2]*0.0625, (16-mc[3])*0.0625] 262 | return bl 263 | 264 | -------------------------------------------------------------------------------- /blender2minecraftTemplate.blend: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/freundTech/blender2minecraft/59d42ebb3b190e7d8a59e81924161c2d0e166b47/blender2minecraftTemplate.blend --------------------------------------------------------------------------------