local wind = dofile(core.get_modpath("breasy") .. "/init.lua")

local zero = vector.zero()

core.register_globalstep(function(dtime)
	for _, player in ipairs(core.get_connected_players()) do
		local pos = player:get_pos()
		pos.y = pos.y + 1

		local wind_vec = wind.get_occluded_wind(pos, true)
		local wind_mag = vector.length(wind_vec)

		-- No need to apply any forces to player.
		if wind_mag <= 8 then
			return
		end

		local player_vel = player:get_velocity() or zero
		local wind_dir = vector.normalize(wind_vec)

		local diff = vector.subtract(wind_vec, vector.new(player_vel.x, 0, player_vel.z))

		local acc_along_wind = vector.multiply(wind_dir, vector.dot(diff, wind_dir))

		local k = 3
		if player:get_player_control().sneak then
			k = k * 0.5
		end

		local delta_v = vector.multiply(acc_along_wind, k * dtime)

		-- Do not apply if a small force.
		if vector.length(delta_v) < 0.2 then
			return
		end

		player:add_velocity(delta_v)
	end
end)
