Trying to load a Bezier Curve in the BabylonJS viewer from a glTF file (from Blender)

Ok so, in fact, it was not too hard to write a Blender Script that export the coordinate of the points and their handles into a json file!

Here is my code, just copy paste it in Blender’s script editor:

import bpy

output = {}
output['curves'] = []
for curve in bpy.data.curves:
    print('Adding the curve: {}'.format(curve.name))
    control_points = curve.splines[0].bezier_points
    scale = bpy.data.objects[curve.name].scale[0]
    
    output['curves'].append({
        'name': curve.name,
        'points': []
    })
    
    out_points = output['curves'][-1]['points']
    
    for p in control_points:
        coord = p.co * scale
        l_handle = p.handle_left * scale
        r_handle = p.handle_right * scale
        print("\t - add points, coord: {}, left_handle: {}, right_handle: {}".format(coord, l_handle, r_handle))
        out_points.append({
            'coord' : coord[:],
            'right_handle' : r_handle[:],
            'left_handle' : l_handle[:],
        })
        
import json, os
filename = bpy.path.basename(bpy.data.filepath).split('.')[0]+'_curve_data.json'
with open(bpy.path.abspath('//'+filename), 'w') as f:
    print('\nWriting the output in:{}'.format(bpy.path.abspath('//'+filename)))
    json.dump(output, f, ensure_ascii=False)

import pprint
print('\nOutput preview:')
json_output = json.dumps(output)
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(json_output)

The output will look like this:

{
	"curves": [
		{
			"name": "BezierCircle",
			"points": [
				{
					"coord": [
						-1.9336860179901123,
						3.6524300575256348,
						0.0
					],
					"right_handle": [
						-1.9362720251083374,
						5.938126087188721,
						0.0
					],
					"left_handle": [
						-1.931984543800354,
						2.148655414581299,
						0.0
					]
				}, ...
        }
    ]
}

Hope that can help some other people!

5 Likes