#!/usr/bin/env python
"""Blender sometimes fails to save the fourth bones of vertices.
Give this script a submesh exported by Blender as the first argument, 
and the original as a second argument, and the script will try to fix 
this where it can.
"""

import sys

import vb

if __name__ == '__main__':
	modifying = vb.Mesh(sys.argv[1])
	comparisons = [vb.Mesh(arg) for arg in sys.argv[2:]]
	for c in comparisons[1:]:
		comparisons[0].vertices.extend(c.vertices)
	changes = {}
	for v in modifying.vertices:
		for w in comparisons[0].vertices:
			if v.bi()[:3] != w.bi()[:3]:
				continue
			if v.bi()[3] != 0:
				continue
			if w.bi()[3] == 0:
				continue
			vw = v.bw()
			ww = w.bw()
			if sum(vw) > 0.99999:
				continue
			if abs(vw[0] - ww[0]) > 0.00001:
				continue
			if abs(vw[1] - ww[1]) > 0.00001:
				continue
			if abs(vw[2] - ww[2]) > 0.00001:
				continue
			if w.distance(v) > 0.00001:
			       continue
			if v in changes:
				changes[v].append(w)
			else:
				changes[v] = [w]
	for v, l in changes.items():
		if l[0].distance(v) < 0.00001:
			v.setbi(l[0].bi())
			v.setbw(l[0].bw())
		else:
			print (v.bi())
			print (v.bw())
			print (v.pos())
			print (l[0].bi())
			print (l[0].bw())
			print (l[0].pos())
			raise Exception()

	if not changes:
		print ('Nothing to fix found')
		sys.exit(0)
	print ('Changed %d vertices' % len(changes))
	input ('Will write on enter...')
	modifying.write(sys.argv[1])


