#include "JSystem/JParticle/JPAExTexShape.h"
#include "JSystem/JParticle/JPAResourceManager.h"
#include "JSystem/JParticle/JPAEmitter.h"
#include "nw4r/math/math_triangular.h"
#include "rvl/MTX.h"
#include "rvl/GX.h"

void JPALoadExTex(JPAEmitterWorkData* work) {
    JPAExTexShape* ets = work->mpRes->getEts();

    GXTexCoordID secTexCoordID = GX_TEXCOORD1;
    if (ets->isUseIndirect()) {
        Mtx m;
        MTXIdentity(m);
        GXLoadTexMtxImm(m, GX_TEXMTX2, GX_MTX2x4);
        GXSetTexCoordGen2(GX_TEXCOORD1, GX_TG_MTX2x4, GX_TG_TEX0, GX_TEXMTX2, GX_FALSE,
                          GX_PTIDENTITY);
        work->mpResMgr->load(work->mpRes->getTexIdx(ets->getIndTexIdx()), GX_TEXMAP2);
        secTexCoordID = GX_TEXCOORD2;
    }

    if (ets->isUseSecTex()) {
        GXSetTexCoordGen2(secTexCoordID, GX_TG_MTX2x4, GX_TG_TEX0, GX_IDENTITY, GX_FALSE,
                          GX_PTIDENTITY);
        work->mpResMgr->load(work->mpRes->getTexIdx(ets->getSecTexIdx()), GX_TEXMAP3);
    }
}

JPAExTexShape::JPAExTexShape(u8 const* data) {
    mpData = (const JPAExTexShapeData*)data;
}

// Similar to JPAGenCalcTexCrdMtxAnm
void JPAExTexShape::fn_8031DE80(const JPABaseShape *shp, f32 f) const {
    f32 tilingS = 0.5f * (1.0f + shp->getTilingS());
    f32 tilingT = 0.5f * (1.0f + shp->getTilingT());
    f32 _0x38_x_0x24 = f * getField_0x38() + getField_0x24();
    f32 _0x3C_x_0x28 = f * getField_0x3C() + getField_0x28();
    f32 _0x40_x_0x2C = f * getField_0x40() + getField_0x2C();
    f32 _0x44_x_0x30 = f * getField_0x44() + getField_0x30();

    s16 v = f * getField_0x48() * 0x8000 + getField_0x34() * 0x8000;
    f32 sin = nw4r::math::SinIdx(v);
    f32 cos = nw4r::math::CosIdx(v);

    Mtx texMtx;

    texMtx[0][0] = _0x40_x_0x2C * cos;
    texMtx[0][1] = -_0x40_x_0x2C * sin;
    texMtx[0][2] = 0.0f;
    texMtx[0][3] = tilingS + (_0x40_x_0x2C * (sin * (tilingT + _0x3C_x_0x28) - cos * (tilingS + _0x38_x_0x24)));

    texMtx[1][0] = _0x44_x_0x30 * sin;
    texMtx[1][1] = _0x44_x_0x30 * cos;
    texMtx[1][2] = 0.0f;
    texMtx[1][3] = tilingT + (-_0x44_x_0x30 * (sin * (tilingS + _0x38_x_0x24) + cos * (tilingT + _0x3C_x_0x28)));

    texMtx[2][0] = 0.0f;
    texMtx[2][1] = 0.0f;
    texMtx[2][2] = 1.0f;
    texMtx[2][3] = 0.0f;
    GXLoadTexMtxImm(texMtx, 0x24, GX_MTX2x4);
}
