I have a CSV containing x,y, and z coordinates. The CSV also has a fourth column containing information on sphere diameter. I need to create a sphere at each coordinate, having the corresponding diameter. Can someone provide me a basic Python script that performs this task? My actual task is much more involved, but I think I can solve it if I have the basics in place.
1 Answer
$\begingroup$
$\endgroup$
It has been a while since I have done any scripting, but the below should work based on your description. Note that the CSV file I made for testing included a header row, and the creation of objects for ease of testing was bpy.ops.mesh.primitive_uv_sphere_add()
bl_info = {
"name": "Blank1",
"author": "Your Name Here",
"version": (1, 0),
"blender": (2, 79, 0),
"location": "View3D > Tools panel 'T' > Blank1 > Blank2",
"description": "",
"warning": "",
"wiki_url": "",
"category": "",
}
import bpy
import csv
from bpy.types import Operator
from bpy.types import Panel
class MeshGenTool():
@classmethod
def main(cls, context):
scene = bpy.context.scene
objs = importCSV(scene['CSVFile'])
for obj in objs:
bpy.ops.mesh.primitive_uv_sphere_add(size=obj[1], location=obj[0])
MyMesh=bpy.context.object
MyMesh.name = "MyMesh"
class MeshGenButton(bpy.types.Operator):
"""Execute generation"""
bl_idname = "object.simple_operator"
bl_label = "Generate"
def execute(self, context):
MeshGenTool.main(context)
return {'FINISHED'}
# This is based on CSV file having a header row with the descriptions 'x', 'y', 'z', 'd'
def importCSV(CSVFile):
obj_loc = ()
obj_dia = 0
obj_data = ()
objs =[]
with open(CSVFile) as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
obj_loc = (float(row['x']), float(row['y']), float(row['z']))
obj_dia = float(row['d'])
obj_data = (obj_loc, obj_dia)
objs.append(obj_data)
return objs
class VIEW3D_PT_Blank1_Blank2(Panel):
bl_space_type = 'VIEW_3D'
bl_region_type = 'TOOLS'
bl_category = "Blank1"
bl_context = "objectmode"
bl_label = "Blank2"
def draw(self, context):
layout = self.layout
scene = bpy.context.scene
row = layout.row()
col = layout.column(align=True)
scn = bpy.context.scene
col.label(text="Blank2")
col.prop(scene, "CSVFile")
col.operator("object.simple_operator", text="Add items", icon='MESH_ICOSPHERE')
def register():
bpy.utils.register_class(VIEW3D_PT_Blank1_Blank2)
bpy.utils.register_class(MeshGenButton)
bpy.types.Scene.CSVFile = bpy.props.StringProperty(
name = "CSVFile",
description = "Path of CSV File to read from",
default = "",
subtype = 'FILE_PATH')
def unregister():
bpy.utils.unregister_class(VIEW3D_PT_Blank1_Blank2)
bpy.utils.unregister_class(MeshGenButton)
del bpy.types.Scene.CSVFile
if __name__ == "__main__":
register()