├── .gitignore ├── images ├── export2.jpg ├── export3.jpg ├── import2.jpg ├── export1-en.jpg ├── export1-jp.jpg ├── import1-en.jpg ├── import1-jp.jpg ├── import3-en.jpg ├── import3-jp.jpg ├── import4-en.jpg ├── import4-jp.jpg ├── Object-setting-en.jpg ├── Object-setting-jp.jpg ├── material-setting-en.jpg ├── material-setting-jp.jpg ├── user-Preferences1-en.jpg ├── user-Preferences1-jp.jpg ├── user-Preferences2-en.jpg ├── user-Preferences2-jp.jpg ├── user-Preferences3-en.jpg └── user-Preferences3-jp.jpg ├── .gitmodules ├── io_scene_csv ├── Transform.py ├── ImportCSV.py ├── ExportCSV.py ├── __init__.py └── CSV.py ├── README-ja.md ├── README.md └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | __pycache__/ 2 | .mypy_cache/ 3 | .vscode/ 4 | .idea/ 5 | debug.py -------------------------------------------------------------------------------- /images/export2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/maisvendoo/blenderCSV/HEAD/images/export2.jpg -------------------------------------------------------------------------------- /images/export3.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/maisvendoo/blenderCSV/HEAD/images/export3.jpg -------------------------------------------------------------------------------- /images/import2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/maisvendoo/blenderCSV/HEAD/images/import2.jpg -------------------------------------------------------------------------------- /images/export1-en.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/maisvendoo/blenderCSV/HEAD/images/export1-en.jpg -------------------------------------------------------------------------------- /images/export1-jp.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/maisvendoo/blenderCSV/HEAD/images/export1-jp.jpg -------------------------------------------------------------------------------- /images/import1-en.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/maisvendoo/blenderCSV/HEAD/images/import1-en.jpg -------------------------------------------------------------------------------- /images/import1-jp.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/maisvendoo/blenderCSV/HEAD/images/import1-jp.jpg -------------------------------------------------------------------------------- /images/import3-en.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/maisvendoo/blenderCSV/HEAD/images/import3-en.jpg -------------------------------------------------------------------------------- /images/import3-jp.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/maisvendoo/blenderCSV/HEAD/images/import3-jp.jpg -------------------------------------------------------------------------------- /images/import4-en.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/maisvendoo/blenderCSV/HEAD/images/import4-en.jpg -------------------------------------------------------------------------------- /images/import4-jp.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/maisvendoo/blenderCSV/HEAD/images/import4-jp.jpg -------------------------------------------------------------------------------- /images/Object-setting-en.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/maisvendoo/blenderCSV/HEAD/images/Object-setting-en.jpg -------------------------------------------------------------------------------- /images/Object-setting-jp.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/maisvendoo/blenderCSV/HEAD/images/Object-setting-jp.jpg -------------------------------------------------------------------------------- /images/material-setting-en.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/maisvendoo/blenderCSV/HEAD/images/material-setting-en.jpg -------------------------------------------------------------------------------- /images/material-setting-jp.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/maisvendoo/blenderCSV/HEAD/images/material-setting-jp.jpg -------------------------------------------------------------------------------- /images/user-Preferences1-en.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/maisvendoo/blenderCSV/HEAD/images/user-Preferences1-en.jpg -------------------------------------------------------------------------------- /images/user-Preferences1-jp.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/maisvendoo/blenderCSV/HEAD/images/user-Preferences1-jp.jpg -------------------------------------------------------------------------------- /images/user-Preferences2-en.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/maisvendoo/blenderCSV/HEAD/images/user-Preferences2-en.jpg -------------------------------------------------------------------------------- /images/user-Preferences2-jp.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/maisvendoo/blenderCSV/HEAD/images/user-Preferences2-jp.jpg -------------------------------------------------------------------------------- /images/user-Preferences3-en.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/maisvendoo/blenderCSV/HEAD/images/user-Preferences3-en.jpg -------------------------------------------------------------------------------- /images/user-Preferences3-jp.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/maisvendoo/blenderCSV/HEAD/images/user-Preferences3-jp.jpg -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "io_scene_csv/chardet"] 2 | path = io_scene_csv/chardet 3 | url = https://github.com/chardet/chardet 4 | branch = stable 5 | -------------------------------------------------------------------------------- /io_scene_csv/Transform.py: -------------------------------------------------------------------------------- 1 | # Copyright 2018, 2019 Dmirty Pritykin, 2019 S520 2 | # 3 | # This file is part of blenderCSV. 4 | # 5 | # blenderCSV is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 2 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # blenderCSV is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with blenderCSV. If not, see . 17 | 18 | import bpy 19 | import bmesh 20 | import mathutils 21 | from typing import Union 22 | 23 | 24 | def swap_coordinate_system(matrix_world: mathutils.Matrix, mesh: Union[bpy.types.Mesh, bmesh.types.BMesh], is_swap: bool) -> None: 25 | swap_mat = mathutils.Matrix.Identity(4) 26 | 27 | if is_swap: 28 | swap_mat[0][0], swap_mat[0][1], swap_mat[0][2], swap_mat[0][3] = 1, 0, 0, 0 29 | swap_mat[1][0], swap_mat[1][1], swap_mat[1][2], swap_mat[1][3] = 0, 0, 1, 0 30 | swap_mat[2][0], swap_mat[2][1], swap_mat[2][2], swap_mat[2][3] = 0, 1, 0, 0 31 | swap_mat[3][0], swap_mat[3][1], swap_mat[3][2], swap_mat[3][3] = 0, 0, 0, 1 32 | 33 | trans, rot, scale = matrix_world.decompose() 34 | 35 | if type(mesh) is bpy.types.Mesh: 36 | for vertex in mesh.vertices: 37 | vertex.co = swap_mat * matrix_world * vertex.co 38 | vertex.normal = (swap_mat * matrix_world).to_3x3().normalized() * vertex.normal 39 | 40 | if is_swap: 41 | mesh.flip_normals() 42 | 43 | if type(mesh) is bmesh.types.BMesh: 44 | for vertex in mesh.verts: 45 | vertex.co = swap_mat * matrix_world * vertex.co 46 | vertex.normal = (swap_mat * matrix_world).to_3x3().normalized() * vertex.normal 47 | 48 | if is_swap: 49 | for face in mesh.faces: 50 | face.normal_flip() 51 | -------------------------------------------------------------------------------- /README-ja.md: -------------------------------------------------------------------------------- 1 | [English](README.md) 2 | 3 | # Blender plugin for Import|Export OpenBVE \*.csv objects 4 | 5 | 本プラグインはBlender2.79に対応しております。**現在のバージョンは2.80への対応しておりません。** 6 | 7 | ## 1. インストールガイド 8 | 9 | 1. 最新のリリースを [Releases section](https://github.com/maisvendoo/blenderCSV/releases) からダウンロードして下さい。 10 | 2. Blenderを開き、メインメニューのファイル -> ユーザー設定 -> アドオンを選択します。 11 | 3. "ファイルからアドオンをインストール"を選択します。 12 | ![user-Preferences1-jp](images/user-Preferences1-jp.jpg) 13 | 4. プラグインのzipファイルを選択します。 14 | ![user-Preferences2-jp](images/user-Preferences2-jp.jpg) 15 | 5. 有効化するために、チェックボックスをONにします。 16 | ![user-Preferences3-jp](images/user-Preferences3-jp.jpg) 17 | 6. "ユーザー設定の保存"を押し、変更を有効にした上でBlenderを再起動します。 18 | ## 2. プラグインを使う 19 | ### 2.1 \*.csvをBlenderにインポートする 20 | 21 | 1. ファイル -> インポート -> OpenBVE CSV model (\*.csv)と選択します。 22 | ![import1-jp](images/import1-jp.jpg) 23 | 24 | 2. インポートオプションを選択します。 25 | 26 | ![import2](images/import2.jpg) 27 | 28 | - *Set logging Level*: ログへ出力する情報の閾値を選択します。デフォルトでは"INFO"です。 29 | - *Transform coordinates*: OpenBVEの左手座標系からBlenderの右手座標系へ変換するか選択します。デフォルトでは有効です。 30 | - *Split AddFace2:* AddFace2で生成される面を別々の面に分割して取り込みます。その際、AddFace2フラグは解除されます。 31 | 32 | 3. ファイルシステムからモデルを選択後、"OpenBVE model (\*.csv)"ボタンを押し、現在のワークスペースにインポートします。 33 | ![import3-jp](images/import3-jp.jpg) 34 | 35 | インポートオプションの*Transform coordinates*を無効にすると下図のようになります。 36 | ![import4-jp](images/import4-jp.jpg) 37 | 38 | ### 2.2 Blenderから\*.csvへエクスポートする 39 | 40 | 1. Blenderでエクスポートしたいモデルを**オブジェクトモードにしてから**選択します。 41 | ![export1-jp](images/export1-jp.jpg) 42 | 2. ファイル -> エクスポート -> OpenBVE CSV model (\*.csv)と選択します。 43 | 3. エクスポートオプションを選択します 44 | 45 | ![export2](images/export2.jpg) 46 | 47 | - *Set logging Level*: ログへ出力する情報の閾値を選択します。デフォルトでは"INFO"です。 48 | - *Transform coordinates*: Blenderの右手座標系からOpenBVEの左手座標系へ変換するか選択します。デフォルトでは有効です。 49 | - *Set global scale*: 大きさの倍率を変更します。デフォルトでは1.0です。 50 | - *Output Normals*: 法線を出力するか選択します。デフォルトでは有効です。 51 | - *Copy textures in separated folder*: 全てのテクスチャファイルを新たなフォルダを作成し、コピーします。csvファイルと同じフォルダ階層に作られ、フォルダ名はモデル名-texturesになります。デフォルトでは有効です。 52 | 53 | 4. ファイルシステムからモデルの出力先を選択後、"OpenBVE model (\*.csv)"ボタンを押し、エクスポートします。 54 | 55 | 5. 結果をOpenBVEのObjectViewerで確認します。 56 | ![export3](images/export3.jpg) 57 | ## 3. OpenBVE特有の属性 58 | Additional properties for CSV meshにおいて、OpenBVE特有の属性を付与することが出来ます。 59 | 60 | **注意: これらの属性はBlenderの3Dビューの表示に反映されません。** 61 | 62 | ### 3.1 オブジェクトプロパティ 63 | ![Object-setting-jp](images/Object-setting-jp.jpg) 64 | 65 | - *SetEmissiveColor*: SetEmissiveColorの有効/無効と、その色を設定できます。 66 | - *SetBlendMode*: SetBlendModeのBlendMode(Normal/Additive)、GlowHalfDistanceの距離、GlowAttenuationMode(DivideExponent2もしくは4)を設定できます。 67 | - *SetDecalTransparentColor*: BMPなどSetDecalTransparentColorが必要なテクスチャを用いる場合、ここで有効/無効と色を設定できます。 68 | 69 | ### 3.2 マテリアルプロパティ 70 | 71 | ![material-setting-jp](images/material-setting-jp.jpg) 72 | 73 | - *Use AddFace2*: マテリアルをエクスポート時にAddFace2で両面化させる際に有効/無効が指定できます。 74 | - *LoadTexture*: LoadTextureのNighttimeTextureを指定できます。 75 | 76 | ## 4. デバッグ 77 | 78 | このプラグインはログをホームディレクトリ直下の`io_scene_csv_log.txt`へ出力します。 79 | 80 | 具体的には下記の通りです。 81 | 82 | - Windows 83 | `C:\Users\\io_scene_csv_log.txt` 84 | - Linux/macOS 85 | `~/io_scene_csv_log.txt` 86 | 87 | ## 5. ライセンス 88 | 89 | このプラグインは*GPL-2.0*の下でライセンスされています。 90 | ### サードパーティのライブラリ 91 | - このプラグインは**Chardet**を文字エンコーディングを決定するために使用しています。これは`io_scene_csv/chardet/LICENSE`に従い、*LGPL-2.1*の下でライセンスされています。 92 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [Japanese](README-ja.md) 2 | 3 | # Blender plugin for Import|Export OpenBVE \*.csv objects 4 | 5 | This plugin only works on Blender 2.79. **Please note that it will NOT work on 2.80.** 6 | 7 | ## 1. Installation guide 8 | 9 | 1. Please download from [Releases section](https://github.com/maisvendoo/blenderCSV/releases) the newest release. 10 | 2. Open Blender, and choose File -> User Preferences... -> Add-ons from main menu. 11 | 3. Choose "Install Add-on from File...". 12 | ![user-Preferences1-en](images/user-Preferences1-en.jpg) 13 | 4. Choose plugins zip file. 14 | ![user-Preferences2-en](images/user-Preferences2-en.jpg) 15 | 5. To enable the plugin, turn on the checkbox. 16 | ![user-Preferences3-en](images/user-Preferences3-en.jpg) 17 | 6. To enabled the setting, press "Save User Settings", and restart Blender. 18 | ## 2. Using plugin 19 | ### 2.1 Import \*.csv model file to Blender 20 | 21 | 1. Choose File -> Import -> OpenBVE CSV model (\*.csv) from main menu. 22 | ![import1-en](images/import1-en.jpg) 23 | 24 | 2. Select import options. 25 | 26 | ![import2](images/import2.jpg) 27 | 28 | - *Set logging Level*: select threshold level for the log file. The default setting is "INFO". 29 | - *Transform coordinates*: If you want to change OpenBVE 's Left-handed coordinate system to Blender's Right-handed coordinate system, check this option. The default is enable. 30 | - *Split AddFace2:* If this option is enabled, AddFace2's double-sided is split to an each face. After split, each faces Material's AddFace2 option is turn off automatically. 31 | 32 | 3. After choose the \*.csv model from filesystem, press the "OpenBVE model (\*.csv)" button, then import the model. 33 | ![import3-en](images/import3-en.jpg) 34 | 35 | If you are turn off the *Transform coordinates* option, the imported model is as shown below. 36 | ![import4-en](images/import4-en.jpg) 37 | 38 | ### 2.2 Exporting from Blender to \*.csv model file 39 | 40 | 1. Before the choose export object, **you must change mode to "Object Mode"**. After changed, you can choose export object(s). 41 | ![export1-en](images/export1-en.jpg) 42 | 2. Choose File -> Export -> OpenBVE CSV model (\*.csv) from main menu. 43 | 3. Choose export options. 44 | 45 | ![export2](images/export2.jpg) 46 | 47 | - *Set logging Level*: select threshold level for the log file. The default setting is "INFO". 48 | - *Transform coordinates*: If you want to change Blender's Right-handed coordinate system to OpenBVE 's Left-handed coordinate system, check this option. The default is enable. 49 | - *Set global scale*: Set the scale factor. The default value is 1.0. 50 | - *Output Normals*: If you want to export add normals, check this option. The default is enable. 51 | - *Copy textures in separated folder*: All texture files are copy to the new folder. the new folder is the same folder level, and folder name is 'model name'-textures. This option is enable by default. 52 | 4. 53 | After choose the \*.csv model from filesystem, press the "OpenBVE model (\*.csv)" button, then export the model. 54 | 55 | 5. Check the export result by the ObjectViewer of OpenBVE. 56 | ![export3](images/export3.jpg) 57 | ## 3. The specific attributes for OpenBVE 58 | At the Additional properties for CSV mesh, you can be assigns the specific attributes for OpenBVE. 59 | 60 | **NOTE: These specific attributes are not reflected to the Blender's 3D view.** 61 | 62 | ### 3.1 Object Property 63 | ![Object-setting-en](images/Object-setting-en.jpg) 64 | 65 | - *SetEmissiveColor*: Enable/Disable ,and set color of SetEmissiveColor. 66 | - *SetBlendMode*: You can set the SetBlendMode's BlendMode(Normal/Additive), GlowHalfDistance's distance, and GlowAttenuationMode(DivideExponent2 or 4). 67 | - *SetDecalTransparentColor*: For example of the BMP, If you want to use the case of require SetDecalTransparentColor, you can set Enable/Disable ,and set color of SetDecalTransparentColor. 68 | 69 | ### 3.2 Material Property 70 | 71 | ![material-setting-en](images/material-setting-en.jpg) 72 | 73 | - *Use AddFace2*: If this option is enabled, when you are the exporting, you can enable the material to the double-sided by Addface2. 74 | - *LoadTexture*: If this file is selected, you can set the NighttimeTexture for LoadTexture. 75 | 76 | ## 4. Debugging 77 | 78 | This plugin is output a log file of `io_scene_csv_log.txt` at the under the home directory. 79 | 80 | Specifically, the folder placing is showing below. 81 | 82 | - Windows 83 | `C:\Users\\io_scene_csv_log.txt` 84 | - Linux/macOS 85 | `~/io_scene_csv_log.txt` 86 | 87 | ## 5. License 88 | 89 | This plugin is licensed under *GPL-2.0*. 90 | 91 | ### Third party license 92 | - This plugin uses **Chardet** to determine the character encoding. This is licensed under the *LGPL-2.1* as per `io_scene_csv/chardet/LICENSE`. 93 | -------------------------------------------------------------------------------- /io_scene_csv/ImportCSV.py: -------------------------------------------------------------------------------- 1 | # Copyright 2018, 2019 Dmirty Pritykin, 2019 S520 2 | # 3 | # This file is part of blenderCSV. 4 | # 5 | # blenderCSV is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 2 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # blenderCSV is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with blenderCSV. If not, see . 17 | 18 | import bpy 19 | import pathlib 20 | import mathutils 21 | from . import CSV 22 | from . import logger 23 | from . import Transform 24 | 25 | 26 | class ImportCsv: 27 | INV255 = 1.0 / 255.0 28 | 29 | def __init__(self): 30 | self.file_path = "" 31 | self.option = CSV.ImportOption() 32 | 33 | def get_same_material(self, csv_mesh: CSV.CsvMesh, mat_name: str) -> bpy.types.Material: 34 | mat = bpy.data.materials.get(mat_name) 35 | 36 | if mat is None: 37 | return None 38 | 39 | if mat.diffuse_color[0] != csv_mesh.diffuse_color[0] * self.INV255 or mat.diffuse_color[1] != csv_mesh.diffuse_color[1] * self.INV255 or mat.diffuse_color[2] != csv_mesh.diffuse_color[2] * self.INV255: 40 | return None 41 | 42 | if csv_mesh.daytime_texture_file == "" and mat.alpha != csv_mesh.diffuse_color[3] * self.INV255: 43 | return None 44 | 45 | if mat.active_texture_index < len(mat.texture_slots): 46 | slot = mat.texture_slots[mat.active_texture_index] 47 | 48 | if slot is None: 49 | return None 50 | 51 | if type(slot.texture) is not bpy.types.ImageTexture: 52 | return None 53 | 54 | if slot.texture.image.filepath != csv_mesh.daytime_texture_file: 55 | return None 56 | 57 | if slot.alpha_factor != csv_mesh.diffuse_color[3] * self.INV255: 58 | return None 59 | 60 | if mat.csv_props.use_add_face2 != csv_mesh.use_add_face2: 61 | return None 62 | 63 | if mat.csv_props.nighttime_texture_file != csv_mesh.nighttime_texture_file: 64 | return None 65 | 66 | return mat 67 | 68 | def create_material(self, csv_mesh: CSV.CsvMesh, blender_mesh: bpy.types.Mesh) -> None: 69 | # Decide the name of the material. If a texture file exists, use that file name. 70 | if csv_mesh.daytime_texture_file != "": 71 | mat_name = pathlib.Path(csv_mesh.daytime_texture_file).stem 72 | else: 73 | mat_name = blender_mesh.name 74 | 75 | # Check if the same material already exists. 76 | mat = self.get_same_material(csv_mesh, mat_name) 77 | 78 | # Since the same material does not exist, create a new one. 79 | if mat is None: 80 | logger.debug("Create new material: " + mat_name) 81 | mat = bpy.data.materials.new(mat_name) 82 | mat.diffuse_color = (csv_mesh.diffuse_color[0] * self.INV255, csv_mesh.diffuse_color[1] * self.INV255, csv_mesh.diffuse_color[2] * self.INV255) 83 | mat.alpha = csv_mesh.diffuse_color[3] * self.INV255 84 | mat.transparency_method = "Z_TRANSPARENCY" 85 | mat.use_transparency = csv_mesh.diffuse_color[3] != 255 86 | 87 | # Set the texture on the material. 88 | if csv_mesh.daytime_texture_file != "": 89 | texture = bpy.data.textures.get(mat_name) 90 | 91 | if texture is None: 92 | texture = bpy.data.textures.new(mat_name, "IMAGE") 93 | texture.image = bpy.data.images.load(csv_mesh.daytime_texture_file) 94 | 95 | slot = mat.texture_slots.add() 96 | slot.texture = texture 97 | slot.texture_coords = "UV" 98 | slot.uv_layer = "default" 99 | slot.use_map_color_diffuse = True 100 | slot.use_map_alpha = True 101 | slot.alpha_factor = mat.alpha 102 | mat.alpha = 0.0 103 | mat.use_transparency = True 104 | 105 | mat.csv_props.use_add_face2 = csv_mesh.use_add_face2 106 | mat.csv_props.nighttime_texture_file = csv_mesh.nighttime_texture_file 107 | 108 | # Set the material on the mesh. 109 | blender_mesh.materials.append(mat) 110 | 111 | def set_texcoords(self, csv_mesh: CSV.CsvMesh, blender_mesh: bpy.types.Mesh) -> None: 112 | blender_mesh.uv_textures.new("default") 113 | 114 | for face in blender_mesh.polygons: 115 | for vert_idx, loop_idx in zip(face.vertices, face.loop_indices): 116 | try: 117 | texcoords = [j for j in csv_mesh.texcoords_list if j[0] == vert_idx][0] 118 | except Exception: 119 | logger.error("VertexIndex: " + str(vert_idx) + " is not defined with the SetTextureCoordinates command.") 120 | continue 121 | 122 | blender_mesh.uv_layers["default"].data[loop_idx].uv = [texcoords[1], 1.0 - texcoords[2]] 123 | 124 | def import_model(self, file_path: str) -> None: 125 | self.file_path = file_path 126 | 127 | meshes_list = CSV.CsvObject().load_csv(self.option, file_path) 128 | 129 | logger.info("Loaded meshes: " + str(len(meshes_list))) 130 | 131 | for i in range(len(meshes_list)): 132 | logger.info("Loaded mesh" + str(i) + ": (Vertex: " + str(len(meshes_list[i].vertex_list)) + ", Face: " + str(len(meshes_list[i].faces_list)) + ")") 133 | 134 | for j in range(len(meshes_list[i].vertex_list)): 135 | logger.debug("Vertex" + str(j) + ": " + str(meshes_list[i].vertex_list[j])) 136 | 137 | for j in range(len(meshes_list[i].faces_list)): 138 | logger.debug("Face" + str(j) + ": " + str(meshes_list[i].faces_list[j])) 139 | pass 140 | 141 | obj_base_name = pathlib.Path(self.file_path).stem 142 | 143 | for i in range(len(meshes_list)): 144 | blender_mesh = bpy.data.meshes.new(str(obj_base_name) + " - " + str(i)) 145 | blender_mesh.from_pydata(meshes_list[i].vertex_list, [], meshes_list[i].faces_list) 146 | blender_mesh.update(True) 147 | 148 | self.create_material(meshes_list[i], blender_mesh) 149 | 150 | self.set_texcoords(meshes_list[i], blender_mesh) 151 | 152 | Transform.swap_coordinate_system(mathutils.Matrix.Identity(4), blender_mesh, self.option.use_transform_coords) 153 | 154 | blender_mesh.calc_normals() 155 | 156 | obj = bpy.data.objects.new(blender_mesh.name, blender_mesh) 157 | obj.select = True 158 | 159 | obj.csv_props.use_emissive_color = meshes_list[i].use_emissive_color 160 | obj.csv_props.emissive_color = (meshes_list[i].emissive_color[0] * self.INV255, meshes_list[i].emissive_color[1] * self.INV255, meshes_list[i].emissive_color[2] * self.INV255) 161 | obj.csv_props.blend_mode = meshes_list[i].blend_mode 162 | obj.csv_props.glow_half_distance = meshes_list[i].glow_half_distance 163 | obj.csv_props.glow_attenuation_mode = meshes_list[i].glow_attenuation_mode 164 | obj.csv_props.use_transparent_color = meshes_list[i].use_transparent_color 165 | obj.csv_props.transparent_color = (meshes_list[i].transparent_color[0] * self.INV255, meshes_list[i].transparent_color[1] * self.INV255, meshes_list[i].transparent_color[2] * self.INV255) 166 | 167 | bpy.context.scene.objects.link(obj) 168 | -------------------------------------------------------------------------------- /io_scene_csv/ExportCSV.py: -------------------------------------------------------------------------------- 1 | # Copyright 2018, 2019 Dmirty Pritykin, 2019 S520 2 | # 3 | # This file is part of blenderCSV. 4 | # 5 | # blenderCSV is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 2 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # blenderCSV is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with blenderCSV. If not, see . 17 | 18 | import bpy 19 | import bmesh 20 | import filecmp 21 | import pathlib 22 | import os 23 | import shutil 24 | from typing import List, Tuple, Dict 25 | from . import CSV 26 | from . import logger 27 | from . import Transform 28 | 29 | 30 | class ExportCsv: 31 | def __init__(self): 32 | self.file_path = "" 33 | self.option = CSV.ExportOption() 34 | 35 | def copy_texture_separate_directory(self, model_dir: pathlib.PurePath, texture_path: pathlib.PurePath) -> str: 36 | texture_dir = model_dir.joinpath(pathlib.Path(self.file_path).stem + "-textures") 37 | 38 | try: 39 | os.makedirs(str(texture_dir), exist_ok=True) 40 | except Exception as ex: 41 | logger.critical(ex) 42 | return str(texture_path) 43 | 44 | try: 45 | dest_path = texture_dir.joinpath(texture_path.name) 46 | 47 | if not os.path.exists(str(dest_path)) or not filecmp.cmp(str(texture_path), str(dest_path)): 48 | shutil.copy2(str(texture_path), str(dest_path)) 49 | 50 | except Exception as ex: 51 | logger.critical(ex) 52 | return str(texture_path) 53 | 54 | return str(dest_path) 55 | 56 | def export_model(self, file_path: str) -> None: 57 | self.file_path = file_path 58 | 59 | meshes_list = [] # type: List[CSV.CsvMesh] 60 | 61 | object_list = bpy.context.selected_objects 62 | 63 | for obj in object_list: 64 | if obj.type != "MESH": 65 | continue 66 | 67 | logger.info("Process object: " + obj.name) 68 | 69 | blender_mesh = bmesh.new() 70 | blender_mesh.from_mesh(obj.data) 71 | 72 | Transform.swap_coordinate_system(obj.matrix_world, blender_mesh, self.option.use_transform_coords) 73 | 74 | # Group faces by material index. 75 | blender_faces = {} # type: Dict[int, List[bmesh.types.BMFace]] 76 | 77 | for face in blender_mesh.faces: 78 | if blender_faces.get(face.material_index) is None: 79 | blender_faces[face.material_index] = [] 80 | 81 | blender_faces[face.material_index].append(face) 82 | 83 | for m_idx, faces in blender_faces.items(): 84 | # Create a new CsvMesh. 85 | mesh = CSV.CsvMesh() 86 | mesh.name = "Mesh: " + obj.data.name 87 | 88 | # Add vertices to mesh 89 | blender_vertices = [] # type: List[Tuple[bmesh.types.BMFace, bmesh.types.BMVert]] 90 | 91 | for face in faces: 92 | for vertex in face.verts: 93 | if (face, vertex) not in blender_vertices: 94 | blender_vertices.append((face, vertex)) 95 | 96 | for vertex in blender_vertices: 97 | mesh.vertex_list.append((vertex[1].co[0], vertex[1].co[1], vertex[1].co[2])) 98 | mesh.normals_list.append((vertex[1].normal[0], vertex[1].normal[1], vertex[1].normal[2])) 99 | 100 | # Add faces to mesh 101 | for face in faces: 102 | indices = [] # type: List[int] 103 | 104 | for vertex in face.verts: 105 | indices.append(blender_vertices.index((face, vertex))) 106 | 107 | mesh.faces_list.append(tuple(indices)) 108 | 109 | # Add texcoords to mesh 110 | if blender_mesh.loops.layers.uv.active is not None: 111 | for face in faces: 112 | for loop in face.loops: 113 | vertex_index = blender_vertices.index((face, loop.vert)) 114 | uv = loop[blender_mesh.loops.layers.uv.active].uv 115 | texcoords = (vertex_index, uv[0], 1.0 - uv[1]) 116 | 117 | if texcoords not in mesh.texcoords_list: 118 | mesh.texcoords_list.append(texcoords) 119 | 120 | # Add material to mesh 121 | if m_idx < len(obj.material_slots): 122 | mat = obj.material_slots[m_idx].material 123 | mesh.name += ", Material: " + mat.name 124 | 125 | # Add diffuse color to mesh 126 | mesh.diffuse_color = (round(mat.diffuse_color[0] * 255), round(mat.diffuse_color[1] * 255), round(mat.diffuse_color[2] * 255), round(mat.alpha * 255) if mat.use_transparency else 255) 127 | 128 | # Add texture to mesh 129 | model_dir = pathlib.Path(self.file_path).parent 130 | 131 | if mat.active_texture_index < len(mat.texture_slots): 132 | texture_slot = mat.texture_slots[mat.active_texture_index] 133 | 134 | if texture_slot is not None and type(texture_slot.texture) is bpy.types.ImageTexture: 135 | if texture_slot.texture.image.filepath != "": 136 | texture_path = pathlib.Path(bpy.path.abspath(texture_slot.texture.image.filepath)).resolve() 137 | 138 | if self.option.use_copy_texture_separate_directory: 139 | mesh.daytime_texture_file = self.copy_texture_separate_directory(model_dir, texture_path) 140 | else: 141 | mesh.daytime_texture_file = str(texture_path) 142 | 143 | mesh.diffuse_color = (mesh.diffuse_color[0], mesh.diffuse_color[1], mesh.diffuse_color[2], round(texture_slot.alpha_factor * 255)) 144 | 145 | mesh.use_add_face2 = mat.csv_props.use_add_face2 146 | 147 | if mat.csv_props.nighttime_texture_file != "": 148 | texture_path = pathlib.Path(bpy.path.abspath(mat.csv_props.nighttime_texture_file)).resolve() 149 | 150 | if self.option.use_copy_texture_separate_directory: 151 | mesh.nighttime_texture_file = self.copy_texture_separate_directory(model_dir, texture_path) 152 | else: 153 | mesh.nighttime_texture_file = str(texture_path) 154 | else: 155 | mesh.name += ", Material: Undefined" 156 | 157 | # Set options to mesh 158 | mesh.use_emissive_color = obj.csv_props.use_emissive_color 159 | mesh.emissive_color = (round(obj.csv_props.emissive_color[0] * 255), round(obj.csv_props.emissive_color[1] * 255), round(obj.csv_props.emissive_color[2] * 255)) 160 | mesh.blend_mode = obj.csv_props.blend_mode 161 | mesh.glow_half_distance = obj.csv_props.glow_half_distance 162 | mesh.glow_attenuation_mode = obj.csv_props.glow_attenuation_mode 163 | mesh.use_transparent_color = obj.csv_props.use_transparent_color 164 | mesh.transparent_color = (round(obj.csv_props.transparent_color[0] * 255), round(obj.csv_props.transparent_color[1] * 255), round(obj.csv_props.transparent_color[2] * 255)) 165 | 166 | # Finalize 167 | meshes_list.append(mesh) 168 | 169 | CSV.CsvObject().export_csv(self.option, meshes_list, self.file_path) 170 | -------------------------------------------------------------------------------- /io_scene_csv/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright 2018, 2019 Dmirty Pritykin, 2018, 2019 S520 2 | # 3 | # This file is part of blenderCSV. 4 | # 5 | # blenderCSV is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 2 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # blenderCSV is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with blenderCSV. If not, see . 17 | 18 | import bpy 19 | import logging 20 | import pathlib 21 | 22 | bl_info = { 23 | "name": "Importer/Exporter OpenBVE CSV models", 24 | "category": "Import-Export", 25 | "author": "Dmitry Pritykin", 26 | "version": (0, 6, 0), 27 | "blender": (2, 79, 0) 28 | } 29 | 30 | logger = logging.getLogger() 31 | file_handler = logging.FileHandler(str(pathlib.Path.home().joinpath("io_scene_csv_log.txt")), "w") 32 | file_handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s: %(message)s on %(funcName)s() at line %(lineno)d")) 33 | logger.addHandler(file_handler) 34 | 35 | loggingLevels = ( 36 | ("NOTSET", "NOTSET", ""), 37 | ("DEBUG", "DEBUG", ""), 38 | ("INFO", "INFO", ""), 39 | ("WARNING", "WARNING", ""), 40 | ("ERROR", "ERROR", ""), 41 | ("CRITICAL", "CRITICAL", "") 42 | ) 43 | 44 | 45 | class CsvImporter(bpy.types.Operator): 46 | bl_idname = "import_scene.csv" 47 | bl_label = "OpenBVE CSV model (*.csv)" 48 | bl_options = {"REGISTER", "UNDO"} 49 | 50 | filepath = bpy.props.StringProperty(subtype="FILE_PATH") 51 | 52 | use_loggingLevel = bpy.props.EnumProperty( 53 | items=loggingLevels, 54 | name="Set logging level", 55 | description="Set logging level", 56 | default="INFO" 57 | ) 58 | 59 | use_transform_coords = bpy.props.BoolProperty( 60 | name="Transform coordinates", 61 | description="Transformation from OpenBVE left crew coordinate system", 62 | default=True 63 | ) 64 | 65 | use_split_add_face2 = bpy.props.BoolProperty( 66 | name="Split AddFace2", 67 | description="Splits the face generated by the AddFace2 command", 68 | default=False 69 | ) 70 | 71 | def invoke(self, context, event): 72 | context.window_manager.fileselect_add(self) 73 | return {"RUNNING_MODAL"} 74 | 75 | def execute(self, context): 76 | logger.setLevel(self.use_loggingLevel) 77 | logger.info("Import started.") 78 | 79 | from . import ImportCSV 80 | importer = ImportCSV.ImportCsv() 81 | 82 | importer.option.use_transform_coords = self.use_transform_coords 83 | importer.option.use_split_add_face2 = self.use_split_add_face2 84 | 85 | importer.import_model(self.filepath) 86 | 87 | logger.info("Import completed.") 88 | return {"FINISHED"} 89 | 90 | 91 | class CsvExporter(bpy.types.Operator): 92 | bl_idname = "export_scene.csv" 93 | bl_label = "OpenBVE CSV model (*.csv)" 94 | bl_options = {"REGISTER"} 95 | 96 | filename_ext = ".csv" 97 | 98 | filter_glob = bpy.props.StringProperty( 99 | default="*.csv", 100 | options={"HIDDEN"} 101 | ) 102 | 103 | filepath = bpy.props.StringProperty(subtype="FILE_PATH") 104 | 105 | use_loggingLevel = bpy.props.EnumProperty( 106 | items=loggingLevels, 107 | name="Set logging level", 108 | description="Set logging level", 109 | default="INFO" 110 | ) 111 | 112 | use_transform_coords = bpy.props.BoolProperty( 113 | name="Transform coordinates", 114 | description="Transformation to OpenBVE left crew coordinate system", 115 | default=True 116 | ) 117 | 118 | global_mesh_scale = bpy.props.FloatProperty( 119 | name="Set global scale", 120 | description="Global scale of the all scene objects", 121 | default=1.0, 122 | min=0.0001, 123 | max=10000.0, 124 | ) 125 | 126 | use_normals = bpy.props.BoolProperty( 127 | name="Output Normals", 128 | description="Output normals", 129 | default=True 130 | ) 131 | 132 | use_copy_texture_separate_directory = bpy.props.BoolProperty( 133 | name="Copy textures in separate folder", 134 | description="Copied textures in directory near *.csv file. Directory name will be: -textures", 135 | default=True 136 | ) 137 | 138 | def invoke(self, context, event): 139 | self.filepath = "undefined" + self.filename_ext 140 | context.window_manager.fileselect_add(self) 141 | return {"RUNNING_MODAL"} 142 | 143 | def execute(self, context): 144 | if bpy.context.mode != "OBJECT": 145 | def draw_context(self, context): 146 | self.layout.label("Please switch to Object Mode.") 147 | 148 | bpy.context.window_manager.popup_menu(draw_context, title="Export CSV", icon="ERROR") 149 | return {"FINISHED"} 150 | 151 | logger.setLevel(self.use_loggingLevel) 152 | logger.info("Export started.") 153 | 154 | from . import ExportCSV 155 | exporter = ExportCSV.ExportCsv() 156 | 157 | exporter.option.use_transform_coords = self.use_transform_coords 158 | exporter.option.global_mesh_scale = self.global_mesh_scale 159 | exporter.option.use_normals = self.use_normals 160 | exporter.option.use_copy_texture_separate_directory = self.use_copy_texture_separate_directory 161 | 162 | exporter.export_model(self.filepath) 163 | 164 | logger.info("Export completed.") 165 | return {"FINISHED"} 166 | 167 | 168 | class CsvMeshProperties(bpy.types.PropertyGroup): 169 | use_emissive_color = bpy.props.BoolProperty( 170 | name="Use SetEmissiveColor", 171 | description="Use SetEmissiveColor command", 172 | default=False 173 | ) 174 | 175 | emissive_color = bpy.props.FloatVectorProperty( 176 | name="Color", 177 | description="Set SetEmissiveColor command's Red, Green and Blue", 178 | default=(0.0, 0.0, 0.0), 179 | min=0.0, 180 | max=1.0, 181 | subtype="COLOR" 182 | ) 183 | 184 | blend_mode = bpy.props.EnumProperty( 185 | items=(("Normal", "Normal", ""), ("Additive", "Additive", "")), 186 | name="BlendMode", 187 | description="Set SetBlendMode command's BlendMode", 188 | default="Normal" 189 | ) 190 | 191 | glow_half_distance = bpy.props.IntProperty( 192 | name="GlowHalfDistance", 193 | description="Set SetBlendMode command's GlowHalfDistance", 194 | default=0, 195 | min=0, 196 | max=4095 197 | ) 198 | 199 | glow_attenuation_mode = bpy.props.EnumProperty( 200 | items=(("DivideExponent2", "DivideExponent2", ""), ("DivideExponent4", "DivideExponent4", "")), 201 | name="GlowAttenuationMode", 202 | description="Set SetBlendMode command's GlowAttenuationMode", 203 | default="DivideExponent4" 204 | ) 205 | 206 | use_transparent_color = bpy.props.BoolProperty( 207 | name="Use SetDecalTransparentColor", 208 | description="Use SetDecalTransparentColor command", 209 | default=False 210 | ) 211 | 212 | transparent_color = bpy.props.FloatVectorProperty( 213 | name="Color", 214 | description="Set SetDecalTransparentColor command's Red, Green and Blue", 215 | default=(0.0, 0.0, 0.0), 216 | min=0.0, 217 | max=1.0, 218 | subtype="COLOR" 219 | ) 220 | 221 | 222 | class CsvMaterialProperties(bpy.types.PropertyGroup): 223 | use_add_face2 = bpy.props.BoolProperty( 224 | name="Use AddFace2", 225 | description="Use AddFace2 command for generate faces in OpenBVE", 226 | default=False 227 | ) 228 | 229 | nighttime_texture_file = bpy.props.StringProperty( 230 | name="NighttimeTexture", 231 | description="Set NighttimeTexture command's LoadTexture", 232 | default="", 233 | subtype="FILE_PATH" 234 | ) 235 | 236 | 237 | class CsvMeshPanel(bpy.types.Panel): 238 | bl_label = "Additional properties for CSV mesh" 239 | bl_context = "object" 240 | bl_space_type = "PROPERTIES" 241 | bl_region_type = "WINDOW" 242 | 243 | @classmethod 244 | def poll(cls, context): 245 | return context.object and context.object.type == "MESH" 246 | 247 | def draw(self, context): 248 | self.layout.label("SetEmissiveColor:") 249 | self.layout.prop(context.object.csv_props, "use_emissive_color") 250 | self.layout.prop(context.object.csv_props, "emissive_color") 251 | self.layout.separator() 252 | self.layout.label("SetBlendMode:") 253 | self.layout.prop(context.object.csv_props, "blend_mode") 254 | self.layout.prop(context.object.csv_props, "glow_half_distance") 255 | self.layout.prop(context.object.csv_props, "glow_attenuation_mode") 256 | self.layout.separator() 257 | self.layout.label("SetDecalTransparentColor:") 258 | self.layout.prop(context.object.csv_props, "use_transparent_color") 259 | self.layout.prop(context.object.csv_props, "transparent_color") 260 | 261 | 262 | class CsvMaterialPanel(bpy.types.Panel): 263 | bl_label = "Additional properties for CSV mesh" 264 | bl_context = "material" 265 | bl_space_type = "PROPERTIES" 266 | bl_region_type = "WINDOW" 267 | 268 | @classmethod 269 | def poll(cls, context): 270 | return context.material 271 | 272 | def draw(self, context): 273 | self.layout.prop(context.material.csv_props, "use_add_face2") 274 | self.layout.separator() 275 | self.layout.label("LoadTexture:") 276 | self.layout.prop(context.material.csv_props, "nighttime_texture_file") 277 | 278 | 279 | def menu_import(self, context): 280 | self.layout.operator(CsvImporter.bl_idname, text=CsvImporter.bl_label) 281 | 282 | 283 | def menu_export(self, context): 284 | self.layout.operator(CsvExporter.bl_idname, text=CsvExporter.bl_label) 285 | 286 | 287 | def register(): 288 | bpy.utils.register_class(CsvImporter) 289 | bpy.types.INFO_MT_file_import.append(menu_import) 290 | 291 | bpy.utils.register_class(CsvExporter) 292 | bpy.types.INFO_MT_file_export.append(menu_export) 293 | 294 | bpy.utils.register_class(CsvMeshProperties) 295 | bpy.types.Object.csv_props = bpy.props.PointerProperty(type=CsvMeshProperties) 296 | 297 | bpy.utils.register_class(CsvMaterialProperties) 298 | bpy.types.Material.csv_props = bpy.props.PointerProperty(type=CsvMaterialProperties) 299 | 300 | bpy.utils.register_class(CsvMeshPanel) 301 | 302 | bpy.utils.register_class(CsvMaterialPanel) 303 | 304 | 305 | def unregister(): 306 | bpy.utils.unregister_class(CsvImporter) 307 | bpy.types.INFO_MT_file_import.remove(menu_import) 308 | 309 | bpy.utils.unregister_class(CsvExporter) 310 | bpy.types.INFO_MT_file_export.remove(menu_export) 311 | 312 | bpy.utils.unregister_class(CsvMeshProperties) 313 | del bpy.types.Object.csv_props 314 | 315 | bpy.utils.unregister_class(CsvMaterialProperties) 316 | del bpy.types.Material.csv_props 317 | 318 | bpy.utils.unregister_class(CsvMeshPanel) 319 | 320 | bpy.utils.unregister_class(CsvMaterialPanel) 321 | 322 | 323 | if __name__ == "__main__": 324 | register() 325 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | 3 | Version 2, June 1991 4 | 5 | Copyright (C) 1989, 1991 Free Software Foundation, Inc. 6 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA 7 | 8 | Everyone is permitted to copy and distribute verbatim copies 9 | of this license document, but changing it is not allowed. 10 | Preamble 11 | 12 | The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. 13 | 14 | When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. 15 | 16 | To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. 17 | 18 | For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. 19 | 20 | We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. 21 | 22 | Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. 23 | 24 | Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. 25 | 26 | The precise terms and conditions for copying, distribution and modification follow. 27 | 28 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 29 | 30 | 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". 31 | 32 | Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 33 | 34 | 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. 35 | 36 | You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 37 | 38 | 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: 39 | 40 | a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. 41 | b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. 42 | c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) 43 | These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. 44 | 45 | Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. 46 | 47 | In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 48 | 49 | 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: 50 | 51 | a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, 52 | b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, 53 | c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) 54 | The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. 55 | 56 | If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 57 | 58 | 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 59 | 60 | 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 61 | 62 | 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 63 | 64 | 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. 65 | 66 | If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. 67 | 68 | It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. 69 | 70 | This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 71 | 72 | 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 73 | 74 | 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. 75 | 76 | Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 77 | 78 | 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. 79 | 80 | NO WARRANTY 81 | 82 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 83 | 84 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 85 | 86 | END OF TERMS AND CONDITIONS 87 | 88 | How to Apply These Terms to Your New Programs 89 | 90 | If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. 91 | 92 | To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. 93 | 94 | one line to give the program's name and an idea of what it does. 95 | Copyright (C) yyyy name of author 96 | 97 | This program is free software; you can redistribute it and/or 98 | modify it under the terms of the GNU General Public License 99 | as published by the Free Software Foundation; either version 2 100 | of the License, or (at your option) any later version. 101 | 102 | This program is distributed in the hope that it will be useful, 103 | but WITHOUT ANY WARRANTY; without even the implied warranty of 104 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 105 | GNU General Public License for more details. 106 | 107 | You should have received a copy of the GNU General Public License 108 | along with this program; if not, write to the Free Software 109 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 110 | Also add information on how to contact you by electronic and paper mail. 111 | 112 | If the program is interactive, make it output a short notice like this when it starts in an interactive mode: 113 | 114 | Gnomovision version 69, Copyright (C) year name of author 115 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details 116 | type `show w'. This is free software, and you are welcome 117 | to redistribute it under certain conditions; type `show c' 118 | for details. 119 | The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. 120 | 121 | You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: 122 | 123 | Yoyodyne, Inc., hereby disclaims all copyright 124 | interest in the program `Gnomovision' 125 | (which makes passes at compilers) written 126 | by James Hacker. 127 | 128 | signature of Ty Coon, 1 April 1989 129 | Ty Coon, President of Vice 130 | This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. 131 | 132 | -------------------------------------------------------------------------------- /io_scene_csv/CSV.py: -------------------------------------------------------------------------------- 1 | # Copyright 2018, 2019 Dmirty Pritykin, 2019 S520 2 | # 3 | # This file is part of blenderCSV. 4 | # 5 | # blenderCSV is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 2 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # blenderCSV is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with blenderCSV. If not, see . 17 | 18 | import math 19 | import os 20 | import pathlib 21 | from typing import List, Tuple 22 | from .chardet import chardet 23 | from . import logger 24 | 25 | 26 | class CsvMesh: 27 | def __init__(self) -> None: 28 | self.name = "" 29 | self.vertex_list = [] # type: List[Tuple[float, float, float]] 30 | self.normals_list = [] # type: List[Tuple[float, float, float]] 31 | self.use_add_face2 = False 32 | self.faces_list = [] # type: List[Tuple[int, ...]] 33 | self.diffuse_color = (255, 255, 255, 255) # type: Tuple[int, int, int, int] 34 | self.use_emissive_color = False 35 | self.emissive_color = (0, 0, 0) # type: Tuple[int, int, int] 36 | self.blend_mode = "Normal" 37 | self.glow_half_distance = 0 38 | self.glow_attenuation_mode = "DivideExponent4" 39 | self.daytime_texture_file = "" 40 | self.nighttime_texture_file = "" 41 | self.use_transparent_color = False 42 | self.transparent_color = (0, 0, 0) # type: Tuple[int, int, int] 43 | self.texcoords_list = [] # type: List[Tuple[int, float, float]] 44 | 45 | 46 | class ImportOption: 47 | def __init__(self): 48 | self.use_transform_coords = True 49 | self.use_split_add_face2 = False 50 | 51 | 52 | class ExportOption: 53 | def __init__(self): 54 | self.use_transform_coords = True 55 | self.global_mesh_scale = 1.0 56 | self.use_normals = True 57 | self.use_copy_texture_separate_directory = True 58 | 59 | 60 | class CsvObject: 61 | def is_potential_path(self, line: str) -> bool: 62 | images = [".bmp", ".gi", ".jpg", ".jpeg", ".png"] 63 | 64 | for image in images: 65 | try: 66 | i = line.index(image) 67 | except ValueError: 68 | i = -1 69 | 70 | if i >= 0: 71 | return True 72 | 73 | return False 74 | 75 | def create_cube(self, mesh: CsvMesh, sx: float, sy: float, sz: float) -> None: 76 | v = len(mesh.vertex_list) 77 | 78 | mesh.vertex_list.append((sx, sy, -sz)) 79 | mesh.vertex_list.append((sx, -sy, -sz)) 80 | mesh.vertex_list.append((-sx, -sy, -sz)) 81 | mesh.vertex_list.append((-sx, sy, -sz)) 82 | mesh.vertex_list.append((sx, sy, sz)) 83 | mesh.vertex_list.append((sx, -sy, sz)) 84 | mesh.vertex_list.append((-sx, -sy, sz)) 85 | mesh.vertex_list.append((-sx, sy, sz)) 86 | 87 | mesh.faces_list.append((v + 0, v + 1, v + 2, v + 3)) 88 | mesh.faces_list.append((v + 0, v + 4, v + 5, v + 1)) 89 | mesh.faces_list.append((v + 0, v + 3, v + 7, v + 4)) 90 | mesh.faces_list.append((v + 6, v + 5, v + 4, v + 7)) 91 | mesh.faces_list.append((v + 6, v + 7, v + 3, v + 2)) 92 | mesh.faces_list.append((v + 6, v + 2, v + 1, v + 5)) 93 | 94 | def create_cylinder(self, mesh: CsvMesh, n: int, r1: float, r2: float, h: float) -> None: 95 | # Parameters 96 | uppercap = r1 > 0.0 97 | lowercap = r2 > 0.0 98 | m = (1 if uppercap else 0) + (1 if lowercap else 0) 99 | r1 = abs(r1) 100 | r2 = abs(r2) 101 | 102 | # Initialization 103 | v = len(mesh.vertex_list) 104 | d = 2.0 * math.pi / float(n) 105 | g = 0.5 * h 106 | t = 0.0 107 | 108 | # Vertices 109 | for i in range(n): 110 | dx = math.cos(t) 111 | dz = math.sin(t) 112 | lx = dx * r2 113 | lz = dz * r2 114 | ux = dx * r1 115 | uz = dz * r1 116 | mesh.vertex_list.append((ux, g, uz)) 117 | mesh.vertex_list.append((lx, -g, lz)) 118 | t += d 119 | 120 | # Faces 121 | for i in range(n): 122 | i0 = (2 * i + 2) % (2 * n) 123 | i1 = (2 * i + 3) % (2 * n) 124 | i2 = 2 * i + 1 125 | i3 = 2 * i 126 | mesh.faces_list.append((v + i0, v + i1, v + i2, v + i3)) 127 | 128 | for i in range(m): 129 | face = [] 130 | 131 | for j in range(n): 132 | if i == 0 and lowercap: 133 | # lower cap 134 | face.append(v + 2 * j + 1) 135 | else: 136 | # upper cap 137 | face.append(v + 2 * (n - j - 1)) 138 | 139 | mesh.faces_list.append(tuple(face)) 140 | 141 | def apply_translation(self, mesh: CsvMesh, x: float, y: float, z: float) -> None: 142 | for i in range(len(mesh.vertex_list)): 143 | mesh.vertex_list[i] = (mesh.vertex_list[i][0] + x, mesh.vertex_list[i][1] + y, mesh.vertex_list[i][2] + z) 144 | 145 | def apply_scale(self, mesh: CsvMesh, x: float, y: float, z: float) -> None: 146 | for i in range(len(mesh.vertex_list)): 147 | mesh.vertex_list[i] = (mesh.vertex_list[i][0] * x, mesh.vertex_list[i][1] * y, mesh.vertex_list[i][2] * z) 148 | 149 | if x * y * z < 0.0: 150 | for i in range(len(mesh.faces_list)): 151 | mesh.faces_list[i] = tuple(reversed(mesh.faces_list[i])) 152 | 153 | def apply_rotation(self, mesh: CsvMesh, r: Tuple[float, float, float], angle: float) -> None: 154 | cosine_of_angle = math.cos(angle) 155 | sine_of_angle = math.sin(angle) 156 | cosine_complement = 1.0 - cosine_of_angle 157 | 158 | for i in range(len(mesh.vertex_list)): 159 | x = (cosine_of_angle + cosine_complement * r[0] * r[0]) * mesh.vertex_list[i][0] + (cosine_complement * r[0] * r[1] - sine_of_angle * r[2]) * mesh.vertex_list[i][1] + (cosine_complement * r[0] * r[2] + sine_of_angle * r[1]) * mesh.vertex_list[i][2] 160 | y = (cosine_of_angle + cosine_complement * r[1] * r[1]) * mesh.vertex_list[i][1] + (cosine_complement * r[0] * r[1] + sine_of_angle * r[2]) * mesh.vertex_list[i][0] + (cosine_complement * r[1] * r[2] - sine_of_angle * r[0]) * mesh.vertex_list[i][2] 161 | z = (cosine_of_angle + cosine_complement * r[2] * r[2]) * mesh.vertex_list[i][2] + (cosine_complement * r[0] * r[2] - sine_of_angle * r[1]) * mesh.vertex_list[i][0] + (cosine_complement * r[1] * r[2] + sine_of_angle * r[0]) * mesh.vertex_list[i][1] 162 | mesh.vertex_list[i] = (x, y, z) 163 | 164 | def apply_shear(self, mesh: CsvMesh, d: Tuple[float, float, float], s: Tuple[float, float, float], r: float) -> None: 165 | for i in range(len(mesh.vertex_list)): 166 | n = r * (d[0] * mesh.vertex_list[i][0] + d[1] * mesh.vertex_list[i][1] + d[2] * mesh.vertex_list[i][2]) 167 | mesh.vertex_list[i] = (mesh.vertex_list[i][0] + s[0] * n, mesh.vertex_list[i][1] + s[1] * n, mesh.vertex_list[i][2] + s[2] * n) 168 | 169 | def apply_mirror(self, mesh: CsvMesh, vx: bool, vy: bool, vz: bool): 170 | for i in range(len(mesh.vertex_list)): 171 | x = mesh.vertex_list[i][0] * -1.0 if vx else mesh.vertex_list[i][0] 172 | y = mesh.vertex_list[i][1] * -1.0 if vx else mesh.vertex_list[i][1] 173 | z = mesh.vertex_list[i][2] * -1.0 if vx else mesh.vertex_list[i][2] 174 | mesh.vertex_list[i] = (x, y, z) 175 | 176 | num_flips = 0 177 | 178 | if vx: 179 | num_flips += 1 180 | 181 | if vy: 182 | num_flips += 1 183 | 184 | if vz: 185 | num_flips += 1 186 | 187 | if num_flips % 2 != 0: 188 | for i in range(len(mesh.faces_list)): 189 | mesh.faces_list[i] = tuple(reversed(mesh.faces_list[i])) 190 | 191 | def normalize(self, v: Tuple[float, float, float]) -> Tuple[float, float, float]: 192 | norm = v[0] * v[0] + v[1] * v[1] + v[2] * v[2] 193 | 194 | if norm == 0.0: 195 | return v 196 | 197 | factor = 1.0 / math.sqrt(norm) 198 | return (v[0] * factor, v[1] * factor, v[2] * factor) 199 | 200 | def load_csv(self, option: ImportOption, file_path: str) -> List[CsvMesh]: 201 | meshes_list = [] # type: List[CsvMesh] 202 | 203 | logger.info("Loading file: " + file_path) 204 | 205 | # Open CSV file 206 | try: 207 | with open(file_path, "rb") as f: 208 | binary = f.read() 209 | 210 | csv_text = binary.decode(chardet.detect(binary)["encoding"]).splitlines() 211 | except Exception as ex: 212 | logger.critical(ex) 213 | return meshes_list 214 | 215 | # Parse CSV file 216 | # Delete comments 217 | comment_started = False 218 | 219 | for i in range(len(csv_text)): 220 | # Strip OpenBVE original standard comments 221 | try: 222 | j = csv_text[i].index(";") 223 | except ValueError: 224 | j = -1 225 | 226 | if j >= 0: 227 | csv_text[i] = csv_text[i][:j] 228 | 229 | # Strip double backslash comments 230 | try: 231 | k = csv_text[i].index("//") 232 | except ValueError: 233 | k = -1 234 | 235 | if k >= 0: 236 | if self.is_potential_path(csv_text[i]): 237 | # HACK: Handles malformed potential paths 238 | continue 239 | 240 | csv_text[i] = csv_text[i][:k] 241 | 242 | # Strip star backslash comments 243 | if not comment_started: 244 | try: 245 | m = csv_text[i].index("/*") 246 | except ValueError: 247 | m = -1 248 | 249 | if m >= 0: 250 | comment_started = True 251 | part1 = csv_text[i][:1] 252 | part2 = "" 253 | 254 | try: 255 | n = csv_text[i].index("*/") 256 | except ValueError: 257 | n = -1 258 | 259 | if n >= 0: 260 | part2 = csv_text[i][n + 2:] 261 | 262 | csv_text[i] = part1 + part2 263 | else: 264 | try: 265 | m = csv_text[i].index("*/") 266 | except ValueError: 267 | m = -1 268 | 269 | if m >= 0: 270 | comment_started = True 271 | 272 | if m + 2 != len(csv_text[i]): 273 | csv_text[i] = csv_text[i][m + 2:] 274 | else: 275 | csv_text[i] = "" 276 | else: 277 | csv_text[i] = "" 278 | 279 | # Parse lines 280 | mesh = None 281 | 282 | for i in range(len(csv_text)): 283 | # Collect arguments 284 | arguments = csv_text[i].split(",") 285 | 286 | for j in range(len(arguments)): 287 | arguments[j] = arguments[j].strip() 288 | 289 | command = arguments.pop(0) 290 | 291 | if command == "": 292 | continue 293 | 294 | # Parse terms 295 | if command.lower() == "CreateMeshBuilder".lower(): 296 | if len(arguments) > 0: 297 | logger.warning("0 arguments are expected in " + command + " at line " + str(i + 1)) 298 | 299 | if mesh is not None: 300 | meshes_list.append(mesh) 301 | 302 | mesh = CsvMesh() 303 | 304 | elif mesh is None: 305 | logger.error(command + " before the first CreateMeshBuilder are ignored at line " + str(i + 1)) 306 | 307 | elif command.lower() == "AddVertex".lower(): 308 | if len(arguments) > 6: 309 | logger.warning("At most 6 arguments are expected in " + command + " at line " + str(i + 1)) 310 | 311 | try: 312 | vx = float(arguments[0]) 313 | except Exception as ex: 314 | if type(ex) is not IndexError: 315 | logger.error("Invalid argument vX in " + command + " at line " + str(i + 1)) 316 | 317 | vx = 0.0 318 | 319 | try: 320 | vy = float(arguments[1]) 321 | except Exception as ex: 322 | if type(ex) is not IndexError: 323 | logger.error("Invalid argument vY in " + command + " at line " + str(i + 1)) 324 | 325 | vy = 0.0 326 | 327 | try: 328 | vz = float(arguments[2]) 329 | except Exception as ex: 330 | if type(ex) is not IndexError: 331 | logger.error("Invalid argument vZ in " + command + " at line " + str(i + 1)) 332 | 333 | vz = 0.0 334 | 335 | if len(arguments) >= 4: 336 | logger.info("This add-on ignores nX, nY and nZ in " + command + " at line " + str(i + 1)) 337 | 338 | mesh.vertex_list.append((vx, vy, vz)) 339 | 340 | elif command.lower() == "AddFace".lower() or command.lower() == "AddFace2".lower(): 341 | if len(arguments) < 3: 342 | logger.error("At least 3 arguments are required in " + command + " at line " + str(i + 1)) 343 | else: 344 | q = True 345 | a = [] 346 | 347 | for j in range(len(arguments)): 348 | try: 349 | a.append(int(arguments[j])) 350 | except Exception as ex: 351 | if type(ex) is not IndexError: 352 | logger.error("v" + str(j) + " is invalid in " + command + " at line " + str(i + 1)) 353 | 354 | q = False 355 | break 356 | 357 | if a[j] < 0 or a[j] >= len(mesh.vertex_list): 358 | logger.error("v" + str(j) + " references a non-existing vertex in " + command + " at line " + str(i + 1)) 359 | q = False 360 | break 361 | 362 | if a[j] > 65535: 363 | logger.error("v" + str(j) + " indexes a vertex above 65535 which is not currently supported in " + command + " at line " + str(i + 1)) 364 | q = False 365 | break 366 | 367 | if q: 368 | mesh.faces_list.append(tuple(a)) 369 | 370 | if command.lower() == "AddFace2".lower(): 371 | if option.use_split_add_face2: 372 | mesh.faces_list.append(tuple(reversed(a))) 373 | else: 374 | mesh.use_add_face2 = True 375 | 376 | elif command.lower() == "Cube".lower(): 377 | if len(arguments) > 3: 378 | logger.warning("At most 3 arguments are expected in " + command + " at line " + str(i + 1)) 379 | 380 | try: 381 | x = float(arguments[0]) 382 | except Exception as ex: 383 | if type(ex) is not IndexError: 384 | logger.error("Invalid argument HalfWidth in " + command + " at line " + str(i + 1)) 385 | 386 | x = 1.0 387 | 388 | try: 389 | y = float(arguments[1]) 390 | except Exception as ex: 391 | if type(ex) is not IndexError: 392 | logger.error("Invalid argument HalfHeight in " + command + " at line " + str(i + 1)) 393 | 394 | y = 1.0 395 | 396 | try: 397 | z = float(arguments[2]) 398 | except Exception as ex: 399 | if type(ex) is not IndexError: 400 | logger.error("Invalid argument HalfDepth in " + command + " at line " + str(i + 1)) 401 | 402 | z = 1.0 403 | 404 | self.create_cube(mesh, x, y, z) 405 | 406 | elif command.lower() == "Cylinder".lower(): 407 | if len(arguments) > 4: 408 | logger.warning("At most 4 arguments are expected in " + command + " at line " + str(i + 1)) 409 | 410 | try: 411 | n = int(arguments[0]) 412 | except Exception as ex: 413 | if type(ex) is not IndexError: 414 | logger.error("Invalid argument n in " + command + " at line " + str(i + 1)) 415 | 416 | n = 8 417 | 418 | if n < 2: 419 | logger.error("n is expected to be at least 2 in " + command + " at line " + str(i + 1)) 420 | n = 8 421 | 422 | try: 423 | r1 = float(arguments[1]) 424 | except Exception as ex: 425 | if type(ex) is not IndexError: 426 | logger.error("Invalid argument UpperRadius in " + command + " at line " + str(i + 1)) 427 | 428 | r1 = 1.0 429 | 430 | try: 431 | r2 = float(arguments[2]) 432 | except Exception as ex: 433 | if type(ex) is not IndexError: 434 | logger.error("Invalid argument LowerRadius in " + command + " at line " + str(i + 1)) 435 | 436 | r2 = 1.0 437 | 438 | try: 439 | h = float(arguments[3]) 440 | except Exception as ex: 441 | if type(ex) is not IndexError: 442 | logger.error("Invalid argument Height in " + command + " at line " + str(i + 1)) 443 | 444 | h = 1.0 445 | 446 | self.create_cylinder(mesh, n, r1, r2, h) 447 | 448 | elif command.lower() == "Translate".lower() or command.lower() == "TranslateAll".lower(): 449 | if len(arguments) > 3: 450 | logger.warning("At most 3 arguments are expected in " + command + " at line " + str(i + 1)) 451 | 452 | try: 453 | x = float(arguments[0]) 454 | except Exception as ex: 455 | if type(ex) is not IndexError: 456 | logger.error("Invalid argument X in " + command + " at line " + str(i + 1)) 457 | 458 | x = 0.0 459 | 460 | try: 461 | y = float(arguments[1]) 462 | except Exception as ex: 463 | if type(ex) is not IndexError: 464 | logger.error("Invalid argument Y in " + command + " at line " + str(i + 1)) 465 | 466 | y = 0.0 467 | 468 | try: 469 | z = float(arguments[2]) 470 | except Exception as ex: 471 | if type(ex) is not IndexError: 472 | logger.error("Invalid argument Z in " + command + " at line " + str(i + 1)) 473 | 474 | z = 0.0 475 | 476 | self.apply_translation(mesh, x, y, z) 477 | 478 | if command.lower() == "TranslateAll".lower(): 479 | for other_mesh in meshes_list: 480 | self.apply_translation(other_mesh, x, y, z) 481 | 482 | elif command.lower() == "Scale".lower() or command.lower() == "ScaleAll".lower(): 483 | if len(arguments) > 3: 484 | logger.warning("At most 3 arguments are expected in " + command + " at line " + str(i + 1)) 485 | 486 | try: 487 | x = float(arguments[0]) 488 | except Exception as ex: 489 | if type(ex) is not IndexError: 490 | logger.error("Invalid argument X in " + command + " at line " + str(i + 1)) 491 | 492 | x = 1.0 493 | 494 | if x == 0.0: 495 | logger.error("X is required to be different from zero in " + command + " at line " + str(i + 1)) 496 | x = 1.0 497 | 498 | try: 499 | y = float(arguments[1]) 500 | except Exception as ex: 501 | if type(ex) is not IndexError: 502 | logger.error("Invalid argument Y in " + command + " at line " + str(i + 1)) 503 | 504 | y = 1.0 505 | 506 | if y == 0.0: 507 | logger.error("Y is required to be different from zero in " + command + " at line " + str(i + 1)) 508 | y = 1.0 509 | 510 | try: 511 | z = float(arguments[2]) 512 | except Exception as ex: 513 | if type(ex) is not IndexError: 514 | logger.error("Invalid argument Z in " + command + " at line " + str(i + 1)) 515 | 516 | z = 1.0 517 | 518 | if z == 0.0: 519 | logger.error("Z is required to be different from zero in " + command + " at line " + str(i + 1)) 520 | z = 1.0 521 | 522 | self.apply_scale(mesh, x, y, z) 523 | 524 | if command.lower() == "ScaleAll".lower(): 525 | for other_mesh in meshes_list: 526 | self.apply_scale(other_mesh, x, y, z) 527 | 528 | elif command.lower() == "Rotate".lower() or command.lower() == "RotateAll".lower(): 529 | if len(arguments) > 4: 530 | logger.warning("At most 4 arguments are expected in " + command + " at line " + str(i + 1)) 531 | 532 | try: 533 | rx = float(arguments[0]) 534 | except Exception as ex: 535 | if type(ex) is not IndexError: 536 | logger.error("Invalid argument X in " + command + " at line " + str(i + 1)) 537 | 538 | rx = 0.0 539 | 540 | try: 541 | ry = float(arguments[1]) 542 | except Exception as ex: 543 | if type(ex) is not IndexError: 544 | logger.error("Invalid argument Y in " + command + " at line " + str(i + 1)) 545 | 546 | ry = 0.0 547 | 548 | try: 549 | rz = float(arguments[2]) 550 | except Exception as ex: 551 | if type(ex) is not IndexError: 552 | logger.error("Invalid argument Z in " + command + " at line " + str(i + 1)) 553 | 554 | rz = 0.0 555 | 556 | try: 557 | angle = float(arguments[3]) 558 | except Exception as ex: 559 | if type(ex) is not IndexError: 560 | logger.error("Invalid argument Angle in " + command + " at line " + str(i + 1)) 561 | 562 | angle = 0.0 563 | 564 | t = rx * rx + ry * ry + rz * rz 565 | 566 | if t == 0.0: 567 | rz = 1.0 568 | ry = rz = 0.0 569 | t = 1.0 570 | 571 | if angle != 0.0: 572 | t = 1.0 / math.sqrt(t) 573 | rx *= t 574 | ry *= t 575 | rz *= t 576 | angle *= math.pi / 180.0 577 | 578 | self.apply_rotation(mesh, (rx, ry, rz), angle) 579 | 580 | if command.lower() == "RotateAll".lower(): 581 | for other_mesh in meshes_list: 582 | self.apply_rotation(other_mesh, (rx, ry, rz), angle) 583 | 584 | elif command.lower() == "Shear".lower() or command.lower() == "ShearAll".lower(): 585 | if len(arguments) > 7: 586 | logger.warning("At most 7 arguments are expected in " + command + " at line " + str(i + 1)) 587 | 588 | try: 589 | dx = float(arguments[0]) 590 | except Exception as ex: 591 | if type(ex) is not IndexError: 592 | logger.error("Invalid argument dX in " + command + " at line " + str(i + 1)) 593 | 594 | dx = 0.0 595 | 596 | try: 597 | dy = float(arguments[1]) 598 | except Exception as ex: 599 | if type(ex) is not IndexError: 600 | logger.error("Invalid argument dY in " + command + " at line " + str(i + 1)) 601 | 602 | dy = 0.0 603 | 604 | try: 605 | dz = float(arguments[2]) 606 | except Exception as ex: 607 | if type(ex) is not IndexError: 608 | logger.error("Invalid argument dZ in " + command + " at line " + str(i + 1)) 609 | 610 | dz = 0.0 611 | 612 | try: 613 | sx = float(arguments[3]) 614 | except Exception as ex: 615 | if type(ex) is not IndexError: 616 | logger.error("Invalid argument sX in " + command + " at line " + str(i + 1)) 617 | 618 | sx = 0.0 619 | 620 | try: 621 | sy = float(arguments[4]) 622 | except Exception as ex: 623 | if type(ex) is not IndexError: 624 | logger.error("Invalid argument sY in " + command + " at line " + str(i + 1)) 625 | 626 | sy = 0.0 627 | 628 | try: 629 | sz = float(arguments[5]) 630 | except Exception as ex: 631 | if type(ex) is not IndexError: 632 | logger.error("Invalid argument sZ in " + command + " at line " + str(i + 1)) 633 | 634 | sz = 0.0 635 | 636 | try: 637 | r = float(arguments[6]) 638 | except Exception as ex: 639 | if type(ex) is not IndexError: 640 | logger.error("Invalid argument Ratio in " + command + " at line " + str(i + 1)) 641 | 642 | r = 0.0 643 | 644 | d = self.normalize((dx, dy, dz)) 645 | s = self.normalize((sx, sy, sz)) 646 | self.apply_shear(mesh, d, s, r) 647 | 648 | if command.lower() == "ShearAll".lower(): 649 | for other_mesh in meshes_list: 650 | self.apply_shear(other_mesh, d, s, r) 651 | 652 | elif command.lower() == "Mirror".lower() or command.lower() == "MirrorAll".lower(): 653 | if len(arguments) > 6: 654 | logger.warning("At most 6 arguments are expected in " + command + " at line " + str(i + 1)) 655 | 656 | try: 657 | vx = float(arguments[0]) 658 | except Exception as ex: 659 | if type(ex) is not IndexError: 660 | logger.error("Invalid argument vX in " + command + " at line " + str(i + 1)) 661 | 662 | vx = 0.0 663 | 664 | try: 665 | vy = float(arguments[1]) 666 | except Exception as ex: 667 | if type(ex) is not IndexError: 668 | logger.error("Invalid argument vY in " + command + " at line " + str(i + 1)) 669 | 670 | vy = 0.0 671 | 672 | try: 673 | vz = float(arguments[2]) 674 | except Exception as ex: 675 | if type(ex) is not IndexError: 676 | logger.error("Invalid argument vZ in " + command + " at line " + str(i + 1)) 677 | 678 | vz = 0.0 679 | 680 | if len(arguments) >= 4: 681 | logger.info("This add-on ignores nX, nY and nZ in " + command + " at line " + str(i + 1)) 682 | 683 | self.apply_mirror(mesh, vx != 0.0, vy != 0.0, vz != 0.0) 684 | 685 | if command.lower() == "MirrorAll".lower(): 686 | for other_mesh in meshes_list: 687 | self.apply_mirror(other_mesh, vx != 0.0, vy != 0.0, vz != 0.0) 688 | 689 | elif command.lower() == "SetColor".lower(): 690 | if len(arguments) > 4: 691 | logger.warning("At most 4 arguments are expected in " + command + " at line " + str(i + 1)) 692 | 693 | try: 694 | red = int(arguments[0]) 695 | except Exception as ex: 696 | if type(ex) is not IndexError: 697 | logger.error("Invalid argument Red in " + command + " at line " + str(i + 1)) 698 | 699 | red = 0 700 | 701 | if red < 0 or red > 255: 702 | logger.error("Red is required to be within the range from 0 to 255 in " + command + " at line " + str(i + 1)) 703 | red = 0 if red < 0 else 255 704 | 705 | try: 706 | green = int(arguments[1]) 707 | except Exception as ex: 708 | if type(ex) is not IndexError: 709 | logger.error("Invalid argument Green in " + command + " at line " + str(i + 1)) 710 | 711 | green = 0 712 | 713 | if green < 0 or green > 255: 714 | logger.error("Green is required to be within the range from 0 to 255 in " + command + " at line " + str(i + 1)) 715 | green = 0 if green < 0 else 255 716 | 717 | try: 718 | blue = int(arguments[2]) 719 | except Exception as ex: 720 | if type(ex) is not IndexError: 721 | logger.error("Invalid argument Blue in " + command + " at line " + str(i + 1)) 722 | 723 | blue = 0 724 | 725 | if blue < 0 or blue > 255: 726 | logger.error("Blue is required to be within the range from 0 to 255 in " + command + " at line " + str(i + 1)) 727 | blue = 0 if blue < 0 else 255 728 | 729 | try: 730 | alpha = int(arguments[3]) 731 | except Exception as ex: 732 | if type(ex) is not IndexError: 733 | logger.error("Invalid argument Alpha in " + command + " at line " + str(i + 1)) 734 | 735 | alpha = 0 736 | 737 | if alpha < 0 or alpha > 255: 738 | logger.error("Alpha is required to be within the range from 0 to 255 in " + command + " at line " + str(i + 1)) 739 | alpha = 0 if alpha < 0 else 255 740 | 741 | mesh.diffuse_color = (red, green, blue, alpha) 742 | 743 | elif command.lower() == "SetEmissiveColor".lower(): 744 | if len(arguments) > 3: 745 | logger.warning("At most 3 arguments are expected in " + command + " at line " + str(i + 1)) 746 | 747 | try: 748 | red = int(arguments[0]) 749 | except Exception as ex: 750 | if type(ex) is not IndexError: 751 | logger.error("Invalid argument Red in " + command + " at line " + str(i + 1)) 752 | 753 | red = 0 754 | 755 | if red < 0 or red > 255: 756 | logger.error("Red is required to be within the range from 0 to 255 in " + command + " at line " + str(i + 1)) 757 | red = 0 if red < 0 else 255 758 | 759 | try: 760 | green = int(arguments[1]) 761 | except Exception as ex: 762 | if type(ex) is not IndexError: 763 | logger.error("Invalid argument Green in " + command + " at line " + str(i + 1)) 764 | 765 | green = 0 766 | 767 | if green < 0 or green > 255: 768 | logger.error("Green is required to be within the range from 0 to 255 in " + command + " at line " + str(i + 1)) 769 | green = 0 if green < 0 else 255 770 | 771 | try: 772 | blue = int(arguments[2]) 773 | except Exception as ex: 774 | if type(ex) is not IndexError: 775 | logger.error("Invalid argument Blue in " + command + " at line " + str(i + 1)) 776 | 777 | blue = 0 778 | 779 | if blue < 0 or blue > 255: 780 | logger.error("Blue is required to be within the range from 0 to 255 in " + command + " at line " + str(i + 1)) 781 | blue = 0 if blue < 0 else 255 782 | 783 | mesh.use_emissive_color = True 784 | mesh.emissive_color = (red, green, blue) 785 | 786 | elif command.lower() == "SetDecalTransparentColor".lower(): 787 | if len(arguments) > 3: 788 | logger.warning("At most 3 arguments are expected in " + command + " at line " + str(i + 1)) 789 | 790 | try: 791 | red = int(arguments[0]) 792 | except Exception as ex: 793 | if type(ex) is not IndexError: 794 | logger.error("Invalid argument Red in " + command + " at line " + str(i + 1)) 795 | 796 | red = 0 797 | 798 | if red < 0 or red > 255: 799 | logger.error("Red is required to be within the range from 0 to 255 in " + command + " at line " + str(i + 1)) 800 | red = 0 if red < 0 else 255 801 | 802 | try: 803 | green = int(arguments[1]) 804 | except Exception as ex: 805 | if type(ex) is not IndexError: 806 | logger.error("Invalid argument Green in " + command + " at line " + str(i + 1)) 807 | 808 | green = 0 809 | 810 | if green < 0 or green > 255: 811 | logger.error("Green is required to be within the range from 0 to 255 in " + command + " at line " + str(i + 1)) 812 | green = 0 if green < 0 else 255 813 | 814 | try: 815 | blue = int(arguments[2]) 816 | except Exception as ex: 817 | if type(ex) is not IndexError: 818 | logger.error("Invalid argument Blue in " + command + " at line " + str(i + 1)) 819 | 820 | blue = 0 821 | 822 | if blue < 0 or blue > 255: 823 | logger.error("Blue is required to be within the range from 0 to 255 in " + command + " at line " + str(i + 1)) 824 | blue = 0 if blue < 0 else 255 825 | 826 | mesh.use_transparent_color = True 827 | mesh.transparent_color = (red, green, blue) 828 | 829 | elif command.lower() == "SetBlendMode".lower() or command.lower() == "SetBlendingMode".lower(): 830 | if len(arguments) > 3: 831 | logger.warning("At most 3 arguments are expected in " + command + " at line " + str(i + 1)) 832 | 833 | try: 834 | if arguments[0].lower() == "normal": 835 | mesh.blend_mode = "Normal" 836 | elif arguments[0].lower() == "additive" or arguments[0].lower() == "glow": 837 | mesh.blend_mode = "Additive" 838 | else: 839 | logger.error("The given BlendMode is not supported in " + command + " at line " + str(i + 1)) 840 | mesh.blend_mode = "Normal" 841 | except Exception: 842 | mesh.blend_mode = "Normal" 843 | 844 | try: 845 | mesh.glow_half_distance = int(arguments[1]) 846 | except Exception: 847 | logger.error("Invalid argument GlowHalfDistance in " + command + " at line " + str(i + 1)) 848 | mesh.glow_half_distance = 0 849 | 850 | try: 851 | if arguments[2].lower() == "DivideExponent2".lower(): 852 | mesh.glow_attenuation_mode = "DivideExponent2" 853 | elif arguments[2].lower() == "DivideExponent4".lower(): 854 | mesh.glow_attenuation_mode = "DivideExponent4" 855 | else: 856 | logger.error("The given GlowAttenuationMode is not supported in " + command + " at line " + str(i + 1)) 857 | mesh.glow_attenuation_mode = "DivideExponent4" 858 | except Exception: 859 | mesh.glow_attenuation_mode = "DivideExponent4" 860 | 861 | elif command.lower() == "LoadTexture".lower(): 862 | if len(arguments) > 2: 863 | logger.warning("At most 2 arguments are expected in " + command + " at line " + str(i + 1)) 864 | 865 | try: 866 | mesh.daytime_texture_file = str(pathlib.Path(file_path).joinpath("..", arguments[0]).resolve()) 867 | except Exception as ex: 868 | if type(ex) is not IndexError: 869 | logger.error("Invalid argument DaytimeTexture in " + command + " at line " + str(i + 1)) 870 | 871 | mesh.daytime_texture_file = "" 872 | 873 | try: 874 | mesh.nighttime_texture_file = str(pathlib.Path(file_path).joinpath("..", arguments[1]).resolve()) 875 | except Exception as ex: 876 | if type(ex) is not IndexError: 877 | logger.error("Invalid argument NighttimeTexture in " + command + " at line " + str(i + 1)) 878 | 879 | mesh.nighttime_texture_file = "" 880 | 881 | elif command.lower() == "SetTextureCoordinates".lower(): 882 | if len(arguments) > 3: 883 | logger.warning("At most 3 arguments are expected in " + command + " at line " + str(i + 1)) 884 | 885 | try: 886 | j = int(arguments[0]) 887 | except Exception as ex: 888 | if type(ex) is not IndexError: 889 | logger.error("Invalid argument VertexIndex in " + command + " at line " + str(i + 1)) 890 | 891 | j = 0 892 | 893 | try: 894 | x = float(arguments[1]) 895 | except Exception as ex: 896 | if type(ex) is not IndexError: 897 | logger.error("Invalid argument X in " + command + " at line " + str(i + 1)) 898 | 899 | x = 0.0 900 | 901 | try: 902 | y = float(arguments[2]) 903 | except Exception as ex: 904 | if type(ex) is not IndexError: 905 | logger.error("Invalid argument Y in " + command + " at line " + str(i + 1)) 906 | 907 | y = 0.0 908 | 909 | if j >= 0 and j < len(mesh.vertex_list): 910 | mesh.texcoords_list.append((j, x, y)) 911 | else: 912 | logger.error("VertexIndex references a non-existing vertex in " + command + " at line " + str(i + 1)) 913 | 914 | else: 915 | logger.error("The command " + command + " is not supported at line " + str(i + 1)) 916 | 917 | # Finalize 918 | if mesh is not None: 919 | meshes_list.append(mesh) 920 | 921 | return meshes_list 922 | 923 | def export_csv(self, option: ExportOption, meshes_list: List[CsvMesh], file_path: str) -> None: 924 | if len(meshes_list) == 0: 925 | logger.error("Select one or more objects to export.") 926 | return 927 | 928 | csv_text = [] # type: List[str] 929 | 930 | # Header 931 | csv_text.append(";---------------------------------------------------------------------------\n") 932 | csv_text.append("; This file was exported from Blender by blenderCSV.\n") 933 | csv_text.append("; https://github.com/maisvendoo/blenderCSV\n") 934 | csv_text.append("; The copyright of this file belongs to the creator of the original content.\n") 935 | csv_text.append(";---------------------------------------------------------------------------\n") 936 | 937 | # Export model 938 | for mesh in meshes_list: 939 | # Apply global scale 940 | self.apply_scale(mesh, option.global_mesh_scale, option.global_mesh_scale, option.global_mesh_scale) 941 | 942 | # New mesh 943 | csv_text.append("\n; " + mesh.name + "\n") 944 | csv_text.append("CreateMeshBuilder\n") 945 | 946 | # Vertices 947 | for vertex, normal in zip(mesh.vertex_list, mesh.normals_list): 948 | vertex_text = str(vertex[0]) + ", " + str(vertex[1]) + ", " + str(vertex[2]) 949 | normal_text = str(normal[0]) + ", " + str(normal[1]) + ", " + str(normal[2]) 950 | 951 | if option.use_normals: 952 | csv_text.append("AddVertex, " + vertex_text + ", " + normal_text + "\n") 953 | else: 954 | csv_text.append("AddVertex, " + vertex_text + "\n") 955 | 956 | # Faces 957 | for face in mesh.faces_list: 958 | face_text = "" 959 | 960 | for vertex_index in face: 961 | face_text += ", " + str(vertex_index) 962 | 963 | if mesh.use_add_face2: 964 | csv_text.append("AddFace2" + face_text + "\n") 965 | else: 966 | csv_text.append("AddFace" + face_text + "\n") 967 | 968 | # Diffuse color 969 | csv_text.append("SetColor, " + str(mesh.diffuse_color[0]) + ", " + str(mesh.diffuse_color[1]) + ", " + str(mesh.diffuse_color[2]) + ", " + str(mesh.diffuse_color[3]) + "\n") 970 | 971 | # Emissive color 972 | if mesh.use_emissive_color: 973 | csv_text.append("SetEmissiveColor, " + str(mesh.emissive_color[0]) + ", " + str(mesh.emissive_color[1]) + ", " + str(mesh.emissive_color[2]) + "\n") 974 | 975 | # Blend mode 976 | csv_text.append("SetBlendMode, " + mesh.blend_mode + ", " + str(mesh.glow_half_distance) + ", " + mesh.glow_attenuation_mode + "\n") 977 | 978 | # Texture 979 | model_dir = pathlib.Path(file_path).parent 980 | 981 | if mesh.daytime_texture_file != "" and mesh.nighttime_texture_file != "": 982 | csv_text.append("LoadTexture, " + os.path.relpath(str(mesh.daytime_texture_file), str(model_dir)) + ", " + os.path.relpath(str(mesh.nighttime_texture_file), str(model_dir)) + "\n") 983 | elif mesh.daytime_texture_file != "": 984 | csv_text.append("LoadTexture, " + os.path.relpath(str(mesh.daytime_texture_file), str(model_dir)) + "\n") 985 | elif mesh.nighttime_texture_file != "": 986 | csv_text.append("LoadTexture, , " + os.path.relpath(str(mesh.nighttime_texture_file), str(model_dir)) + "\n") 987 | 988 | # Transparent color 989 | if mesh.use_transparent_color: 990 | csv_text.append("SetDecalTransparentColor, " + str(mesh.transparent_color[0]) + ", " + str(mesh.transparent_color[1]) + ", " + str(mesh.transparent_color[2]) + "\n") 991 | 992 | # Texture coordinates 993 | for texcoords in mesh.texcoords_list: 994 | csv_text.append("SetTextureCoordinates, " + str(texcoords[0]) + ", " + str(texcoords[1]) + ", " + str(texcoords[2]) + "\n") 995 | 996 | # Write file 997 | try: 998 | with open(file_path, "wt", encoding="utf-8") as f: 999 | f.writelines(csv_text) 1000 | except Exception as ex: 1001 | logger.critical(ex) 1002 | --------------------------------------------------------------------------------