/*
	This script file is part of the Sonic 3 A.I.R. script software distribution.
	Copyright (C) 2017-2024 by Eukaryot

	Published under the GNU GPLv3 open source software license, see license.txt
	or https://www.gnu.org/licenses/gpl-3.0.en.html
*/



//-------------------------------------------------------//
// Looping used in SOZ 2 right before the ghost capsule  //
//-------------------------------------------------------//

//# address-hook(0x04044a) end(0x040458)
function void fn04044a()
{
	D0.u16 = (objA0.subtype2c & 0x7f) << 4
	u16[A0 + 0x30] = D0.u16
	objA0.update_address = 0x04045e
	fn04045e()
}


//# address-hook(0x04045e) end(0x04046e)
function void fn04045e()
{
	A1 = 0xffffb000
	D6 = 3		// object.flag.P1_ON_OBJECT
	fn040474()

	A1 = 0xffffb04a
	D6 = 4		// object.flag.P2_ON_OBJECT
	fn040474()

	CheckForUnloadObject()
}


//# address-hook(0x040474) end(0x040544)
function void fn040474()
{
	u8 bit = (1 << D6.u8)

	if ((objA0.flags2a & bit) == 0)
	{
		D0.u16 = objA1.position.x.u16 - objA0.position.x.u16 + 0x10
		if (D0.u16 < 0x20)
		{
			D0.u16 = objA1.position.y.u16 - objA0.position.y.u16 + 0x10
			if (D0.u16 < 0x20)
			{
				if ((u8[A1 + 0x2a] & char.flag.ON_OBJECT) == 0 && u8[A1 + 0x05] < 0x04 && u8[A1 + 0x2e] == 0 && objA1.velocity.y >= 0x0800)
				{
					objA0.flags2a |= bit
					objA1.hitbox_extends.y = char.hitbox.y.ROLLING
					objA1.hitbox_extends.x = char.hitbox.x.ROLLING
					objA1.state = char.state.ROLLING
					objA1.flags2a |= (char.flag.IN_AIR | char.flag.ROLLING | char.flag.ON_OBJECT)
					objA1.flags2a &= ~char.flag.CONTROL_LOCK
					u8[A1 + 0x2f] = 0
					u8[A1 + 0x40] = 0
					u8[A1 + 0x2e] = (control_flag.DISABLE_INTERACTION | control_flag.DISABLE_UPDATE)
					objA1.velocity.x = 0
				}
			}
		}
	}
	else
	{
		objA1.position.x += s32(objA1.velocity.x) << 8
		objA1.position.y += s32(objA1.velocity.y) << 8
		objA1.velocity.y += 0x38

		D0.s16 = objA1.position.y.u16 - u16[A0 + 0x30]
		if (D0.s16 >= s16(objA0.position.y.u16))
		{
			u8[A1 + 0x2a] &= ~char.flag.ON_OBJECT
			objA0.flags2a &= ~bit
			u8[A1 + 0x2e] = 0
		}
	}
}
