/**
**/


:-object rgb : [bcilib].

	var url = 'rgb.wrl'.

	main :-
		format('Loading RGB example from ~w~n', [url]),
		format('Please wait ...~n'),
		loadURL(url),
		sleep(3000),
		init_RGBs(board),
		eventObserverQueue(cylR, isOver, cyl_queue),
		eventObserverQueue(cylG, isOver, cyl_queue),
		eventObserverQueue(cylB, isOver, cyl_queue),
		eventObserverQueue(cylR, isActive, cyl_queue),
		eventObserverQueue(cylG, isActive, cyl_queue),
		eventObserverQueue(cylB, isActive, cyl_queue),
        	new(event(cyl_queue), _).

	init_RGBs(BoardName) :-
		getSFVec3f(cylR, boxposition, X1, _, _),
		getSFVec3f(cylG, boxposition, X2, _, _),
		getSFVec3f(cylB, boxposition, X3, _, _),
		event <- rgb_value(cylR, X1, R),
		event <- rgb_value(cylG, X2, G),
		event <- rgb_value(cylB, X3, B),
		setSFColor(cylR, boxcolor, R, 0.0, 0.0),
		setSFColor(cylG, boxcolor, 0.0, G, 0.0),
		setSFColor(cylB, boxcolor, 0.0, 0.0, B),
		setSFColor(cube, boxcolor, R,G,B),
		event <- update_board(BoardName, R,G,B).

:-end_object rgb.


:-object event : [bcilib].

	var is_over.
	var is_active.

	event(Queue) :-
		repeat,
			get_queue(Queue, Event),
			format('event : ~w~n', [Event]),
			mouse_event(Event),
		fail.

	mouse_event(isOver(sfbool(Value),_Time, CylName)) :-
		!,
		is_over := Value,
		mouse_click(is_active, is_over, CylName).
	mouse_event(isActive(sfbool(Value),_Time, CylName)) :-
		!,
		is_active := Value,
		mouse_click(is_active, is_over, CylName).
	mouse_event(Event) :-
		format('unknown event ~w~n', [Event]).

mouse_click(true, true, CylName) :-
	!,
	getSFVec3f(CylName, hitPoint_changed, XHit, _YHit, _ZHit),
	getSFVec3f(CylName, boxposition, _XBox, YBox, ZBox),
	setSFVec3f(CylName, boxposition,  XHit, YBox, ZBox),

	rgb_value(CylName, XHit, RGB),
	getSFColor(cube, boxcolor, RC,GC,BC),
	update_color(CylName, cube, board, RGB, RC,GC,BC).
mouse_click( _dont_let, _mouse_click, _fail).


update_color(cylR, CubeName, BoardName, RGB, _RC,GC,BC) :-
	!,
	setSFColor(cylR, boxcolor, RGB, 0.0, 0.0),
	setSFColor(CubeName, boxcolor, RGB,GC,BC),
	update_board(BoardName, RGB,GC,BC).
update_color(cylG, CubeName, BoardName, RGB, RC,_GC,BC) :-
	!,
	setSFColor(cylG, boxcolor, 0.0, RGB, 0.0),
	setSFColor(CubeName, boxcolor, RC,RGB,BC),
	update_board(BoardName, RC,RGB,BC).
update_color(cylB, CubeName, BoardName, RGB, RC,GC,_BC) :-
	setSFColor(cylB, boxcolor, 0.0, 0.0, RGB),
	setSFColor(CubeName, boxcolor, RC,GC,RGB),
	update_board(BoardName, RC,GC,RGB).

rgb_value(CylName, X, RGB) :-
	getSFFloat(CylName, height, H),
	RGB is X / H + 0.5 .

update_board(BoardName, RC,GC,BC) :-
	format_to_atom(Rtext, 'R = ~w', [RC]),
	format_to_atom(Gtext, 'G = ~w', [GC]),
	format_to_atom(Btext, 'B = ~w', [BC]),
	setMFString(BoardName, text, [Rtext,Gtext,Btext]).

:-end_object event.


/**
**/