:NAME door_proximity_trigger


:PARAM float32 trigger_distance

:VAR s_vector2d p



-- ------------------- constants ------------------- 

--local vectorlib = require "scripts/vector_math"

k_default_open_threshold= 4
k_path_follow_component= e_value("e_component", "_component_path_follow")

-- ------------------- initialization ------------------- 


function param_initialize(p)
	p.trigger_distance = k_default_open_threshold
end

function var_initialize(v)
	v.p.x= 0
	v.p.y= 0
end

-- ------------------- component ------------------- 

function attach(object)

	local position= object.world_position_get()
	local p= var.p

	p.x= position.x
	p.y= position.y

	local model= object.model_get()
	if (model) then
		local iterator= model.markers.iterator_get()
		local marker0= iterator.next()
		
		if (marker0) then
			local pos0= marker0.world_position_get(object)
			p.x= pos0.x
			p.y= pos0.y
		end
	end
end

function update(object)

	local door_script= object._c.door
	
	if (door_script) then
		local desired_position= 0
		local ws = world_state_get()
		
		local p= var.p
		local closest_distance= ws.distance_to_nearest_object_with_component(k_path_follow_component, p.x, p.y)
		if (closest_distance < param.trigger_distance) then
			desired_position= 1
		end

		--[[

		local player_components = ws.component_cache.component_player.iterator_get()
		local cur_player = player_components.next()
		while (cur_player) do
			local player_position = cur_player.object.world_position_get()
			local d= vectorlib.distance2d(player_position, p)

			if (d < param.trigger_distance) then
				desired_position= 1
			end
			
			cur_player = player_components.next()
		end		
	
		local perception_components = ws.component_cache.component_perception.iterator_get()
		local cur_NPC = perception_components.next()
		while (cur_NPC) do
			local NPC_position = cur_NPC.object.world_position_get()
			local d= vectorlib.distance2d(NPC_position, p)
			
			if (d < param.trigger_distance) then -- CB_TODO: Also need to check if the player has been seen?
				desired_position= 1
			end
			
			cur_NPC = perception_components.next()
		end
		--]]

		door_script.desired_position= desired_position
	end	
end

component_register(attach, update, nil, nil)
